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 |
|---|---|---|---|---|---|---|---|---|
namespace Dev.DevKit.Shared.Entities
{
public partial class SiteMap
{
#region --- PROPERTIES ---
//public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } }
#endregion
#region --- STATIC METHODS ---
#endregion
}
}
| 17.764706 | 97 | 0.576159 | [
"MIT"
] | Kayserheimer/Dynamics-Crm-DevKit | test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/SiteMap.cs | 304 | C# |
using MediatR;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Hb.Application.PipelineBehaviours
{
public class PerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly Stopwatch _timer;
private readonly ILogger<TRequest> _logger;
public PerformanceBehaviour(ILogger<TRequest> logger)
{
_timer = new Stopwatch();
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
_timer.Start();
var response = await next();
_timer.Stop();
var elapsedMilliseconds = _timer.ElapsedMilliseconds;
if(elapsedMilliseconds > 500)
{
var requestName = typeof(TRequest).Name;
_logger.LogWarning("Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@Request}",
requestName, elapsedMilliseconds, request);
}
return response;
}
}
}
| 28.619048 | 138 | 0.634775 | [
"MIT"
] | gkctnn/HbCase | src/Services/Catalog/Hb.Application/PipelineBehaviours/PerformanceBehaviour.cs | 1,204 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace SerialPortTools
{
static class Program
{
public static frmMain frm;
public static frmWaiting frma;
public static Thread thread = new Thread(RunFrm);
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
frma = new frmWaiting();
thread.Start();
frm = new frmMain();
Application.Run(frm);
}
public static DataTable dt = new DataTable();
public static void RunFrm()
{
Application.Run(frma);
}
#region ConfigFile
private static string ConfigFilePath = "./" + Application.ProductName + ".exe";
private static string CheckConfig(string ConfigFilePath)
{
System.IO.FileInfo fi = new System.IO.FileInfo(ConfigFilePath);
if (!fi.Directory.Exists) System.IO.Directory.CreateDirectory(fi.DirectoryName);
return ConfigFilePath;
}
public static void UpdateAppConfig(string Key, string Value)
{
string filePath = ConfigFilePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(CheckConfig(filePath));
if (config.AppSettings.Settings[Key] == null) config.AppSettings.Settings.Add(Key, Value);
else config.AppSettings.Settings[Key].Value = Value;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
public static string GetConfigValue(string Key)
{
string filePath = ConfigFilePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(CheckConfig(filePath));
if (config.AppSettings.Settings[Key] == null) config.AppSettings.Settings.Add(Key, "");
config.Save(ConfigurationSaveMode.Modified);
return config.AppSettings.Settings[Key].Value;
}
public static void DeleteConfigValue(string Key)
{
string filePath = ConfigFilePath;
Configuration config = ConfigurationManager.OpenExeConfiguration(CheckConfig(filePath));
config.AppSettings.Settings.Remove(Key);
config.Save(ConfigurationSaveMode.Modified);
}
#endregion
#region Threshold
public static ShowValue SelectedSV;
public static Color DefaultFontColor = Color.Black;
public static Color DefaultBackColor = Color.White;
public static Dictionary<string, Threshold> threshold = new Dictionary<string, Threshold> { };
public static string C2S(Color C)
{
return C.R + "," + C.G + "," + C.B;
}
public static Color S2C(string S)
{
try
{
string[] temp = S.Split(',');
if (temp.Length != 3) return Color.Red;
int R = Convert.ToInt16(temp[0]);
int G = Convert.ToInt16(temp[1]);
int B = Convert.ToInt16(temp[2]);
return Color.FromArgb(R, G, B);
}
catch
{
return Color.Red;
}
}
public static void ChangeColor()
{
frm.UpdateValue();
}
#endregion
public static void ChangeText(ShowValue sender)
{
CheckBox cbx = (CheckBox)sender.Tag;
if (cbx == null) return;
cbx.Text = sender.Name + "(" + GetConfigValue("#Variable_" + sender.Name) + ")";
}
}
}
| 29.961538 | 102 | 0.583312 | [
"MIT"
] | zzudongxiang/SerialPort.Tools | SerialPortTools/Program.cs | 3,917 | C# |
using System;
using System.Text;
using Aspose.Cloud.Marketplace.HTML.Converter.Helpers;
using Aspose.Cloud.Marketplace.HTML.Converter.Models;
using Aspose.Cloud.Marketplace.HTML.Converter.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Aspose.Cloud.Marketplace.HTML.Converter.Controllers
{
/// <summary>
/// API controller for Markdown handling
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class MarkdownController : ControllerBase
{
private string _contentType;
private readonly ILogger<MarkdownController> _logger;
private readonly Aspose.Html.Cloud.Sdk.Api.Interfaces.IImportApi _importApi;
private readonly Aspose.Html.Cloud.Sdk.Api.Interfaces.IConversionApi _conversionApi;
private readonly Aspose.Html.Cloud.Sdk.Api.Interfaces.IStorageFileApi _storageApi;
private readonly IWebHostEnvironment _env;
private readonly StatisticalService _statisticalService;
/// <summary>
/// Constructor. Initialize services for conversion
/// </summary>
/// <param name="logger">Logger service</param>
/// <param name="env">Host environment</param>
/// <param name="conversionApi">HTML-to-PDF API</param>
/// <param name="importApi">MD-to-PDF API</param>
/// <param name="storageApi">Storage API</param>
/// <param name="statisticalService">Statistical Service</param>
public MarkdownController(
ILogger<MarkdownController> logger,
IWebHostEnvironment env,
Aspose.Html.Cloud.Sdk.Api.Interfaces.IConversionApi conversionApi,
Aspose.Html.Cloud.Sdk.Api.Interfaces.IImportApi importApi,
Aspose.Html.Cloud.Sdk.Api.Interfaces.IStorageFileApi storageApi,
StatisticalService statisticalService)
{
_logger = logger;
_env = env;
_importApi = importApi;
_storageApi = storageApi;
_conversionApi = conversionApi;
_statisticalService = statisticalService;
}
/// <summary>
/// Converter. Accepts incoming options, calculate settings for printable pages (if necessary) and render output content.
/// </summary>
/// <param name="converterOptions">Incoming options</param>
/// <returns></returns>
[HttpPost]
public IActionResult Post(ConverterOptions converterOptions)
{
System.IO.Stream resultStream = null;
var startTime = DateTime.Now;
var tempFileGuid = Guid.NewGuid();
_logger.LogInformation($"Conversion started: {tempFileGuid} from MD to {converterOptions.To.ToUpper()} / {startTime}");
var htmlFileName = tempFileGuid + ".html";
var cssFileTheme = System.IO.Path.Combine(_env.WebRootPath, "css/markdown.css");
var cssContent = System.IO.File.ReadAllText(cssFileTheme);
var resultedContent = converterOptions.To.ToLower() != "html"
? string.Concat("<style>", cssContent, "</style>\n\n", converterOptions.Content)
: converterOptions.Content;
var file = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(resultedContent));
Aspose.Html.Cloud.Sdk.Api.Model.AsposeResponse response;
try
{
response = _importApi.PostImportMarkdownToHtml(file, htmlFileName);
}
catch (AggregateException ae)
{
ae.Handle((x) =>
{
_logger.LogError($"Error file uploading {tempFileGuid}. {x.Message}");
return true;
});
throw;
}
catch (Exception ex)
{
_logger.LogError($"Error file uploading {tempFileGuid}. {ex.Message}");
throw;
}
switch (converterOptions.To.ToLower())
{
case "pdf":
_logger.LogInformation($"Converter options: {converterOptions.Paper.Size} {converterOptions.Paper.Width}x{converterOptions.Paper.Height}");
var options = SettingsConverter.GetPageSettings(converterOptions);
_logger.LogInformation($"Calculated options: {options}");
var streamResponse = _conversionApi.GetConvertDocumentToPdf(htmlFileName,
options.Width, options.Height,
options.Left, options.Bottom,
options.Right, options.Top);
if (streamResponse != null && streamResponse.Status == "OK")
{
try
{
resultStream = streamResponse.ContentStream;
}
catch (Exception ex)
{
_logger.LogError($"Conversion error: {ex.Message}");
throw;
}
_contentType = "application/pdf";
}
break;
case "html":
try
{
if (response != null && response.Status == "OK")
resultStream = _storageApi.DownloadFile(htmlFileName).ContentStream;
}
catch (Exception ex)
{
_logger.LogError("Error file downloading {0} {1}", tempFileGuid, ex.Message);
throw;
}
_contentType = "text/html; charset=utf-8";
break;
default:
throw new NotImplementedException($"MD-to-{converterOptions.To} is not supported.");
}
if (resultStream == null)
{
_logger.LogError("Error MD to PDF conversion {0} {1}", tempFileGuid, htmlFileName);
throw new Exception("Error MD to PDF conversion");
}
var finishTime = DateTime.Now;
_logger.LogInformation(message: $"Conversion completed: {tempFileGuid} / {finishTime}");
_logger.LogInformation(message: $"Conversion time: {tempFileGuid} / {finishTime.Subtract(startTime).Milliseconds}ms");
//TODO: Implement gather stats
_statisticalService.IncrementCounter(converterOptions.MachineId);
return File(resultStream, _contentType);
}
}
} | 44.697987 | 159 | 0.56952 | [
"MIT"
] | andruhovski/aspose-html-converter | Aspose.Cloud.Marketplace.HTML.MarkdownConverter/Controllers/MarkdownController.cs | 6,662 | C# |
using System;
using System.Collections.Generic;
namespace Shoko.Server.Providers.AniDB.UDP.Info
{
public class ResponseGetFile
{
/// AniDB File ID
public int FileID { get; set; }
/// AniDB Anime ID
public int AnimeID { get; set; }
/// AniDB Release Group ID, if available
public int? GroupID { get; set; }
// AniDB Episode IDs for episodes that this file may link to. The eid is listed here as 100%
public List<EpisodeXRef> EpisodeIDs { get; set; }
// Is the file deprecated/replaced
public bool Deprecated { get; set; }
// the version, will be higher than 1 if it's replacing a deprecated file
public int Version { get; set; }
// Mostly for AniDB's use. Does the CRC in the filename match the actual CRC
public bool? CRCMatches { get; set; }
// Chaptered. This is likely to be wrong, as it is undocumented
public bool Chaptered { get; set; }
// trinary state for Censoring. Null means no data is marked.
public bool? Censored { get; set; }
// quality. Usually high or very high for new releases. for old stuff, it can vary
public GetFile_Quality Quality { get; set; }
// source. Where this release came from, ie TV, Webrip, etc
public GetFile_Source Source { get; set; }
// Audio Languages
public List<string> AudioLanguages { get; set; }
// Subtitle Languages
public List<string> SubtitleLanguages { get; set; }
// Description of the file. Usually blank
public string Description { get; set; }
// Filename as reported in AVDump
public string Filename { get; set; }
// MyList Info, if applicable
public MyListInfo MyList { get; set; }
public class EpisodeXRef
{
// AniDB Episode ID
public int EpisodeID { get; set; }
// Percentage of the Episode it represents. May not be exact, and has no info of where in the episode it lies
public byte Percentage { get; set; }
}
public class MyListInfo
{
// things here aren't nullable because this whole model will be null in that case.
// Generic File info is not applicable in this context, as GetFile won't match in those cases
// AniDB MyListID for the current user, if applicable
public int MyListID { get; set; }
// Location of the file as marked in MyList
public MyList_State State { get; set; }
// state of the file as marked in MyList. This is stuff like corrupted, etc
public MyList_FileState FileState { get; set; }
// View Count
public int ViewCount { get; set; }
// Latest View Date
public DateTime? ViewDate { get; set; }
}
}
}
| 43.818182 | 121 | 0.606846 | [
"MIT"
] | Hitsounds/ShokoServer | Shoko.Server/Providers/AniDB/UDP/Info/ResponseGetFile.cs | 2,892 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// As informações gerais sobre um assembly são controladas por
// conjunto de atributos. Altere estes valores de atributo para modificar as informações
// associada a um assembly.
[assembly: AssemblyTitle("Bz2Helper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Bz2Helper")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Definir ComVisible como false torna os tipos neste assembly invisíveis
// para componentes COM. Caso precise acessar um tipo neste assembly de
// COM, defina o atributo ComVisible como true nesse tipo.
[assembly: ComVisible(false)]
// O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM
[assembly: Guid("a270a5d5-c459-4552-bf8f-11cc79b79ca2")]
// As informações da versão de um assembly consistem nos quatro valores a seguir:
//
// Versão Principal
// Versão Secundária
// Número da Versão
// Revisão
//
// É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão
// usando o "*" como mostrado abaixo:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38 | 95 | 0.751778 | [
"MIT"
] | danielhidalgojunior/zrageadminpanel | Bz2Helper/Properties/AssemblyInfo.cs | 1,431 | C# |
namespace PedroLamas.WP7.UnitConverter.Framework
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
/// <summary>
/// A base implementation of <see cref="IScreen"/>.
/// </summary>
public class Screen : PropertyChangedBase, IScreen, IChild<IConductor>, IViewAware
{
protected static readonly ILog Log = LogManager.GetLog(typeof(Screen));
bool isActive;
bool isInitialized;
IConductor parent;
string displayName;
readonly Dictionary<object, object> views = new Dictionary<object, object>();
/// <summary>
/// Creates an instance of the screen.
/// </summary>
public Screen()
{
DisplayName = GetType().FullName;
}
/// <summary>
/// Gets or Sets the Parent <see cref="IConductor"/>
/// </summary>
public IConductor Parent
{
get { return parent; }
set
{
parent = value;
NotifyOfPropertyChange("Parent");
}
}
/// <summary>
/// Gets or Sets the Display Name
/// </summary>
public string DisplayName
{
get { return displayName; }
set
{
displayName = value;
NotifyOfPropertyChange("DisplayName");
}
}
/// <summary>
/// Indicates whether or not this instance is currently active.
/// </summary>
public bool IsActive
{
get { return isActive; }
private set
{
isActive = value;
NotifyOfPropertyChange("IsActive");
}
}
/// <summary>
/// Indicates whether or not this instance is currently initialized.
/// </summary>
public bool IsInitialized
{
get { return isInitialized; }
private set
{
isInitialized = value;
NotifyOfPropertyChange("IsInitialized");
}
}
/// <summary>
/// Raised after activation occurs.
/// </summary>
public event EventHandler<ActivationEventArgs> Activated = delegate { };
/// <summary>
/// Raised before deactivation.
/// </summary>
public event EventHandler<DeactivationEventArgs> AttemptingDeactivation = delegate { };
/// <summary>
/// Raised after deactivation.
/// </summary>
public event EventHandler<DeactivationEventArgs> Deactivated = delegate { };
void IActivate.Activate()
{
if (IsActive)
return;
var initialized = false;
if (!IsInitialized)
{
IsInitialized = initialized = true;
OnInitialize();
}
IsActive = true;
Log.Info("Activating {0}.", this);
OnActivate();
Activated(this, new ActivationEventArgs
{
WasInitialized = initialized
});
}
/// <summary>
/// Called when initializing.
/// </summary>
protected virtual void OnInitialize() { }
/// <summary>
/// Called when activating.
/// </summary>
protected virtual void OnActivate() { }
void IDeactivate.Deactivate(bool close)
{
if (!IsActive && !IsInitialized)
return;
AttemptingDeactivation(this, new DeactivationEventArgs
{
WasClosed = close
});
IsActive = false;
Log.Info("Deactivating {0}.", this);
OnDeactivate(close);
if (close)
Log.Info("Closed {0}.", this);
Deactivated(this, new DeactivationEventArgs
{
WasClosed = close
});
}
/// <summary>
/// Called when deactivating.
/// </summary>
/// <param name="close">Inidicates whether this instance will be closed.</param>
protected virtual void OnDeactivate(bool close) { }
/// <summary>
/// Called to check whether or not this instance can close.
/// </summary>
/// <param name="callback">The implementor calls this action with the result of the close check.</param>
public virtual void CanClose(Action<bool> callback)
{
callback(true);
}
/// <summary>
/// Attaches a view to this instance.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="context">The context in which the view appears.</param>
public virtual void AttachView(object view, object context)
{
var loadWired = views.Values.Contains(view);
views[context ?? ViewLocator.DefaultContext] = view;
var element = view as FrameworkElement;
if (!loadWired && element != null)
element.Loaded += delegate { OnViewLoaded(view); };
if (!loadWired)
ViewAttached(this, new ViewAttachedEventArgs { View = view, Context = context });
}
/// <summary>
/// Called when an attached view's Loaded event fires.
/// </summary>
/// <param name="view"></param>
protected virtual void OnViewLoaded(object view) { }
/// <summary>
/// Gets a view previously attached to this instance.
/// </summary>
/// <param name="context">The context denoting which view to retrieve.</param>
/// <returns>The view.</returns>
public virtual object GetView(object context)
{
object view;
views.TryGetValue(context ?? ViewLocator.DefaultContext, out view);
return view;
}
/// <summary>
/// Raised when a view is attached.
/// </summary>
public event EventHandler<ViewAttachedEventArgs> ViewAttached = delegate { };
/// <summary>
/// Tries to close this instance by asking its Parent to initiate shutdown or by asking its corresponding default view to close.
/// </summary>
public void TryClose()
{
if (Parent != null)
Parent.CloseItem(this);
else
{
var view = GetView(null);
if (view == null)
{
var ex = new NotSupportedException("A Parent or default view is required.");
Log.Error(ex);
throw ex;
}
var method = view.GetType().GetMethod("Close");
if (method != null)
{
method.Invoke(view, null);
return;
}
var property = view.GetType().GetProperty("IsOpen");
if (property != null)
{
property.SetValue(view, false, new object[] { });
return;
}
var ex2 = new NotSupportedException("The default view does not support Close/IsOpen.");
Log.Error(ex2);
throw ex2;
}
}
#if !SILVERLIGHT
/// <summary>
/// Closes this instance by asking its Parent to initiate shutdown or by asking it's corresponding default view to close.
/// This overload also provides an opportunity to pass a dialog result to it's corresponding default view.
/// </summary>
/// <param name="dialogResult">The dialog result.</param>
public virtual void TryClose(bool? dialogResult)
{
var view = GetView(null);
if (view != null)
{
var property = view.GetType().GetProperty("DialogResult");
if (property != null)
property.SetValue(view, dialogResult, null);
}
TryClose();
}
#endif
}
}
| 30.225926 | 136 | 0.509987 | [
"MIT"
] | PedroLamas/PedroLamas.WP7.UnitConverter | src/PedroLamas.WP7.UnitConverter/Framework/Screen.cs | 8,161 | 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.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Proximity
{
/// <summary>
/// Manages a proximity placement group for virtual machines, virtual machine scale sets and availability sets.
///
/// > This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/r/proximity_placement_group.html.markdown.
/// </summary>
public partial class PlacementGroup : Pulumi.CustomResource
{
/// <summary>
/// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
/// </summary>
[Output("location")]
public Output<string> Location { get; private set; } = null!;
/// <summary>
/// Specifies the name of the availability set. Changing this forces a new resource to be created.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The name of the resource group in which to create the availability set. Changing this forces a new resource to be created.
/// </summary>
[Output("resourceGroupName")]
public Output<string> ResourceGroupName { get; private set; } = null!;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>> Tags { get; private set; } = null!;
/// <summary>
/// Create a PlacementGroup resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public PlacementGroup(string name, PlacementGroupArgs args, CustomResourceOptions? options = null)
: base("azure:proximity/placementGroup:PlacementGroup", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, ""))
{
}
private PlacementGroup(string name, Input<string> id, PlacementGroupState? state = null, CustomResourceOptions? options = null)
: base("azure:proximity/placementGroup:PlacementGroup", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing PlacementGroup resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static PlacementGroup Get(string name, Input<string> id, PlacementGroupState? state = null, CustomResourceOptions? options = null)
{
return new PlacementGroup(name, id, state, options);
}
}
public sealed class PlacementGroupArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Specifies the name of the availability set. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the resource group in which to create the availability set. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public PlacementGroupArgs()
{
}
}
public sealed class PlacementGroupState : Pulumi.ResourceArgs
{
/// <summary>
/// Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// Specifies the name of the availability set. Changing this forces a new resource to be created.
/// </summary>
[Input("name")]
public Input<string>? Name { get; set; }
/// <summary>
/// The name of the resource group in which to create the availability set. Changing this forces a new resource to be created.
/// </summary>
[Input("resourceGroupName")]
public Input<string>? ResourceGroupName { get; set; }
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// A mapping of tags to assign to the resource.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public PlacementGroupState()
{
}
}
}
| 40.7 | 175 | 0.614558 | [
"ECL-2.0",
"Apache-2.0"
] | apollo2030/pulumi-azure | sdk/dotnet/Proximity/PlacementGroup.cs | 6,512 | C# |
using UnityEngine;
public class MiniMap : MonoBehaviour
{
public Transform miniMapCameraTransform;
public Transform playerTransform;
private Vector3 cameraFromPlayerOffset;
[SerializeField] float rotationSpeed = 120f;
[SerializeField] Transform player;
[SerializeField] private Camera cam;
private Vector3 previousPosition;
void Start()
{
cameraFromPlayerOffset = new Vector3(0, 11, 0);
}
private void LateUpdate()
{
miniMapCameraTransform.position = playerTransform.position + cameraFromPlayerOffset;
var position = player.position;
transform.RotateAround(position, player.up, Input.GetAxis("Horizontal") * Time.deltaTime * rotationSpeed);
if (Input.GetMouseButton(2))
{
Vector3 direction = previousPosition - cam.ScreenToViewportPoint(Input.mousePosition);
cam.transform.position = player.position;
cam.transform.Rotate(new Vector3(0,0.1f,0),-direction.x*90,Space.World);
cam.transform.Translate(new Vector3(0,0,0));
previousPosition = Camera.main.ScreenToViewportPoint(Input.mousePosition);
}
}
}
| 32.090909 | 109 | 0.764873 | [
"MIT"
] | Cecilija-Simic-Rihtnesberg/game21-2021-1129-arpg-team-3 | Assets/Scripts/UI/MiniMap.cs | 1,059 | C# |
using System.Windows;
using System.Windows.Media;
using BuildNotifications.Resources.BuildTree.TriggerActions;
using TweenSharp.Animation;
using TweenSharp.Factory;
namespace BuildNotifications.Resources.GroupDefinitionSelection
{
internal class GroupDefinitionFadeIn : TweenTriggerAction<UIElement>
{
protected override void Invoke(object parameter)
{
var globalTweenHandler = App.GlobalTweenHandler;
globalTweenHandler.ClearTweensOf(TargetElement);
var anchor = Anchor.Position(TargetElement);
var scaleTransform = new ScaleTransform(0.2, 0.7, anchor.X, anchor.Y);
TargetElement.Opacity = 0;
globalTweenHandler.Add(scaleTransform.Tween(x => x.ScaleX).To(1.0).In(Duration).Ease(Easing.ExpoEaseInOut));
globalTweenHandler.Add(scaleTransform.Tween(x => x.ScaleY).To(1.0).In(Duration).Ease(Easing.ExpoEaseInOut));
globalTweenHandler.Add(TargetElement.Tween(x => x.Opacity).To(1.0).In(Duration).Ease(Easing.ExpoEaseInOut));
TargetElement.RenderTransform = scaleTransform;
}
}
} | 43.153846 | 120 | 0.710339 | [
"MIT"
] | TheSylence/BuildNotifications | BuildNotifications/Resources/GroupDefinitionSelection/GroupDefinitionFadeIn.cs | 1,124 | C# |
//
// CRegistry.cs
//
// Lunar Unity Mobile Console
// https://github.com/SpaceMadness/lunar-unity-console
//
// Copyright 2017 Alex Lementuev, SpaceMadness.
//
// 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.Generic;
using System.Reflection;
using UnityEngine;
using LunarConsolePlugin;
namespace LunarConsolePluginInternal
{
delegate bool CActionFilter(CAction action);
public interface ICRegistryDelegate
{
void OnActionRegistered(CRegistry registry, CAction action);
void OnActionUnregistered(CRegistry registry, CAction action);
void OnVariableRegistered(CRegistry registry, CVar cvar);
void OnVariableUpdated(CRegistry registry, CVar cvar);
}
public class CRegistry
{
private readonly CActionList m_actions = new CActionList();
private readonly CVarList m_vars = new CVarList();
private ICRegistryDelegate m_delegate;
#region Commands registry
public CAction RegisterAction(string name, Delegate actionDelegate)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (name.Length == 0)
{
throw new ArgumentException("Action's name is empty");
}
if (actionDelegate == null)
{
throw new ArgumentNullException("actionDelegate");
}
CAction action = m_actions.Find(name);
if (action != null)
{
// Log.w("Overriding action: {0}", name);
action.ActionDelegate = actionDelegate;
}
else
{
action = new CAction(name, actionDelegate);
m_actions.Add(action);
if (m_delegate != null)
{
m_delegate.OnActionRegistered(this, action);
}
}
return action;
}
public bool Unregister(string name)
{
return Unregister(delegate(CAction action)
{
return action.Name == name;
});
}
public bool Unregister(int id)
{
return Unregister(delegate(CAction action)
{
return action.Id == id;
});
}
public bool Unregister(Delegate del)
{
return Unregister(delegate(CAction action)
{
return action.ActionDelegate == del;
});
}
public bool UnregisterAll(object target)
{
return target != null && Unregister(delegate(CAction action)
{
return action.ActionDelegate.Target == target;
});
}
bool Unregister(CActionFilter filter)
{
if (filter == null)
{
throw new ArgumentNullException("filter");
}
IList<CAction> actionsToRemove = new List<CAction>();
foreach (var action in m_actions)
{
if (filter(action))
{
actionsToRemove.Add(action);
}
}
foreach (var action in actionsToRemove)
{
RemoveAction(action);
}
return actionsToRemove.Count > 0;
}
bool RemoveAction(CAction action)
{
if (m_actions.Remove(action.Id))
{
if (m_delegate != null)
{
m_delegate.OnActionUnregistered(this, action);
}
return true;
}
return false;
}
public CAction FindAction(int id)
{
return m_actions.Find(id);
}
#endregion
#region Variables
public void Register(CVar cvar)
{
m_vars.Add(cvar);
if (m_delegate != null)
{
m_delegate.OnVariableRegistered(this, cvar);
}
}
public CVar FindVariable(int variableId)
{
return m_vars.Find(variableId);
}
public CVar FindVariable(string variableName)
{
return m_vars.Find(variableName);
}
#endregion
#region Destroyable
public void Destroy()
{
m_actions.Clear();
m_vars.Clear();
m_delegate = null;
}
#endregion
#region Properties
public ICRegistryDelegate registryDelegate
{
get { return m_delegate; }
set { m_delegate = value; }
}
public CActionList actions
{
get { return m_actions; }
}
public CVarList cvars
{
get { return m_vars; }
}
#endregion
}
}
| 24.81982 | 76 | 0.524319 | [
"MIT"
] | pdyxs/UnityProjectStarter | Assets/Plugins/Externals/LunarConsole/Scripts/Actions/CRegistry.cs | 5,512 | C# |
// ----------------------------------------------------------------------------
// <copyright file="PhotonViewInspector.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH
// </copyright>
// <summary>
// Custom inspector for the PhotonView component.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System;
using UnityEditor;
using UnityEngine;
using Photon.Realtime;
namespace Photon.Pun
{
[CustomEditor(typeof(PhotonView))]
internal class PhotonViewInspector : Editor
{
private PhotonView m_Target;
public override void OnInspectorGUI()
{
this.m_Target = (PhotonView)this.target;
bool isProjectPrefab = PhotonEditorUtils.IsPrefab(this.m_Target.gameObject);
if (this.m_Target.ObservedComponents == null)
{
this.m_Target.ObservedComponents = new System.Collections.Generic.List<Component>();
}
if (this.m_Target.ObservedComponents.Count == 0)
{
this.m_Target.ObservedComponents.Add(null);
}
EditorGUILayout.BeginHorizontal();
// Owner
if (isProjectPrefab)
{
EditorGUILayout.LabelField("Owner:", "Set at runtime");
}
else if (!this.m_Target.IsOwnerActive)
{
EditorGUILayout.LabelField("Owner", "Scene");
}
else
{
Player owner = this.m_Target.Owner;
string ownerInfo = (owner != null) ? owner.NickName : "<no Player found>";
if (string.IsNullOrEmpty(ownerInfo))
{
ownerInfo = "<no playername set>";
}
EditorGUILayout.LabelField("Owner", "[" + this.m_Target.OwnerActorNr + "] " + ownerInfo);
}
// ownership requests
EditorGUI.BeginDisabledGroup(Application.isPlaying);
OwnershipOption own = (OwnershipOption) EditorGUILayout.EnumPopup(this.m_Target.OwnershipTransfer, GUILayout.Width(100), GUILayout.MinWidth(75));
if (own != this.m_Target.OwnershipTransfer)
{
// jf: fixed 5 and up prefab not accepting changes if you quit Unity straight after change.
// not touching the define nor the rest of the code to avoid bringing more problem than solving.
EditorUtility.SetDirty(this.m_Target);
Undo.RecordObject(this.m_Target, "Change PhotonView Ownership Transfer");
this.m_Target.OwnershipTransfer = own;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
// View ID
if (isProjectPrefab)
{
EditorGUILayout.LabelField("View ID", "Set at runtime");
}
else if (EditorApplication.isPlaying)
{
EditorGUILayout.LabelField("View ID", this.m_Target.ViewID.ToString());
}
else
{
int idValue = EditorGUILayout.IntField("View ID [1.." + (PhotonNetwork.MAX_VIEW_IDS - 1) + "]", this.m_Target.ViewID);
if (this.m_Target.ViewID != idValue)
{
Undo.RecordObject(this.m_Target, "Change PhotonView viewID");
this.m_Target.ViewID = idValue;
}
}
// Locally Controlled
if (EditorApplication.isPlaying)
{
string masterClientHint = PhotonNetwork.IsMasterClient ? "(master)" : "";
EditorGUILayout.Toggle("Controlled locally: " + masterClientHint, this.m_Target.IsMine);
}
// ViewSynchronization (reliability)
if (this.m_Target.Synchronization == ViewSynchronization.Off)
{
GUI.color = Color.grey;
}
EditorGUILayout.PropertyField(this.serializedObject.FindProperty("Synchronization"), new GUIContent("Observe option:"));
if (this.m_Target.Synchronization != ViewSynchronization.Off && this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0)
{
EditorGUILayout.HelpBox("Setting the synchronization option only makes sense if you observe something.", MessageType.Warning);
}
GUI.color = Color.white;
this.DrawObservedComponentsList();
// Cleanup: save and fix look
if (GUI.changed)
{
PhotonViewHandler.OnHierarchyChanged(); // TODO: check if needed
}
GUI.color = Color.white;
}
private int GetObservedComponentsCount()
{
int count = 0;
for (int i = 0; i < this.m_Target.ObservedComponents.Count; ++i)
{
if (this.m_Target.ObservedComponents[i] != null)
{
count++;
}
}
return count;
}
private void DrawObservedComponentsList()
{
GUILayout.Space(5);
SerializedProperty listProperty = this.serializedObject.FindProperty("ObservedComponents");
if (listProperty == null)
{
return;
}
float containerElementHeight = 22;
float containerHeight = listProperty.arraySize * containerElementHeight;
bool isOpen = PhotonGUI.ContainerHeaderFoldout("Observed Components (" + this.GetObservedComponentsCount() + ")", this.serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue);
this.serializedObject.FindProperty("ObservedComponentsFoldoutOpen").boolValue = isOpen;
if (isOpen == false)
{
containerHeight = 0;
}
//Texture2D statsIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/PhotonViewStats.png", typeof( Texture2D ) ) as Texture2D;
Rect containerRect = PhotonGUI.ContainerBody(containerHeight);
bool wasObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0;
if (isOpen == true)
{
for (int i = 0; i < listProperty.arraySize; ++i)
{
Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + containerElementHeight * i, containerRect.width, containerElementHeight);
{
Rect texturePosition = new Rect(elementRect.xMin + 6, elementRect.yMin + elementRect.height / 2f - 1, 9, 5);
ReorderableListResources.DrawTexture(texturePosition, ReorderableListResources.texGrabHandle);
Rect propertyPosition = new Rect(elementRect.xMin + 20, elementRect.yMin + 3, elementRect.width - 45, 16);
// keep track of old type to catch when a new type is observed
Type _oldType = listProperty.GetArrayElementAtIndex(i).objectReferenceValue != null ? listProperty.GetArrayElementAtIndex(i).objectReferenceValue.GetType() : null;
EditorGUI.PropertyField(propertyPosition, listProperty.GetArrayElementAtIndex(i), new GUIContent());
// new type, could be different from old type
Type _newType = listProperty.GetArrayElementAtIndex(i).objectReferenceValue != null ? listProperty.GetArrayElementAtIndex(i).objectReferenceValue.GetType() : null;
// the user dropped a Transform, we must change it by adding a PhotonTransformView and observe that instead
if (_oldType != _newType)
{
if (_newType == typeof(PhotonView))
{
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = null;
Debug.LogError("PhotonView Detected you dropped a PhotonView, this is not allowed. \n It's been removed from observed field.");
}
else if (_newType == typeof(Transform))
{
// try to get an existing PhotonTransformView ( we don't want any duplicates...)
PhotonTransformView _ptv = this.m_Target.gameObject.GetComponent<PhotonTransformView>();
if (_ptv == null)
{
// no ptv yet, we create one and enable position and rotation, no scaling, as it's too rarely needed to take bandwidth for nothing
_ptv = Undo.AddComponent<PhotonTransformView>(this.m_Target.gameObject);
}
// switch observe from transform to _ptv
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _ptv;
Debug.Log("PhotonView has detected you dropped a Transform. Instead it's better to observe a PhotonTransformView for better control and performances");
}
else if (_newType == typeof(Rigidbody))
{
Rigidbody _rb = listProperty.GetArrayElementAtIndex(i).objectReferenceValue as Rigidbody;
// try to get an existing PhotonRigidbodyView ( we don't want any duplicates...)
PhotonRigidbodyView _prbv = _rb.gameObject.GetComponent<PhotonRigidbodyView>();
if (_prbv == null)
{
// no _prbv yet, we create one
_prbv = Undo.AddComponent<PhotonRigidbodyView>(_rb.gameObject);
}
// switch observe from transform to _prbv
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _prbv;
Debug.Log("PhotonView has detected you dropped a RigidBody. Instead it's better to observe a PhotonRigidbodyView for better control and performances");
}
else if (_newType == typeof(Rigidbody2D))
{
// try to get an existing PhotonRigidbody2DView ( we don't want any duplicates...)
PhotonRigidbody2DView _prb2dv = this.m_Target.gameObject.GetComponent<PhotonRigidbody2DView>();
if (_prb2dv == null)
{
// no _prb2dv yet, we create one
_prb2dv = Undo.AddComponent<PhotonRigidbody2DView>(this.m_Target.gameObject);
}
// switch observe from transform to _prb2dv
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _prb2dv;
Debug.Log("PhotonView has detected you dropped a Rigidbody2D. Instead it's better to observe a PhotonRigidbody2DView for better control and performances");
}
else if (_newType == typeof(Animator))
{
// try to get an existing PhotonAnimatorView ( we don't want any duplicates...)
PhotonAnimatorView _pav = this.m_Target.gameObject.GetComponent<PhotonAnimatorView>();
if (_pav == null)
{
// no _pav yet, we create one
_pav = Undo.AddComponent<PhotonAnimatorView>(this.m_Target.gameObject);
}
// switch observe from transform to _prb2dv
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = _pav;
Debug.Log("PhotonView has detected you dropped a Animator, so we switched to PhotonAnimatorView so that you can serialized the Animator variables");
}
else if (!typeof(IPunObservable).IsAssignableFrom(_newType))
{
bool _ignore = false;
#if PLAYMAKER
_ignore = _newType == typeof(PlayMakerFSM);// Photon Integration for PlayMaker will swap at runtime to a proxy using iPunObservable.
#endif
if (_newType == null || _newType == typeof(Rigidbody) || _newType == typeof(Rigidbody2D))
{
_ignore = true;
}
if (!_ignore)
{
listProperty.GetArrayElementAtIndex(i).objectReferenceValue = null;
Debug.LogError("PhotonView Detected you dropped a Component missing IPunObservable Interface,\n You dropped a <" + _newType + "> instead. It's been removed from observed field.");
}
}
}
//Debug.Log( listProperty.GetArrayElementAtIndex( i ).objectReferenceValue.GetType() );
//Rect statsPosition = new Rect( propertyPosition.xMax + 7, propertyPosition.yMin, statsIcon.width, statsIcon.height );
//ReorderableListResources.DrawTexture( statsPosition, statsIcon );
Rect removeButtonRect = new Rect(elementRect.xMax - PhotonGUI.DefaultRemoveButtonStyle.fixedWidth,
elementRect.yMin + 2,
PhotonGUI.DefaultRemoveButtonStyle.fixedWidth,
PhotonGUI.DefaultRemoveButtonStyle.fixedHeight);
GUI.enabled = listProperty.arraySize > 1;
if (GUI.Button(removeButtonRect, new GUIContent(ReorderableListResources.texRemoveButton), PhotonGUI.DefaultRemoveButtonStyle))
{
listProperty.DeleteArrayElementAtIndex(i);
}
GUI.enabled = true;
if (i < listProperty.arraySize - 1)
{
texturePosition = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1);
PhotonGUI.DrawSplitter(texturePosition);
}
}
}
}
if (PhotonGUI.AddButton())
{
listProperty.InsertArrayElementAtIndex(Mathf.Max(0, listProperty.arraySize - 1));
}
this.serializedObject.ApplyModifiedProperties();
bool isObservedComponentsEmpty = this.m_Target.ObservedComponents.FindAll(item => item != null).Count == 0;
if (wasObservedComponentsEmpty == true && isObservedComponentsEmpty == false && this.m_Target.Synchronization == ViewSynchronization.Off)
{
Undo.RecordObject(this.m_Target, "Change PhotonView");
this.m_Target.Synchronization = ViewSynchronization.UnreliableOnChange;
this.serializedObject.Update();
}
if (wasObservedComponentsEmpty == false && isObservedComponentsEmpty == true)
{
Undo.RecordObject(this.m_Target, "Change PhotonView");
this.m_Target.Synchronization = ViewSynchronization.Off;
this.serializedObject.Update();
}
}
}
} | 51.134969 | 216 | 0.518896 | [
"MIT"
] | Andre-LA/unity-snake | Assets/Photon/PhotonUnityNetworking/Code/Editor/PhotonViewInspector.cs | 16,670 | C# |
namespace AmplaData.AmplaData2008
{
public class CredentialsProvider : ICredentialsProvider
{
private readonly string session;
private readonly string userName;
private readonly string password;
private CredentialsProvider(string userName, string password)
{
this.userName = userName;
this.password = password;
}
private CredentialsProvider(string session)
{
this.session = session;
}
public Credentials GetCredentials()
{
if (session == null)
{
return new Credentials {Username = userName, Password = password};
}
return new Credentials {Session = session};
}
public static CredentialsProvider ForSession(string session)
{
return new CredentialsProvider(session);
}
public static CredentialsProvider ForUsernameAndPassword(string userName, string password)
{
return new CredentialsProvider(userName, password);
}
}
} | 28.282051 | 98 | 0.600181 | [
"MIT"
] | Ampla/Ampla-Data | src/AmplaData/AmplaData2008/CredentialsProvider.cs | 1,105 | 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("YDL-UI")]
[assembly: AssemblyDescription("A UI for the command-line video downloader \"youtube - dl\"")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YDL-UI")]
[assembly: AssemblyCopyright("Copyright © Maxstupo 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dad7ea1a-dbb7-4291-9e85-960e21773af4")]
// 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.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.0")]
| 39.108108 | 94 | 0.745681 | [
"MIT"
] | vaginessa/ydl-ui | YDL-UI/Properties/AssemblyInfo.cs | 1,450 | C# |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using System.Diagnostics;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* A Cipher Text Stealing (CTS) mode cipher. CTS allows block ciphers to
* be used to produce cipher text which is the same outLength as the plain text.
*/
public class CtsBlockCipher
: BufferedBlockCipher
{
private readonly int blockSize;
/**
* Create a buffered block cipher that uses Cipher Text Stealing
*
* @param cipher the underlying block cipher this buffering object wraps.
*/
public CtsBlockCipher(
IBlockCipher cipher)
{
// TODO Should this test for acceptable ones instead?
if (cipher is OfbBlockCipher || cipher is CfbBlockCipher)
throw new ArgumentException("CtsBlockCipher can only accept ECB, or CBC ciphers");
this.cipher = cipher;
blockSize = cipher.GetBlockSize();
buf = new byte[blockSize * 2];
bufOff = 0;
}
/**
* return the size of the output buffer required for an update of 'length' bytes.
*
* @param length the outLength of the input.
* @return the space required to accommodate a call to update
* with length bytes of input.
*/
public override int GetUpdateOutputSize(
int length)
{
int total = length + bufOff;
int leftOver = total % buf.Length;
if (leftOver == 0)
{
return total - buf.Length;
}
return total - leftOver;
}
/**
* return the size of the output buffer required for an update plus a
* doFinal with an input of length bytes.
*
* @param length the outLength of the input.
* @return the space required to accommodate a call to update and doFinal
* with length bytes of input.
*/
public override int GetOutputSize(
int length)
{
return length + bufOff;
}
/**
* process a single byte, producing an output block if necessary.
*
* @param in the input byte.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessByte(
byte input,
byte[] output,
int outOff)
{
int resultLen = 0;
if (bufOff == buf.Length)
{
resultLen = cipher.ProcessBlock(buf, 0, output, outOff);
Debug.Assert(resultLen == blockSize);
Array.Copy(buf, blockSize, buf, 0, blockSize);
bufOff = blockSize;
}
buf[bufOff++] = input;
return resultLen;
}
/**
* process an array of bytes, producing output if necessary.
*
* @param in the input byte array.
* @param inOff the offset at which the input data starts.
* @param length the number of bytes to be copied out of the input array.
* @param out the space for any output that might be produced.
* @param outOff the offset from which the output will be copied.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there isn't enough space in out.
* @exception InvalidOperationException if the cipher isn't initialised.
*/
public override int ProcessBytes(
byte[] input,
int inOff,
int length,
byte[] output,
int outOff)
{
if (length < 0)
{
throw new ArgumentException("Can't have a negative input outLength!");
}
int blockSize = GetBlockSize();
int outLength = GetUpdateOutputSize(length);
if (outLength > 0)
{
if ((outOff + outLength) > output.Length)
{
throw new DataLengthException("output buffer too short");
}
}
int resultLen = 0;
int gapLen = buf.Length - bufOff;
if (length > gapLen)
{
Array.Copy(input, inOff, buf, bufOff, gapLen);
resultLen += cipher.ProcessBlock(buf, 0, output, outOff);
Array.Copy(buf, blockSize, buf, 0, blockSize);
bufOff = blockSize;
length -= gapLen;
inOff += gapLen;
while (length > blockSize)
{
Array.Copy(input, inOff, buf, bufOff, blockSize);
resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen);
Array.Copy(buf, blockSize, buf, 0, blockSize);
length -= blockSize;
inOff += blockSize;
}
}
Array.Copy(input, inOff, buf, bufOff, length);
bufOff += length;
return resultLen;
}
/**
* Process the last block in the buffer.
*
* @param out the array the block currently being held is copied into.
* @param outOff the offset at which the copying starts.
* @return the number of output bytes copied to out.
* @exception DataLengthException if there is insufficient space in out for
* the output.
* @exception InvalidOperationException if the underlying cipher is not
* initialised.
* @exception InvalidCipherTextException if cipher text decrypts wrongly (in
* case the exception will never Get thrown).
*/
public override int DoFinal(
byte[] output,
int outOff)
{
if (bufOff + outOff > output.Length)
{
throw new DataLengthException("output buffer too small in doFinal");
}
int blockSize = cipher.GetBlockSize();
int length = bufOff - blockSize;
byte[] block = new byte[blockSize];
if (forEncryption)
{
cipher.ProcessBlock(buf, 0, block, 0);
if (bufOff < blockSize)
{
throw new DataLengthException("need at least one block of input for CTS");
}
for (int i = bufOff; i != buf.Length; i++)
{
buf[i] = block[i - blockSize];
}
for (int i = blockSize; i != bufOff; i++)
{
buf[i] ^= block[i - blockSize];
}
IBlockCipher c = (cipher is CbcBlockCipher)
? ((CbcBlockCipher)cipher).GetUnderlyingCipher()
: cipher;
c.ProcessBlock(buf, blockSize, output, outOff);
Array.Copy(block, 0, output, outOff + blockSize, length);
}
else
{
byte[] lastBlock = new byte[blockSize];
IBlockCipher c = (cipher is CbcBlockCipher)
? ((CbcBlockCipher)cipher).GetUnderlyingCipher()
: cipher;
c.ProcessBlock(buf, 0, block, 0);
for (int i = blockSize; i != bufOff; i++)
{
lastBlock[i - blockSize] = (byte)(block[i - blockSize] ^ buf[i]);
}
Array.Copy(buf, blockSize, block, 0, length);
cipher.ProcessBlock(block, 0, output, outOff);
Array.Copy(lastBlock, 0, output, outOff + blockSize, length);
}
int offset = bufOff;
Reset();
return offset;
}
}
}
#endif
| 30.988372 | 98 | 0.542089 | [
"MIT"
] | Manolomon/space-checkers | client/Assets/Libs/Best HTTP (Pro)/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/modes/CtsBlockCipher.cs | 7,995 | C# |
#if ALTCOINS
using BTCPayServer.Contracts;
using BTCPayServer.Payments;
using BTCPayServer.Services.Altcoins.Stripe.Payments;
using Microsoft.Extensions.DependencyInjection;
namespace BTCPayServer.Services.Altcoins.Stripe
{
public static class StripeExtensions
{
public static IServiceCollection AddStripe(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<StripePaymentMethodHandler>();
serviceCollection.AddSingleton<IPaymentMethodHandler>(provider =>
provider.GetService<StripePaymentMethodHandler>());
serviceCollection.AddSingleton<IUIExtension>(new UIExtension("Stripe/StoreNavStripeExtension", "store-nav"));
serviceCollection.AddHostedService<StripeService>();
return serviceCollection;
}
}
}
#endif
| 35.291667 | 121 | 0.74144 | [
"MIT"
] | XPayServer/btcpayserver | BTCPayServer/Services/Altcoins/Stripe/StripeExtensions.cs | 847 | C# |
// Copyright 2020 Maksym Liannoi
//
// 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.Collections.Concurrent;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Autocomplete.WindowUI.UI.Helpers
{
public class Bindable : INotifyPropertyChanged
{
private readonly ConcurrentDictionary<string, object> _properties;
public event PropertyChangedEventHandler PropertyChanged;
protected bool CallPropertyChangeEvent { get; set; } = true;
public Bindable()
{
_properties = new ConcurrentDictionary<string, object>();
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected T Get<T>(T defValue = default, [CallerMemberName] string name = null)
{
if (string.IsNullOrEmpty(name))
{
return defValue;
}
if (_properties.TryGetValue(name, out object value))
{
return (T)value;
}
_properties.AddOrUpdate(name, defValue, (s, o) => defValue);
return defValue;
}
protected bool Set(object value, [CallerMemberName] string name = null)
{
if (string.IsNullOrEmpty(name))
{
return false;
}
bool isExists = _properties.TryGetValue(name, out object getValue);
if (isExists && Equals(value, getValue))
{
return false;
}
_properties.AddOrUpdate(name, value, (s, o) => value);
if (CallPropertyChangeEvent)
{
OnPropertyChanged(name);
}
return true;
}
}
}
| 30.088608 | 87 | 0.611695 | [
"Apache-2.0"
] | liannoi/autocomplete | src/Autocomplete.WindowUI/Autocomplete.WindowUI.UI/Helpers/Bindable.cs | 2,379 | C# |
// -----------------------------------------------------------------------
// <copyright file="TestActors.cs" company="Asynkron AB">
// Copyright (C) 2015-2022 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System.Threading.Tasks;
using Proto;
namespace ProtoActorBenchmarks;
public class PingActor : IActor
{
private readonly int _batchSize;
private readonly TaskCompletionSource<bool> _wgStop;
private int _batch;
private int _messageCount;
public PingActor(TaskCompletionSource<bool> wgStop, int messageCount, int batchSize)
{
_wgStop = wgStop;
_messageCount = messageCount;
_batchSize = batchSize;
}
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case Start s:
SendBatch(context, s.Sender);
break;
case Msg m:
_batch--;
if (_batch > 0) break;
if (!SendBatch(context, m.Sender)) _wgStop.SetResult(true);
break;
}
return Task.CompletedTask;
}
private bool SendBatch(IContext context, PID sender)
{
if (_messageCount == 0) return false;
var m = new Msg(context.Self);
for (var i = 0; i < _batchSize; i++)
{
context.Send(sender, m);
}
_messageCount -= _batchSize;
_batch = _batchSize;
return true;
}
}
public class EchoActor : IActor
{
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case Msg msg:
context.Send(msg.Sender, msg);
break;
}
return Task.CompletedTask;
}
}
public class EchoActor2 : IActor
{
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case string _:
context.Send(context.Sender, "pong");
break;
}
return Task.CompletedTask;
}
}
public class Start
{
public Start(PID sender) => Sender = sender;
public PID Sender { get; }
}
public class Msg
{
public Msg(PID sender) => Sender = sender;
public PID Sender { get; }
} | 22.173077 | 88 | 0.531657 | [
"Apache-2.0"
] | BearerPipelineTest/protoactor-dotnet | benchmarks/ProtoActorBenchmarks/TestActors.cs | 2,306 | C# |
// Copyright (c) Richasy. All rights reserved.
using Richasy.Bili.Models.App.Other;
using Richasy.Bili.ViewModels.Uwp.Common;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Richasy.Bili.App.Controls
{
/// <summary>
/// 弹幕发送设置.
/// </summary>
public sealed partial class DanmakuSendOptions : UserControl
{
/// <summary>
/// <see cref="ViewModel"/>的视图模型.
/// </summary>
public static readonly DependencyProperty ViewModelProperty =
DependencyProperty.Register(nameof(ViewModel), typeof(DanmakuViewModel), typeof(DanmakuSendOptions), new PropertyMetadata(DanmakuViewModel.Instance));
/// <summary>
/// Initializes a new instance of the <see cref="DanmakuSendOptions"/> class.
/// </summary>
public DanmakuSendOptions()
{
InitializeComponent();
}
/// <summary>
/// 视图模型.
/// </summary>
public DanmakuViewModel ViewModel
{
get { return (DanmakuViewModel)GetValue(ViewModelProperty); }
set { SetValue(ViewModelProperty, value); }
}
/// <summary>
/// 初始化.
/// </summary>
public void Initialize()
{
if (ViewModel.IsStandardSize)
{
StandardItem.IsChecked = true;
SmallItem.IsChecked = false;
}
else
{
StandardItem.IsChecked = false;
SmallItem.IsChecked = true;
}
}
private void OnColorItemClick(object sender, RoutedEventArgs e)
{
var item = (sender as FrameworkElement).DataContext as KeyValue<string>;
ViewModel.Color = item.Value;
}
}
}
| 28.83871 | 162 | 0.565996 | [
"MIT"
] | ELI2sdkm/Bili.Uwp | src/App/Controls/Danmaku/DanmakuSendOptions.xaml.cs | 1,826 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Domain.Models.Dtos.Transactions
{
public class RegisterTransactionResponse
{
}
}
| 14.416667 | 44 | 0.751445 | [
"MIT"
] | hsulipe/UmHelper-desafio-tecnico | Domain/Models/Dtos/Transactions/RegisterTransactionResponse.cs | 175 | C# |
namespace TrafficManager.API.Traffic.Enums {
using System;
[Flags]
public enum ExtTransportMode {
/// <summary>
/// No information about which mode of transport is used
/// </summary>
None = 0,
/// <summary>
/// Travelling by car
/// </summary>
Car = 1,
/// <summary>
/// Travelling by means of public transport
/// </summary>
PublicTransport = 2,
}
} | 22.190476 | 64 | 0.515021 | [
"MIT"
] | CitiesSkylinesMods/TMPE | TLM/TMPE.API/Traffic/Enums/ExtTransportMode.cs | 466 | C# |
// Copyright © John Gietzen. All Rights Reserved. This source is subject to the MIT license. Please see license.md for more information.
namespace Pegasus.Tests
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.CSharp;
using NUnit.Framework;
using Pegasus.Common;
using Pegasus.Common.Tracing;
using Pegasus.Compiler;
public static class CodeCompiler
{
public static ParserWrapper<T> Compile<T>(CompileResult result, params string[] referenceAssemblies)
{
Assert.That(result.Errors.Where(e => !e.IsWarning), Is.Empty);
var compiler = new CSharpCodeProvider();
var options = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true,
};
options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.Core.dll");
options.ReferencedAssemblies.Add(typeof(Pegasus.Common.Cursor).Assembly.Location);
options.ReferencedAssemblies.AddRange(referenceAssemblies);
var results = compiler.CompileAssemblyFromSource(options, result.Code);
if (results.Errors.HasErrors)
{
throw new CodeCompileFailedException(results.Errors.Cast<CompilerError>().ToArray(), results.Output.Cast<string>().ToArray());
}
var assembly = results.CompiledAssembly;
var type = assembly.GetType("Parsers.Parser");
return new ParserWrapper<T>(type);
}
public class ParserWrapper<T>
{
private readonly object instance;
private readonly Lazy<PropertyInfo> tracerProperty;
private readonly Lazy<MethodInfo> parseMethod;
private readonly Lazy<MethodInfo> parseLexicalMethod;
public ParserWrapper(Type type)
{
this.Type = type;
this.instance = Activator.CreateInstance(type);
this.tracerProperty = new Lazy<PropertyInfo>(() => type.GetProperty("Tracer", typeof(ITracer)));
this.parseMethod = new Lazy<MethodInfo>(() => type.GetMethod("Parse", new[] { typeof(string), typeof(string) }));
this.parseLexicalMethod = new Lazy<MethodInfo>(() => type.GetMethod("Parse", new[] { typeof(string), typeof(string), typeof(IList<LexicalElement>).MakeByRefType() }));
}
public Type Type { get; }
public ITracer Tracer
{
get
{
try
{
return (ITracer)this.tracerProperty.Value.GetValue(this.instance);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
set
{
try
{
this.tracerProperty.Value.SetValue(this.instance, value);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
}
public T Parse(string subject, string fileName = null)
{
try
{
return (T)this.parseMethod.Value.Invoke(this.instance, new[] { subject, fileName });
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
public T Parse(string subject, string fileName, out IList<LexicalElement> lexicalElements)
{
try
{
var args = new object[] { subject, fileName, null };
var result = (T)this.parseLexicalMethod.Value.Invoke(this.instance, args);
lexicalElements = (IList<LexicalElement>)args[2];
return result;
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
}
}
}
| 36.773109 | 183 | 0.529022 | [
"MIT"
] | otac0n/Pegasus | Pegasus.Tests/CodeCompiler.cs | 4,377 | C# |
/***********************************************************************
* Project: CoreCms
* ProjectName: 核心内容管理系统
* Web: https://www.corecms.net
* Author: 大灰灰
* Email: jianweie@163.com
* CreateTime: 2021/1/31 21:45:10
* Description: 暂无
***********************************************************************/
using System.Collections.Generic;
using CoreCms.Net.Model.Entities;
namespace CoreCms.Net.Model.ViewModels.DTO
{
/// <summary>
/// OrderToAftersales返回类
/// </summary>
public class OrderToAftersalesDto
{
public decimal refundMoney { get; set; } = 0;
public Dictionary<int, reshipGoods> reshipGoods { get; set; } = null;
public List<CoreCmsBillAftersales> billAftersales { get; set; } = new();
}
} | 36 | 80 | 0.424897 | [
"Apache-2.0"
] | CoreUnion/CoreShop | CoreCms.Net.Model/ViewModels/DTO/BillAftersalesDto.cs | 1,006 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Microsoft.Dynamics.CRM.phonetocaseprocess
/// </summary>
public partial class MicrosoftDynamicsCRMphonetocaseprocess
{
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMphonetocaseprocess class.
/// </summary>
public MicrosoftDynamicsCRMphonetocaseprocess()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// MicrosoftDynamicsCRMphonetocaseprocess class.
/// </summary>
/// <param name="_modifiedbyValue">Shows who last updated the
/// record.</param>
/// <param name="statecode">Shows whether the Delve action record is
/// pending, completed, or tracking.</param>
/// <param name="modifiedon">Shows the date and time when the record
/// was last updated. The date and time are displayed in the time zone
/// selected in Microsoft Dynamics CRM options.</param>
/// <param name="traversedpath">Traversed Path</param>
/// <param name="statuscode">Select the delve action record
/// status.</param>
/// <param name="businessprocessflowinstanceid">Unique identifier for
/// Phone To Case Process bpf entity instances</param>
/// <param name="duration">Duration between completed on and started
/// on, used by business process flow.</param>
/// <param name="importsequencenumber">Unique identifier of the data
/// import or data migration that created this record.</param>
/// <param name="versionnumber">Version number of the business process
/// instance.</param>
/// <param name="_createdbyValue">Shows who created the record.</param>
/// <param name="overriddencreatedon">Date and time that the record was
/// migrated.</param>
/// <param name="_transactioncurrencyidValue">Choose the local currency
/// for the record to make sure budgets are reported in the correct
/// currency.</param>
/// <param name="exchangerate">Shows the conversion rate of the
/// record's currency. The exchange rate is used to convert all money
/// fields in the record from the local currency to the system's
/// default currency.</param>
/// <param name="_organizationidValue">Unique identifier of the
/// organization with which the SDK message request is
/// associated.</param>
/// <param name="completedon">Date and time when Business Process Flow
/// instance is completed.</param>
/// <param name="activestagestartedon">Date and time when current
/// active stage is started.</param>
/// <param name="_modifiedonbehalfbyValue">Shows who last updated the
/// record on behalf of another user.</param>
/// <param name="_activestageidValue">Unique identifier of the active
/// stage for the Business Process Flow instance.</param>
/// <param name="name">Process Name.</param>
/// <param name="_createdonbehalfbyValue">Shows who created the record
/// on behalf of another user.</param>
/// <param name="_incidentidValue">Unique identifier of the workflow
/// associated to the Business Process Flow instance.</param>
/// <param name="createdon">Shows the date and time when the record was
/// created. The date and time are displayed in the time zone selected
/// in Microsoft Dynamics CRM options.</param>
/// <param name="_processidValue">Unique identifier of the
/// PhoneToCaseProcess associated to the Business Process Flow
/// instance.</param>
public MicrosoftDynamicsCRMphonetocaseprocess(string _modifiedbyValue = default(string), int? statecode = default(int?), System.DateTimeOffset? modifiedon = default(System.DateTimeOffset?), string traversedpath = default(string), int? statuscode = default(int?), string businessprocessflowinstanceid = default(string), int? duration = default(int?), int? importsequencenumber = default(int?), string versionnumber = default(string), string _createdbyValue = default(string), System.DateTimeOffset? overriddencreatedon = default(System.DateTimeOffset?), string _transactioncurrencyidValue = default(string), decimal? exchangerate = default(decimal?), string _organizationidValue = default(string), System.DateTimeOffset? completedon = default(System.DateTimeOffset?), System.DateTimeOffset? activestagestartedon = default(System.DateTimeOffset?), string _modifiedonbehalfbyValue = default(string), string _activestageidValue = default(string), string name = default(string), string _createdonbehalfbyValue = default(string), string _incidentidValue = default(string), System.DateTimeOffset? createdon = default(System.DateTimeOffset?), string _processidValue = default(string), MicrosoftDynamicsCRMtransactioncurrency transactioncurrencyid = default(MicrosoftDynamicsCRMtransactioncurrency), MicrosoftDynamicsCRMorganization organizationid = default(MicrosoftDynamicsCRMorganization), MicrosoftDynamicsCRMsystemuser createdbyname = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMincident incidentid = default(MicrosoftDynamicsCRMincident), MicrosoftDynamicsCRMsystemuser createdonbehalfbyname = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMsystemuser modifiedonbehalfbyname = default(MicrosoftDynamicsCRMsystemuser), MicrosoftDynamicsCRMworkflow processid = default(MicrosoftDynamicsCRMworkflow), IList<MicrosoftDynamicsCRMworkflowlog> workflowlogsPhonetocaseprocess = default(IList<MicrosoftDynamicsCRMworkflowlog>), MicrosoftDynamicsCRMprocessstage activestageid = default(MicrosoftDynamicsCRMprocessstage), IList<MicrosoftDynamicsCRMsyncerror> phoneToCaseProcessSyncErrors = default(IList<MicrosoftDynamicsCRMsyncerror>), MicrosoftDynamicsCRMsystemuser modifiedbyname = default(MicrosoftDynamicsCRMsystemuser))
{
this._modifiedbyValue = _modifiedbyValue;
Statecode = statecode;
Modifiedon = modifiedon;
Traversedpath = traversedpath;
Statuscode = statuscode;
Businessprocessflowinstanceid = businessprocessflowinstanceid;
Duration = duration;
Importsequencenumber = importsequencenumber;
Versionnumber = versionnumber;
this._createdbyValue = _createdbyValue;
Overriddencreatedon = overriddencreatedon;
this._transactioncurrencyidValue = _transactioncurrencyidValue;
Exchangerate = exchangerate;
this._organizationidValue = _organizationidValue;
Completedon = completedon;
Activestagestartedon = activestagestartedon;
this._modifiedonbehalfbyValue = _modifiedonbehalfbyValue;
this._activestageidValue = _activestageidValue;
Name = name;
this._createdonbehalfbyValue = _createdonbehalfbyValue;
this._incidentidValue = _incidentidValue;
Createdon = createdon;
this._processidValue = _processidValue;
Transactioncurrencyid = transactioncurrencyid;
Organizationid = organizationid;
Createdbyname = createdbyname;
Incidentid = incidentid;
Createdonbehalfbyname = createdonbehalfbyname;
Modifiedonbehalfbyname = modifiedonbehalfbyname;
Processid = processid;
WorkflowlogsPhonetocaseprocess = workflowlogsPhonetocaseprocess;
Activestageid = activestageid;
PhoneToCaseProcessSyncErrors = phoneToCaseProcessSyncErrors;
Modifiedbyname = modifiedbyname;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets shows who last updated the record.
/// </summary>
[JsonProperty(PropertyName = "_modifiedby_value")]
public string _modifiedbyValue { get; set; }
/// <summary>
/// Gets or sets shows whether the Delve action record is pending,
/// completed, or tracking.
/// </summary>
[JsonProperty(PropertyName = "statecode")]
public int? Statecode { get; set; }
/// <summary>
/// Gets or sets shows the date and time when the record was last
/// updated. The date and time are displayed in the time zone selected
/// in Microsoft Dynamics CRM options.
/// </summary>
[JsonProperty(PropertyName = "modifiedon")]
public System.DateTimeOffset? Modifiedon { get; set; }
/// <summary>
/// Gets or sets traversed Path
/// </summary>
[JsonProperty(PropertyName = "traversedpath")]
public string Traversedpath { get; set; }
/// <summary>
/// Gets or sets select the delve action record status.
/// </summary>
[JsonProperty(PropertyName = "statuscode")]
public int? Statuscode { get; set; }
/// <summary>
/// Gets or sets unique identifier for Phone To Case Process bpf entity
/// instances
/// </summary>
[JsonProperty(PropertyName = "businessprocessflowinstanceid")]
public string Businessprocessflowinstanceid { get; set; }
/// <summary>
/// Gets or sets duration between completed on and started on, used by
/// business process flow.
/// </summary>
[JsonProperty(PropertyName = "duration")]
public int? Duration { get; set; }
/// <summary>
/// Gets or sets unique identifier of the data import or data migration
/// that created this record.
/// </summary>
[JsonProperty(PropertyName = "importsequencenumber")]
public int? Importsequencenumber { get; set; }
/// <summary>
/// Gets or sets version number of the business process instance.
/// </summary>
[JsonProperty(PropertyName = "versionnumber")]
public string Versionnumber { get; set; }
/// <summary>
/// Gets or sets shows who created the record.
/// </summary>
[JsonProperty(PropertyName = "_createdby_value")]
public string _createdbyValue { get; set; }
/// <summary>
/// Gets or sets date and time that the record was migrated.
/// </summary>
[JsonProperty(PropertyName = "overriddencreatedon")]
public System.DateTimeOffset? Overriddencreatedon { get; set; }
/// <summary>
/// Gets or sets choose the local currency for the record to make sure
/// budgets are reported in the correct currency.
/// </summary>
[JsonProperty(PropertyName = "_transactioncurrencyid_value")]
public string _transactioncurrencyidValue { get; set; }
/// <summary>
/// Gets or sets shows the conversion rate of the record's currency.
/// The exchange rate is used to convert all money fields in the record
/// from the local currency to the system's default currency.
/// </summary>
[JsonProperty(PropertyName = "exchangerate")]
public decimal? Exchangerate { get; set; }
/// <summary>
/// Gets or sets unique identifier of the organization with which the
/// SDK message request is associated.
/// </summary>
[JsonProperty(PropertyName = "_organizationid_value")]
public string _organizationidValue { get; set; }
/// <summary>
/// Gets or sets date and time when Business Process Flow instance is
/// completed.
/// </summary>
[JsonProperty(PropertyName = "completedon")]
public System.DateTimeOffset? Completedon { get; set; }
/// <summary>
/// Gets or sets date and time when current active stage is started.
/// </summary>
[JsonProperty(PropertyName = "activestagestartedon")]
public System.DateTimeOffset? Activestagestartedon { get; set; }
/// <summary>
/// Gets or sets shows who last updated the record on behalf of another
/// user.
/// </summary>
[JsonProperty(PropertyName = "_modifiedonbehalfby_value")]
public string _modifiedonbehalfbyValue { get; set; }
/// <summary>
/// Gets or sets unique identifier of the active stage for the Business
/// Process Flow instance.
/// </summary>
[JsonProperty(PropertyName = "_activestageid_value")]
public string _activestageidValue { get; set; }
/// <summary>
/// Gets or sets process Name.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets shows who created the record on behalf of another
/// user.
/// </summary>
[JsonProperty(PropertyName = "_createdonbehalfby_value")]
public string _createdonbehalfbyValue { get; set; }
/// <summary>
/// Gets or sets unique identifier of the workflow associated to the
/// Business Process Flow instance.
/// </summary>
[JsonProperty(PropertyName = "_incidentid_value")]
public string _incidentidValue { get; set; }
/// <summary>
/// Gets or sets shows the date and time when the record was created.
/// The date and time are displayed in the time zone selected in
/// Microsoft Dynamics CRM options.
/// </summary>
[JsonProperty(PropertyName = "createdon")]
public System.DateTimeOffset? Createdon { get; set; }
/// <summary>
/// Gets or sets unique identifier of the PhoneToCaseProcess associated
/// to the Business Process Flow instance.
/// </summary>
[JsonProperty(PropertyName = "_processid_value")]
public string _processidValue { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "transactioncurrencyid")]
public MicrosoftDynamicsCRMtransactioncurrency Transactioncurrencyid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "organizationid")]
public MicrosoftDynamicsCRMorganization Organizationid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdbyname")]
public MicrosoftDynamicsCRMsystemuser Createdbyname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "incidentid")]
public MicrosoftDynamicsCRMincident Incidentid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "createdonbehalfbyname")]
public MicrosoftDynamicsCRMsystemuser Createdonbehalfbyname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedonbehalfbyname")]
public MicrosoftDynamicsCRMsystemuser Modifiedonbehalfbyname { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "processid")]
public MicrosoftDynamicsCRMworkflow Processid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "workflowlogs_phonetocaseprocess")]
public IList<MicrosoftDynamicsCRMworkflowlog> WorkflowlogsPhonetocaseprocess { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "activestageid")]
public MicrosoftDynamicsCRMprocessstage Activestageid { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "PhoneToCaseProcess_SyncErrors")]
public IList<MicrosoftDynamicsCRMsyncerror> PhoneToCaseProcessSyncErrors { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "modifiedbyname")]
public MicrosoftDynamicsCRMsystemuser Modifiedbyname { get; set; }
}
}
| 48.654867 | 2,250 | 0.656117 | [
"Apache-2.0"
] | ElizabethWolfe/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Models/MicrosoftDynamicsCRMphonetocaseprocess.cs | 16,494 | C# |
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* File:TypeProperties.cs
****/
using System;
using PropertyModel;
namespace TestModel
{
/// <summary>
/// Supported properties
/// </summary>
public interface ITypeProperties
{
TypeFlags TypeFlags { set; get; }
TypeNonFlags TypeNonFlags { set; get; }
bool BooleanProperty { get; set; }
short ShortProperty { get; set; }
ushort UShortProperty { get; set; }
int IntProperty { get; set; }
uint UIntProperty { get; set; }
long LongProperty { get; set; }
ulong ULongProperty { get; set; }
string StringProperty { get; set; }
byte ByteProperty { get; set; }
double DoubleProperty { get; set; }
float FloatProperty { get; set; }
Guid GuidProperty { get; set; }
System.Object ObjectProperty { get; set; }
System.DateTime DateTimeProperty { get; set; }
string[] StringArrayProperty { get; set; }
object[] ObjectArrayProperty { get; set; }
IDictionary DictionaryProperty { get; set; }
}
[EnumerationAttribute(ItemType = typeof(ITypeProperties))]
public interface IEnumerable_ITypeProperties
{
}
[CollectionAttribute(ItemType = typeof(ITypeProperties))]
public interface ICollection_ITypeProperties
{
}
public interface ITypePropertiesTest
{
ITypeProperties TypeProperties { get; }
[MethodAttribute(IsAsync = true)]
void ChangePropertyAsync(uint propertyId, object propertyValue);
}
}
| 24.901408 | 105 | 0.611425 | [
"MIT"
] | Bhaskers-Blu-Org2/pmod | tests/src/schemas/TypeProperties.cs | 1,768 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Http;
using System.Net.Http.QPack;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.PipeWriterHelpers;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3
{
internal class Http3FrameWriter
{
// Size based on HTTP/2 default frame size
private const int MaxDataFrameSize = 16 * 1024;
private const int HeaderBufferSize = 16 * 1024;
private readonly object _writeLock = new object();
private readonly int _maxTotalHeaderSize;
private readonly ConnectionContext _connectionContext;
private readonly ITimeoutControl _timeoutControl;
private readonly MinDataRate? _minResponseDataRate;
private readonly MemoryPool<byte> _memoryPool;
private readonly IKestrelTrace _log;
private readonly IStreamIdFeature _streamIdFeature;
private readonly IHttp3Stream _http3Stream;
private readonly Http3RawFrame _outgoingFrame;
private readonly TimingPipeFlusher _flusher;
private PipeWriter _outputWriter = default!;
private string _connectionId = default!;
// HTTP/3 doesn't have a max frame size (peer can optionally specify a size).
// Write headers to a buffer that can grow. Possible performance improvement
// by writing directly to output writer (difficult as frame length is prefixed).
private readonly ArrayBufferWriter<byte> _headerEncodingBuffer;
private readonly Http3HeadersEnumerator _headersEnumerator = new();
private int _headersTotalSize;
private long _unflushedBytes;
private bool _completed;
private bool _aborted;
public Http3FrameWriter(ConnectionContext connectionContext, ITimeoutControl timeoutControl, MinDataRate? minResponseDataRate, MemoryPool<byte> memoryPool, IKestrelTrace log, IStreamIdFeature streamIdFeature, Http3PeerSettings clientPeerSettings, IHttp3Stream http3Stream)
{
_connectionContext = connectionContext;
_timeoutControl = timeoutControl;
_minResponseDataRate = minResponseDataRate;
_memoryPool = memoryPool;
_log = log;
_streamIdFeature = streamIdFeature;
_http3Stream = http3Stream;
_outgoingFrame = new Http3RawFrame();
_flusher = new TimingPipeFlusher(timeoutControl, log);
_headerEncodingBuffer = new ArrayBufferWriter<byte>(HeaderBufferSize);
// Note that max total header size value doesn't react to settings change during a stream.
// Unlikely to be a problem in practice:
// - Settings rarely change after the start of a connection.
// - Response header size limits are a best-effort requirement in the spec.
_maxTotalHeaderSize = clientPeerSettings.MaxRequestHeaderFieldSectionSize > int.MaxValue
? int.MaxValue
: (int)clientPeerSettings.MaxRequestHeaderFieldSectionSize;
}
public void Reset(PipeWriter output, string connectionId)
{
_outputWriter = output;
_flusher.Initialize(output);
_connectionId = connectionId;
_headersTotalSize = 0;
_headerEncodingBuffer.Clear();
_unflushedBytes = 0;
_completed = false;
_aborted = false;
}
internal Task WriteSettingsAsync(List<Http3PeerSetting> settings)
{
_outgoingFrame.PrepareSettings();
// Calculate how long settings are before allocating.
var settingsLength = CalculateSettingsSize(settings);
// Call GetSpan with enough room for
// - One encoded length int for setting size
// - 1 byte for setting type
// - settings length
var buffer = _outputWriter.GetSpan(settingsLength + VariableLengthIntegerHelper.MaximumEncodedLength + 1);
// Length start at 1 for type
var totalLength = 1;
// Write setting type
buffer[0] = (byte)_outgoingFrame.Type;
buffer = buffer[1..];
// Write settings length
var settingsBytesWritten = VariableLengthIntegerHelper.WriteInteger(buffer, settingsLength);
buffer = buffer.Slice(settingsBytesWritten);
totalLength += settingsBytesWritten + settingsLength;
WriteSettings(settings, buffer);
// Advance pipe writer and flush
_outgoingFrame.Length = totalLength;
_outputWriter.Advance(totalLength);
return _outputWriter.FlushAsync().AsTask();
}
internal static int CalculateSettingsSize(List<Http3PeerSetting> settings)
{
var length = 0;
foreach (var setting in settings)
{
length += VariableLengthIntegerHelper.GetByteCount((long)setting.Parameter);
length += VariableLengthIntegerHelper.GetByteCount(setting.Value);
}
return length;
}
internal static void WriteSettings(List<Http3PeerSetting> settings, Span<byte> destination)
{
foreach (var setting in settings)
{
var parameterLength = VariableLengthIntegerHelper.WriteInteger(destination, (long)setting.Parameter);
destination = destination.Slice(parameterLength);
var valueLength = VariableLengthIntegerHelper.WriteInteger(destination, (long)setting.Value);
destination = destination.Slice(valueLength);
}
}
internal Task WriteStreamIdAsync(long id)
{
var buffer = _outputWriter.GetSpan(8);
_outputWriter.Advance(VariableLengthIntegerHelper.WriteInteger(buffer, id));
return _outputWriter.FlushAsync().AsTask();
}
public ValueTask<FlushResult> WriteDataAsync(in ReadOnlySequence<byte> data)
{
// The Length property of a ReadOnlySequence can be expensive, so we cache the value.
var dataLength = data.Length;
lock (_writeLock)
{
if (_completed)
{
return default;
}
WriteDataUnsynchronized(data, dataLength);
return TimeFlushUnsynchronizedAsync();
}
}
private void WriteDataUnsynchronized(in ReadOnlySequence<byte> data, long dataLength)
{
Debug.Assert(dataLength == data.Length);
_outgoingFrame.PrepareData();
if (dataLength > MaxDataFrameSize)
{
SplitAndWriteDataUnsynchronized(in data, dataLength);
return;
}
_outgoingFrame.Length = (int)dataLength;
WriteHeaderUnsynchronized();
foreach (var buffer in data)
{
_outputWriter.Write(buffer.Span);
}
return;
void SplitAndWriteDataUnsynchronized(in ReadOnlySequence<byte> data, long dataLength)
{
Debug.Assert(dataLength == data.Length);
var dataPayloadLength = (int)MaxDataFrameSize;
Debug.Assert(dataLength > dataPayloadLength);
var remainingData = data;
do
{
var currentData = remainingData.Slice(0, dataPayloadLength);
_outgoingFrame.Length = dataPayloadLength;
WriteHeaderUnsynchronized();
foreach (var buffer in currentData)
{
_outputWriter.Write(buffer.Span);
}
dataLength -= dataPayloadLength;
remainingData = remainingData.Slice(dataPayloadLength);
} while (dataLength > dataPayloadLength);
_outgoingFrame.Length = (int)dataLength;
WriteHeaderUnsynchronized();
foreach (var buffer in remainingData)
{
_outputWriter.Write(buffer.Span);
}
}
}
internal ValueTask<FlushResult> WriteGoAway(long id)
{
_outgoingFrame.PrepareGoAway();
var length = VariableLengthIntegerHelper.GetByteCount(id);
_outgoingFrame.Length = length;
WriteHeaderUnsynchronized();
var buffer = _outputWriter.GetSpan(8);
VariableLengthIntegerHelper.WriteInteger(buffer, id);
_outputWriter.Advance(length);
return _outputWriter.FlushAsync();
}
private void WriteHeaderUnsynchronized()
{
_log.Http3FrameSending(_connectionId, _streamIdFeature.StreamId, _outgoingFrame);
var headerLength = WriteHeader(_outgoingFrame.Type, _outgoingFrame.Length, _outputWriter);
// We assume the payload will be written prior to the next flush.
_unflushedBytes += headerLength + _outgoingFrame.Length;
}
internal static int WriteHeader(Http3FrameType frameType, long frameLength, PipeWriter output)
{
// max size of the header is 16, most likely it will be smaller.
var buffer = output.GetSpan(16);
var typeLength = VariableLengthIntegerHelper.WriteInteger(buffer, (int)frameType);
buffer = buffer.Slice(typeLength);
var lengthLength = VariableLengthIntegerHelper.WriteInteger(buffer, (int)frameLength);
var totalLength = typeLength + lengthLength;
output.Advance(typeLength + lengthLength);
return totalLength;
}
public ValueTask<FlushResult> WriteResponseTrailersAsync(long streamId, HttpResponseTrailers headers)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
try
{
_headersEnumerator.Initialize(headers);
_headersTotalSize = 0;
_headerEncodingBuffer.Clear();
_outgoingFrame.PrepareHeaders();
var buffer = _headerEncodingBuffer.GetSpan(HeaderBufferSize);
var done = QPackHeaderWriter.BeginEncode(_headersEnumerator, buffer, ref _headersTotalSize, out var payloadLength);
FinishWritingHeaders(payloadLength, done);
}
// Any exception from the QPack encoder can leave the dynamic table in a corrupt state.
// Since we allow custom header encoders we don't know what type of exceptions to expect.
catch (Exception ex)
{
_log.QPackEncodingError(_connectionId, streamId, ex);
_connectionContext.Abort(new ConnectionAbortedException(ex.Message, ex));
_http3Stream.Abort(new ConnectionAbortedException(ex.Message, ex), Http3ErrorCode.InternalError);
}
return TimeFlushUnsynchronizedAsync();
}
}
private ValueTask<FlushResult> TimeFlushUnsynchronizedAsync()
{
var bytesWritten = _unflushedBytes;
_unflushedBytes = 0;
return _flusher.FlushAsync(_minResponseDataRate, bytesWritten);
}
public ValueTask<FlushResult> FlushAsync(IHttpOutputAborter? outputAborter, CancellationToken cancellationToken)
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
var bytesWritten = _unflushedBytes;
_unflushedBytes = 0;
return _flusher.FlushAsync(_minResponseDataRate, bytesWritten, outputAborter, cancellationToken);
}
}
internal void WriteResponseHeaders(int statusCode, HttpResponseHeaders headers)
{
lock (_writeLock)
{
if (_completed)
{
return;
}
try
{
_headersEnumerator.Initialize(headers);
_outgoingFrame.PrepareHeaders();
var buffer = _headerEncodingBuffer.GetSpan(HeaderBufferSize);
var done = QPackHeaderWriter.BeginEncode(statusCode, _headersEnumerator, buffer, ref _headersTotalSize, out var payloadLength);
FinishWritingHeaders(payloadLength, done);
}
// Any exception from the QPack encoder can leave the dynamic table in a corrupt state.
// Since we allow custom header encoders we don't know what type of exceptions to expect.
catch (Exception ex)
{
_log.QPackEncodingError(_connectionId, _http3Stream.StreamId, ex);
_connectionContext.Abort(new ConnectionAbortedException(ex.Message, ex));
_http3Stream.Abort(new ConnectionAbortedException(ex.Message, ex), Http3ErrorCode.InternalError);
throw new InvalidOperationException(ex.Message, ex); // Report the error to the user if this was the first write.
}
}
}
private void FinishWritingHeaders(int payloadLength, bool done)
{
_headerEncodingBuffer.Advance(payloadLength);
while (!done)
{
ValidateHeadersTotalSize();
var buffer = _headerEncodingBuffer.GetSpan(HeaderBufferSize);
done = QPackHeaderWriter.Encode(_headersEnumerator!, buffer, ref _headersTotalSize, out payloadLength);
_headerEncodingBuffer.Advance(payloadLength);
}
ValidateHeadersTotalSize();
_outgoingFrame.Length = _headerEncodingBuffer.WrittenCount;
WriteHeaderUnsynchronized();
_outputWriter.Write(_headerEncodingBuffer.WrittenSpan);
void ValidateHeadersTotalSize()
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.3
if (_headersTotalSize > _maxTotalHeaderSize)
{
throw new QPackEncodingException($"The encoded HTTP headers length exceeds the limit specified by the peer of {_maxTotalHeaderSize} bytes.");
}
}
}
public ValueTask CompleteAsync()
{
lock (_writeLock)
{
if (_completed)
{
return default;
}
_completed = true;
return _outputWriter.CompleteAsync();
}
}
public void Abort(ConnectionAbortedException error)
{
lock (_writeLock)
{
if (_aborted)
{
return;
}
_aborted = true;
_connectionContext.Abort(error);
if (_completed)
{
return;
}
_completed = true;
_outputWriter.Complete();
}
}
}
}
| 37.380841 | 280 | 0.600538 | [
"MIT"
] | ChiragRupani/AspNetCore | src/Servers/Kestrel/Core/src/Internal/Http3/Http3FrameWriter.cs | 15,999 | 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.ApplicationInsights.Models.Api202002
{
using Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ComponentPurgeBody" />
/// </summary>
public partial class ComponentPurgeBodyTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="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 <see cref="sourceValue"/> parameter to the <see cref="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 <see cref="sourceValue"/> parameter to the <see cref="ComponentPurgeBody"
/// type/>.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ComponentPurgeBody"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="ComponentPurgeBody" /> 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.ApplicationInsights.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="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 <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="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="ComponentPurgeBody" />, 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 <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="ComponentPurgeBody" />.</param>
/// <returns>
/// an instance of <see cref="ComponentPurgeBody" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api202002.IComponentPurgeBody ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api202002.IComponentPurgeBody).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return ComponentPurgeBody.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return ComponentPurgeBody.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return ComponentPurgeBody.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;
}
} | 52.265306 | 269 | 0.593909 | [
"MIT"
] | arpit-gagneja/azure-powershell | src/ApplicationInsights/generated/api/Models/Api202002/ComponentPurgeBody.TypeConverter.cs | 7,537 | C# |
namespace Sitecore.MediaFramework.Upload
{
using System;
using System.Web;
using Sitecore.Configuration;
using Sitecore.Integration.Common.Providers;
public class UploadManager
{
#region Initialization
static UploadManager()
{
var helper = new ProviderHelper<UploadProviderBase, ProviderCollection<UploadProviderBase>>("mediaFramework/uploadManager");
Providers = helper.Providers;
Provider = helper.Provider;
}
public static UploadProviderBase Provider { get; set; }
public static ProviderCollection<UploadProviderBase> Providers { get; private set; }
#endregion
public static void Update(Guid mediaItemId, Guid fileId, Guid accountId, byte progress, string error = null)
{
Provider.Update(mediaItemId, fileId, accountId, progress, error);
}
public static void Cancel(Guid fileId, Guid accountId)
{
Provider.Update(Guid.Empty, fileId, accountId, 0, string.Empty, true);
}
public static FileUploadStatus GetStatus(Guid fileId)
{
return Provider.GetStatus(fileId);
}
public static void HandleUploadRequest(HttpContext context)
{
Provider.HandleUploadRequest(context);
}
}
} | 27.391304 | 131 | 0.688889 | [
"Apache-2.0"
] | KRazguliaev/pmi.sitecore.9.1.brightcove | src/Sitecore.MediaFramework/Upload/UploadManager.cs | 1,217 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Diagnostics;
namespace System.Text.Json
{
public static partial class JsonSerializer
{
private static bool HandleEnumerable(
JsonClassInfo elementClassInfo,
JsonSerializerOptions options,
Utf8JsonWriter writer,
ref WriteStack state)
{
Debug.Assert(state.Current.JsonPropertyInfo.ClassType == ClassType.Enumerable);
if (state.Current.Enumerator == null)
{
IEnumerable enumerable = (IEnumerable)state.Current.JsonPropertyInfo.GetValueAsObject(state.Current.CurrentValue);
if (enumerable == null)
{
if (!state.Current.JsonPropertyInfo.IgnoreNullValues)
{
// Write a null object or enumerable.
state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer, writeNull: true);
}
return true;
}
state.Current.Enumerator = enumerable.GetEnumerator();
state.Current.WriteObjectOrArrayStart(ClassType.Enumerable, writer);
}
if (state.Current.Enumerator.MoveNext())
{
// Check for polymorphism.
if (elementClassInfo.ClassType == ClassType.Unknown)
{
object currentValue = state.Current.Enumerator.Current;
GetRuntimeClassInfo(currentValue, ref elementClassInfo, options);
}
if (elementClassInfo.ClassType == ClassType.Value)
{
elementClassInfo.GetPolicyProperty().WriteEnumerable(ref state.Current, writer);
}
else if (state.Current.Enumerator.Current == null)
{
// Write a null object or enumerable.
writer.WriteNullValue();
}
else
{
// An object or another enumerator requires a new stack frame.
object nextValue = state.Current.Enumerator.Current;
state.Push(elementClassInfo, nextValue);
}
return false;
}
// We are done enumerating.
writer.WriteEndArray();
if (state.Current.PopStackOnEnd)
{
state.Pop();
}
else
{
state.Current.EndArray();
}
return true;
}
}
}
| 33.714286 | 130 | 0.532486 | [
"MIT"
] | Castaneda1914/corefx | src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.HandleEnumerable.cs | 2,834 | C# |
namespace GSA.OpenItems.Web
{
using System;
using System.Data;
using Data;
public partial class FundsReview : PageBase
{
const string DEFAULT_VALUE_BUDGET_ACTIVITY = "PG61";
protected override void PageLoadEvent(object sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
ctrlCriteria.ScreenType = (int)FundsStatusScreenType.stFundsReview;
ctrlCriteria.InitControls();
if (Request.QueryString["back"] != null && Request.QueryString["back"] == "y")
{
//back from Funds Search results screen - display previous report:
ctrlCriteria.DisplayPrevSelectedValues(FundsReviewSelectedValues);
//build expanded detailed view:
ctrlCriteria.ExpandedByMonthView = true;
BuildResultsTable();
}
}
}
catch (Exception ex)
{
AddError(ex);
}
finally
{
//if (Errors.Count > 0)
// lblError.Text = GetErrors();
}
}
protected void Page_Init(object sender, System.EventArgs e)
{
ctrlCriteria.Submit += new EventHandler(ctrlCriteria_Submit);
}
void ctrlCriteria_Submit(object sender, EventArgs e)
{
try
{
//save report criteria:
FundsReviewSelectedValues = ctrlCriteria.SaveCurrentSelectedValues();
BuildResultsTable();
}
catch (Exception ex)
{
AddError(ex);
}
finally
{
//if (Errors.Count > 0)
// lblError.Text = GetErrors();
}
}
private void BuildResultsTable()
{
var last_book_month_included = (ctrlCriteria.BookMonth == "00") ? "09" : ctrlCriteria.BookMonth;
//get Totals data always:
DataSet ds = null;
var dsTotals = FSTotalsReport.GetSummaryState(ctrlCriteria.FiscalYear, ctrlCriteria.Organization, ctrlCriteria.BusinessLine, last_book_month_included, ctrlCriteria.ViewMode, false);
//get Monthly data only if needed:
if (ctrlCriteria.ExpandedByMonthView)
ds = FSTotalsReport.GetSummaryState(ctrlCriteria.FiscalYear, ctrlCriteria.Organization, ctrlCriteria.BusinessLine, last_book_month_included, ctrlCriteria.ViewMode, ctrlCriteria.ExpandedByMonthView);
if (dsTotals == null || dsTotals.Tables[0].Rows.Count == 0)
{
lblMessages.Text = "No records found.";
}
else
{
lblMessages.Text = "";
//draw the table tblData:
var drawing_class = new FSReviewUI();
drawing_class.TotalsDataTable = dsTotals.Tables[0];
drawing_class.SourceDataTable = (ds == null) ? null : ds.Tables[0];
drawing_class.TableToDraw = tblData;
drawing_class.MonthlyView = ctrlCriteria.ExpandedByMonthView;
if (ctrlCriteria.ViewMode == (int)FundsReviewViewMode.fvIncome)
drawing_class.DisplayColumnObjClassCode = false;
drawing_class.BookMonth = ctrlCriteria.BookMonth;
var link = String.Format("FundSearch.aspx?vm={0}&org={1}&fy={2}&ba={3}&bl={4}", ctrlCriteria.ViewMode, ctrlCriteria.Organization, ctrlCriteria.FiscalYear, DEFAULT_VALUE_BUDGET_ACTIVITY, ctrlCriteria.BusinessLine);
link = link + "&bm={0}&sf={1}&oc={2}";
drawing_class.CellLinkOnClick = link;
drawing_class.BuildTheTable();
tblData = drawing_class.TableToDraw;
}
}
}
} | 38.737864 | 229 | 0.545363 | [
"CC0-1.0"
] | gaybro8777/FM-ULO | Archive/OpenItems/FundStatus/FundsReview.aspx.cs | 3,990 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WSC
{
class Program
{
static void Main(string[] args)
{
}
}
}
| 14.125 | 39 | 0.632743 | [
"MIT"
] | Nathanha/eiin839 | TD5/MathsLibrary/WSC/Program.cs | 228 | C# |
using System;
using System.Collections.Generic;
namespace esharp.transpiler
{
public class Transpiler
{
private readonly String _version;
public Transpiler(String solcVersion)
{
_version = solcVersion;
}
public List<String> CastContract(String line)
{
throw new NotImplementedException();
}
}
}
| 18.619048 | 53 | 0.603581 | [
"CC0-1.0"
] | bitcoinbrisbane/EthSharp | esharp.transpiler/Transpiler.cs | 393 | C# |
using ForgeModGenerator.Controls;
using ForgeModGenerator.Core;
using ForgeModGenerator.ItemGenerator.Models;
using ForgeModGenerator.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace ForgeModGenerator.ItemGenerator.Controls
{
public partial class ItemEditForm : UserControl, IUIElement
{
public ItemEditForm()
{
InitializeComponent();
ItemTypeComboBox.SelectionChanged += ItemTypeComboBox_SelectionChanged;
}
public IEnumerable<ItemType> ItemTypes => ReflectionHelper.GetEnumValues<ItemType>();
public IEnumerable<ArmorType> ArmorTypes => ReflectionHelper.GetEnumValues<ArmorType>();
public static readonly DependencyProperty MaterialsProperty =
DependencyProperty.Register("Materials", typeof(IEnumerable<string>), typeof(ItemEditForm), new PropertyMetadata(Enumerable.Empty<string>()));
public IEnumerable<string> Materials {
get => (IEnumerable<string>)GetValue(MaterialsProperty);
set => SetValue(MaterialsProperty, value);
}
public void SetDataContext(object context) => DataContext = context;
private void ItemTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ItemType newType = (ItemType)e.AddedItems[0];
bool shouldCollapseArmor = newType != ItemType.Armor;
ArmorTypeComboBox.Visibility = shouldCollapseArmor ? Visibility.Collapsed : Visibility.Visible;
}
private async void ItemButton_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
btn.Command.Execute(btn.CommandParameter);
ItemListForm form = new ItemListForm();
bool changed = await StaticCommands.ShowMCItemList(btn, (string)DialogHost.Identifier, form).ConfigureAwait(true);
if (changed)
{
MCItemLocator locator = form.SelectedLocator;
if (DataContext is Item item)
{
item.TextureName = locator.Name;
}
}
}
}
}
| 39.589286 | 154 | 0.671177 | [
"MIT"
] | Prastiwar/ForgeModGenerator | ForgeModGenerator/app/ForgeModGenerator.Wpf/Source/Modules/ItemGenerator/Controls/ItemEditForm.xaml.cs | 2,219 | C# |
using System;
using Expressive.Expressions.Binary.Multiplicative;
using Expressive.Operators;
using Expressive.Operators.Multiplicative;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Expressive.Tests.Operators.Multiplicative
{
[TestClass]
public class MultiplyOperatorTests : OperatorBaseTests
{
#region OperatorBaseTests Members
internal override IOperator Operator => new MultiplyOperator();
protected override Type ExpectedExpressionType => typeof(MultiplyExpression);
internal override OperatorPrecedence ExpectedOperatorPrecedence => OperatorPrecedence.Multiply;
protected override string[] ExpectedTags => new[] { "*", "\u00d7" };
#endregion
}
}
| 29.56 | 103 | 0.753721 | [
"MIT"
] | antoniaelek/expressive | Source/Expressive.Tests/Operators/Multiplicative/MultiplyOperatorTests.cs | 741 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Conversations.V1.Conversation
{
/// <summary>
/// Add a new participant to the conversation
/// </summary>
public class CreateParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The unique ID of the Conversation for this participant.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A unique string identifier for the conversation participant as Conversation User.
/// </summary>
public string Identity { get; set; }
/// <summary>
/// The address of the participant's device.
/// </summary>
public string MessagingBindingAddress { get; set; }
/// <summary>
/// The address of the Twilio phone number that the participant is in contact with.
/// </summary>
public string MessagingBindingProxyAddress { get; set; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// An optional string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The address of the Twilio phone number that is used in Group MMS.
/// </summary>
public string MessagingBindingProjectedAddress { get; set; }
/// <summary>
/// The SID of a conversation-level Role to assign to the participant
/// </summary>
public string RoleSid { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ParticipantResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new CreateParticipantOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this participant. </param>
public CreateParticipantOptions(string pathConversationSid)
{
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Identity != null)
{
p.Add(new KeyValuePair<string, string>("Identity", Identity));
}
if (MessagingBindingAddress != null)
{
p.Add(new KeyValuePair<string, string>("MessagingBinding.Address", MessagingBindingAddress));
}
if (MessagingBindingProxyAddress != null)
{
p.Add(new KeyValuePair<string, string>("MessagingBinding.ProxyAddress", MessagingBindingProxyAddress));
}
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (MessagingBindingProjectedAddress != null)
{
p.Add(new KeyValuePair<string, string>("MessagingBinding.ProjectedAddress", MessagingBindingProjectedAddress));
}
if (RoleSid != null)
{
p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString()));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Update an existing participant in the conversation
/// </summary>
public class UpdateParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The unique ID of the Conversation for this participant.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The date that this resource was created.
/// </summary>
public DateTime? DateCreated { get; set; }
/// <summary>
/// The date that this resource was last updated.
/// </summary>
public DateTime? DateUpdated { get; set; }
/// <summary>
/// An optional string metadata field you can use to store any data you wish.
/// </summary>
public string Attributes { get; set; }
/// <summary>
/// The SID of a conversation-level Role to assign to the participant
/// </summary>
public string RoleSid { get; set; }
/// <summary>
/// The address of the Twilio phone number that the participant is in contact with.
/// </summary>
public string MessagingBindingProxyAddress { get; set; }
/// <summary>
/// The address of the Twilio phone number that is used in Group MMS.
/// </summary>
public string MessagingBindingProjectedAddress { get; set; }
/// <summary>
/// A unique string identifier for the conversation participant as Conversation User.
/// </summary>
public string Identity { get; set; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ParticipantResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new UpdateParticipantOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this participant. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public UpdateParticipantOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (DateCreated != null)
{
p.Add(new KeyValuePair<string, string>("DateCreated", Serializers.DateTimeIso8601(DateCreated)));
}
if (DateUpdated != null)
{
p.Add(new KeyValuePair<string, string>("DateUpdated", Serializers.DateTimeIso8601(DateUpdated)));
}
if (Attributes != null)
{
p.Add(new KeyValuePair<string, string>("Attributes", Attributes));
}
if (RoleSid != null)
{
p.Add(new KeyValuePair<string, string>("RoleSid", RoleSid.ToString()));
}
if (MessagingBindingProxyAddress != null)
{
p.Add(new KeyValuePair<string, string>("MessagingBinding.ProxyAddress", MessagingBindingProxyAddress));
}
if (MessagingBindingProjectedAddress != null)
{
p.Add(new KeyValuePair<string, string>("MessagingBinding.ProjectedAddress", MessagingBindingProjectedAddress));
}
if (Identity != null)
{
p.Add(new KeyValuePair<string, string>("Identity", Identity));
}
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Remove a participant from the conversation
/// </summary>
public class DeleteParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The unique ID of the Conversation for this participant.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// The X-Twilio-Webhook-Enabled HTTP request header
/// </summary>
public ParticipantResource.WebhookEnabledTypeEnum XTwilioWebhookEnabled { get; set; }
/// <summary>
/// Construct a new DeleteParticipantOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this participant. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public DeleteParticipantOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
/// <summary>
/// Generate the necessary header parameters
/// </summary>
public List<KeyValuePair<string, string>> GetHeaderParams()
{
var p = new List<KeyValuePair<string, string>>();
if (XTwilioWebhookEnabled != null)
{
p.Add(new KeyValuePair<string, string>("X-Twilio-Webhook-Enabled", XTwilioWebhookEnabled.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch a participant of the conversation
/// </summary>
public class FetchParticipantOptions : IOptions<ParticipantResource>
{
/// <summary>
/// The unique ID of the Conversation for this participant.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// A 34 character string that uniquely identifies this resource.
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchParticipantOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for this participant. </param>
/// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param>
public FetchParticipantOptions(string pathConversationSid, string pathSid)
{
PathConversationSid = pathConversationSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of all participants of the conversation
/// </summary>
public class ReadParticipantOptions : ReadOptions<ParticipantResource>
{
/// <summary>
/// The unique ID of the Conversation for participants.
/// </summary>
public string PathConversationSid { get; }
/// <summary>
/// Construct a new ReadParticipantOptions
/// </summary>
/// <param name="pathConversationSid"> The unique ID of the Conversation for participants. </param>
public ReadParticipantOptions(string pathConversationSid)
{
PathConversationSid = pathConversationSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
} | 35.975741 | 127 | 0.570241 | [
"MIT"
] | charliesantos/twilio-csharp | src/Twilio/Rest/Conversations/V1/Conversation/ParticipantOptions.cs | 13,347 | C# |
using System;
using NServiceBus;
public class ShipOrder :
IMessage
{
public Guid OrderId { get; set; }
} | 15.125 | 38 | 0.644628 | [
"Apache-2.0"
] | A-Franklin/docs.particular.net | samples/nhibernate/simple/NHibernate_5/Server/ShipOrder.cs | 116 | C# |
using Autofac;
using Hangfire.Demo.Job;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangfire.Demo.Server
{
public class Service
{
private BackgroundJobServer backgroundJobServer;
/// <summary>
///
/// </summary>
public void Start()
{
// Setup Sql Server Storage
GlobalConfiguration.Configuration.UseSqlServerStorage("HangfireDemo", new SqlServer.SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true
});
GlobalConfiguration.Configuration.UseNLogLogProvider();
GlobalConfiguration.Configuration.UseAutofacActivator(ConfigureContainer());
// Run Hangfire
backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
{
ServerName = Guid.NewGuid().ToString(),
WorkerCount = 4,
Queues = new string[] { "default"}
});
}
/// <summary>
///
/// </summary>
public void Stop()
{
backgroundJobServer?.Dispose();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private IContainer ConfigureContainer()
{
var builder = new ContainerBuilder();
RegisterApplicationComponents(builder);
return builder.Build();
}
/// <summary>
///
/// </summary>
/// <param name="builder"></param>
private void RegisterApplicationComponents(ContainerBuilder builder)
{
builder.RegisterType<DemoJob>().As<IDemoJob>().InstancePerLifetimeScope();
}
}
}
| 29.1 | 119 | 0.564556 | [
"MIT"
] | from-zero-fr/Hangfire.Demo | Hangfire.Demo.Server/Service.cs | 2,039 | C# |
using UnityEngine;
[CreateAssetMenu(fileName = "Vector2", menuName = "SO/Vector2", order = 1)]
public class SVector2 : SharedVariable<Vector2> { }
| 29.6 | 75 | 0.736486 | [
"MIT"
] | imrealnow/com.liamgreen.sharedvariables | Variables/SVector2.cs | 148 | C# |
using System;
namespace _Exercise_WorkoutTrapezoidArea
{
class MainClass
{
public static void Main(string[] args)
{
// 编写一个程序,输入梯形的上底、下底和高,计算梯形的面积并输出
Console.WriteLine("Enter the topline, baseline and the high of a trapezoid:");
Console.WriteLine("Topline:");
string str1 = Console.ReadLine();
double topline = Convert.ToDouble(str1);
Console.WriteLine("Baseline:");
string str2 = Console.ReadLine();
double baseline = Convert.ToDouble(str2);
Console.WriteLine("High");
string str3 = Console.ReadLine();
double high = Convert.ToDouble(str3);
Console.WriteLine("The area of the trapezoid is {0}", (topline + baseline) * high / 2);
}
}
}
| 32.76 | 99 | 0.583639 | [
"MIT"
] | PaddyHuang/Basic | Languages/C#/017_Exercise_WorkoutTrapeziumArea/Program.cs | 881 | 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;
namespace Microsoft.Build.Shared.LanguageParser
{
/*
* Class: Token
*
* Base class for all token classes.
*
*/
internal abstract class Token
{
// The text from the originating source file that caused this token.
private string _innerText = null;
// The line number that the token fell on.
private int _line = 0;
/*
* Method: InnerText
*
* Get or set the InnerText for this token
*/
internal string InnerText
{
get { return _innerText; }
set { _innerText = value; }
}
/*
* Method: Line
*
* Get or set the Line for this token
*/
internal int Line
{
get
{
return _line;
}
set
{
_line = value;
}
}
/*
* Method: EqualsIgnoreCase
*
* Return true if the given string equals the content of this token
*/
internal bool EqualsIgnoreCase(string compareTo)
{
return String.Equals(_innerText, compareTo, StringComparison.OrdinalIgnoreCase);
}
}
/*
Table of tokens shared by the parsers.
Tokens that are specific to a particular parser are nested within the given
parser class.
*/
internal class WhitespaceToken : Token { }
internal abstract class LiteralToken : Token { }
internal class BooleanLiteralToken : Token { } // i.e. true or false
internal abstract class IntegerLiteralToken : Token { } // i.e. a literal integer
internal class HexIntegerLiteralToken : IntegerLiteralToken { } // i.e. a hex literal integer
internal class DecimalIntegerLiteralToken : IntegerLiteralToken { } // i.e. a hex literal integer
internal class StringLiteralToken : Token { } // i.e. A string value.
internal abstract class SyntaxErrorToken : Token { } // A syntax error.
internal class ExpectedIdentifierToken : SyntaxErrorToken { }
internal class ExpectedValidHexDigitToken : SyntaxErrorToken { } // Got a non-hex digit when we expected to have one.
internal class EndOfFileInsideStringToken : SyntaxErrorToken { } // The file ended inside a string.
internal class UnrecognizedToken : SyntaxErrorToken { } // An unrecognized token was spotted.
internal class CommentToken : Token { }
internal class IdentifierToken : Token { } // An identifier
internal class KeywordToken : Token { } // An keyword
internal class PreprocessorToken : Token { } // #if, #region, etc.
internal class OpenConditionalDirectiveToken : PreprocessorToken { }
internal class CloseConditionalDirectiveToken : PreprocessorToken { }
internal class OperatorOrPunctuatorToken : Token { } // One of the predefined operators or punctuators
internal class OperatorToken : OperatorOrPunctuatorToken { }
}
| 36.662791 | 121 | 0.632096 | [
"MIT"
] | 0xced/msbuild | src/Shared/LanguageParser/token.cs | 3,155 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class HealthStatListener : gameScriptStatPoolsListener
{
[Ordinal(0)] [RED("healthEvent")] public CHandle<HealthUpdateEvent> HealthEvent { get; set; }
[Ordinal(1)] [RED("ownerPuppet")] public wCHandle<PlayerPuppet> OwnerPuppet { get; set; }
public HealthStatListener(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 30.705882 | 105 | 0.724138 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/HealthStatListener.cs | 506 | C# |
using System;
using System.Collections.Generic;
namespace KeikoObfuscator.Renaming
{
public class SymbolRenamingPhase : ObfuscatorTaskPhase
{
public SymbolRenamingPhase(SymbolRenamingTask task)
{
Task = task;
}
public SymbolRenamingTask Task { get; private set; }
public SymbolAnalysisReport Report
{
get { return Task.AnalysisReport; }
}
public override string Name
{
get { return "Symbol Renaming Phase"; }
}
public override string Description
{
get { return "Applies the renaming procedure on all symbols marked in the analysis phase."; }
}
public override void Apply(IObfuscationContext context)
{
var typeNameGenerator = context.GetSymbolNameGenerator();
foreach (var symbolType in Report.TypesToRename)
{
symbolType.NewName = typeNameGenerator.Next();
var memberNameGenerators = new Dictionary<Type, SymbolNameGenerator>();
foreach (var overload in symbolType.MemberOverloads)
{
SymbolNameGenerator memberNameGenerator;
var memberType = overload.Symbols[0].Member.GetType();
if (!memberNameGenerators.TryGetValue(memberType, out memberNameGenerator))
memberNameGenerators.Add(memberType, memberNameGenerator = context.GetSymbolNameGenerator());
overload.NewName = memberNameGenerator.Next();
}
symbolType.Apply(context);
}
}
}
} | 31.716981 | 117 | 0.593694 | [
"MIT"
] | Marwix/PP-Obfuscator | KeikoObfuscator/Renaming/SymbolRenamingPhase.cs | 1,683 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Efs
{
[Serializable]
[EfsFile("/nv/item_files/rfnv/00022738", true, 0xE1FF)]
[Attributes(9)]
public class WcdmaB2TxLinVsTemp2Addl
{
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F0CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F1CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F2CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F3CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F4CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F5CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F6CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F7CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F8CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F9CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F10CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F11CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F12CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F13CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F14CompVsTemp { get; set; }
[ElementsCount(8)]
[ElementType("int8")]
[Description("")]
public sbyte[] F15CompVsTemp { get; set; }
}
}
| 27.854167 | 60 | 0.497008 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Efs/WcdmaB2TxLinVsTemp2AddlI.cs | 2,674 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class ProgressBar : MonoBehaviour
{
[Header("Title Setting")]
public string Title;
public Color TitleColor;
public Font TitleFont;
public int TitleFontSize = 10;
[Header("Bar Setting")]
public Color BarColor;
public Color BarBackGroundColor;
public Sprite BarBackGroundSprite;
[Range(1f, 100f)]
public int Alert = 20;
public Color BarAlertColor;
[Header("Sound Alert")]
public AudioClip sound;
public bool repeat = false;
public float RepeatRate = 1f;
private Image bar, barBackground;
private float nextPlay;
private AudioSource audiosource;
private Text txtTitle;
private float barValue;
public float BarValue
{
get { return barValue; }
set
{
value = Mathf.Clamp(value, 0, 100);
barValue = value;
UpdateValue(barValue);
}
}
private void Awake()
{
bar = transform.Find("Bar").GetComponent<Image>();
barBackground = GetComponent<Image>();
txtTitle = transform.Find("Text").GetComponent<Text>();
barBackground = transform.Find("BarBackground").GetComponent<Image>();
audiosource = GetComponent<AudioSource>();
}
private void Start()
{
txtTitle.text = Title;
txtTitle.color = TitleColor;
txtTitle.font = TitleFont;
txtTitle.fontSize = TitleFontSize;
bar.color = BarColor;
barBackground.color = BarBackGroundColor;
barBackground.sprite = BarBackGroundSprite;
UpdateValue(barValue);
}
void UpdateValue(float val)
{
bar.fillAmount = val / 100;
txtTitle.text = Title + " " + val + "%";
if (Alert >= val)
{
bar.color = BarAlertColor;
}
else
{
bar.color = BarColor;
}
}
private void Update()
{
if (!Application.isPlaying)
{
UpdateValue(50);
txtTitle.color = TitleColor;
txtTitle.font = TitleFont;
txtTitle.fontSize = TitleFontSize;
bar.color = BarColor;
barBackground.color = BarBackGroundColor;
barBackground.sprite = BarBackGroundSprite;
}
else
{
if (Alert >= barValue && Time.time > nextPlay)
{
nextPlay = Time.time + RepeatRate;
//audiosource.PlayOneShot(sound);
}
}
}
}
| 22.533898 | 78 | 0.570515 | [
"MIT"
] | zeidanbm/Surviving-Mars-Unity-VR-Game | Assets/ProgressBar/Script/ProgressBar.cs | 2,661 | 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 KryptonBreadCrumbExamples.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.8.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;
}
}
}
}
| 40 | 151 | 0.587037 | [
"BSD-3-Clause"
] | BMBH/Krypton | Source/Krypton Toolkit Examples/KryptonBreadCrumb Examples/Properties/Settings.Designer.cs | 1,082 | C# |
// Copyright (c) Mark Nichols. All Rights Reserved.
// Licensed under the MIT License.
using Azure.Deployments.Core.Extensions;
using BicepFlex.Process;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
var loggerProvider = new ConsoleLoggerProvider(new OptionsMonitor<ConsoleLoggerOptions>(new ConsoleLoggerOptions()));
var logger = loggerProvider.CreateLogger("logger");
var templateFileName = "vnet.bicep";
var parameterFileName = @"params.main.json";
var templateParameters = BicepDecoder.DecodeTemplate(templateFileName).Parameters;
var parametersInFile = JObject.Parse(File.ReadAllText(parameterFileName))["parameters"];
List<string> parameterNamesInFile = new List<string>();
List<string> parametersToDelete = new List<string>();
// Get the list of parameter names in the parameter file
if (parametersInFile != null)
{
// Scan each parameter in the file to see if it should be kept or discarded
foreach (JProperty parameter in parametersInFile.Children())
{
// if the key("Parameter Name") is not in the fileParameterNames list then
// add it. If it is there already, then there's a duplicate named parm in the file
if (!parameterNamesInFile.Any(x => x.Contains(parameter.Name)))
{
// It doesn't already exist, so add it to the list
parameterNamesInFile.Add(parameter.Name);
// Look for the name in the template parameter list
var paramFound = templateParameters.FirstOrDefault(x => x.Name == parameter.Name);
// If we cannot find the parameter from the parm file in the template,
// then delete the parm from the parameter file list
if (paramFound == null)
{
parametersToDelete.Add(parameter.Name);
}
}
else
{
// Log the error
logger.LogError($"Duplicate parameter found ({parameter.Name}) in the parameter file: {parameterFileName}");
}
}
}
// Remove all of the unused parameters
if (parametersInFile != null) {
foreach (var name in parametersToDelete)
{
var paramsFound = parametersInFile.Where(x => ((JProperty)x).Name == name).ToArray();
if (paramsFound.Any())
{
for (var i=0; i<paramsFound.Length; i++)
{
paramsFound[i].Remove();
}
}
}
}
// Check for errors of omission
// if a parameter in a template is not in the parameter file AND it does not have a default value,
// then it is an error
if (parameterNamesInFile.Count > 0)
{
foreach (var templateParm in templateParameters)
{
if (!parameterNamesInFile.Contains(templateParm.Name))
{
if (string.IsNullOrWhiteSpace(templateParm.DefaultVal))
{
logger.LogError($"A parameter in the template ({templateFileName}) was not found in the parameter file: {parameterFileName}. Note: there wasn't a default value found in the template.");
} else
{
logger.LogInformation($"A parameter in the template ({templateFileName}) was not found in the parameter file: {parameterFileName}. However, a default value was found.");
}
}
else
{
logger.LogInformation($"The parameter in the template ({templateParm.Name}) was matched with the parameter in the file: {parameterFileName}");
}
}
}
public class OptionsMonitor<T> : IOptionsMonitor<T>
{
private readonly T options;
public OptionsMonitor(T options)
{
this.options = options;
}
public T CurrentValue => options;
public T Get(string name) => options;
public IDisposable OnChange(Action<T, string> listener) => new NullDisposable();
private class NullDisposable : IDisposable
{
public void Dispose() { }
}
}
| 33.125 | 202 | 0.655094 | [
"MIT"
] | marknic/BicepXray | src/ParameterTest/Program.cs | 3,977 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Compute.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedInstanceGroupsClientTest
{
[xunit::FactAttribute]
public void GetRequestObject()
{
moq::Mock<InstanceGroups.InstanceGroupsClient> mockGrpcClient = new moq::Mock<InstanceGroups.InstanceGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceGroupRequest request = new GetInstanceGroupRequest
{
Zone = "zone255f4ea8",
InstanceGroup = "instance_group6bf5a5ef",
Project = "projectaa6ff846",
};
InstanceGroup expectedResponse = new InstanceGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Subnetwork = "subnetworkf55bf572",
Description = "description2cf9da67",
NamedPorts = { new NamedPort(), },
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceGroupsClient client = new InstanceGroupsClientImpl(mockGrpcClient.Object, null);
InstanceGroup response = client.Get(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRequestObjectAsync()
{
moq::Mock<InstanceGroups.InstanceGroupsClient> mockGrpcClient = new moq::Mock<InstanceGroups.InstanceGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceGroupRequest request = new GetInstanceGroupRequest
{
Zone = "zone255f4ea8",
InstanceGroup = "instance_group6bf5a5ef",
Project = "projectaa6ff846",
};
InstanceGroup expectedResponse = new InstanceGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Subnetwork = "subnetworkf55bf572",
Description = "description2cf9da67",
NamedPorts = { new NamedPort(), },
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceGroupsClient client = new InstanceGroupsClientImpl(mockGrpcClient.Object, null);
InstanceGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InstanceGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void Get()
{
moq::Mock<InstanceGroups.InstanceGroupsClient> mockGrpcClient = new moq::Mock<InstanceGroups.InstanceGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceGroupRequest request = new GetInstanceGroupRequest
{
Zone = "zone255f4ea8",
InstanceGroup = "instance_group6bf5a5ef",
Project = "projectaa6ff846",
};
InstanceGroup expectedResponse = new InstanceGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Subnetwork = "subnetworkf55bf572",
Description = "description2cf9da67",
NamedPorts = { new NamedPort(), },
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
InstanceGroupsClient client = new InstanceGroupsClientImpl(mockGrpcClient.Object, null);
InstanceGroup response = client.Get(request.Project, request.Zone, request.InstanceGroup);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetAsync()
{
moq::Mock<InstanceGroups.InstanceGroupsClient> mockGrpcClient = new moq::Mock<InstanceGroups.InstanceGroupsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetInstanceGroupRequest request = new GetInstanceGroupRequest
{
Zone = "zone255f4ea8",
InstanceGroup = "instance_group6bf5a5ef",
Project = "projectaa6ff846",
};
InstanceGroup expectedResponse = new InstanceGroup
{
Id = 11672635353343658936UL,
Kind = "kindf7aa39d9",
Name = "name1c9368b0",
Size = -1218396681,
Zone = "zone255f4ea8",
CreationTimestamp = "creation_timestamp235e59a1",
Region = "regionedb20d96",
Network = "networkd22ce091",
Fingerprint = "fingerprint009e6052",
Subnetwork = "subnetworkf55bf572",
Description = "description2cf9da67",
NamedPorts = { new NamedPort(), },
SelfLink = "self_link7e87f12d",
};
mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstanceGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null));
InstanceGroupsClient client = new InstanceGroupsClientImpl(mockGrpcClient.Object, null);
InstanceGroup responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.InstanceGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
InstanceGroup responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.InstanceGroup, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| 51.438596 | 216 | 0.629036 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.Tests/InstanceGroupsClientTest.g.cs | 8,796 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
namespace System.IdentityModel.Tokens
{
/// <summary>
/// This class defines the encrypting credentials which can be used to
/// encrypt the proof key. It is very similar to SigningCredentials class defined
/// in System.IdentityModel.dll
/// </summary>
public class EncryptingCredentials
{
string _algorithm;
SecurityKey _key;
SecurityKeyIdentifier _keyIdentifier;
/// <summary>
/// Constructor for easy subclassing.
/// </summary>
public EncryptingCredentials()
{
}
/// <summary>
/// Constructs an EncryptingCredentials with a security key, a security key identifier and
/// the encryption algorithm.
/// </summary>
/// <param name="key">A security key for encryption.</param>
/// <param name="keyIdentifier">A security key identifier for the encryption key.</param>
/// <param name="algorithm">The encryption algorithm.</param>
/// <exception cref="ArgumentNullException">When key is null.</exception>
/// <exception cref="ArgumentNullException">When key identifier is null.</exception>
/// <exception cref="ArgumentNullException">When algorithm is null.</exception>
public EncryptingCredentials(SecurityKey key, SecurityKeyIdentifier keyIdentifier, string algorithm)
{
if (key == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("key");
}
if (keyIdentifier == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("keyIdentifier");
}
if (string.IsNullOrEmpty(algorithm))
{
throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("algorithm");
}
//
// It is possible that keyIdentifier is pointing to a token which
// is not capable of doing the given algorithm, we have no way verify
// that at this level.
//
_algorithm = algorithm;
_key = key;
_keyIdentifier = keyIdentifier;
}
/// <summary>
/// Gets or sets the encryption algorithm.
/// </summary>
public string Algorithm
{
get
{
return _algorithm;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw DiagnosticUtility.ThrowHelperArgumentNullOrEmptyString("value");
}
_algorithm = value;
}
}
/// <summary>
/// Gets or sets the encryption key material.
/// </summary>
public SecurityKey SecurityKey
{
get
{
return _key;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
_key = value;
}
}
/// <summary>
/// Gets or sets the SecurityKeyIdentifier that identifies the encrypting credential.
/// </summary>
public SecurityKeyIdentifier SecurityKeyIdentifier
{
get
{
return _keyIdentifier;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
_keyIdentifier = value;
}
}
}
}
| 31.119048 | 108 | 0.515175 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/ndp/cdf/src/WCF/IdentityModel/System/IdentityModel/Tokens/EncryptingCredentials.cs | 3,921 | C# |
using System.Text.RegularExpressions;
using FirebirdMonitorTool.Transaction;
namespace FirebirdMonitorTool.Function
{
abstract class ParseFunction : ParseTransaction, IFunction
{
static readonly Regex Parser =
new Regex(
@"^\s*Function (?<FunctionName>.+?):((\r\s*)|(\s*$))",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
public ParseFunction(RawCommand rawCommand)
: base(rawCommand)
{
}
public string FunctionName { get; private set; }
public override bool Parse()
{
var result = base.Parse();
if (result)
{
var match = Parser.Match(Message);
result = match.Success;
if (result)
{
FunctionName = match.Groups["FunctionName"].Value;
RemoveFirstCharactersOfMessage(match.Groups[0].Length);
}
}
return result;
}
}
}
| 20.769231 | 60 | 0.680247 | [
"MIT"
] | MagicAndre1981/FirebirdMonitorTool | src/FirebirdMonitorTool/Function/ParseFunction.cs | 812 | C# |
using System;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Serialization;
using UnityEngine;
namespace UnityEditor.Graphing
{
[Serializable]
struct SlotReference : IEquatable<SlotReference>, IComparable<SlotReference>
{
[SerializeField]
JsonRef<AbstractMaterialNode> m_Node;
[SerializeField]
int m_SlotId;
public SlotReference(AbstractMaterialNode node, int slotId)
{
m_Node = node;
m_SlotId = slotId;
}
public AbstractMaterialNode node => m_Node;
// public Guid nodeGuid => m_Node.value.guid;
public int slotId => m_SlotId;
public MaterialSlot slot => m_Node.value?.FindSlot<MaterialSlot>(m_SlotId);
public bool Equals(SlotReference other) => m_SlotId == other.m_SlotId && m_Node.value == other.m_Node.value;
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj.GetType() == GetType() && Equals((SlotReference)obj);
}
public override int GetHashCode()
{
unchecked
{
return (m_SlotId * 397) ^ m_Node.GetHashCode();
}
}
public int CompareTo(SlotReference other)
{
var nodeIdComparison = m_Node.value.objectId.CompareTo(other.m_Node.value.objectId);
if (nodeIdComparison != 0)
{
return nodeIdComparison;
}
return m_SlotId.CompareTo(other.m_SlotId);
}
}
}
| 26.898305 | 116 | 0.599244 | [
"Apache-2.0"
] | AJTheEnder/E428 | Projet/E428/Library/PackageCache/com.unity.shadergraph@10.4.0/Editor/Data/Interfaces/Graph/SlotReference.cs | 1,587 | C# |
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace SharpSound.SoundCloud.Query
{
public static class Evaluator
{
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <param name="fnCanBeEvaluated">A function that decides whether a given expression node can be part of the local function.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression, Func<Expression, bool> fnCanBeEvaluated)
{
return new SubtreeEvaluator(new Nominator(fnCanBeEvaluated).Nominate(expression)).Eval(expression);
}
/// <summary>
/// Performs evaluation & replacement of independent sub-trees
/// </summary>
/// <param name="expression">The root of the expression tree.</param>
/// <returns>A new tree with sub-trees evaluated and replaced.</returns>
public static Expression PartialEval(Expression expression)
{
return PartialEval(expression, CanBeEvaluatedLocally);
}
private static bool CanBeEvaluatedLocally(Expression expression)
{
return expression.NodeType != ExpressionType.Parameter;
}
/// <summary>
/// Evaluates & replaces sub-trees when first candidate is reached (top-down)
/// </summary>
private class SubtreeEvaluator : ExpressionVisitor
{
private readonly HashSet<Expression> candidates;
internal SubtreeEvaluator(HashSet<Expression> candidates)
{
this.candidates = candidates;
}
internal Expression Eval(Expression exp)
{
return this.Visit(exp);
}
public override Expression Visit(Expression exp)
{
if (exp == null)
{
return null;
}
if (this.candidates.Contains(exp))
{
return this.Evaluate(exp);
}
return base.Visit(exp);
}
private Expression Evaluate(Expression e)
{
if (e.NodeType == ExpressionType.Constant)
{
return e;
}
var lambda = Expression.Lambda(e);
var fn = lambda.Compile();
return Expression.Constant(fn.DynamicInvoke(null), e.Type);
}
}
/// <summary>
/// Performs bottom-up analysis to determine which nodes can possibly
/// be part of an evaluated sub-tree.
/// </summary>
private class Nominator : ExpressionVisitor
{
private HashSet<Expression> candidates;
private bool cannotBeEvaluated;
private readonly Func<Expression, bool> fnCanBeEvaluated;
internal Nominator(Func<Expression, bool> fnCanBeEvaluated)
{
this.fnCanBeEvaluated = fnCanBeEvaluated;
}
internal HashSet<Expression> Nominate(Expression expression)
{
this.candidates = new HashSet<Expression>();
this.Visit(expression);
return this.candidates;
}
public override Expression Visit(Expression expression)
{
if (expression != null)
{
var saveCannotBeEvaluated = this.cannotBeEvaluated;
this.cannotBeEvaluated = false;
base.Visit(expression);
if (!this.cannotBeEvaluated)
{
if (this.fnCanBeEvaluated(expression))
{
this.candidates.Add(expression);
}
else
{
this.cannotBeEvaluated = true;
}
}
this.cannotBeEvaluated |= saveCannotBeEvaluated;
}
return expression;
}
}
}
} | 34.265625 | 141 | 0.526448 | [
"MIT"
] | RyuzakiH/SoundCloud.Api | SoundCloud.Api/Query/Evaluator.cs | 4,388 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, SetLastError = true)]
internal static extern uint GetFileType(IntPtr hFile);
}
}
| 29 | 71 | 0.739224 | [
"MIT"
] | 06needhamt/runtime | src/libraries/Common/src/Interop/Windows/Kernel32/Interop.GetFileType_IntPtr.cs | 464 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamarinAzure.Mobile.Controls;
using XamarinAzure.Mobile.Pages.Acesso;
using XamarinAzure.Mobile.Pages.Home;
namespace XamarinAzure.Mobile.Pages.Android
{
public sealed class DroidRootPage : MasterDetailPage
{
Dictionary<NavigationItens, XamarinAzureNavigationPage> pages;
bool isRunning = false;
public DroidRootPage()
{
pages = new Dictionary<NavigationItens, XamarinAzureNavigationPage>();
Master = new MenuPage(this);
pages.Add(NavigationItens.Home, new XamarinAzureNavigationPage(new HomePage()));
Detail = pages[NavigationItens.Home];
}
public async Task NavigateAsync(NavigationItens pSelectedItem)
{
XamarinAzureNavigationPage _new = null;
if (!pages.ContainsKey(pSelectedItem))
{
switch (pSelectedItem)
{
case NavigationItens.Home:
pages.Add(pSelectedItem, new XamarinAzureNavigationPage(new HomePage()));
break;
case NavigationItens.Login:
pages.Add(pSelectedItem, new XamarinAzureNavigationPage(new LoginPage()));
break;
}
}
if (_new == null)
_new = pages[pSelectedItem];
if (_new == null)
return;
//if we are on the same tab and pressed it again.
if (this.Detail == _new)
await _new.Navigation.PopToRootAsync();
this.Detail = _new;
}
protected override async void OnAppearing()
{
base.OnAppearing();
//if (Settings.Current.FirstRun)
//{
// MessagingService.Current.SendMessage(MessageKeys.NavigateLogin);
//}
isRunning = true;
}
}
}
| 27.630137 | 98 | 0.564204 | [
"MIT"
] | onfriday/exemplo-xamarin-azure | XamarinAzureSolution/XamarinAzure.Mobile/XamarinAzure.Mobile/Pages/Android/DroidRootPage.cs | 2,019 | C# |
namespace ShopManage
{
partial class MainInterface
{
/// <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.lbShops = new System.Windows.Forms.ListBox();
this.lblShops = new System.Windows.Forms.Label();
this.btnAdd = new System.Windows.Forms.Button();
this.btnRemove = new System.Windows.Forms.Button();
this.tbxName = new System.Windows.Forms.TextBox();
this.rbtnShop = new System.Windows.Forms.RadioButton();
this.rbtnLoanStand = new System.Windows.Forms.RadioButton();
this.lblName = new System.Windows.Forms.Label();
this.btnRefresh = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// lbShops
//
this.lbShops.FormattingEnabled = true;
this.lbShops.Location = new System.Drawing.Point(27, 121);
this.lbShops.Name = "lbShops";
this.lbShops.Size = new System.Drawing.Size(272, 69);
this.lbShops.TabIndex = 0;
//
// lblShops
//
this.lblShops.AutoSize = true;
this.lblShops.Location = new System.Drawing.Point(24, 105);
this.lblShops.Name = "lblShops";
this.lblShops.Size = new System.Drawing.Size(40, 13);
this.lblShops.TabIndex = 1;
this.lblShops.Text = "Shops:";
//
// btnAdd
//
this.btnAdd.Location = new System.Drawing.Point(224, 41);
this.btnAdd.Name = "btnAdd";
this.btnAdd.Size = new System.Drawing.Size(75, 23);
this.btnAdd.TabIndex = 2;
this.btnAdd.Text = "Add";
this.btnAdd.UseVisualStyleBackColor = true;
this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
//
// btnRemove
//
this.btnRemove.Location = new System.Drawing.Point(27, 196);
this.btnRemove.Name = "btnRemove";
this.btnRemove.Size = new System.Drawing.Size(75, 23);
this.btnRemove.TabIndex = 3;
this.btnRemove.Text = "Remove";
this.btnRemove.UseVisualStyleBackColor = true;
this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click);
//
// tbxName
//
this.tbxName.Location = new System.Drawing.Point(27, 44);
this.tbxName.Name = "tbxName";
this.tbxName.Size = new System.Drawing.Size(191, 20);
this.tbxName.TabIndex = 4;
//
// rbtnShop
//
this.rbtnShop.AutoSize = true;
this.rbtnShop.Checked = true;
this.rbtnShop.Location = new System.Drawing.Point(27, 70);
this.rbtnShop.Name = "rbtnShop";
this.rbtnShop.Size = new System.Drawing.Size(112, 17);
this.rbtnShop.TabIndex = 5;
this.rbtnShop.TabStop = true;
this.rbtnShop.Text = "Food / drink stand";
this.rbtnShop.UseVisualStyleBackColor = true;
//
// rbtnLoanStand
//
this.rbtnLoanStand.AutoSize = true;
this.rbtnLoanStand.Location = new System.Drawing.Point(140, 70);
this.rbtnLoanStand.Name = "rbtnLoanStand";
this.rbtnLoanStand.Size = new System.Drawing.Size(78, 17);
this.rbtnLoanStand.TabIndex = 6;
this.rbtnLoanStand.Text = "Loan stand";
this.rbtnLoanStand.UseVisualStyleBackColor = true;
//
// lblName
//
this.lblName.AutoSize = true;
this.lblName.Location = new System.Drawing.Point(24, 26);
this.lblName.Name = "lblName";
this.lblName.Size = new System.Drawing.Size(38, 13);
this.lblName.TabIndex = 7;
this.lblName.Text = "Name:";
//
// btnRefresh
//
this.btnRefresh.Location = new System.Drawing.Point(224, 196);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(75, 23);
this.btnRefresh.TabIndex = 8;
this.btnRefresh.Text = "Refresh";
this.btnRefresh.UseVisualStyleBackColor = true;
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// MainInterface
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(338, 257);
this.Controls.Add(this.btnRefresh);
this.Controls.Add(this.lblName);
this.Controls.Add(this.rbtnLoanStand);
this.Controls.Add(this.rbtnShop);
this.Controls.Add(this.tbxName);
this.Controls.Add(this.btnRemove);
this.Controls.Add(this.btnAdd);
this.Controls.Add(this.lblShops);
this.Controls.Add(this.lbShops);
this.Name = "MainInterface";
this.Text = "Manage shops";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListBox lbShops;
private System.Windows.Forms.Label lblShops;
private System.Windows.Forms.Button btnAdd;
private System.Windows.Forms.Button btnRemove;
private System.Windows.Forms.TextBox tbxName;
private System.Windows.Forms.RadioButton rbtnShop;
private System.Windows.Forms.RadioButton rbtnLoanStand;
private System.Windows.Forms.Label lblName;
private System.Windows.Forms.Button btnRefresh;
}
} | 41.39375 | 107 | 0.563793 | [
"Apache-2.0"
] | nikolaynikolaevn/Mysteryland | ShopManage/MainInterface.Designer.cs | 6,625 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.ImageSharp.MetaData.Profiles.Icc
{
/// <summary>
/// Provides methods to read ICC data types
/// </summary>
internal sealed partial class IccDataReader
{
/// <summary>
/// Reads a two dimensional matrix
/// </summary>
/// <param name="xCount">Number of values in X</param>
/// <param name="yCount">Number of values in Y</param>
/// <param name="isSingle">True if the values are encoded as Single; false if encoded as Fix16</param>
/// <returns>The read matrix</returns>
public float[,] ReadMatrix(int xCount, int yCount, bool isSingle)
{
float[,] matrix = new float[xCount, yCount];
for (int y = 0; y < yCount; y++)
{
for (int x = 0; x < xCount; x++)
{
if (isSingle)
{
matrix[x, y] = this.ReadSingle();
}
else
{
matrix[x, y] = this.ReadFix16();
}
}
}
return matrix;
}
/// <summary>
/// Reads a one dimensional matrix
/// </summary>
/// <param name="yCount">Number of values</param>
/// <param name="isSingle">True if the values are encoded as Single; false if encoded as Fix16</param>
/// <returns>The read matrix</returns>
public float[] ReadMatrix(int yCount, bool isSingle)
{
float[] matrix = new float[yCount];
for (int i = 0; i < yCount; i++)
{
if (isSingle)
{
matrix[i] = this.ReadSingle();
}
else
{
matrix[i] = this.ReadFix16();
}
}
return matrix;
}
}
}
| 31.734375 | 110 | 0.458887 | [
"Apache-2.0"
] | 4thOffice/ImageSharp | src/ImageSharp/MetaData/Profiles/ICC/DataReader/IccDataReader.Matrix.cs | 2,033 | C# |
using Moq;
using NUnit.Framework;
using PackageManager.Info.Contracts;
using PackageManager.Models.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PackageManager.Tests.Repositories.PackageRepositoryTests.Fakes
{
[TestFixture]
class Update_Should
{
[Test]
public void ThrowArgumentNullException_WhenPassedNullPackage()
{
var package = new Mock<IPackage>();
var logger = new Mock<ILogger>();
var packages = new List<IPackage>() { package.Object };
var packageRepository = new PackageRepositoryFake(logger.Object, null);
Assert.Throws<ArgumentNullException>(() => packageRepository.Update(package.Object));
}
//[Test]
//public void TestValidPackage()
//{
// var package = new Mock<IPackage>();
// var logger = new Mock<ILogger>();
// var packages = new List<IPackage>() { package.Object };
// var anotherPackage = new Mock<IPackage>();
// var packageRepository = new PackageRepositoryFake(logger.Object, packages);
// Assert.Throws<ArgumentNullException>(() => packageRepository.Update(anotherPackage.Object));
//}
}
}
| 31.380952 | 106 | 0.645675 | [
"MIT"
] | SimonaArsova/TelerikAcademy | C# Programming/C#UnitTesting/Exam_Skeleton/Skeleton/AcademyPackageManager/PackageManager.Tests/Repositories/PackageRepositoryTests/Update_Should.cs | 1,320 | C# |
namespace mazes.Core.Cells {
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
public abstract class Cell {
// Position in the maze
public int Row { get; }
public int Column { get; }
public Point Location => new Point(Column, Row);
// Cells that are linked to this cell
private readonly Dictionary<Cell, bool> _links;
public List<Cell> Links => _links.Keys.ToList();
public abstract List<Cell> Neighbors { get; }
public int Weight { get; set; }
public Cell(int row, int col) {
Row = row;
Column = col;
Weight = 1;
_links = new Dictionary<Cell, bool>();
}
public virtual void Link(Cell cell, bool bidirectional = true) {
_links[cell] = true;
if (bidirectional) {
cell.Link(this, false);
}
}
public virtual void Unlink(Cell cell, bool bidirectional = true) {
_links.Remove(cell);
if (bidirectional) {
cell.Unlink(this, false);
}
}
public bool IsLinked(Cell cell) {
if (cell == null) {
return false;
}
return _links.ContainsKey(cell);
}
public Distances Distances {
get {
var distances = new Distances(this);
var frontier = new HashSet<Cell> {
this
};
while (frontier.Any()) {
var newFrontier = new HashSet<Cell>();
foreach (var cell in frontier) {
foreach (var linked in cell.Links) {
if (distances[linked] >= 0) {
continue;
}
distances[linked] = distances[cell] + 1;
newFrontier.Add(linked);
}
}
frontier = newFrontier;
}
return distances;
}
}
public Distances WeightedDistances {
get {
var weights = new Distances(this);
var pending = new HashSet<Cell>{this};
while (pending.Any()) {
var cell = pending.OrderBy(c => weights[c]).First();
pending.Remove(cell);
foreach (var neighbor in cell.Links) {
var totalWeight = weights[cell] + neighbor.Weight;
if (weights[neighbor] >= 0 || totalWeight < weights[neighbor]) {
pending.Add(neighbor);
weights[neighbor] = totalWeight;
}
}
}
return weights;
}
}
}
} | 32.43956 | 88 | 0.442751 | [
"MIT"
] | ericrrichards/mazes | mazes/Core/Cells/Cell.cs | 2,954 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.CAS.Models
{
public class CreateVpcVroutertableResponse : TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
[NameInMap("req_msg_id")]
[Validation(Required=false)]
public string ReqMsgId { get; set; }
// 结果码,一般OK表示调用成功
[NameInMap("result_code")]
[Validation(Required=false)]
public string ResultCode { get; set; }
// 异常信息的文本描述
[NameInMap("result_msg")]
[Validation(Required=false)]
public string ResultMsg { get; set; }
}
}
| 22.366667 | 59 | 0.631893 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | cas/csharp/core/Models/CreateVpcVroutertableResponse.cs | 745 | C# |
using System.Net.Http.Headers;
using UnityEngine;
using UnityEngine.XR;
public class Enemy : MonoBehaviour
{
public float speed = 10f;
public int enemyHealth = 100;
public int moneyGain = 50;
public GameObject deathEffect;
private Transform target;
private int waypointIndex = 0;
void Start ()
{
target = WaypointManager.points[0];
}
public void DamageCalculator (int amount)
{
enemyHealth -= amount;
if (enemyHealth <= 0 )
{
DespawnEnemy();
}
}
void DespawnEnemy()
{
PlayerAttributes.Money += moneyGain;
PlayerAttributes.EnemiesKillled ++;
GameObject effect = (GameObject)Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(effect, 1f);
Destroy(gameObject);
}
void Update ()
{
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.4f)
{
GetNextWaypoint();
}
}
void GetNextWaypoint()
{
if (waypointIndex >= WaypointManager.points.Length - 1)
{
PathEnd();
return;
}
waypointIndex++;
target = WaypointManager.points[waypointIndex];
}
void PathEnd()
{
PlayerAttributes.Health--;
Destroy(gameObject);
}
}
| 20.712329 | 106 | 0.583995 | [
"CC0-1.0"
] | benji-rea/RaidDefenceLeague | Tower Defence Game/Assets/Scripts/Enemy.cs | 1,514 | C# |
using System;
namespace SshConfig
{
public class Program
{
public static int Main(string[] args)
{
if (args.Length < 1)
{
Console.Error.WriteLine("Usage: dotnet SshConfig.dll [group]");
return 1;
}
var result = Handle(args);
if (result == 0)
{
Console.WriteLine("Finished successfully!");
}
return result;
}
private static int Handle(string[] args)
{
switch (args[0])
{
case "sshd":
return SshdHandler.Handle(args);
case "hosts":
return HostsHandler.Handle(args);
default:
Console.Error.WriteLine($"Group '{args[0]}' is not supported.");
return 1;
}
}
}
}
| 23.275 | 84 | 0.424275 | [
"MIT"
] | IgorMilavec/IntegrationTests | src/SshConfig/Program.cs | 933 | C# |
using System;
using System.Linq;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using WebApi.Common;
using WebApi.DBOperations;
namespace WebApi.Application.BookOperations.Queries.GetBookDetail
{
public class GetBookDetailQuery
{
private readonly IBookStoreDbContext _dbContext;
private readonly IMapper _mapper;
public int BookId {get; set;}
public GetBookDetailQuery(IBookStoreDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
public BookDetailViewModel Handle()
{
var book = _dbContext.Books.Include(x=> x.Genre).Include(x=> x.Author).Where(book => book.Id == BookId).SingleOrDefault();
if(book is null)
throw new InvalidOperationException("Kitap bulunamadı.");
BookDetailViewModel vm = _mapper.Map<BookDetailViewModel>(book);
return vm;
}
}
public class BookDetailViewModel
{
public string Title { get; set; }
public string Genre { get; set; }
public string Author { get; set; }
public int PageCount { get; set; }
public string PublishDate { get; set; }
}
} | 29.333333 | 134 | 0.638799 | [
"MIT"
] | MuhammetFatihYilmaz/BookStore | WebApi/Application/BookOperations/Queries/GetBookDetail/GetBookDetailQuery.cs | 1,233 | C# |
using ComLight;
using Diligent.Graphics;
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Vrmac;
using Vrmac.ModeSet;
namespace RenderSamples
{
static class SampleRenderer
{
const eLogLevel consoleLoggingLevel = eLogLevel.Verbose;
/// <summary>When running full screen, will switch to this resolution.</summary>
/// <remarks>If it's not supported by GPU + display combination, will fail with exception.</remarks>
static readonly CSize fullscreenResolution = new CSize( 1920, 1080 );
/// <summary>When running full screen, will use this format if it's available.</summary>
/// <remarks>If it's not supported by GPU + display combination, will pick another one.</remarks>
const eDrmFormat idealDrmFormat = eDrmFormat.ARGB8888;
const string dll = "Vrmac";
[DllImport( dll, PreserveSig = false )]
static extern void createEngine( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Marshaler<iGraphicsEngine> ) )] out iGraphicsEngine engine );
static void runFullScreen( iGraphicsEngine engine, SampleBase sample )
{
iVideoSetup videoSetup = new Utils.VideoSetup( idealDrmFormat );
var dispatcher = engine.dispatcher();
ThreadPool.QueueUserWorkItem( obj => { Console.ReadKey(); dispatcher.postQuitMessage( 0 ); } );
engine.renderFullScreen( sample.context, fullscreenResolution, videoSetup );
}
static void runWindowed( iGraphicsEngine engine, SampleBase sample )
{
iWindowSetup setup = new Utils.WindowSetup();
engine.renderWindowed( sample.context, null, setup );
}
public static void runSample( SampleBase sample )
{
SetupNativeLibraries.setup();
createEngine( out var engine );
engine.setConsoleLoggerSink( consoleLoggingLevel );
// Utils.Tests.PrintConnectors.print( engine );
try
{
eCapabilityFlags capabilityFlags = engine.getCapabilityFlags();
if( capabilityFlags.HasFlag( eCapabilityFlags.GraphicsWindowed ) )
runWindowed( engine, sample );
else
{
if( !capabilityFlags.HasFlag( eCapabilityFlags.GraphicsFullscreen ) )
throw new ApplicationException( "The native library doesn't implement any 3D rendering" );
runFullScreen( engine, sample );
}
}
catch( ShaderCompilerException sce )
{
sce.saveSourceCode();
throw;
}
finally
{
engine.clearLoggerSink();
}
}
}
} | 33.520548 | 165 | 0.710666 | [
"MIT"
] | Const-me/Vrmac | RenderSamples/Utils/SampleRenderer.cs | 2,449 | C# |
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/UnitTestEx
using UnitTestEx.NUnit.Internal;
using NFI = NUnit.Framework.Internal;
namespace UnitTestEx.NUnit
{
/// <summary>
/// Provides the <b>NUnit</b> <see cref="Mocking.MockHttpClientFactory"/> implementation.
/// </summary>
public static class MockHttpClientFactory
{
/// <summary>
/// Creates the <see cref="Mocking.MockHttpClientFactory"/>.
/// </summary>
/// <returns>The <see cref="Mocking.MockHttpClientFactory"/>.</returns>
public static Mocking.MockHttpClientFactory Create() => new(new NUnitTestImplementor(NFI.TestExecutionContext.CurrentContext));
}
} | 38.052632 | 135 | 0.688797 | [
"MIT"
] | Avanade/UnitTestEx | src/UnitTestEx.NUnit/MockHttpClientFactory.cs | 725 | 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.Collections.Generic;
using Microsoft.SqlTools.Hosting.Protocol.Contracts;
namespace Microsoft.SqlTools.ServiceLayer.LanguageServices.Contracts
{
public class FindModuleRequest
{
public static readonly
RequestType<List<PSModuleMessage>, object> Type =
RequestType<List<PSModuleMessage>, object>.Create("SqlTools/findModule");
}
public class PSModuleMessage
{
public string Name { get; set; }
public string Description { get; set; }
}
}
| 27.28 | 101 | 0.703812 | [
"MIT"
] | Bhaskers-Blu-Org2/sqltoolsservice | src/Microsoft.SqlTools.ServiceLayer/LanguageServices/Contracts/FindModuleRequest.cs | 684 | C# |
using Tizen.NET.MaterialComponents;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Compatibility.Material.Tizen;
using Microsoft.Maui.Controls.Platform.Tizen;
using Microsoft.Maui.Controls.Platform.Tizen.Native;
[assembly: ExportRenderer(typeof(Frame), typeof(MaterialFrameRenderer), new[] { typeof(VisualMarker.MaterialVisual) }, Priority = short.MinValue)]
namespace Microsoft.Maui.Controls.Compatibility.Material.Tizen
{
public class MaterialFrameRenderer : ViewRenderer<Frame, MCard>
{
public MaterialFrameRenderer()
{
RegisterPropertyHandler(Frame.BorderColorProperty, UpdateBorderColor);
RegisterPropertyHandler(Frame.HasShadowProperty, UpdateShadowVisibility);
}
protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
{
if (Control == null)
{
SetNativeControl(new MaterialCanvas(Forms.NativeParent));
}
base.OnElementChanged(e);
}
void UpdateBorderColor()
{
Control.BorderColor = Element.BorderColor.ToNative();
}
void UpdateShadowVisibility()
{
Control.HasShadow = Element.HasShadow;
}
}
}
| 28.710526 | 146 | 0.779102 | [
"MIT"
] | 3DSX/maui | src/Compatibility/Material/src/Tizen/MaterialFrameRenderer.cs | 1,091 | C# |
/*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
namespace Sportradar.OddsFeed.SDK.Entities.REST
{
/// <summary>
/// Defines a contract implemented by classes representing a hole of a golf course
/// </summary>
public interface IHole
{
/// <summary>
/// Gets the number of the hole
/// </summary>
int Number { get; }
/// <summary>
/// Gets the par
/// </summary>
/// <value>The par</value>
int Par { get; }
}
}
| 23.73913 | 86 | 0.553114 | [
"Apache-2.0"
] | Honore-Gaming/UnifiedOddsSdkNetCore | src/Sportradar.OddsFeed.SDK/Entities/REST/IHole.cs | 548 | C# |
// ============================================================================
// FileName: RecordCNAME.cs
//
// Description:
//
//
// Author(s):
// Alphons van der Heijden
//
// History:
// 28 Mar 2008 Aaron Clauson Added to sipswitch code base based on http://www.codeproject.com/KB/library/DNS.NET_Resolver.aspx.
//
// License:
// The Code Project Open License (CPOL) https://www.codeproject.com/info/cpol10.aspx
// ============================================================================
/*
*
3.3.1. CNAME RDATA format
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/ CNAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
where:
CNAME A <domain-name> which specifies the canonical or primary
name for the owner. The owner name is an alias.
CNAME RRs cause no additional section processing, but name servers may
choose to restart the query at the canonical name in certain cases. See
the description of name server logic in [RFC-1034] for details.
*
*/
namespace Heijden.DNS
{
public class RecordCNAME : Record
{
public string CNAME;
public RecordCNAME(RecordReader rr)
{
CNAME = rr.ReadDomainName();
}
public override string ToString()
{
return CNAME;
}
}
}
| 25.763636 | 129 | 0.47777 | [
"MIT"
] | go2sleep/GB28181.Solution | sipsorcery/src/net/DNS/Records/RecordCNAME.cs | 1,417 | 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.DataFactory.Latest.Outputs
{
[OutputType]
public sealed class AmazonMWSLinkedServiceResponse
{
/// <summary>
/// The access key id used to access data.
/// </summary>
public readonly object AccessKeyId;
/// <summary>
/// List of tags that can be used for describing the linked service.
/// </summary>
public readonly ImmutableArray<object> Annotations;
/// <summary>
/// The integration runtime reference.
/// </summary>
public readonly Outputs.IntegrationRuntimeReferenceResponse? ConnectVia;
/// <summary>
/// Linked service description.
/// </summary>
public readonly string? Description;
/// <summary>
/// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? EncryptedCredential;
/// <summary>
/// The endpoint of the Amazon MWS server, (i.e. mws.amazonservices.com)
/// </summary>
public readonly object Endpoint;
/// <summary>
/// The Amazon Marketplace ID you want to retrieve data from. To retrieve data from multiple Marketplace IDs, separate them with a comma (,). (i.e. A2EUQ1WTGCTBG2)
/// </summary>
public readonly object MarketplaceID;
/// <summary>
/// The Amazon MWS authentication token.
/// </summary>
public readonly Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? MwsAuthToken;
/// <summary>
/// Parameters for linked service.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? Parameters;
/// <summary>
/// The secret key used to access data.
/// </summary>
public readonly Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? SecretKey;
/// <summary>
/// The Amazon seller ID.
/// </summary>
public readonly object SellerID;
/// <summary>
/// Type of linked service.
/// Expected value is 'AmazonMWS'.
/// </summary>
public readonly string Type;
/// <summary>
/// Specifies whether the data source endpoints are encrypted using HTTPS. The default value is true.
/// </summary>
public readonly object? UseEncryptedEndpoints;
/// <summary>
/// Specifies whether to require the host name in the server's certificate to match the host name of the server when connecting over SSL. The default value is true.
/// </summary>
public readonly object? UseHostVerification;
/// <summary>
/// Specifies whether to verify the identity of the server when connecting over SSL. The default value is true.
/// </summary>
public readonly object? UsePeerVerification;
[OutputConstructor]
private AmazonMWSLinkedServiceResponse(
object accessKeyId,
ImmutableArray<object> annotations,
Outputs.IntegrationRuntimeReferenceResponse? connectVia,
string? description,
object? encryptedCredential,
object endpoint,
object marketplaceID,
Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? mwsAuthToken,
ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? parameters,
Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? secretKey,
object sellerID,
string type,
object? useEncryptedEndpoints,
object? useHostVerification,
object? usePeerVerification)
{
AccessKeyId = accessKeyId;
Annotations = annotations;
ConnectVia = connectVia;
Description = description;
EncryptedCredential = encryptedCredential;
Endpoint = endpoint;
MarketplaceID = marketplaceID;
MwsAuthToken = mwsAuthToken;
Parameters = parameters;
SecretKey = secretKey;
SellerID = sellerID;
Type = type;
UseEncryptedEndpoints = useEncryptedEndpoints;
UseHostVerification = useHostVerification;
UsePeerVerification = usePeerVerification;
}
}
}
| 38.257813 | 190 | 0.637942 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/DataFactory/Latest/Outputs/AmazonMWSLinkedServiceResponse.cs | 4,897 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SalesWebMvc.Data;
namespace SalesWebMvc.Migrations
{
[DbContext(typeof(SalesWebMvcContext))]
[Migration("20200908193644_OtherEntities")]
partial class OtherEntities
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.14-servicing-32113")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("SalesWebMvc.Models.Department", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Department");
});
modelBuilder.Entity("SalesWebMvc.Models.SalesRecord", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<double>("Amount");
b.Property<DateTime>("Date");
b.Property<int?>("SellerId");
b.Property<int>("Status");
b.HasKey("Id");
b.HasIndex("SellerId");
b.ToTable("SalesRecords");
});
modelBuilder.Entity("SalesWebMvc.Models.Seller", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<double>("BaseSalary");
b.Property<DateTime>("BirthDate");
b.Property<int?>("DepartmentId");
b.Property<string>("Email");
b.Property<string>("Name");
b.HasKey("Id");
b.HasIndex("DepartmentId");
b.ToTable("Seller");
});
modelBuilder.Entity("SalesWebMvc.Models.SalesRecord", b =>
{
b.HasOne("SalesWebMvc.Models.Seller")
.WithMany("Sales")
.HasForeignKey("SellerId");
});
modelBuilder.Entity("SalesWebMvc.Models.Seller", b =>
{
b.HasOne("SalesWebMvc.Models.Department", "Department")
.WithMany("Sellers")
.HasForeignKey("DepartmentId");
});
#pragma warning restore 612, 618
}
}
}
| 29.677419 | 75 | 0.493478 | [
"MIT"
] | Igor-IS/SalesWeb | SalesWebMvc/Migrations/20200908193644_OtherEntities.Designer.cs | 2,762 | C# |
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using WindowsTemplateSample.Models;
using WindowsTemplateSample.ViewModels;
namespace WindowsTemplateSample.Views
{
public sealed partial class ImageGallery1DetailPage : Page
{
public ImageGallery1DetailViewModel ViewModel { get; } = new ImageGallery1DetailViewModel();
public ImageGallery1DetailPage()
{
InitializeComponent();
ViewModel.SetImage(previewImage);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ViewModel.Initialize(e.Parameter as SampleImage);
showFlipView.Begin();
}
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
if (e.NavigationMode == NavigationMode.Back)
{
previewImage.Visibility = Visibility.Visible;
ViewModel.SetAnimation();
}
}
}
}
| 27.275 | 100 | 0.64253 | [
"MIT"
] | CNinnovation/MVVMWorkshopMar2018 | WindowsTemplateSample/WindowsTemplateSample/Views/ImageGallery1DetailPage.xaml.cs | 1,093 | 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("FitnessOfBand")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FitnessOfBand")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 35.965517 | 84 | 0.74209 | [
"MIT"
] | sergioctorres/FitnessOfBand | FitnessOfBand/Properties/AssemblyInfo.cs | 1,046 | C# |
using System.IO.Compression;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Bundler.AspNet;
using Bundler.Defaults;
using Bundler.Example;
using Bundler.Infrastructure;
using Bundler.JavaScript;
using Bundler.Less;
[assembly: PreApplicationStartMethod(typeof(MvcApplication), nameof(MvcApplication.InitBundlerModule))]
namespace Bundler.Example {
public class MvcApplication : System.Web.HttpApplication {
public IBundleProvider BundleProvider => AspNetBundler.Current;
public static void InitBundlerModule() {
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(AspNetBundler.HttpModule);
}
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
var configuration = new DefaultBundleConfigurationBuilder()
.SetupBundling(new BundlingSettings {
AutoRefresh = true,
CombineResponse = true,
FallbackOnError = true,
IncludeContentHash = true
})
.SetupCaching(new CachingSettings {
Enabled = true,
UseEtag = true
})
.SetupCompression(new CompressSettings {
CompressionAlgorithm = CompressionAlgorithm.All
})
.SetupLess(new LessSettings {
Compress = true,
Debug = true
})
.SetupJavaScript(new JavaScriptSettings {
Minify = true
})
.Create();
// Setup BundleProvider
var bundleContext = new AspNetBundleContext(configuration, new DebugBundleDiagnostic());
var bundleProvider = new BundleProvider(bundleContext);
// Init initial bundles
BundleConfig.SetupBundler(bundleProvider);
// Initialize Bundling engine
AspNetBundler.Initialize(bundleProvider);
}
}
}
| 35.66129 | 123 | 0.610131 | [
"MIT"
] | irii/Bundler | Bundler.Example/Global.asax.cs | 2,213 | C# |
using System;
namespace SoliditySHA3Miner.NetworkInterface
{
public delegate void GetMiningParameterStatusEvent(INetworkInterface sender, bool success, MiningParameters miningParameters);
public delegate void NewMessagePrefixEvent(INetworkInterface sender, string messagePrefix);
public delegate void NewTargetEvent(INetworkInterface sender, string target);
public delegate void GetTotalHashrateEvent(INetworkInterface sender, ref ulong totalHashrate);
public interface INetworkInterface : IDisposable
{
event GetMiningParameterStatusEvent OnGetMiningParameterStatusEvent;
event NewMessagePrefixEvent OnNewMessagePrefixEvent;
event NewTargetEvent OnNewTargetEvent;
event GetTotalHashrateEvent OnGetTotalHashrate;
bool IsPool { get; }
ulong SubmittedShares { get; }
ulong RejectedShares { get; }
ulong Difficulty { get; }
string DifficultyHex { get; }
int LastSubmitLatency { get; }
int Latency { get; }
string MinerAddress { get; }
string SubmitURL { get; }
string CurrentChallenge { get; }
ulong GetEffectiveHashrate();
void ResetEffectiveHashrate();
void UpdateMiningParameters();
bool SubmitSolution(string digest, string fromAddress, string challenge, string difficulty, string target, string solution, Miner.IMiner sender);
}
} | 39.222222 | 153 | 0.728754 | [
"MIT"
] | Aristophanes888/SoliditySHA3Miner | SoliditySHA3Miner/NetworkInterface/INetworkInterface.cs | 1,414 | C# |
using Microsoft.Extensions.Localization;
using OwnID.Extensibility.Services;
namespace OwnID.Web
{
/// <summary>
/// Default localization mechanism
/// </summary>
/// <remarks>
/// Uses default and userDefined localizer
/// </remarks>
/// <inheritdoc cref="ILocalizationService" />
public class LocalizationService : ILocalizationService
{
private readonly IStringLocalizer _customLocalizer;
private readonly bool _customWasSet;
private readonly IStringLocalizer _defaultLocalizer;
private readonly bool _disabled = false;
/// <param name="defaultLocalizer">Default localizer provided by OwnId SDK</param>
/// <param name="userDefinedLocalizer">User defined localizer</param>
public LocalizationService(IStringLocalizer defaultLocalizer, IStringLocalizer userDefinedLocalizer = null)
{
_defaultLocalizer = defaultLocalizer;
if (userDefinedLocalizer != null)
{
_customLocalizer = userDefinedLocalizer;
_customWasSet = true;
}
else
{
_customLocalizer = defaultLocalizer;
}
}
public string GetLocalizedString(string key, bool defaultAsAlternative = false)
{
if (_disabled)
return key;
var originalItem = _customLocalizer[key];
if (originalItem.ResourceNotFound && defaultAsAlternative && _customWasSet)
{
var defaultItem = _defaultLocalizer[key];
if (!defaultItem.ResourceNotFound)
return defaultItem.Value;
}
return originalItem.Value;
}
}
} | 32.054545 | 115 | 0.609189 | [
"Apache-2.0",
"MIT"
] | I343796/ownid-server-sdk-net | OwnID.Web/LocalizationService.cs | 1,763 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
// no manager
public class SnHBasketController : MonoBehaviour
{
public Players players;
public int playerID;
private PlayerStats snhPlayerStats;
public SnHGameConstants gameConstants;
// is player engaged with basket now
public int engagedWithPlayer;
// can be stolen from
public bool canBeStolenFromBool;
// basket status
public SpriteRenderer Basket;
// to switch on and off when another player is nearby
public GameObject Unselected;
public GameObject OwnedSelectedCorrect;
public GameObject OwnedSelectedWrong;
public GameObject NotOwnedSelected;
// unselected
public Image UnselectedAvatar;
// owned and selected
public Image OwnedSelectedAvatar;
public Image TPBackground;
public TMP_Text TPCollected;
public Image OtherItem;
public Image OtherBackground;
public TMP_Text OtherCollected;
// not owned and selected
public Image NotOwnedSelectedAvatar;
public GameObject StealBubble;
// sprite inserts
public Sprite emptyBasket;
public Sprite fullBasket;
public List<Sprite> itemSprites;
public void Initialise()
{
engagedWithPlayer = -1;
if (players.GetPlayers().ContainsKey(playerID))
{
snhPlayerStats = players.GetPlayers()[playerID].playerStats;
// set the ownership of the basket
// set the basket to empty
Basket.sprite = emptyBasket;
// set all the avatars
UnselectedAvatar.sprite = snhPlayerStats.playerAvatar;
OwnedSelectedAvatar.sprite = snhPlayerStats.playerAvatar;
NotOwnedSelectedAvatar.sprite = snhPlayerStats.playerAvatar;
// default the states for owned selected
TPCollected.text = formatString(snhPlayerStats.TPCollected);
Debug.Log("Item sprite index: " + gameConstants.OtherIndex.ToString());
OtherItem.sprite = itemSprites[gameConstants.OtherIndex];
OtherCollected.text =
formatString(snhPlayerStats.otherObjectCollected);
// no one interacting with the basket
engagedWithPlayer = -1;
// default to unselected
Unselected.SetActive(true);
OwnedSelectedCorrect.SetActive(false);
OwnedSelectedWrong.SetActive(false);
NotOwnedSelected.SetActive(false);
StealBubble.SetActive(false);
}
else
{
gameObject.SetActive(false);
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player") && engagedWithPlayer == -1)
{
engagedWithPlayer =
collision
.GetComponent<PlayerStatsManager>()
.GetPlayerStats()
.playerID;
if (engagedWithPlayer == playerID)
{
BelongsToPlayer();
}
else
{
DoesNotBelongToPlayer();
CanBeStolenFrom();
}
}
}
public void OnTriggerExit2D(Collider2D collision)
{
if (collision.CompareTag("Player") && engagedWithPlayer != -1)
{
if (
collision
.GetComponent<PlayerStatsManager>()
.GetPlayerStats()
.playerID ==
engagedWithPlayer
)
{
engagedWithPlayer = -1;
// switch back to unselected bubble
Unselected.SetActive(true);
OwnedSelectedCorrect.SetActive(false);
OwnedSelectedWrong.SetActive(false);
NotOwnedSelected.SetActive(false);
StealBubble.SetActive(false);
}
}
}
public void BelongsToPlayer()
{
// display correct bubble
Unselected.SetActive(false);
NotOwnedSelected.SetActive(false);
OwnedSelectedCorrect.SetActive(true);
OwnedSelectedWrong.SetActive(false);
StealBubble.SetActive(false);
}
public void DoesNotBelongToPlayer()
{
// display correct bubble
Unselected.SetActive(false);
NotOwnedSelected.SetActive(true);
OwnedSelectedCorrect.SetActive(false);
OwnedSelectedWrong.SetActive(false);
StealBubble.SetActive(false);
}
public void WrongPickupAdded()
{
OwnedSelectedCorrect.SetActive(false);
OwnedSelectedWrong.SetActive(true);
}
public void IsPickedUp()
{
engagedWithPlayer = -1;
}
// confirm can be stolen from
public PickUpTypeEnum StolenFrom()
{
// when there are both TP and other to steal from
if (
snhPlayerStats.TPCollected != 0 &&
snhPlayerStats.otherObjectCollected != 0
)
{
int selected = Random.Range(0, 1);
if (selected == 0)
{
snhPlayerStats.TPCollected -= 1;
Debug.Log("TP stolen from" + playerID.ToString());
return PickUpTypeEnum.toiletPaper;
}
else
{
snhPlayerStats.otherObjectCollected -= 1;
Debug.Log("Other object stolen from" + playerID.ToString());
return (PickUpTypeEnum) gameConstants.OtherIndex;
}
} // only can steal toilet paper
else if (snhPlayerStats.TPCollected != 0)
{
snhPlayerStats.TPCollected -= 1;
Debug.Log("TP stolen from" + playerID.ToString());
return PickUpTypeEnum.toiletPaper;
}
else
// only can steal other object
{
snhPlayerStats.otherObjectCollected -= 1;
Debug.Log("Other object stolen from" + playerID.ToString());
return (PickUpTypeEnum) gameConstants.OtherIndex;
}
}
// checks if the basket can be stolen from
public void CanBeStolenFrom()
{
int totalItems =
snhPlayerStats.TPCollected + snhPlayerStats.otherObjectCollected;
if (totalItems > 0)
{
StealBubble.SetActive(true);
canBeStolenFromBool = true;
}
else
{
StealBubble.SetActive(false);
canBeStolenFromBool = false;
}
}
public void Update()
{
// refresh the list for this basket
TPCollected.text = formatString(snhPlayerStats.TPCollected);
OtherCollected.text = formatString(snhPlayerStats.otherObjectCollected);
// set the background colour to indicate if reached target numbers
if (snhPlayerStats.TPCollected == gameConstants.CollectTP)
{
TPBackground.color = gameConstants.completeBackgroundColor;
}
else
{
TPBackground.color = gameConstants.incompleteBackgroundColor;
}
if (snhPlayerStats.otherObjectCollected == gameConstants.CollectOther)
{
OtherBackground.color = gameConstants.completeBackgroundColor;
}
else
{
OtherBackground.color = gameConstants.incompleteBackgroundColor;
}
// check if there are items in the basket
int total_items =
snhPlayerStats.TPCollected + snhPlayerStats.otherObjectCollected;
if (total_items == 0)
{
Basket.sprite = emptyBasket;
}
else
{
Basket.sprite = fullBasket;
}
}
private string formatString(int score)
{
if (score.ToString().Length == 1)
{
return "0" + score.ToString();
}
else
{
return score.ToString();
}
}
}
| 28.010563 | 83 | 0.586298 | [
"MIT"
] | xmliszt/CB2.0 | CB2.0/Assets/Scripts/Snatch&Hoard/PrefabControllers/SnHBasketController.cs | 7,955 | C# |
using System.Web.Mvc;
namespace GroupDocs.Total.MVC.Controllers
{
/// <summary>
/// Search Web page controller
/// </summary>
public class SearchController : Controller
{
public ActionResult Index()
{
return View("Index");
}
}
} | 19.8 | 46 | 0.558923 | [
"MIT"
] | faizin87/GroupDocs.Total-for-.NET | Demos/MVC/src/Controllers/SearchController.cs | 299 | C# |
using System;
using MediatR;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands
{
// DDD and CQRS patterns comment: Note that it is recommended to implement immutable Commands
// In this case, its immutability is achieved by having all the setters as private
// plus only being able to update the data just once, when creating the object through its constructor.
// References on Immutable Commands:
// http://cqrs.nu/Faq
// https://docs.spine3.org/motivation/immutability.html
// http://blog.gauffin.org/2012/06/griffin-container-introducing-command-support/
// https://msdn.microsoft.com/en-us/library/bb383979.aspx
[DataContract]
public class CreateOrderCommand
:IAsyncRequest<bool>
{
[DataMember]
private readonly List<OrderItemDTO> _orderItems;
[DataMember]
public string City { get; private set; }
[DataMember]
public string Street { get; private set; }
[DataMember]
public string State { get; private set; }
[DataMember]
public string Country { get; private set; }
[DataMember]
public string ZipCode { get; private set; }
[DataMember]
public string CardNumber { get; private set; }
[DataMember]
public string CardHolderName { get; private set; }
[DataMember]
public DateTime CardExpiration { get; private set; }
[DataMember]
public string CardSecurityNumber { get; private set; }
[DataMember]
public int CardTypeId { get; private set; }
[DataMember]
public IEnumerable<OrderItemDTO> OrderItems => _orderItems;
public void AddOrderItem(OrderItemDTO item)
{
_orderItems.Add(item);
}
public CreateOrderCommand()
{
_orderItems = new List<OrderItemDTO>();
}
public CreateOrderCommand(string city, string street, string state, string country, string zipcode,
string cardNumber, string cardHolderName, DateTime cardExpiration,
string cardSecurityNumber, int cardTypeId) : this()
{
City = city;
Street = street;
State = state;
Country = country;
ZipCode = zipcode;
CardNumber = cardNumber;
CardHolderName = cardHolderName;
CardSecurityNumber = cardSecurityNumber;
CardTypeId = cardTypeId;
CardExpiration = cardExpiration;
}
public class OrderItemDTO
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public decimal Discount { get; set; }
public int Units { get; set; }
public string PictureUrl { get; set; }
}
}
}
| 29.9 | 107 | 0.618395 | [
"MIT"
] | HydAu/eShopOnContainers | src/Services/Ordering/Ordering.API/Application/Commands/CreateOrderCommand.cs | 2,992 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Entities.DataTransferObjects.Writable.Manipulatable
{
public abstract class CompanyForManipulationDTOW
{
[Required(ErrorMessage = "Company name is a required field.")]
[MaxLength(60, ErrorMessage = "Maximum length for the name is 60 characters")]
public string Name { get; set; }
[Required(ErrorMessage = "Company address is a required field.")]
[MaxLength(150, ErrorMessage = "Maximum length for the name is 150 characters")]
public string Address { get; set; }
public string Country { get; set; }
// To create children rexources(employees) together with the parent(company)
public IEnumerable<EmployeeDTOW> Employees { get; set; }
}
}
| 40.65 | 88 | 0.698647 | [
"MIT"
] | IfeanyiNwachukwu/EmployeeRegisterAPI | Entities/DataTransferObjects/Writable/Manipulatable/CompanyForManipulationDTOW.cs | 815 | C# |
// WARNING
//
// This file has been generated automatically by MonoDevelop to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using MonoMac.Foundation;
namespace NBTExplorer.Mac
{
[Register ("CancelFindWindowController")]
partial class CancelFindWindowController
{
[Action ("ActionCancel:")]
partial void ActionCancel (MonoMac.Foundation.NSObject sender);
void ReleaseDesignerOutlets ()
{
}
}
[Register ("CancelFindWindow")]
partial class CancelFindWindow
{
void ReleaseDesignerOutlets ()
{
}
}
}
| 20.612903 | 81 | 0.735524 | [
"MIT"
] | 3prm3/NBTExplorer-Reloaded | NBTExplorer/Mac/CancelFindWindow.designer.cs | 639 | C# |
using System.IdentityModel.Tokens.Jwt;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Skoruba.AuditLogging.EntityFramework.Entities;
using Skoruba.IdentityServer4.Admin.BusinessLogic.Identity.Dtos.Identity;
using SkorubaIdentityServer4Admin.Admin.Configuration.Interfaces;
using SkorubaIdentityServer4Admin.Admin.EntityFramework.Shared.DbContexts;
using SkorubaIdentityServer4Admin.Admin.EntityFramework.Shared.Entities.Identity;
using SkorubaIdentityServer4Admin.Admin.Helpers;
using SkorubaIdentityServer4Admin.Admin.Configuration;
using SkorubaIdentityServer4Admin.Admin.Configuration.Constants;
using System;
using Microsoft.AspNetCore.DataProtection;
using SkorubaIdentityServer4Admin.Shared.Dtos;
using SkorubaIdentityServer4Admin.Shared.Dtos.Identity;
using SkorubaIdentityServer4Admin.Shared.Helpers;
namespace SkorubaIdentityServer4Admin.Admin
{
public class Startup
{
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
HostingEnvironment = env;
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IWebHostEnvironment HostingEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
var rootConfiguration = CreateRootConfiguration();
services.AddSingleton(rootConfiguration);
// Add DbContexts for Asp.Net Core Identity, Logging and IdentityServer - Configuration store and Operational store
RegisterDbContexts(services);
// Save data protection keys to db, using a common application name shared between Admin and STS
services.AddDataProtection()
.SetApplicationName("SkorubaIdentityServer4Admin")
.PersistKeysToDbContext<IdentityServerDataProtectionDbContext>();
// Add email senders which is currently setup for SendGrid and SMTP
services.AddEmailSenders(Configuration);
// Add Asp.Net Core Identity Configuration and OpenIdConnect auth as well
RegisterAuthentication(services);
// Add HSTS options
RegisterHstsOptions(services);
// Add exception filters in MVC
services.AddMvcExceptionFilters();
// Add all dependencies for IdentityServer Admin
services.AddAdminServices<IdentityServerConfigurationDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext>();
// Add all dependencies for Asp.Net Core Identity
// If you want to change primary keys or use another db model for Asp.Net Core Identity:
services.AddAdminAspNetIdentityServices<AdminIdentityDbContext, IdentityServerPersistedGrantDbContext,
IdentityUserDto, IdentityRoleDto, UserIdentity, UserIdentityRole, string, UserIdentityUserClaim, UserIdentityUserRole,
UserIdentityUserLogin, UserIdentityRoleClaim, UserIdentityUserToken,
IdentityUsersDto, IdentityRolesDto, IdentityUserRolesDto,
IdentityUserClaimsDto, IdentityUserProviderDto, IdentityUserProvidersDto, IdentityUserChangePasswordDto,
IdentityRoleClaimsDto, IdentityUserClaimDto, IdentityRoleClaimDto>();
// Add all dependencies for Asp.Net Core Identity in MVC - these dependencies are injected into generic Controllers
// Including settings for MVC and Localization
// If you want to change primary keys or use another db model for Asp.Net Core Identity:
services.AddMvcWithLocalization<IdentityUserDto, IdentityRoleDto,
UserIdentity, UserIdentityRole, string, UserIdentityUserClaim, UserIdentityUserRole,
UserIdentityUserLogin, UserIdentityRoleClaim, UserIdentityUserToken,
IdentityUsersDto, IdentityRolesDto, IdentityUserRolesDto,
IdentityUserClaimsDto, IdentityUserProviderDto, IdentityUserProvidersDto, IdentityUserChangePasswordDto,
IdentityRoleClaimsDto, IdentityUserClaimDto, IdentityRoleClaimDto>(Configuration);
// Add authorization policies for MVC
RegisterAuthorization(services);
// Add audit logging
services.AddAuditEventLogging<AdminAuditLogDbContext, AuditLog>(Configuration);
services.AddIdSHealthChecks<IdentityServerConfigurationDbContext, IdentityServerPersistedGrantDbContext, AdminIdentityDbContext, AdminLogDbContext, AdminAuditLogDbContext, IdentityServerDataProtectionDbContext>(Configuration, rootConfiguration.AdminConfiguration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCookiePolicy();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UsePathBase(Configuration.GetValue<string>("BasePath"));
// Add custom security headers
app.UseSecurityHeaders();
app.UseStaticFiles();
UseAuthentication(app);
// Use Localization
app.ConfigureLocalization();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoint =>
{
endpoint.MapDefaultControllerRoute();
endpoint.MapHealthChecks("/health", new HealthCheckOptions
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});
});
}
public virtual void RegisterDbContexts(IServiceCollection services)
{
services.RegisterDbContexts<AdminIdentityDbContext, IdentityServerConfigurationDbContext, IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext, IdentityServerDataProtectionDbContext>(Configuration);
}
public virtual void RegisterAuthentication(IServiceCollection services)
{
var rootConfiguration = CreateRootConfiguration();
services.AddAuthenticationServices<AdminIdentityDbContext, UserIdentity, UserIdentityRole>(Configuration);
}
public virtual void RegisterAuthorization(IServiceCollection services)
{
var rootConfiguration = CreateRootConfiguration();
services.AddAuthorizationPolicies(rootConfiguration);
}
public virtual void UseAuthentication(IApplicationBuilder app)
{
app.UseAuthentication();
}
public virtual void RegisterHstsOptions(IServiceCollection services)
{
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(365);
});
}
protected IRootConfiguration CreateRootConfiguration()
{
var rootConfiguration = new RootConfiguration();
Configuration.GetSection(ConfigurationConsts.AdminConfigurationKey).Bind(rootConfiguration.AdminConfiguration);
Configuration.GetSection(ConfigurationConsts.IdentityDataConfigurationKey).Bind(rootConfiguration.IdentityDataConfiguration);
Configuration.GetSection(ConfigurationConsts.IdentityServerDataConfigurationKey).Bind(rootConfiguration.IdentityServerDataConfiguration);
return rootConfiguration;
}
}
}
| 44.638889 | 276 | 0.701805 | [
"MIT"
] | CC-Expertise/IdentityServer4.Admin | templates/template-publish/content/src/SkorubaIdentityServer4Admin.Admin/Startup.cs | 8,037 | C# |
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using Moryx.AbstractionLayer.Products;
using Moryx.Configuration;
using Moryx.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Moryx.Products.Management.Modification
{
/// <summary>
/// Specialized serialization that only considers properties of derived classes
/// </summary>
internal class PartialSerialization<T> : PossibleValuesSerialization
where T : class
{
/// <summary>
/// Properties that shall be excluded from the generic collection
/// </summary>
private static readonly string[] FilteredProperties = typeof(T).GetProperties().Select(p => p.Name).ToArray();
public PartialSerialization() : base(null, new EmptyValueProvider())
{
}
/// <see cref="T:Moryx.Serialization.ICustomSerialization"/>
public override IEnumerable<PropertyInfo> GetProperties(Type sourceType)
{
// Only simple properties not defined in the base
return EntrySerializeSerialization.Instance.GetProperties(sourceType)
.Where(SimpleProp);
}
protected bool SimpleProp(PropertyInfo prop)
{
// Skip reference or domain model properties
var type = prop.PropertyType;
if (type == typeof(ProductFile) ||
typeof(IProductType).IsAssignableFrom(type) ||
typeof(IProductPartLink).IsAssignableFrom(type) ||
typeof(IEnumerable<IProductPartLink>).IsAssignableFrom(type))
return false;
// Filter default properties
if (FilteredProperties.Contains(prop.Name))
return false;
return true;
}
/// <see cref="T:Moryx.Serialization.ICustomSerialization"/>
public override IEnumerable<MappedProperty> WriteFilter(Type sourceType, IEnumerable<Entry> encoded)
{
// Only update properties with values from client
return base.WriteFilter(sourceType, encoded).Where(mapped => mapped.Entry != null);
}
private class EmptyValueProvider : IEmptyPropertyProvider
{
public void FillEmpty(object obj)
{
ValueProviderExecutor.Execute(obj, new ValueProviderExecutorSettings().AddDefaultValueProvider());
}
}
}
}
| 35.785714 | 118 | 0.642315 | [
"Apache-2.0"
] | milmilkat/MORYX-AbstractionLayer | src/Moryx.Products.Management/Modifications/PartialSerialization.cs | 2,505 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Acr.UserDialogs.Forms;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Samples.Infrastructure;
using Samples.Models;
using Shiny;
using Shiny.Push;
namespace Samples.Push
{
public class PushViewModel : AbstractLogViewModel<CommandItem>
{
readonly SampleSqliteConnection conn;
readonly IUserDialogs dialogs;
readonly IPushManager? pushManager;
public PushViewModel(SampleSqliteConnection conn,
IUserDialogs dialogs,
IPushManager? pushManager = null) : base(dialogs)
{
this.conn = conn;
this.dialogs = dialogs;
this.pushManager = pushManager;
this.CheckPermission = this.Create(async () =>
{
var status = await pushManager.RequestAccess();
this.AccessStatus = status.Status;
this.RegToken = status.RegistrationToken;
});
this.UnRegister = this.Create(async () =>
{
await pushManager.UnRegister();
this.AccessStatus = AccessState.Disabled;
this.RegToken = String.Empty;
});
}
public override async void OnAppearing()
{
base.OnAppearing();
if (this.pushManager == null)
{
await this.dialogs.Alert("Push not supported");
}
else
{
this.pushManager
.WhenReceived()
.SubOnMainThread(_ => ((ICommand)this.Load).Execute(null))
.DisposedBy(this.DeactivateWith);
}
}
public ICommand CheckPermission { get; }
public ICommand UnRegister { get; }
[Reactive] public string RegToken { get; private set; }
[Reactive] public AccessState AccessStatus { get; private set; }
protected override Task ClearLogs() => this.conn.DeleteAllAsync<PushEvent>();
protected override async Task<IEnumerable<CommandItem>> LoadLogs()
{
var data = await this.conn
.PushEvents
.OrderByDescending(x => x.Timestamp)
.ToListAsync();
return data.Select(x => new CommandItem
{
Text = x.Payload,
Detail = x.Timestamp.ToLocalTime().ToString()
});
}
ICommand Create(Func<Task> create) => ReactiveCommand.CreateFromTask(async () =>
{
if (this.pushManager == null)
{
await this.dialogs.Alert("Push not supported");
return;
}
await create();
});
}
}
| 29.90625 | 88 | 0.546499 | [
"MIT"
] | shuheydev/shinysamples | Samples/Push/PushViewModel.cs | 2,873 | C# |
using Abp.Authorization;
using Abp.Zero.SampleApp.MultiTenancy;
using Abp.Zero.SampleApp.Roles;
using Abp.Zero.SampleApp.Users;
namespace Abp.Zero.SampleApp.Authorization
{
public class AppPermissionChecker : PermissionChecker<Tenant, Role, User>
{
public AppPermissionChecker(UserManager userManager)
: base(userManager)
{
}
}
}
| 23.75 | 77 | 0.707895 | [
"MIT"
] | MaikelE/module-zero-fork | src/Tests/Abp.Zero.SampleApp/Authorization/AppPermissionChecker.cs | 382 | C# |
using System;
namespace Framework.DomainDriven.BLL
{
public interface IBLLOperationEventListener<TDomainObject, TOperation> : IForceEventContainer<TDomainObject, TOperation>
where TDomainObject : class
where TOperation : struct, Enum
{
event EventHandler<DomainOperationEventArgs<TDomainObject, TOperation>> OperationProcessed;
}
}
| 31.75 | 125 | 0.737533 | [
"MIT"
] | Luxoft/BSSFramework | src/_DomainDriven/Framework.DomainDriven.Core/BLL/Events/Operation/_Base/IBLLOperationEventListener.cs | 372 | C# |
using System;
namespace UAOOI.Networking.SemanticData.Encoding
{
internal static class CommonDefinitions
{
/// <summary>
/// The time base DateTime to calculate ticks sent over wire for UA binary representation.
/// </summary>
public static readonly DateTime TimeBase = new DateTime(1601, 1, 1); //
public static readonly DateTime TimeBaseMaxValue = new DateTime(9999, 12, 31, 23, 59, 59); //
/// <summary>
/// Decode the UA date and time form ticks.
/// </summary>
/// <param name="ticks">The ticks as defined in <see cref="DateTime"/>.</param>
/// <returns>Decoded from the stream <see cref="DateTime"/>.</returns>
internal static DateTime GetUADateTime(this Int64 ticks)
{
if (ticks == Int64.MaxValue)
return TimeBaseMaxValue;
if (ticks >= (Int64.MaxValue - TimeBase.Ticks))
return TimeBaseMaxValue;
ticks += TimeBase.Ticks;
if (ticks >= DateTime.MaxValue.Ticks)
return DateTime.MaxValue;
if (ticks < TimeBase.Ticks)
return DateTime.MinValue;
return new DateTime(ticks, DateTimeKind.Utc);
}
/// <summary>
/// Encode the UA <see cref="DateTime"/> as ticks is relation to <see cref="TimeBase"/>.
/// </summary>
/// <param name="value">The value to be encoded.</param>
/// <returns>Returns ticks as defined in <see cref="DateTime"/>.</returns>
internal static Int64 GetUADataTimeTicks(this DateTime value)
{
if (value.Kind == DateTimeKind.Local)
value = value.ToUniversalTime();
long _ticks = value.Ticks;
if (_ticks >= TimeBaseMaxValue.Ticks)
_ticks = Int64.MaxValue;
else
{
_ticks -= TimeBase.Ticks;
if (_ticks <= 0)
_ticks = 0;
}
return _ticks;
}
/// <summary>
/// Reads the <see cref="Guid"/> form a buffer using <see cref="IBinaryDecoder"/>.
/// </summary>
/// <param name="decoder">The decoder to be used to recover data from a buffer.</param>
/// <returns>Guid.</returns>
internal static Guid ReadGuid(this IBinaryDecoder decoder)
{
int m_EncodedGuidLength = 16;
byte[] bytes = decoder.ReadBytes(m_EncodedGuidLength);
return new Guid(bytes);
}
}
}
| 34.121212 | 97 | 0.629218 | [
"MIT"
] | BiancoRoyal/OPC-UA-OOI | Networking/SemanticData/Encoding/CommonDefinitions.cs | 2,254 | C# |
namespace _05._Kings_Gambit_Extended.Interfaces
{
public interface IDieable
{
bool IsAlive { get; }
int Health { get; }
void TakeDamage();
void Die();
}
} | 15.538462 | 48 | 0.564356 | [
"MIT"
] | thelad43/CSharp-OOP-Advanced-SoftUni | 12. Object Communication and Events - Exercise/05. Kings Gambit Extended/Interfaces/IDieable.cs | 204 | C# |
namespace NEventStore.Benchmark.Support
{
internal static class EventStoreHelpers
{
internal static IStoreEvents WireupEventStore()
{
return Wireup.Init()
// .LogToOutputWindow(LogLevel.Verbose)
// .LogToConsoleWindow(LogLevel.Verbose)
.UsingInMemoryPersistence()
.InitializeStorageEngine()
#if !NETSTANDARD1_6 && !NETSTANDARD2_0
.TrackPerformanceInstance("example")
#endif
// .HookIntoPipelineUsing(new[] { new AuthorizationPipelineHook() })
.Build();
}
}
}
| 30.65 | 83 | 0.595432 | [
"MIT"
] | tralivali1234/NEventStore | src/NEventStore.Benchmark/Support/EventStoreHelpers.cs | 615 | C# |
// Copyright 2014-2017 ClassicalSharp | Licensed under BSD-3
using System;
using ClassicalSharp.Model;
using ClassicalSharp.Physics;
using OpenTK;
using BlockID = System.UInt16;
namespace ClassicalSharp.Entities {
/// <summary> Entity component that performs collision detection. </summary>
public sealed class PhysicsComponent {
bool useLiquidGravity = false; // used by BlockDefinitions.
bool canLiquidJump = true;
internal bool jumping;
internal int multiJumps;
Entity entity;
Game game;
internal float jumpVel = 0.42f, userJumpVel = 0.42f, serverJumpVel = 0.42f;
internal HacksComponent hacks;
internal CollisionsComponent collisions;
public PhysicsComponent(Game game, Entity entity) {
this.game = game;
this.entity = entity;
}
public void UpdateVelocityState() {
if (hacks.Floating) {
entity.Velocity.Y = 0; // eliminate the effect of gravity
int dir = (hacks.FlyingUp || jumping) ? 1 : (hacks.FlyingDown ? -1 : 0);
entity.Velocity.Y += 0.12f * dir;
if (hacks.Speeding && hacks.CanSpeed) entity.Velocity.Y += 0.12f * dir;
if (hacks.HalfSpeeding && hacks.CanSpeed) entity.Velocity.Y += 0.06f * dir;
} else if (jumping && entity.TouchesAnyRope() && entity.Velocity.Y > 0.02f) {
entity.Velocity.Y = 0.02f;
}
if (!jumping) {
canLiquidJump = false; return;
}
bool touchWater = entity.TouchesAnyWater();
bool touchLava = entity.TouchesAnyLava();
if (touchWater || touchLava) {
AABB bounds = entity.Bounds;
int feetY = Utils.Floor(bounds.Min.Y), bodyY = feetY + 1;
int headY = Utils.Floor(bounds.Max.Y);
if (bodyY > headY) bodyY = headY;
bounds.Max.Y = bounds.Min.Y = feetY;
bool liquidFeet = entity.TouchesAny(bounds, touchesLiquid);
bounds.Min.Y = Math.Min(bodyY, headY);
bounds.Max.Y = Math.Max(bodyY, headY);
bool liquidRest = entity.TouchesAny(bounds, touchesLiquid);
bool pastJumpPoint = liquidFeet && !liquidRest && (entity.Position.Y % 1 >= 0.4);
if (!pastJumpPoint) {
canLiquidJump = true;
entity.Velocity.Y += 0.04f;
if (hacks.Speeding && hacks.CanSpeed) entity.Velocity.Y += 0.04f;
if (hacks.HalfSpeeding && hacks.CanSpeed) entity.Velocity.Y += 0.02f;
} else if (pastJumpPoint) {
// either A) jump bob in water B) climb up solid on side
if (collisions.HorizontalCollision)
entity.Velocity.Y += touchLava ? 0.30f : 0.13f;
else if (canLiquidJump)
entity.Velocity.Y += touchLava ? 0.20f : 0.10f;
canLiquidJump = false;
}
} else if (useLiquidGravity) {
entity.Velocity.Y += 0.04f;
if (hacks.Speeding && hacks.CanSpeed) entity.Velocity.Y += 0.04f;
if (hacks.HalfSpeeding && hacks.CanSpeed) entity.Velocity.Y += 0.02f;
canLiquidJump = false;
} else if (entity.TouchesAnyRope()) {
entity.Velocity.Y += (hacks.Speeding && hacks.CanSpeed) ? 0.15f : 0.10f;
canLiquidJump = false;
} else if (entity.onGround) {
DoNormalJump();
}
}
public void DoNormalJump() {
if (jumpVel == 0 || hacks.MaxJumps == 0) return;
entity.Velocity.Y = jumpVel;
if (hacks.Speeding && hacks.CanSpeed) entity.Velocity.Y += jumpVel;
if (hacks.HalfSpeeding && hacks.CanSpeed) entity.Velocity.Y += jumpVel / 2;
canLiquidJump = false;
}
static Predicate<BlockID> touchesLiquid = IsLiquidCollide;
static bool IsLiquidCollide(BlockID block) { return BlockInfo.Collide[block] == CollideType.Liquid; }
static Vector3 waterDrag = new Vector3(0.8f, 0.8f, 0.8f),
lavaDrag = new Vector3(0.5f, 0.5f, 0.5f),
ropeDrag = new Vector3(0.5f, 0.85f, 0.5f);
const float liquidGrav = 0.02f, ropeGrav = 0.034f;
public void PhysicsTick(Vector3 vel) {
if (hacks.Noclip) entity.onGround = false;
float baseSpeed = GetBaseSpeed();
float verSpeed = baseSpeed * Math.Max(1, GetSpeed(8f) / 5);
float horSpeed = baseSpeed * hacks.BaseHorSpeed * GetSpeed(8f/5);
// previously horSpeed used to be multiplied by factor of 0.02 in last case
// it's now multiplied by 0.1, so need to divide by 5 so user speed modifier comes out same
// TODO: this is a temp fix to avoid crashing for high horizontal speed
if (horSpeed > 75.0f) horSpeed = 75.0f;
bool womSpeedBoost = hacks.CanDoubleJump && hacks.WOMStyleHacks;
if (!hacks.Floating && womSpeedBoost) {
if (multiJumps == 1) { horSpeed *= 46.5f; verSpeed *= 7.5f; }
else if (multiJumps > 1) { horSpeed *= 93f; verSpeed *= 10f; }
}
if (entity.TouchesAnyWater() && !hacks.Floating) {
MoveNormal(vel, 0.02f * horSpeed, waterDrag, liquidGrav, verSpeed);
} else if (entity.TouchesAnyLava() && !hacks.Floating) {
MoveNormal(vel, 0.02f * horSpeed, lavaDrag, liquidGrav, verSpeed);
} else if (entity.TouchesAnyRope() && !hacks.Floating) {
MoveNormal(vel, 0.02f * 1.7f, ropeDrag, ropeGrav, verSpeed);
} else {
float factor = hacks.Floating || entity.onGround ? 0.1f : 0.02f;
float gravity = useLiquidGravity ? liquidGrav : entity.Model.Gravity;
if (hacks.Floating) {
MoveFlying(vel, factor * horSpeed, entity.Model.Drag, gravity, verSpeed);
} else {
MoveNormal(vel, factor * horSpeed, entity.Model.Drag, gravity, verSpeed);
}
if (OnIce(entity) && !hacks.Floating) {
// limit components to +-0.25f by rescaling vector to [-0.25, 0.25]
if (Math.Abs(entity.Velocity.X) > 0.25f || Math.Abs(entity.Velocity.Z) > 0.25f) {
float scale = Math.Min(
Math.Abs(0.25f / entity.Velocity.X), Math.Abs(0.25f / entity.Velocity.Z));
entity.Velocity.X *= scale;
entity.Velocity.Z *= scale;
}
} else if (entity.onGround || hacks.Flying) {
entity.Velocity = Utils.Mul(entity.Velocity, entity.Model.GroundFriction); // air drag or ground friction
}
}
if (entity.onGround) multiJumps = 0;
}
bool OnIce(Entity entity) {
Vector3 under = entity.Position; under.Y -= 0.01f;
if (BlockInfo.ExtendedCollide[GetBlock(under)] == CollideType.Ice) return true;
AABB bounds = entity.Bounds;
bounds.Min.Y -= 0.01f; bounds.Max.Y = bounds.Min.Y;
return entity.TouchesAny(bounds, touchesSlipperyIce);
}
BlockID GetBlock(Vector3 coords) {
return game.World.SafeGetBlock(Vector3I.Floor(coords));
}
static Predicate<BlockID> touchesSlipperyIce = IsSlipperyIce;
static bool IsSlipperyIce(BlockID b) { return BlockInfo.ExtendedCollide[b] == CollideType.SlipperyIce; }
void MoveHor(Vector3 vel, float factor) {
float dist = (float)Math.Sqrt(vel.X * vel.X + vel.Z * vel.Z);
if (dist < 0.00001f) return;
if (dist < 1) dist = 1;
entity.Velocity += vel * (factor / dist);
}
void MoveFlying(Vector3 vel, float factor, Vector3 drag, float gravity, float yMul) {
MoveHor(vel, factor);
float yVel = (float)Math.Sqrt(entity.Velocity.X * entity.Velocity.X + entity.Velocity.Z * entity.Velocity.Z);
// make horizontal speed the same as vertical speed.
if ((vel.X != 0 || vel.Z != 0) && yVel > 0.001f) {
entity.Velocity.Y = 0;
yMul = 1;
if (hacks.FlyingUp || jumping) entity.Velocity.Y += yVel;
if (hacks.FlyingDown) entity.Velocity.Y -= yVel;
}
Move(drag, gravity, yMul);
}
void MoveNormal(Vector3 vel, float factor, Vector3 drag, float gravity, float yMul) {
MoveHor(vel, factor);
Move(drag, gravity, yMul);
}
void Move(Vector3 drag, float gravity, float yMul) {
entity.Velocity.Y *= yMul;
if (!hacks.Noclip)
collisions.MoveAndWallSlide();
entity.Position += entity.Velocity;
entity.Velocity.Y /= yMul;
entity.Velocity = Utils.Mul(entity.Velocity, drag);
entity.Velocity.Y -= gravity;
}
float GetSpeed(float speedMul) {
float factor = hacks.Floating ? speedMul : 1, speed = factor;
if (hacks.Speeding && hacks.CanSpeed) speed += factor * hacks.SpeedMultiplier;
if (hacks.HalfSpeeding && hacks.CanSpeed) speed += factor * hacks.SpeedMultiplier / 2;
return hacks.CanSpeed ? speed : Math.Min(speed, 1.0f);
}
const float inf = float.PositiveInfinity;
float GetBaseSpeed() {
AABB bounds = entity.Bounds;
useLiquidGravity = false;
float baseModifier = LowestModifier(bounds, false);
bounds.Min.Y -= 0.5f/16f; // also check block standing on
float solidModifier = LowestModifier(bounds, true);
if (baseModifier == inf && solidModifier == inf) return 1;
return baseModifier == inf ? solidModifier : baseModifier;
}
float LowestModifier(AABB bounds, bool checkSolid) {
Vector3I min = Vector3I.Floor(bounds.Min);
Vector3I max = Vector3I.Floor(bounds.Max);
float modifier = inf;
AABB blockBB = default(AABB);
min.X = min.X < 0 ? 0 : min.X; max.X = max.X > game.World.MaxX ? game.World.MaxX : max.X;
min.Y = min.Y < 0 ? 0 : min.Y; max.Y = max.Y > game.World.MaxY ? game.World.MaxY : max.Y;
min.Z = min.Z < 0 ? 0 : min.Z; max.Z = max.Z > game.World.MaxZ ? game.World.MaxZ : max.Z;
for (int y = min.Y; y <= max.Y; y++)
for (int z = min.Z; z <= max.Z; z++)
for (int x = min.X; x <= max.X; x++)
{
BlockID block = game.World.GetBlock(x, y, z);
if (block == 0) continue;
byte collide = BlockInfo.Collide[block];
if (collide == CollideType.Solid && !checkSolid) continue;
Vector3 v = new Vector3(x, y, z);
blockBB.Min = v + BlockInfo.MinBB[block];
blockBB.Max = v + BlockInfo.MaxBB[block];
if (!blockBB.Intersects(bounds)) continue;
modifier = Math.Min(modifier, BlockInfo.SpeedMultiplier[block]);
if (BlockInfo.ExtendedCollide[block] == CollideType.Liquid)
useLiquidGravity = true;
}
return modifier;
}
/// <summary> Calculates the jump velocity required such that when a client presses
/// the jump binding they will be able to jump up to the given height. </summary>
internal void CalculateJumpVelocity(bool userVel, float jumpHeight) {
jumpVel = 0;
if (jumpHeight == 0) return;
if (jumpHeight >= 256) jumpVel = 10.0f;
if (jumpHeight >= 512) jumpVel = 16.5f;
if (jumpHeight >= 768) jumpVel = 22.5f;
while (GetMaxHeight(jumpVel) <= jumpHeight) { jumpVel += 0.001f; }
if (userVel) userJumpVel = jumpVel;
}
public static double GetMaxHeight(float u) {
// equation below comes from solving diff(x(t, u))= 0
// We only work in discrete timesteps, so test both rounded up and down.
double t = 49.49831645 * Math.Log(0.247483075 * u + 0.9899323);
return Math.Max(YPosAt((int)t, u), YPosAt((int)t + 1, u));
}
static double YPosAt(int t, float u) {
// v(t, u) = (4 + u) * (0.98^t) - 4, where u = initial velocity
// x(t, u) = Σv(t, u) from 0 to t (since we work in discrete timesteps)
// plugging into Wolfram Alpha gives 1 equation as
// (0.98^t) * (-49u - 196) - 4t + 50u + 196
double a = Math.Exp(-0.0202027 * t); //~0.98^t
return a * (-49 * u - 196) - 4 * t + 50 * u + 196;
}
public void DoEntityPush() {
for (int id = 0; id < EntityList.MaxCount; id++) {
Entity other = game.Entities.List[id];
if (other == null || other == entity) continue;
if (!other.Model.Pushes) continue;
bool yIntersects =
entity.Position.Y <= (other.Position.Y + other.Size.Y) &&
other.Position.Y <= (entity.Position.Y + entity.Size.Y);
if (!yIntersects) continue;
float dx = other.Position.X - entity.Position.X;
float dz = other.Position.Z - entity.Position.Z;
float dist = dx * dx + dz * dz;
if (dist < 0.002f || dist > 1f) continue; // TODO: range needs to be lower?
Vector3 dir = Vector3.Normalize(dx, 0, dz);
float pushStrength = (1 - dist) / 32f; // TODO: should be 24/25
entity.Velocity -= dir * pushStrength;
}
}
}
} | 38.980519 | 113 | 0.635182 | [
"BSD-3-Clause"
] | Andresian/ClassicalSharp | ClassicalSharp/Entities/Components/PhysicsComponent.cs | 11,702 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v6/services/campaign_extension_setting_service.proto
// </auto-generated>
// Original file comments:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
//
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace Google.Ads.GoogleAds.V6.Services {
/// <summary>
/// Service to manage campaign extension settings.
/// </summary>
public static partial class CampaignExtensionSettingService
{
static readonly string __ServiceName = "google.ads.googleads.v6.services.CampaignExtensionSettingService";
static void __Helper_SerializeMessage(global::Google.Protobuf.IMessage message, grpc::SerializationContext context)
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (message is global::Google.Protobuf.IBufferMessage)
{
context.SetPayloadLength(message.CalculateSize());
global::Google.Protobuf.MessageExtensions.WriteTo(message, context.GetBufferWriter());
context.Complete();
return;
}
#endif
context.Complete(global::Google.Protobuf.MessageExtensions.ToByteArray(message));
}
static class __Helper_MessageCache<T>
{
public static readonly bool IsBufferMessage = global::System.Reflection.IntrospectionExtensions.GetTypeInfo(typeof(global::Google.Protobuf.IBufferMessage)).IsAssignableFrom(typeof(T));
}
static T __Helper_DeserializeMessage<T>(grpc::DeserializationContext context, global::Google.Protobuf.MessageParser<T> parser) where T : global::Google.Protobuf.IMessage<T>
{
#if !GRPC_DISABLE_PROTOBUF_BUFFER_SERIALIZATION
if (__Helper_MessageCache<T>.IsBufferMessage)
{
return parser.ParseFrom(context.PayloadAsReadOnlySequence());
}
#endif
return parser.ParseFrom(context.PayloadAsNewBuffer());
}
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest> __Marshaller_google_ads_googleads_v6_services_GetCampaignExtensionSettingRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest.Parser));
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting> __Marshaller_google_ads_googleads_v6_resources_CampaignExtensionSetting = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting.Parser));
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest> __Marshaller_google_ads_googleads_v6_services_MutateCampaignExtensionSettingsRequest = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest.Parser));
static readonly grpc::Marshaller<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse> __Marshaller_google_ads_googleads_v6_services_MutateCampaignExtensionSettingsResponse = grpc::Marshallers.Create(__Helper_SerializeMessage, context => __Helper_DeserializeMessage(context, global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse.Parser));
static readonly grpc::Method<global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest, global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting> __Method_GetCampaignExtensionSetting = new grpc::Method<global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest, global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting>(
grpc::MethodType.Unary,
__ServiceName,
"GetCampaignExtensionSetting",
__Marshaller_google_ads_googleads_v6_services_GetCampaignExtensionSettingRequest,
__Marshaller_google_ads_googleads_v6_resources_CampaignExtensionSetting);
static readonly grpc::Method<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest, global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse> __Method_MutateCampaignExtensionSettings = new grpc::Method<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest, global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse>(
grpc::MethodType.Unary,
__ServiceName,
"MutateCampaignExtensionSettings",
__Marshaller_google_ads_googleads_v6_services_MutateCampaignExtensionSettingsRequest,
__Marshaller_google_ads_googleads_v6_services_MutateCampaignExtensionSettingsResponse);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Ads.GoogleAds.V6.Services.CampaignExtensionSettingServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of CampaignExtensionSettingService</summary>
[grpc::BindServiceMethod(typeof(CampaignExtensionSettingService), "BindService")]
public abstract partial class CampaignExtensionSettingServiceBase
{
/// <summary>
/// Returns the requested campaign extension setting in full detail.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting> GetCampaignExtensionSetting(global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
/// </summary>
/// <param name="request">The request received from the client.</param>
/// <param name="context">The context of the server-side call handler being invoked.</param>
/// <returns>The response to send back to the client (wrapped by a task).</returns>
public virtual global::System.Threading.Tasks.Task<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettings(global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for CampaignExtensionSettingService</summary>
public partial class CampaignExtensionSettingServiceClient : grpc::ClientBase<CampaignExtensionSettingServiceClient>
{
/// <summary>Creates a new client for CampaignExtensionSettingService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public CampaignExtensionSettingServiceClient(grpc::ChannelBase channel) : base(channel)
{
}
/// <summary>Creates a new client for CampaignExtensionSettingService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public CampaignExtensionSettingServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected CampaignExtensionSettingServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected CampaignExtensionSettingServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Returns the requested campaign extension setting in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting GetCampaignExtensionSetting(global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetCampaignExtensionSetting(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested campaign extension setting in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting GetCampaignExtensionSetting(global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetCampaignExtensionSetting, null, options, request);
}
/// <summary>
/// Returns the requested campaign extension setting in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting> GetCampaignExtensionSettingAsync(global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return GetCampaignExtensionSettingAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Returns the requested campaign extension setting in full detail.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting> GetCampaignExtensionSettingAsync(global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetCampaignExtensionSetting, null, options, request);
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse MutateCampaignExtensionSettings(global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return MutateCampaignExtensionSettings(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The response received from the server.</returns>
public virtual global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse MutateCampaignExtensionSettings(global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_MutateCampaignExtensionSettings, null, options, request);
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
/// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
/// <param name="cancellationToken">An optional token for canceling the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return MutateCampaignExtensionSettingsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates, updates, or removes campaign extension settings. Operation
/// statuses are returned.
/// </summary>
/// <param name="request">The request to send to the server.</param>
/// <param name="options">The options for the call.</param>
/// <returns>The call object.</returns>
public virtual grpc::AsyncUnaryCall<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse> MutateCampaignExtensionSettingsAsync(global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_MutateCampaignExtensionSettings, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override CampaignExtensionSettingServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new CampaignExtensionSettingServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(CampaignExtensionSettingServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_GetCampaignExtensionSetting, serviceImpl.GetCampaignExtensionSetting)
.AddMethod(__Method_MutateCampaignExtensionSettings, serviceImpl.MutateCampaignExtensionSettings).Build();
}
/// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic.
/// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary>
/// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static void BindService(grpc::ServiceBinderBase serviceBinder, CampaignExtensionSettingServiceBase serviceImpl)
{
serviceBinder.AddMethod(__Method_GetCampaignExtensionSetting, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V6.Services.GetCampaignExtensionSettingRequest, global::Google.Ads.GoogleAds.V6.Resources.CampaignExtensionSetting>(serviceImpl.GetCampaignExtensionSetting));
serviceBinder.AddMethod(__Method_MutateCampaignExtensionSettings, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsRequest, global::Google.Ads.GoogleAds.V6.Services.MutateCampaignExtensionSettingsResponse>(serviceImpl.MutateCampaignExtensionSettings));
}
}
}
#endregion
| 70.421456 | 438 | 0.75914 | [
"Apache-2.0"
] | PierrickVoulet/google-ads-dotnet | src/V6/Services/CampaignExtensionSettingServiceGrpc.cs | 18,380 | C# |
namespace Mirai.Net.Data.Messengers.Enums
{
public enum ImageMessengerType
{
Friend,
Group,
Temp
}
} | 15.222222 | 42 | 0.576642 | [
"MIT"
] | nidbCN/Mirai.Net | Mirai.Net/Data/Messengers/Enums/ImageMessengerType.cs | 139 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v5/enums/manager_link_status.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V5.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v5/enums/manager_link_status.proto</summary>
public static partial class ManagerLinkStatusReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v5/enums/manager_link_status.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ManagerLinkStatusReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjdnb29nbGUvYWRzL2dvb2dsZWFkcy92NS9lbnVtcy9tYW5hZ2VyX2xpbmtf",
"c3RhdHVzLnByb3RvEh1nb29nbGUuYWRzLmdvb2dsZWFkcy52NS5lbnVtcxoc",
"Z29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byKMAQoVTWFuYWdlckxpbmtT",
"dGF0dXNFbnVtInMKEU1hbmFnZXJMaW5rU3RhdHVzEg8KC1VOU1BFQ0lGSUVE",
"EAASCwoHVU5LTk9XThABEgoKBkFDVElWRRACEgwKCElOQUNUSVZFEAMSCwoH",
"UEVORElORxAEEgsKB1JFRlVTRUQQBRIMCghDQU5DRUxFRBAGQusBCiFjb20u",
"Z29vZ2xlLmFkcy5nb29nbGVhZHMudjUuZW51bXNCFk1hbmFnZXJMaW5rU3Rh",
"dHVzUHJvdG9QAVpCZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xl",
"YXBpcy9hZHMvZ29vZ2xlYWRzL3Y1L2VudW1zO2VudW1zogIDR0FBqgIdR29v",
"Z2xlLkFkcy5Hb29nbGVBZHMuVjUuRW51bXPKAh1Hb29nbGVcQWRzXEdvb2ds",
"ZUFkc1xWNVxFbnVtc+oCIUdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlY1OjpF",
"bnVtc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V5.Enums.ManagerLinkStatusEnum), global::Google.Ads.GoogleAds.V5.Enums.ManagerLinkStatusEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V5.Enums.ManagerLinkStatusEnum.Types.ManagerLinkStatus) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing possible status of a manager and client link.
/// </summary>
public sealed partial class ManagerLinkStatusEnum : pb::IMessage<ManagerLinkStatusEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ManagerLinkStatusEnum> _parser = new pb::MessageParser<ManagerLinkStatusEnum>(() => new ManagerLinkStatusEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ManagerLinkStatusEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V5.Enums.ManagerLinkStatusReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ManagerLinkStatusEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ManagerLinkStatusEnum(ManagerLinkStatusEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ManagerLinkStatusEnum Clone() {
return new ManagerLinkStatusEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ManagerLinkStatusEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ManagerLinkStatusEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
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 !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ManagerLinkStatusEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the ManagerLinkStatusEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Possible statuses of a link.
/// </summary>
public enum ManagerLinkStatus {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Indicates current in-effect relationship
/// </summary>
[pbr::OriginalName("ACTIVE")] Active = 2,
/// <summary>
/// Indicates terminated relationship
/// </summary>
[pbr::OriginalName("INACTIVE")] Inactive = 3,
/// <summary>
/// Indicates relationship has been requested by manager, but the client
/// hasn't accepted yet.
/// </summary>
[pbr::OriginalName("PENDING")] Pending = 4,
/// <summary>
/// Relationship was requested by the manager, but the client has refused.
/// </summary>
[pbr::OriginalName("REFUSED")] Refused = 5,
/// <summary>
/// Indicates relationship has been requested by manager, but manager
/// canceled it.
/// </summary>
[pbr::OriginalName("CANCELED")] Canceled = 6,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 36.902542 | 304 | 0.688483 | [
"Apache-2.0"
] | GraphikaPS/google-ads-dotnet | src/V5/Types/ManagerLinkStatus.cs | 8,709 | C# |
using MediatR;
using System;
using System.Collections.Generic;
namespace PharmVerse.Domain.Common
{
public abstract class Entity
{
int? _requestedHashCode;
Guid _Id;
public virtual Guid Id
{
get
{
return _Id;
}
protected set
{
_Id = value;
}
}
public byte[] RowVersion { get; set; }
private List<INotification> _domainEvents;
public IReadOnlyCollection<INotification> DomainEvents => _domainEvents?.AsReadOnly();
public void AddDomainEvent(INotification eventItem)
{
_domainEvents ??= new List<INotification>();
_domainEvents.Add(eventItem);
}
public void RemoveDomainEvent(INotification eventItem)
{
_domainEvents?.Remove(eventItem);
}
public void ClearDomainEvents()
{
_domainEvents?.Clear();
}
public bool IsTransient()
{
return this.Id == default(Guid);
}
public override bool Equals(object obj)
{
if (obj == null || !(obj is Entity))
return false;
if (Object.ReferenceEquals(this, obj))
return true;
if (this.GetType() != obj.GetType())
return false;
Entity item = (Entity)obj;
if (item.IsTransient() || this.IsTransient())
return false;
else
return item.Id == this.Id;
}
public override int GetHashCode()
{
if (!IsTransient())
{
if (!_requestedHashCode.HasValue)
_requestedHashCode = this.Id.GetHashCode() ^ 31;
return _requestedHashCode.Value;
}
else
return base.GetHashCode();
}
public static bool operator ==(Entity left, Entity right)
{
if (Object.Equals(left, null))
return (Object.Equals(right, null)) ? true : false;
else
return left.Equals(right);
}
public static bool operator !=(Entity left, Entity right)
{
return !(left == right);
}
}
}
| 26.652632 | 96 | 0.459321 | [
"MIT"
] | ddynamight/PharmVerse | PharmVerse/PharmVerse.Domain/Common/Entity.cs | 2,534 | C# |
//==============================================================================
// TorqueLab ->
// Copyright (c) 2015 All Right Reserved, http://nordiklab.com/
//------------------------------------------------------------------------------
//==============================================================================
//==============================================================================
function SEP_DatablockPage::checkObjectDatablock( %this, %object ) {
//If no object supplied, try with WorldEditor selected object 0
if (%object $= "")
{
if (EWorldEditor.getSelectionSize() <= 0)
return;
%object = EWorldEditor.getSelectedObject(0);
}
// Select datablock of object if this is a GameBase object.
if( %object.isMethod( "getDatablock" ) )
{
%datablock = %object.getDatablock();
SceneEd.selectDatablock( %object.getDatablock() );
}
else if( %object.isMemberOfClass( "SFXEmitter" ) && isObject( %object.track ) )
{
SceneEd.selectDatablock( %object.track );
}
else if( %object.isMemberOfClass( "LightBase" ) && isObject( %object.animationType ) )
{
SceneEd.selectDatablock( %object.animationType );
}
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::selectDatablock( %this, %datablock, %add, %dontSyncTree ) {
%dirty = Scene.DBPM.isDirty(%datablock);
%this.setDatablockDirty(%datablock,%dirty);
Scene.doInspect(%datablock);
}
//------------------------------------------------------------------------------
//==============================================================================
//Called from EditorInspectorBase to open selected datablock
function SceneEd::openDatablock( %this, %datablock ) {
// EditorGui.setEditor( SceneEd );
%this.selectDatablock( %datablock );
SceneDatablockTreeTabBook.selectedPage = 0;
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::onSelectObject( %this, %object ) {
// Select datablock of object if this is a GameBase object.
if( %object.isMemberOfClass( "GameBase" ) )
%this.selectDatablock( %object.getDatablock() );
else if( %object.isMemberOfClass( "SFXEmitter" ) && isObject( %object.track ) )
%this.selectDatablock( %object.track );
else if( %object.isMemberOfClass( "LightBase" ) && isObject( %object.animationType ) )
%this.selectDatablock( %object.animationType );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::getNumSelectedDatablocks( %this ) {
return SceneDatablockTree.getSelectedItemsCount();
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::getSelectedDatablock( %this, %index ) {
%tree = SceneDatablockTree;
if( !%tree.getSelectedItemsCount() )
return 0;
if( !%index )
%id = %tree.getSelectedItem();
else
%id = getWord( %tree.getSelectedItemList(), %index );
return %tree.getItemValue( %id );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::selectDatablockCheck( %this, %datablock ) {
if( %this.selectedDatablockIsDirty() )
%this.showSaveDialog( %datablock );
else
%this.selectDatablock( %datablock );
}
//------------------------------------------------------------------------------
//==============================================================================
function SceneEd::unselectDatablock( %this, %datablock, %dontSyncTree ) {
Scene.doRemoveInspect( %datablock );
//if( !%dontSyncTree ) {
// %id = SceneDatablockTree.findItemByValue( %datablock.getId() );
// SceneDatablockTree.selectItem( %id, false );
// }
%this.syncDirtyState();
// If we have exactly one selected datablock remaining, re-enable
// the save-as button.
%numSelected = %this.getNumSelectedDatablocks();
if( %numSelected == 1 ) {
DatablockEditorInspectorWindow-->saveAsButton.setActive( true );
%fileNameField = DatablockEditorInspectorWindow-->DatablockFile;
%fileNameField.setText( %this.getSelectedDatablock().getFilename() );
%fileNameField.setActive( true );
}
EditorGuiStatusBar.setSelection( %this.getNumSelectedDatablocks() @ " Datablocks Selected" );
}
//------------------------------------------------------------------------------
| 38.614754 | 94 | 0.478455 | [
"MIT"
] | Torque3D-Resources/TorqueLab-v0.5-Alpha | tlab/sceneEditor/treeBook/PageDatablock/dbSelectData.cs | 4,711 | C# |
using System;
namespace LibA
{
public class Class1
{
}
}
| 7.888889 | 23 | 0.577465 | [
"MIT"
] | 01xOfFoo/sdk | src/Assets/TestProjects/AppWithProjRefCaseDiff/LibA/Class1.cs | 73 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1/vulnerability.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.SecurityCenter.V1 {
/// <summary>Holder for reflection information generated from google/cloud/securitycenter/v1/vulnerability.proto</summary>
public static partial class VulnerabilityReflection {
#region Descriptor
/// <summary>File descriptor for google/cloud/securitycenter/v1/vulnerability.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static VulnerabilityReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjJnb29nbGUvY2xvdWQvc2VjdXJpdHljZW50ZXIvdjEvdnVsbmVyYWJpbGl0",
"eS5wcm90bxIeZ29vZ2xlLmNsb3VkLnNlY3VyaXR5Y2VudGVyLnYxIkEKDVZ1",
"bG5lcmFiaWxpdHkSMAoDY3ZlGAEgASgLMiMuZ29vZ2xlLmNsb3VkLnNlY3Vy",
"aXR5Y2VudGVyLnYxLkN2ZSKoAQoDQ3ZlEgoKAmlkGAEgASgJEj0KCnJlZmVy",
"ZW5jZXMYAiADKAsyKS5nb29nbGUuY2xvdWQuc2VjdXJpdHljZW50ZXIudjEu",
"UmVmZXJlbmNlEjYKBmN2c3N2MxgDIAEoCzImLmdvb2dsZS5jbG91ZC5zZWN1",
"cml0eWNlbnRlci52MS5DdnNzdjMSHgoWdXBzdHJlYW1fZml4X2F2YWlsYWJs",
"ZRgEIAEoCCIoCglSZWZlcmVuY2USDgoGc291cmNlGAEgASgJEgsKA3VyaRgC",
"IAEoCSKxCgoGQ3Zzc3YzEhIKCmJhc2Vfc2NvcmUYASABKAESSgoNYXR0YWNr",
"X3ZlY3RvchgFIAEoDjIzLmdvb2dsZS5jbG91ZC5zZWN1cml0eWNlbnRlci52",
"MS5DdnNzdjMuQXR0YWNrVmVjdG9yElIKEWF0dGFja19jb21wbGV4aXR5GAYg",
"ASgOMjcuZ29vZ2xlLmNsb3VkLnNlY3VyaXR5Y2VudGVyLnYxLkN2c3N2My5B",
"dHRhY2tDb21wbGV4aXR5ElYKE3ByaXZpbGVnZXNfcmVxdWlyZWQYByABKA4y",
"OS5nb29nbGUuY2xvdWQuc2VjdXJpdHljZW50ZXIudjEuQ3Zzc3YzLlByaXZp",
"bGVnZXNSZXF1aXJlZBJQChB1c2VyX2ludGVyYWN0aW9uGAggASgOMjYuZ29v",
"Z2xlLmNsb3VkLnNlY3VyaXR5Y2VudGVyLnYxLkN2c3N2My5Vc2VySW50ZXJh",
"Y3Rpb24SOwoFc2NvcGUYCSABKA4yLC5nb29nbGUuY2xvdWQuc2VjdXJpdHlj",
"ZW50ZXIudjEuQ3Zzc3YzLlNjb3BlEk0KFmNvbmZpZGVudGlhbGl0eV9pbXBh",
"Y3QYCiABKA4yLS5nb29nbGUuY2xvdWQuc2VjdXJpdHljZW50ZXIudjEuQ3Zz",
"c3YzLkltcGFjdBJHChBpbnRlZ3JpdHlfaW1wYWN0GAsgASgOMi0uZ29vZ2xl",
"LmNsb3VkLnNlY3VyaXR5Y2VudGVyLnYxLkN2c3N2My5JbXBhY3QSSgoTYXZh",
"aWxhYmlsaXR5X2ltcGFjdBgMIAEoDjItLmdvb2dsZS5jbG91ZC5zZWN1cml0",
"eWNlbnRlci52MS5DdnNzdjMuSW1wYWN0IpkBCgxBdHRhY2tWZWN0b3ISHQoZ",
"QVRUQUNLX1ZFQ1RPUl9VTlNQRUNJRklFRBAAEhkKFUFUVEFDS19WRUNUT1Jf",
"TkVUV09SSxABEhoKFkFUVEFDS19WRUNUT1JfQURKQUNFTlQQAhIXChNBVFRB",
"Q0tfVkVDVE9SX0xPQ0FMEAMSGgoWQVRUQUNLX1ZFQ1RPUl9QSFlTSUNBTBAE",
"ImwKEEF0dGFja0NvbXBsZXhpdHkSIQodQVRUQUNLX0NPTVBMRVhJVFlfVU5T",
"UEVDSUZJRUQQABIZChVBVFRBQ0tfQ09NUExFWElUWV9MT1cQARIaChZBVFRB",
"Q0tfQ09NUExFWElUWV9ISUdIEAIikgEKElByaXZpbGVnZXNSZXF1aXJlZBIj",
"Ch9QUklWSUxFR0VTX1JFUVVJUkVEX1VOU1BFQ0lGSUVEEAASHAoYUFJJVklM",
"RUdFU19SRVFVSVJFRF9OT05FEAESGwoXUFJJVklMRUdFU19SRVFVSVJFRF9M",
"T1cQAhIcChhQUklWSUxFR0VTX1JFUVVJUkVEX0hJR0gQAyJtCg9Vc2VySW50",
"ZXJhY3Rpb24SIAocVVNFUl9JTlRFUkFDVElPTl9VTlNQRUNJRklFRBAAEhkK",
"FVVTRVJfSU5URVJBQ1RJT05fTk9ORRABEh0KGVVTRVJfSU5URVJBQ1RJT05f",
"UkVRVUlSRUQQAiJGCgVTY29wZRIVChFTQ09QRV9VTlNQRUNJRklFRBAAEhMK",
"D1NDT1BFX1VOQ0hBTkdFRBABEhEKDVNDT1BFX0NIQU5HRUQQAiJSCgZJbXBh",
"Y3QSFgoSSU1QQUNUX1VOU1BFQ0lGSUVEEAASDwoLSU1QQUNUX0hJR0gQARIO",
"CgpJTVBBQ1RfTE9XEAISDwoLSU1QQUNUX05PTkUQA0LuAQoiY29tLmdvb2ds",
"ZS5jbG91ZC5zZWN1cml0eWNlbnRlci52MUISVnVsbmVyYWJpbGl0eVByb3Rv",
"UAFaTGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvY2xv",
"dWQvc2VjdXJpdHljZW50ZXIvdjE7c2VjdXJpdHljZW50ZXKqAh5Hb29nbGUu",
"Q2xvdWQuU2VjdXJpdHlDZW50ZXIuVjHKAh5Hb29nbGVcQ2xvdWRcU2VjdXJp",
"dHlDZW50ZXJcVjHqAiFHb29nbGU6OkNsb3VkOjpTZWN1cml0eUNlbnRlcjo6",
"VjFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.SecurityCenter.V1.Vulnerability), global::Google.Cloud.SecurityCenter.V1.Vulnerability.Parser, new[]{ "Cve" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.SecurityCenter.V1.Cve), global::Google.Cloud.SecurityCenter.V1.Cve.Parser, new[]{ "Id", "References", "Cvssv3", "UpstreamFixAvailable" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.SecurityCenter.V1.Reference), global::Google.Cloud.SecurityCenter.V1.Reference.Parser, new[]{ "Source", "Uri" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3), global::Google.Cloud.SecurityCenter.V1.Cvssv3.Parser, new[]{ "BaseScore", "AttackVector", "AttackComplexity", "PrivilegesRequired", "UserInteraction", "Scope", "ConfidentialityImpact", "IntegrityImpact", "AvailabilityImpact" }, null, new[]{ typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector), typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity), typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired), typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction), typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope), typeof(global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Refers to common vulnerability fields e.g. cve, cvss, cwe etc.
/// </summary>
public sealed partial class Vulnerability : pb::IMessage<Vulnerability>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Vulnerability> _parser = new pb::MessageParser<Vulnerability>(() => new Vulnerability());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Vulnerability> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.SecurityCenter.V1.VulnerabilityReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Vulnerability() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Vulnerability(Vulnerability other) : this() {
cve_ = other.cve_ != null ? other.cve_.Clone() : null;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Vulnerability Clone() {
return new Vulnerability(this);
}
/// <summary>Field number for the "cve" field.</summary>
public const int CveFieldNumber = 1;
private global::Google.Cloud.SecurityCenter.V1.Cve cve_;
/// <summary>
/// CVE stands for Common Vulnerabilities and Exposures
/// (https://cve.mitre.org/about/)
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cve Cve {
get { return cve_; }
set {
cve_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Vulnerability);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Vulnerability other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(Cve, other.Cve)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (cve_ != null) hash ^= Cve.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (cve_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Cve);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (cve_ != null) {
output.WriteRawTag(10);
output.WriteMessage(Cve);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (cve_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cve);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Vulnerability other) {
if (other == null) {
return;
}
if (other.cve_ != null) {
if (cve_ == null) {
Cve = new global::Google.Cloud.SecurityCenter.V1.Cve();
}
Cve.MergeFrom(other.Cve);
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
if (cve_ == null) {
Cve = new global::Google.Cloud.SecurityCenter.V1.Cve();
}
input.ReadMessage(Cve);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
if (cve_ == null) {
Cve = new global::Google.Cloud.SecurityCenter.V1.Cve();
}
input.ReadMessage(Cve);
break;
}
}
}
}
#endif
}
/// <summary>
/// CVE stands for Common Vulnerabilities and Exposures.
/// More information: https://cve.mitre.org
/// </summary>
public sealed partial class Cve : pb::IMessage<Cve>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Cve> _parser = new pb::MessageParser<Cve>(() => new Cve());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Cve> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.SecurityCenter.V1.VulnerabilityReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cve() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cve(Cve other) : this() {
id_ = other.id_;
references_ = other.references_.Clone();
cvssv3_ = other.cvssv3_ != null ? other.cvssv3_.Clone() : null;
upstreamFixAvailable_ = other.upstreamFixAvailable_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cve Clone() {
return new Cve(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
/// <summary>
/// The unique identifier for the vulnerability. e.g. CVE-2021-34527
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "references" field.</summary>
public const int ReferencesFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Cloud.SecurityCenter.V1.Reference> _repeated_references_codec
= pb::FieldCodec.ForMessage(18, global::Google.Cloud.SecurityCenter.V1.Reference.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.SecurityCenter.V1.Reference> references_ = new pbc::RepeatedField<global::Google.Cloud.SecurityCenter.V1.Reference>();
/// <summary>
/// Additional information about the CVE.
/// e.g. https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Cloud.SecurityCenter.V1.Reference> References {
get { return references_; }
}
/// <summary>Field number for the "cvssv3" field.</summary>
public const int Cvssv3FieldNumber = 3;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3 cvssv3_;
/// <summary>
/// Describe Common Vulnerability Scoring System specified at
/// https://www.first.org/cvss/v3.1/specification-document
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3 Cvssv3 {
get { return cvssv3_; }
set {
cvssv3_ = value;
}
}
/// <summary>Field number for the "upstream_fix_available" field.</summary>
public const int UpstreamFixAvailableFieldNumber = 4;
private bool upstreamFixAvailable_;
/// <summary>
/// Whether upstream fix is available for the CVE.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool UpstreamFixAvailable {
get { return upstreamFixAvailable_; }
set {
upstreamFixAvailable_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Cve);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Cve other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if(!references_.Equals(other.references_)) return false;
if (!object.Equals(Cvssv3, other.Cvssv3)) return false;
if (UpstreamFixAvailable != other.UpstreamFixAvailable) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
hash ^= references_.GetHashCode();
if (cvssv3_ != null) hash ^= Cvssv3.GetHashCode();
if (UpstreamFixAvailable != false) hash ^= UpstreamFixAvailable.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
references_.WriteTo(output, _repeated_references_codec);
if (cvssv3_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Cvssv3);
}
if (UpstreamFixAvailable != false) {
output.WriteRawTag(32);
output.WriteBool(UpstreamFixAvailable);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
references_.WriteTo(ref output, _repeated_references_codec);
if (cvssv3_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Cvssv3);
}
if (UpstreamFixAvailable != false) {
output.WriteRawTag(32);
output.WriteBool(UpstreamFixAvailable);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
size += references_.CalculateSize(_repeated_references_codec);
if (cvssv3_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Cvssv3);
}
if (UpstreamFixAvailable != false) {
size += 1 + 1;
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Cve other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
references_.Add(other.references_);
if (other.cvssv3_ != null) {
if (cvssv3_ == null) {
Cvssv3 = new global::Google.Cloud.SecurityCenter.V1.Cvssv3();
}
Cvssv3.MergeFrom(other.Cvssv3);
}
if (other.UpstreamFixAvailable != false) {
UpstreamFixAvailable = other.UpstreamFixAvailable;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
references_.AddEntriesFrom(input, _repeated_references_codec);
break;
}
case 26: {
if (cvssv3_ == null) {
Cvssv3 = new global::Google.Cloud.SecurityCenter.V1.Cvssv3();
}
input.ReadMessage(Cvssv3);
break;
}
case 32: {
UpstreamFixAvailable = input.ReadBool();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
references_.AddEntriesFrom(ref input, _repeated_references_codec);
break;
}
case 26: {
if (cvssv3_ == null) {
Cvssv3 = new global::Google.Cloud.SecurityCenter.V1.Cvssv3();
}
input.ReadMessage(Cvssv3);
break;
}
case 32: {
UpstreamFixAvailable = input.ReadBool();
break;
}
}
}
}
#endif
}
/// <summary>
/// Additional Links
/// </summary>
public sealed partial class Reference : pb::IMessage<Reference>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Reference> _parser = new pb::MessageParser<Reference>(() => new Reference());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Reference> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.SecurityCenter.V1.VulnerabilityReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Reference() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Reference(Reference other) : this() {
source_ = other.source_;
uri_ = other.uri_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Reference Clone() {
return new Reference(this);
}
/// <summary>Field number for the "source" field.</summary>
public const int SourceFieldNumber = 1;
private string source_ = "";
/// <summary>
/// Source of the reference e.g. NVD
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Source {
get { return source_; }
set {
source_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "uri" field.</summary>
public const int UriFieldNumber = 2;
private string uri_ = "";
/// <summary>
/// Uri for the mentioned source e.g.
/// https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-34527.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Uri {
get { return uri_; }
set {
uri_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Reference);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Reference other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Source != other.Source) return false;
if (Uri != other.Uri) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Source.Length != 0) hash ^= Source.GetHashCode();
if (Uri.Length != 0) hash ^= Uri.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Source.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Source);
}
if (Uri.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Uri);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Source.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Source);
}
if (Uri.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Uri);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Source.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Source);
}
if (Uri.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Uri);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Reference other) {
if (other == null) {
return;
}
if (other.Source.Length != 0) {
Source = other.Source;
}
if (other.Uri.Length != 0) {
Uri = other.Uri;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Source = input.ReadString();
break;
}
case 18: {
Uri = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Source = input.ReadString();
break;
}
case 18: {
Uri = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// Common Vulnerability Scoring System version 3.
/// </summary>
public sealed partial class Cvssv3 : pb::IMessage<Cvssv3>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Cvssv3> _parser = new pb::MessageParser<Cvssv3>(() => new Cvssv3());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Cvssv3> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.SecurityCenter.V1.VulnerabilityReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cvssv3() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cvssv3(Cvssv3 other) : this() {
baseScore_ = other.baseScore_;
attackVector_ = other.attackVector_;
attackComplexity_ = other.attackComplexity_;
privilegesRequired_ = other.privilegesRequired_;
userInteraction_ = other.userInteraction_;
scope_ = other.scope_;
confidentialityImpact_ = other.confidentialityImpact_;
integrityImpact_ = other.integrityImpact_;
availabilityImpact_ = other.availabilityImpact_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Cvssv3 Clone() {
return new Cvssv3(this);
}
/// <summary>Field number for the "base_score" field.</summary>
public const int BaseScoreFieldNumber = 1;
private double baseScore_;
/// <summary>
/// The base score is a function of the base metric scores.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public double BaseScore {
get { return baseScore_; }
set {
baseScore_ = value;
}
}
/// <summary>Field number for the "attack_vector" field.</summary>
public const int AttackVectorFieldNumber = 5;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector attackVector_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified;
/// <summary>
/// Base Metrics
/// Represents the intrinsic characteristics of a vulnerability that are
/// constant over time and across user environments.
/// This metric reflects the context by which vulnerability exploitation is
/// possible.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector AttackVector {
get { return attackVector_; }
set {
attackVector_ = value;
}
}
/// <summary>Field number for the "attack_complexity" field.</summary>
public const int AttackComplexityFieldNumber = 6;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity attackComplexity_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified;
/// <summary>
/// This metric describes the conditions beyond the attacker's control that
/// must exist in order to exploit the vulnerability.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity AttackComplexity {
get { return attackComplexity_; }
set {
attackComplexity_ = value;
}
}
/// <summary>Field number for the "privileges_required" field.</summary>
public const int PrivilegesRequiredFieldNumber = 7;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired privilegesRequired_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified;
/// <summary>
/// This metric describes the level of privileges an attacker must possess
/// before successfully exploiting the vulnerability.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired PrivilegesRequired {
get { return privilegesRequired_; }
set {
privilegesRequired_ = value;
}
}
/// <summary>Field number for the "user_interaction" field.</summary>
public const int UserInteractionFieldNumber = 8;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction userInteraction_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified;
/// <summary>
/// This metric captures the requirement for a human user, other than the
/// attacker, to participate in the successful compromise of the vulnerable
/// component.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction UserInteraction {
get { return userInteraction_; }
set {
userInteraction_ = value;
}
}
/// <summary>Field number for the "scope" field.</summary>
public const int ScopeFieldNumber = 9;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope scope_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified;
/// <summary>
/// The Scope metric captures whether a vulnerability in one vulnerable
/// component impacts resources in components beyond its security scope.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope Scope {
get { return scope_; }
set {
scope_ = value;
}
}
/// <summary>Field number for the "confidentiality_impact" field.</summary>
public const int ConfidentialityImpactFieldNumber = 10;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact confidentialityImpact_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified;
/// <summary>
/// This metric measures the impact to the confidentiality of the information
/// resources managed by a software component due to a successfully exploited
/// vulnerability.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact ConfidentialityImpact {
get { return confidentialityImpact_; }
set {
confidentialityImpact_ = value;
}
}
/// <summary>Field number for the "integrity_impact" field.</summary>
public const int IntegrityImpactFieldNumber = 11;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact integrityImpact_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified;
/// <summary>
/// This metric measures the impact to integrity of a successfully exploited
/// vulnerability.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact IntegrityImpact {
get { return integrityImpact_; }
set {
integrityImpact_ = value;
}
}
/// <summary>Field number for the "availability_impact" field.</summary>
public const int AvailabilityImpactFieldNumber = 12;
private global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact availabilityImpact_ = global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified;
/// <summary>
/// This metric measures the impact to the availability of the impacted
/// component resulting from a successfully exploited vulnerability.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact AvailabilityImpact {
get { return availabilityImpact_; }
set {
availabilityImpact_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Cvssv3);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Cvssv3 other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.Equals(BaseScore, other.BaseScore)) return false;
if (AttackVector != other.AttackVector) return false;
if (AttackComplexity != other.AttackComplexity) return false;
if (PrivilegesRequired != other.PrivilegesRequired) return false;
if (UserInteraction != other.UserInteraction) return false;
if (Scope != other.Scope) return false;
if (ConfidentialityImpact != other.ConfidentialityImpact) return false;
if (IntegrityImpact != other.IntegrityImpact) return false;
if (AvailabilityImpact != other.AvailabilityImpact) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (BaseScore != 0D) hash ^= pbc::ProtobufEqualityComparers.BitwiseDoubleEqualityComparer.GetHashCode(BaseScore);
if (AttackVector != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified) hash ^= AttackVector.GetHashCode();
if (AttackComplexity != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified) hash ^= AttackComplexity.GetHashCode();
if (PrivilegesRequired != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified) hash ^= PrivilegesRequired.GetHashCode();
if (UserInteraction != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified) hash ^= UserInteraction.GetHashCode();
if (Scope != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified) hash ^= Scope.GetHashCode();
if (ConfidentialityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) hash ^= ConfidentialityImpact.GetHashCode();
if (IntegrityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) hash ^= IntegrityImpact.GetHashCode();
if (AvailabilityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) hash ^= AvailabilityImpact.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (BaseScore != 0D) {
output.WriteRawTag(9);
output.WriteDouble(BaseScore);
}
if (AttackVector != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified) {
output.WriteRawTag(40);
output.WriteEnum((int) AttackVector);
}
if (AttackComplexity != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified) {
output.WriteRawTag(48);
output.WriteEnum((int) AttackComplexity);
}
if (PrivilegesRequired != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified) {
output.WriteRawTag(56);
output.WriteEnum((int) PrivilegesRequired);
}
if (UserInteraction != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified) {
output.WriteRawTag(64);
output.WriteEnum((int) UserInteraction);
}
if (Scope != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified) {
output.WriteRawTag(72);
output.WriteEnum((int) Scope);
}
if (ConfidentialityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(80);
output.WriteEnum((int) ConfidentialityImpact);
}
if (IntegrityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(88);
output.WriteEnum((int) IntegrityImpact);
}
if (AvailabilityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(96);
output.WriteEnum((int) AvailabilityImpact);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (BaseScore != 0D) {
output.WriteRawTag(9);
output.WriteDouble(BaseScore);
}
if (AttackVector != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified) {
output.WriteRawTag(40);
output.WriteEnum((int) AttackVector);
}
if (AttackComplexity != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified) {
output.WriteRawTag(48);
output.WriteEnum((int) AttackComplexity);
}
if (PrivilegesRequired != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified) {
output.WriteRawTag(56);
output.WriteEnum((int) PrivilegesRequired);
}
if (UserInteraction != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified) {
output.WriteRawTag(64);
output.WriteEnum((int) UserInteraction);
}
if (Scope != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified) {
output.WriteRawTag(72);
output.WriteEnum((int) Scope);
}
if (ConfidentialityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(80);
output.WriteEnum((int) ConfidentialityImpact);
}
if (IntegrityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(88);
output.WriteEnum((int) IntegrityImpact);
}
if (AvailabilityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
output.WriteRawTag(96);
output.WriteEnum((int) AvailabilityImpact);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (BaseScore != 0D) {
size += 1 + 8;
}
if (AttackVector != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AttackVector);
}
if (AttackComplexity != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AttackComplexity);
}
if (PrivilegesRequired != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PrivilegesRequired);
}
if (UserInteraction != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UserInteraction);
}
if (Scope != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Scope);
}
if (ConfidentialityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ConfidentialityImpact);
}
if (IntegrityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) IntegrityImpact);
}
if (AvailabilityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) AvailabilityImpact);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Cvssv3 other) {
if (other == null) {
return;
}
if (other.BaseScore != 0D) {
BaseScore = other.BaseScore;
}
if (other.AttackVector != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector.Unspecified) {
AttackVector = other.AttackVector;
}
if (other.AttackComplexity != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity.Unspecified) {
AttackComplexity = other.AttackComplexity;
}
if (other.PrivilegesRequired != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired.Unspecified) {
PrivilegesRequired = other.PrivilegesRequired;
}
if (other.UserInteraction != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction.Unspecified) {
UserInteraction = other.UserInteraction;
}
if (other.Scope != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope.Unspecified) {
Scope = other.Scope;
}
if (other.ConfidentialityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
ConfidentialityImpact = other.ConfidentialityImpact;
}
if (other.IntegrityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
IntegrityImpact = other.IntegrityImpact;
}
if (other.AvailabilityImpact != global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact.Unspecified) {
AvailabilityImpact = other.AvailabilityImpact;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 9: {
BaseScore = input.ReadDouble();
break;
}
case 40: {
AttackVector = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector) input.ReadEnum();
break;
}
case 48: {
AttackComplexity = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity) input.ReadEnum();
break;
}
case 56: {
PrivilegesRequired = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired) input.ReadEnum();
break;
}
case 64: {
UserInteraction = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction) input.ReadEnum();
break;
}
case 72: {
Scope = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope) input.ReadEnum();
break;
}
case 80: {
ConfidentialityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
case 88: {
IntegrityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
case 96: {
AvailabilityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 9: {
BaseScore = input.ReadDouble();
break;
}
case 40: {
AttackVector = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackVector) input.ReadEnum();
break;
}
case 48: {
AttackComplexity = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.AttackComplexity) input.ReadEnum();
break;
}
case 56: {
PrivilegesRequired = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.PrivilegesRequired) input.ReadEnum();
break;
}
case 64: {
UserInteraction = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.UserInteraction) input.ReadEnum();
break;
}
case 72: {
Scope = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Scope) input.ReadEnum();
break;
}
case 80: {
ConfidentialityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
case 88: {
IntegrityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
case 96: {
AvailabilityImpact = (global::Google.Cloud.SecurityCenter.V1.Cvssv3.Types.Impact) input.ReadEnum();
break;
}
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the Cvssv3 message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static partial class Types {
/// <summary>
/// This metric reflects the context by which vulnerability exploitation is
/// possible.
/// </summary>
public enum AttackVector {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("ATTACK_VECTOR_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The vulnerable component is bound to the network stack and the set of
/// possible attackers extends beyond the other options listed below, up to
/// and including the entire Internet.
/// </summary>
[pbr::OriginalName("ATTACK_VECTOR_NETWORK")] Network = 1,
/// <summary>
/// The vulnerable component is bound to the network stack, but the attack is
/// limited at the protocol level to a logically adjacent topology.
/// </summary>
[pbr::OriginalName("ATTACK_VECTOR_ADJACENT")] Adjacent = 2,
/// <summary>
/// The vulnerable component is not bound to the network stack and the
/// attacker's path is via read/write/execute capabilities.
/// </summary>
[pbr::OriginalName("ATTACK_VECTOR_LOCAL")] Local = 3,
/// <summary>
/// The attack requires the attacker to physically touch or manipulate the
/// vulnerable component.
/// </summary>
[pbr::OriginalName("ATTACK_VECTOR_PHYSICAL")] Physical = 4,
}
/// <summary>
/// This metric describes the conditions beyond the attacker's control that
/// must exist in order to exploit the vulnerability.
/// </summary>
public enum AttackComplexity {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("ATTACK_COMPLEXITY_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Specialized access conditions or extenuating circumstances do not exist.
/// An attacker can expect repeatable success when attacking the vulnerable
/// component.
/// </summary>
[pbr::OriginalName("ATTACK_COMPLEXITY_LOW")] Low = 1,
/// <summary>
/// A successful attack depends on conditions beyond the attacker's control.
/// That is, a successful attack cannot be accomplished at will, but requires
/// the attacker to invest in some measurable amount of effort in preparation
/// or execution against the vulnerable component before a successful attack
/// can be expected.
/// </summary>
[pbr::OriginalName("ATTACK_COMPLEXITY_HIGH")] High = 2,
}
/// <summary>
/// This metric describes the level of privileges an attacker must possess
/// before successfully exploiting the vulnerability.
/// </summary>
public enum PrivilegesRequired {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("PRIVILEGES_REQUIRED_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The attacker is unauthorized prior to attack, and therefore does not
/// require any access to settings or files of the vulnerable system to
/// carry out an attack.
/// </summary>
[pbr::OriginalName("PRIVILEGES_REQUIRED_NONE")] None = 1,
/// <summary>
/// The attacker requires privileges that provide basic user capabilities
/// that could normally affect only settings and files owned by a user.
/// Alternatively, an attacker with Low privileges has the ability to access
/// only non-sensitive resources.
/// </summary>
[pbr::OriginalName("PRIVILEGES_REQUIRED_LOW")] Low = 2,
/// <summary>
/// The attacker requires privileges that provide significant (e.g.,
/// administrative) control over the vulnerable component allowing access to
/// component-wide settings and files.
/// </summary>
[pbr::OriginalName("PRIVILEGES_REQUIRED_HIGH")] High = 3,
}
/// <summary>
/// This metric captures the requirement for a human user, other than the
/// attacker, to participate in the successful compromise of the vulnerable
/// component.
/// </summary>
public enum UserInteraction {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("USER_INTERACTION_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// The vulnerable system can be exploited without interaction from any user.
/// </summary>
[pbr::OriginalName("USER_INTERACTION_NONE")] None = 1,
/// <summary>
/// Successful exploitation of this vulnerability requires a user to take
/// some action before the vulnerability can be exploited.
/// </summary>
[pbr::OriginalName("USER_INTERACTION_REQUIRED")] Required = 2,
}
/// <summary>
/// The Scope metric captures whether a vulnerability in one vulnerable
/// component impacts resources in components beyond its security scope.
/// </summary>
public enum Scope {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("SCOPE_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// An exploited vulnerability can only affect resources managed by the same
/// security authority.
/// </summary>
[pbr::OriginalName("SCOPE_UNCHANGED")] Unchanged = 1,
/// <summary>
/// An exploited vulnerability can affect resources beyond the security scope
/// managed by the security authority of the vulnerable component.
/// </summary>
[pbr::OriginalName("SCOPE_CHANGED")] Changed = 2,
}
/// <summary>
/// The Impact metrics capture the effects of a successfully exploited
/// vulnerability on the component that suffers the worst outcome that is most
/// directly and predictably associated with the attack.
/// </summary>
public enum Impact {
/// <summary>
/// Invalid value.
/// </summary>
[pbr::OriginalName("IMPACT_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// High impact.
/// </summary>
[pbr::OriginalName("IMPACT_HIGH")] High = 1,
/// <summary>
/// Low impact.
/// </summary>
[pbr::OriginalName("IMPACT_LOW")] Low = 2,
/// <summary>
/// No impact.
/// </summary>
[pbr::OriginalName("IMPACT_NONE")] None = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 41.200651 | 795 | 0.671015 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.SecurityCenter.V1/Google.Cloud.SecurityCenter.V1/Vulnerability.g.cs | 63,243 | C# |
/*
Copyright (c) 2014 Antmicro <www.antmicro.com>
Authors:
* Konrad Kruczynski (kkruczynski@antmicro.com)
* Piotr Zierhoffer (pzierhoffer@antmicro.com)
* Mateusz Holenko (mholenko@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System.IO;
namespace Migrantoid.PerformanceTester.Serializers
{
public sealed class MigrantSerializer : ISerializer
{
public MigrantSerializer()
{
serializer = new Serializer();
}
public void Serialize<T>(T what, Stream where)
{
serializer.Serialize(what, where);
}
public T Deserialize<T>(Stream from)
{
return serializer.Deserialize<T>(from);
}
private readonly Serializer serializer;
}
}
| 32.09434 | 72 | 0.757202 | [
"MIT"
] | konrad-kruczynski/Migrant | PerformanceTester/Serializers/MigrantSerializer.cs | 1,701 | C# |
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.SqlServer.Server;
using MoreLinq;
using NetTopologySuite;
using NetTopologySuite.IO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using WesternStatesWater.WaDE.Accessors.EntityFramework;
using WesternStatesWater.WaDE.Accessors.Mapping;
using AccessorApi = WesternStatesWater.WaDE.Accessors.Contracts.Api;
using AccessorImport = WesternStatesWater.WaDE.Accessors.Contracts.Import;
using System.Data.Sql;
namespace WesternStatesWater.WaDE.Accessors
{
public class WaterAllocationAccessor : AccessorApi.IWaterAllocationAccessor, AccessorImport.IWaterAllocationAccessor
{
public WaterAllocationAccessor(IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
Logger = loggerFactory.CreateLogger<WaterAllocationAccessor>();
}
private ILogger Logger { get; }
private IConfiguration Configuration { get; }
async Task<AccessorApi.WaterAllocations> AccessorApi.IWaterAllocationAccessor.GetSiteAllocationAmountsAsync(AccessorApi.SiteAllocationAmountsFilters filters, int startIndex, int recordCount)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
{
var sw = Stopwatch.StartNew();
var query = db.AllocationAmountsFact.AsNoTracking();
if (filters.StartPriorityDate != null)
{
query = query.Where(a => a.AllocationPriorityDateNavigation.Date >= filters.StartPriorityDate);
}
if (filters.EndPriorityDate != null)
{
query = query.Where(a => a.AllocationPriorityDateNavigation.Date <= filters.EndPriorityDate);
}
if (!string.IsNullOrWhiteSpace(filters.SiteUuid))
{
query = query.Where(a => a.AllocationBridgeSitesFact.Any(s => s.Site.SiteUuid == filters.SiteUuid));
}
if (!string.IsNullOrWhiteSpace(filters.BeneficialUseCv))
{
query = query.Where(a => a.PrimaryUseCategoryCV == filters.BeneficialUseCv || a.AllocationBridgeBeneficialUsesFact.Any(b => b.BeneficialUseCV == filters.BeneficialUseCv));
}
if (!string.IsNullOrWhiteSpace(filters.UsgsCategoryNameCv))
{
query = query.Where(a => a.PrimaryBeneficialUse.UsgscategoryNameCv == filters.UsgsCategoryNameCv || a.AllocationBridgeBeneficialUsesFact.Any(b => b.BeneficialUse.UsgscategoryNameCv == filters.UsgsCategoryNameCv));
}
if (!string.IsNullOrWhiteSpace(filters.Geometry))
{
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
WKTReader reader = new WKTReader(geometryFactory);
var shape = reader.Read(filters.Geometry);
query = query.Where(
a => a.AllocationBridgeSitesFact.Any(site => site.Site.Geometry != null && site.Site.Geometry.Intersects(shape)) ||
a.AllocationBridgeSitesFact.Any(site => site.Site.SitePoint != null && site.Site.SitePoint.Intersects(shape)));
}
if (!string.IsNullOrWhiteSpace(filters.HUC8))
{
query = query.Where(a => a.AllocationBridgeSitesFact.Any(b => b.Site.HUC8 == filters.HUC8));
}
if (!string.IsNullOrWhiteSpace(filters.HUC12))
{
query = query.Where(a => a.AllocationBridgeSitesFact.Any(b => b.Site.HUC12 == filters.HUC12));
}
if (!string.IsNullOrWhiteSpace(filters.County))
{
query = query.Where(a => a.AllocationBridgeSitesFact.Any(b => b.Site.County == filters.County));
}
if (!string.IsNullOrWhiteSpace(filters.State))
{
query = query.Where(a => a.Organization.State == filters.State);
}
var totalCount = query.Count();
var results = await query
.OrderBy(a => a.AllocationAmountId)
.Skip(startIndex)
.Take(recordCount)
.ProjectTo<AllocationHelper>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var allocationIds = results.Select(a => a.AllocationAmountId).ToList();
var sitesTask = db.AllocationBridgeSitesFact
.Where(a => allocationIds.Contains(a.AllocationAmountId))
.Select(a => new { a.AllocationAmountId, a.Site })
.ToListAsync();
var beneficialUseTask = db.AllocationBridgeBeneficialUsesFact
.Where(a => allocationIds.Contains(a.AllocationAmountId))
.Select(a => new { a.AllocationAmountId, a.BeneficialUse })
.ToListAsync();
var orgIds = results.Select(a => a.OrganizationId).ToHashSet();
var orgsTask = db.OrganizationsDim
.Where(a => orgIds.Contains(a.OrganizationId))
.ProjectTo<AccessorApi.WaterAllocationOrganization>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var waterSourceIds = results.Select(a => a.WaterSourceId).ToHashSet();
var waterSourceTask = db.WaterSourcesDim
.Where(a => waterSourceIds.Contains(a.WaterSourceId))
.ProjectTo<AccessorApi.WaterSource>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var variableSpecificIds = results.Select(a => a.VariableSpecificId).ToHashSet();
var variableSpecificTask = db.VariablesDim
.Where(a => variableSpecificIds.Contains(a.VariableSpecificId))
.ProjectTo<AccessorApi.VariableSpecific>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var methodIds = results.Select(a => a.MethodId).ToHashSet();
var methodTask = db.MethodsDim
.Where(a => methodIds.Contains(a.MethodId))
.ProjectTo<AccessorApi.Method>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var sites = (await sitesTask).Select(a => (a.AllocationAmountId, a.Site)).ToList();
var beneficialUses = (await beneficialUseTask).Select(a => (a.AllocationAmountId, a.BeneficialUse)).ToList();
var waterSources = await waterSourceTask;
var variableSpecifics = await variableSpecificTask;
var methods = await methodTask;
var waterAllocationOrganizations = new List<AccessorApi.WaterAllocationOrganization>();
foreach (var org in await orgsTask)
{
ProcessWaterAllocationOrganization(org, results, waterSources, variableSpecifics, methods, beneficialUses, sites);
waterAllocationOrganizations.Add(org);
}
sw.Stop();
Logger.LogInformation($"Completed WaterAllocation [{sw.ElapsedMilliseconds } ms]");
return new AccessorApi.WaterAllocations
{
TotalWaterAllocationsCount = totalCount,
Organizations = waterAllocationOrganizations
};
}
}
async Task<IEnumerable<AccessorApi.WaterAllocationsDigest>> AccessorApi.IWaterAllocationAccessor.GetSiteAllocationAmountsDigestAsync(AccessorApi.SiteAllocationAmountsDigestFilters filters, int startIndex, int recordCount)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
{
var sw = Stopwatch.StartNew();
var query = db.AllocationAmountsFact.AsNoTracking();
if (filters.StartPriorityDate != null)
{
query = query.Where(a => a.AllocationPriorityDateNavigation.Date >= filters.StartPriorityDate);
}
if (filters.EndPriorityDate != null)
{
query = query.Where(a => a.AllocationPriorityDateNavigation.Date <= filters.EndPriorityDate);
}
if (!string.IsNullOrWhiteSpace(filters.BeneficialUseCv))
{
query = query.Where(a => a.PrimaryUseCategoryCV == filters.BeneficialUseCv || a.AllocationBridgeBeneficialUsesFact.Any(b => b.BeneficialUseCV == filters.BeneficialUseCv));
}
if (!string.IsNullOrWhiteSpace(filters.UsgsCategoryNameCv))
{
query = query.Where(a => a.PrimaryBeneficialUse.UsgscategoryNameCv == filters.UsgsCategoryNameCv || a.AllocationBridgeBeneficialUsesFact.Any(b => b.BeneficialUse.UsgscategoryNameCv == filters.UsgsCategoryNameCv));
}
if (!string.IsNullOrWhiteSpace(filters.Geometry))
{
var geometryFactory = NtsGeometryServices.Instance.CreateGeometryFactory(srid: 4326);
WKTReader reader = new WKTReader(geometryFactory);
var shape = reader.Read(filters.Geometry);
query = query.Where(
a => a.AllocationBridgeSitesFact.Any(site => site.Site.Geometry != null && site.Site.Geometry.Intersects(shape)) ||
a.AllocationBridgeSitesFact.Any(site => site.Site.SitePoint != null && site.Site.SitePoint.Intersects(shape)));
}
if (!string.IsNullOrWhiteSpace(filters.OrganizationUUID))
{
query = query.Where(a => a.Organization.OrganizationUuid == filters.OrganizationUUID);
}
var results = await query
.OrderBy(a => a.AllocationAmountId)
.Skip(startIndex)
.Take(recordCount)
.ProjectTo<AllocationHelper>(Mapping.DtoMapper.Configuration)
.ToListAsync();
var allocationIds = results.Select(a => a.AllocationAmountId).ToList();
var sitesTask = db.AllocationBridgeSitesFact
.Where(a => allocationIds.Contains(a.AllocationAmountId))
.Select(a => new { a.AllocationAmountId, a.Site })
.ToListAsync();
var sites = (await sitesTask).Select(a => (a.AllocationAmountId, a.Site)).ToList();
var waterAllocationsLight = new List<AccessorApi.WaterAllocationsDigest>();
foreach (var allocationAmounts in results)
{
var record = new AccessorApi.WaterAllocationsDigest
{
AllocationAmountId = allocationAmounts.AllocationAmountId,
AllocationFlow_CFS = allocationAmounts.AllocationFlow_CFS,
AllocationVolume_AF = allocationAmounts.AllocationVolume_AF,
AllocationPriorityDate = allocationAmounts.AllocationPriorityDate
};
var sights = new List<AccessorApi.SiteDigest>();
sights.AddRange(sites.Where(x => x.AllocationAmountId == allocationAmounts.AllocationAmountId)
.Select(x => new AccessorApi.SiteDigest
{
Latitude = x.Site.Latitude,
Longitude = x.Site.Longitude,
SiteUUID = x.Site.SiteUuid
}));
record.Sites = sights;
waterAllocationsLight.Add(record);
}
sw.Stop();
Logger.LogInformation($"Completed WaterAllocationLight [{sw.ElapsedMilliseconds } ms]");
return waterAllocationsLight;
}
}
private static void ProcessWaterAllocationOrganization(AccessorApi.WaterAllocationOrganization org,
List<AllocationHelper> results,
List<AccessorApi.WaterSource> waterSources,
List<AccessorApi.VariableSpecific> variableSpecifics,
List<AccessorApi.Method> methods,
List<(long AllocationAmountId, BeneficialUsesCV BeneficialUse)> beneficialUses,
List<(long AllocationAmountId, SitesDim Site)> sites)
{
var allocations = results.Where(a => a.OrganizationId == org.OrganizationId).ToList();
var allocationIds = allocations.Select(a => a.AllocationAmountId).ToHashSet();
var waterSourceIds = allocations.Select(a => a.WaterSourceId).ToHashSet();
var variableSpecificIds = allocations.Select(a => a.VariableSpecificId).ToHashSet();
var methodIds = allocations.Select(a => a.MethodId).ToHashSet();
org.WaterSources = waterSources
.Where(a => waterSourceIds.Contains(a.WaterSourceId))
.Map<List<AccessorApi.WaterSource>>();
org.VariableSpecifics = variableSpecifics
.Where(a => variableSpecificIds.Contains(a.VariableSpecificId))
.Map<List<AccessorApi.VariableSpecific>>();
org.Methods = methods
.Where(a => methodIds.Contains(a.MethodId))
.Map<List<AccessorApi.Method>>();
org.BeneficialUses = beneficialUses
.Where(a => allocationIds.Contains(a.AllocationAmountId))
.Select(a => a.BeneficialUse)
.DistinctBy(a => a.Name)
.Map<List<AccessorApi.BeneficialUse>>();
org.WaterAllocations = allocations.Map<List<AccessorApi.Allocation>>();
foreach (var waterAllocation in org.WaterAllocations)
{
waterAllocation.BeneficialUses = beneficialUses
.Where(a => a.AllocationAmountId == waterAllocation.AllocationAmountId)
.Select(a => a.BeneficialUse.Name).ToList();
waterAllocation.Sites = sites
.Where(a => a.AllocationAmountId == waterAllocation.AllocationAmountId)
.Select(a => a.Site)
.Map<List<AccessorApi.Site>>();
}
}
internal class AllocationHelper
{
public long OrganizationId { get; set; }
public long AllocationAmountId { get; set; }
public string AllocationNativeID { get; set; }
public long WaterSourceId { get; set; }
public string WaterSourceUUID { get; set; }
public string AllocationOwner { get; set; }
public DateTime? AllocationApplicationDate { get; set; }
public DateTime? AllocationPriorityDate { get; set; }
public string AllocationLegalStatusCodeCV { get; set; }
public DateTime? AllocationExpirationDate { get; set; }
public string AllocationChangeApplicationIndicator { get; set; }
public string LegacyAllocationIDs { get; set; }
public double? AllocationAcreage { get; set; }
public string AllocationBasisCV { get; set; }
public DateTime? TimeframeStart { get; set; }
public DateTime? TimeframeEnd { get; set; }
public DateTime? DataPublicationDate { get; set; }
public double? AllocationCropDutyAmount { get; set; }
public double? AllocationFlow_CFS { get; set; }
public double? AllocationVolume_AF { get; set; }
public long? PopulationServed { get; set; }
public double? GeneratedPowerCapacityMW { get; set; }
public string AllocationCommunityWaterSupplySystem { get; set; }
public string AllocationSDWISIdentifier { get; set; }
public long MethodId { get; set; }
public string MethodUUID { get; set; }
public long VariableSpecificId { get; set; }
public string VariableSpecificTypeCV { get; set; }
public string PrimaryUseCategoryCV { get; set; }
public bool ExemptOfVolumeFlowPriority { get; set; }
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadOrganizations(string runId, IEnumerable<AccessorImport.Organization> organizations)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadOrganization";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter();
runIdParam.ParameterName = "@RunId";
runIdParam.Value = runId;
cmd.Parameters.Add(runIdParam);
var orgsParam = new SqlParameter();
orgsParam.ParameterName = "@OrganizationTable";
orgsParam.SqlDbType = SqlDbType.Structured;
orgsParam.Value = organizations.Select(ConvertObjectToSqlDataRecords<AccessorImport.Organization>.Convert).ToList();
orgsParam.TypeName = "Core.OrganizationTableType";
cmd.Parameters.Add(orgsParam);
var resultParam = new SqlParameter();
resultParam.SqlDbType = SqlDbType.Bit;
resultParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadWaterAllocation(string runId, IEnumerable<AccessorImport.WaterAllocation> waterAllocations)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadWaterAllocation";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter();
runIdParam.ParameterName = "@RunId";
runIdParam.Value = runId;
cmd.Parameters.Add(runIdParam);
var orgsParam = new SqlParameter();
orgsParam.ParameterName = "@WaterAllocationTable";
orgsParam.SqlDbType = SqlDbType.Structured;
orgsParam.Value = waterAllocations.Select(ConvertObjectToSqlDataRecords<AccessorImport.WaterAllocation>.Convert).ToList();
orgsParam.TypeName = "Core.WaterAllocationTableType";
cmd.Parameters.Add(orgsParam);
var resultParam = new SqlParameter();
resultParam.SqlDbType = SqlDbType.Bit;
resultParam.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadAggregatedAmounts(string runId, IEnumerable<AccessorImport.AggregatedAmount> aggregatedAmounts)
{
var count = aggregatedAmounts.Where(a => string.IsNullOrWhiteSpace(a.PrimaryUseCategory)).ToArray();
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadAggregatedAmounts";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var amountsParam = new SqlParameter
{
ParameterName = "@AggregatedAmountTable",
SqlDbType = SqlDbType.Structured,
Value = aggregatedAmounts.Select(ConvertObjectToSqlDataRecords<AccessorImport.AggregatedAmount>.Convert).ToList(),
TypeName = "Core.AggregatedAmountTableType"
};
cmd.Parameters.Add(amountsParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadMethods(string runId, IEnumerable<AccessorImport.Method> methods)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadMethods";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var methodsParam = new SqlParameter
{
ParameterName = "@MethodTable",
SqlDbType = SqlDbType.Structured,
Value = methods.Select(ConvertObjectToSqlDataRecords<AccessorImport.Method>.Convert).ToList(),
TypeName = "Core.MethodTableType"
};
cmd.Parameters.Add(methodsParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadRegulatoryOverlays(string runId, IEnumerable<AccessorImport.RegulatoryOverlay> regulatoryOverlays)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadRegulatoryOverlays";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var regulatoryParam = new SqlParameter
{
ParameterName = "@RegulatoryOverlayTable",
SqlDbType = SqlDbType.Structured,
Value = regulatoryOverlays.Select(ConvertObjectToSqlDataRecords<AccessorImport.RegulatoryOverlay>.Convert).ToList(),
TypeName = "Core.RegulatoryOverlayTableType"
};
cmd.Parameters.Add(regulatoryParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadRegulatoryReportingUnits(string runId, IEnumerable<AccessorImport.RegulatoryReportingUnits> LoadRegulatoryReportingUnits)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadRegulatoryReportingUnits";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var regulatoryParam = new SqlParameter
{
ParameterName = "@RegulatoryReportingUnitsTableType",
SqlDbType = SqlDbType.Structured,
Value = LoadRegulatoryReportingUnits.Select(ConvertObjectToSqlDataRecords<AccessorImport.RegulatoryReportingUnits>.Convert).ToList(),
TypeName = "Core.RegulatoryReportingUnitsTableType"
};
cmd.Parameters.Add(regulatoryParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadReportingUnits(string runId, IEnumerable<AccessorImport.ReportingUnit> reportingUnits)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadReportingUnits";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var regulatoryParam = new SqlParameter
{
ParameterName = "@ReportingUnitTable",
SqlDbType = SqlDbType.Structured,
Value = reportingUnits.Select(ConvertObjectToSqlDataRecords<AccessorImport.ReportingUnit>.Convert).ToList(),
TypeName = "Core.ReportingUnitTableType"
};
cmd.Parameters.Add(regulatoryParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadSites(string runId, IEnumerable<AccessorImport.Site> sites)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadSites";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var siteParam = new SqlParameter
{
ParameterName = "@SiteTable",
SqlDbType = SqlDbType.Structured,
Value = sites.Select(ConvertObjectToSqlDataRecords<AccessorImport.Site>.Convert).ToList(),
TypeName = "Core.SiteTableType"
};
cmd.Parameters.Add(siteParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadSiteSpecificAmounts(string runId, IEnumerable<AccessorImport.SiteSpecificAmount> siteSpecificAmounts)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadSiteSpecificAmounts";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var amountParam = new SqlParameter
{
ParameterName = "@SiteSpecificAmountTable",
SqlDbType = SqlDbType.Structured,
Value = siteSpecificAmounts.Select(ConvertObjectToSqlDataRecords<AccessorImport.SiteSpecificAmount>.Convert).ToList(),
TypeName = "Core.SiteSpecificAmountTableType"
};
cmd.Parameters.Add(amountParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadVariables(string runId, IEnumerable<AccessorImport.Variable> variables)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadVariables";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var amountParam = new SqlParameter
{
ParameterName = "@VariableTable",
SqlDbType = SqlDbType.Structured,
Value = variables.Select(ConvertObjectToSqlDataRecords<AccessorImport.Variable>.Convert).ToList(),
TypeName = "Core.VariableTableType"
};
cmd.Parameters.Add(amountParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
async Task<bool> AccessorImport.IWaterAllocationAccessor.LoadWaterSources(string runId, IEnumerable<AccessorImport.WaterSource> waterSources)
{
using (var db = new EntityFramework.WaDEContext(Configuration))
using (var cmd = db.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "Core.LoadWaterSources";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
var runIdParam = new SqlParameter
{
ParameterName = "@RunId",
Value = runId
};
cmd.Parameters.Add(runIdParam);
var amountParam = new SqlParameter
{
ParameterName = "@WaterSourceTable",
SqlDbType = SqlDbType.Structured,
Value = waterSources.Select(ConvertObjectToSqlDataRecords<AccessorImport.WaterSource>.Convert).ToList(),
TypeName = "Core.WaterSourceTableType"
};
cmd.Parameters.Add(amountParam);
var resultParam = new SqlParameter
{
SqlDbType = SqlDbType.Bit,
Direction = ParameterDirection.ReturnValue
};
cmd.Parameters.Add(resultParam);
await db.Database.OpenConnectionAsync();
await cmd.ExecuteNonQueryAsync();
return (int)resultParam.Value == 0;
}
}
private static class ConvertObjectToSqlDataRecords<T>
{
private static PropertyInfo[] Properties = typeof(T).GetProperties();
private static SqlMetaData[] TableSchema;
static ConvertObjectToSqlDataRecords()
{
var tableSchema = new List<SqlMetaData>();
foreach (var prop in Properties)
{
//todo: add support for other types
if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?))
{
tableSchema.Add(new SqlMetaData(prop.Name, SqlDbType.Date));
}
else if (prop.PropertyType == typeof(double) || prop.PropertyType == typeof(double?))
{
tableSchema.Add(new SqlMetaData(prop.Name, SqlDbType.Float));
}
else if (prop.PropertyType == typeof(long) || prop.PropertyType == typeof(long?))
{
tableSchema.Add(new SqlMetaData(prop.Name, SqlDbType.BigInt));
}
else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
{
tableSchema.Add(new SqlMetaData(prop.Name, SqlDbType.Bit));
}
else
{
tableSchema.Add(new SqlMetaData(prop.Name, SqlDbType.NVarChar, -1));
}
}
TableSchema = tableSchema.ToArray();
}
public static SqlDataRecord Convert(T obj)
{
var tableRow = new SqlDataRecord(TableSchema);
for (int i = 0; i < Properties.Length; i++)
{
tableRow.SetValue(i, Properties[i].GetGetMethod().Invoke(obj, new object[0]));
}
return tableRow;
}
}
}
}
| 44.578624 | 233 | 0.567173 | [
"BSD-3-Clause"
] | WSWCWaterDataExchange/WaDE2.0 | source/WesternStatesWater.WaDE.Accessors/WaterAllocationAccessor.cs | 36,289 | C# |
// MonoGame - Copyright (C) The MonoGame Team
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
using System;
using System.IO;
using MediaPlayer;
using Foundation;
using Microsoft.Xna.Framework.Graphics;
namespace Microsoft.Xna.Framework.Media
{
/// <summary>
/// Represents a video.
/// </summary>
public sealed partial class Video : IDisposable
{
internal MPMoviePlayerViewController MovieView { get; private set; }
/*
// NOTE: https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/Reference.html
// It looks like BackgroundColor doesn't even exist anymore
// in recent versions of iOS... Why still have this?
public Color BackgroundColor
{
get
{
var col = MovieView.MoviePlayer.BackgroundColor;
return new Color(col.X, col.Y, col.Z, col.W);
}
set
{
var col = value.ToVector4();
return MovieView.MoviePlayer.BackgroundColor = UIKit.UIColor(col.X, col.Y, col.Z, col.W);
}
}
*/
private void PlatformInitialize()
{
var url = NSUrl.FromFilename(Path.GetFullPath(FileName));
MovieView = new MPMoviePlayerViewController(url);
MovieView.MoviePlayer.ScalingMode = MPMovieScalingMode.AspectFill;
MovieView.MoviePlayer.ControlStyle = MPMovieControlStyle.None;
MovieView.MoviePlayer.PrepareToPlay();
}
private void PlatformDispose(bool disposing)
{
if (MovieView == null)
return;
MovieView.Dispose();
MovieView = null;
}
}
}
| 30.672131 | 147 | 0.60449 | [
"MIT"
] | 06needhamt/MonoGame | MonoGame.Framework/Platform/Media/Video.iOS.cs | 1,873 | C# |
//
// BodyBuilder.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2019 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A message body builder.
/// </summary>
/// <remarks>
/// <see cref="BodyBuilder"/> is a helper class for building common MIME body structures.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
public class BodyBuilder
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.BodyBuilder"/> class.
/// </summary>
/// <remarks>
/// Creates a new <see cref="BodyBuilder"/>.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
public BodyBuilder ()
{
LinkedResources = new AttachmentCollection (true);
Attachments = new AttachmentCollection ();
}
/// <summary>
/// Gets the attachments.
/// </summary>
/// <remarks>
/// Represents a collection of file attachments that will be included in the message.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
/// <value>The attachments.</value>
public AttachmentCollection Attachments {
get; private set;
}
/// <summary>
/// Gets the linked resources.
/// </summary>
/// <remarks>
/// Linked resources are a special type of attachment which are linked to from the <see cref="HtmlBody"/>.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
/// <value>The linked resources.</value>
public AttachmentCollection LinkedResources {
get; private set;
}
/// <summary>
/// Gets or sets the text body.
/// </summary>
/// <remarks>
/// Represents the plain-text formatted version of the message body.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
/// <value>The text body.</value>
public string TextBody {
get; set;
}
/// <summary>
/// Gets or sets the html body.
/// </summary>
/// <remarks>
/// Represents the html formatted version of the message body and may link to any of the <see cref="LinkedResources"/>.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
/// <value>The html body.</value>
public string HtmlBody {
get; set;
}
/// <summary>
/// Constructs the message body based on the text-based bodies, the linked resources, and the attachments.
/// </summary>
/// <remarks>
/// Combines the <see cref="Attachments"/>, <see cref="LinkedResources"/>, <see cref="TextBody"/>,
/// and <see cref="HtmlBody"/> into the proper MIME structure suitable for display in many common
/// mail clients.
/// </remarks>
/// <example>
/// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
/// </example>
/// <returns>The message body.</returns>
public MimeEntity ToMessageBody ()
{
MultipartAlternative alternative = null;
MimeEntity body = null;
if (TextBody != null) {
var text = new TextPart ("plain");
text.Text = TextBody;
if (!string.IsNullOrEmpty (HtmlBody)) {
alternative = new MultipartAlternative ();
alternative.Add (text);
body = alternative;
} else {
body = text;
}
}
if (HtmlBody != null) {
var text = new TextPart ("html");
MimeEntity html;
text.ContentId = MimeUtils.GenerateMessageId ();
text.Text = HtmlBody;
if (LinkedResources.Count > 0) {
var related = new MultipartRelated {
Root = text
};
foreach (var resource in LinkedResources)
related.Add (resource);
html = related;
} else {
html = text;
}
if (alternative != null)
alternative.Add (html);
else
body = html;
}
if (Attachments.Count > 0) {
if (body == null && Attachments.Count == 1)
return Attachments[0];
var mixed = new Multipart ("mixed");
if (body != null)
mixed.Add (body);
foreach (var attachment in Attachments)
mixed.Add (attachment);
body = mixed;
}
return body ?? new TextPart ("plain") { Text = string.Empty };
}
}
}
| 29.069519 | 121 | 0.648455 | [
"MIT"
] | humayun-ahmed/MimeKit | MimeKit/BodyBuilder.cs | 5,438 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using BMap.NET.HTTPService;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
namespace BMap.NET.WindowsForm.BMapElements
{
/// <summary>
/// 地图瓦片
/// </summary>
internal class BTile : BMapElement
{
static BTile()
{
int minWorker, minIOC;
// 设置线程池最小线程数目
ThreadPool.GetMinThreads(out minWorker, out minIOC);
ThreadPool.SetMinThreads(100, minIOC);
}
/// <summary>
/// 瓦片X坐标
/// </summary>
public int X
{
get;
set;
}
/// <summary>
/// 瓦片Y坐标
/// </summary>
public int Y
{
get;
set;
}
/// <summary>
/// 当前地图缩放级别
/// </summary>
public int Zoom
{
set;
get;
}
/// <summary>
/// 当前所在地图控件
/// </summary>
public Control BMapControl
{
get;
set;
}
private MapMode _mode;
/// <summary>
/// 地图模式
/// </summary>
[DefaultValue(MapMode.Normal)]
public MapMode Mode
{
get
{
return _mode;
}
set
{
if (value != _mode)
{
_mode = value;
}
}
}
private LoadMapMode _loadMode;
/// <summary>
/// 地图样式
/// </summary>
public MapStyle MapStyle
{
get { return _mapStyle; }
set { _mapStyle = value; }
}
private MapStyle _mapStyle = MapStyle.normal;
/// <summary>
/// 瓦片加载模式
/// </summary>
[DefaultValue(LoadMapMode.CacheServer)]
public LoadMapMode LoadMode
{
get
{
return _loadMode;
}
set
{
if (_loadMode != value)
{
_loadMode = value;
_loading = false;
_load_error = false;
_normal = null;
_sate = null;
_road_net = null;
}
}
}
private Bitmap _normal;
private Bitmap _sate;
private Bitmap _road_net;
private bool _loading = false;
private bool _load_error = false;
/// <summary>
/// 构造方法
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="z"></param>
/// <param name="parent"></param>
/// <param name="mode"></param>
/// <param name="loadmode"></param>
/// <param name="mapStyle"></param>
public BTile(int x, int y, int z, Control parent, MapMode mode, LoadMapMode loadmode, MapStyle mapStyle)
{
X = x;
Y = y;
Zoom = z;
BMapControl = parent;
Mode = mode;
LoadMode = loadmode;
this.MapStyle = mapStyle;
}
/// <summary>
/// 绘制
/// </summary>
/// <param name="g"></param>
/// <param name="center"></param>
/// <param name="zoom"></param>
/// <param name="screen_size"></param>
public override void Draw(System.Drawing.Graphics g, LatLngPoint center, int zoom, Size screen_size)
{
//偏移处理
//LatLngPoint offset = new LatLngPoint(MapHelper.OFFSET_LNG, MapHelper.OFFSET_LAT);
//PointF offset_p = MapHelper.GetLocationByLatLng(offset, zoom);
PointF center_p = MapHelper.GetLocationByLatLng(center, zoom); //中心点像素坐标
PointF toleft_p = new PointF(X * 256, (Y + 1) * 256); //瓦片左上角像素坐标
PointF p = new PointF((int)(screen_size.Width / 2 + (toleft_p.X - center_p.X)), (int)(screen_size.Height / 2 + (toleft_p.Y - center_p.Y) * (-1))); //屏幕坐标
//在绘制范围之内
if (!new Rectangle(-256, -256, screen_size.Width + 256, screen_size.Height + 256).Contains(new Point((int)p.X, (int)p.Y)))
{
return;
}
if (Mode == MapMode.Normal && _normal == null && !_loading) //开始下载普通瓦片
{
_loading = true;
if (!_load_error)
((Action)(delegate ()
{
MapService ms = new MapService();
_normal = ms.LoadMapTile(X, Y, Zoom, Mode, LoadMode, this.MapStyle);
_loading = false;
if (_normal == null)
{
_load_error = true;
}
BMapControl.Invoke((Action)delegate ()
{
BMapControl.Invalidate();
});
})).BeginInvoke(null, null);
}
if (Mode == MapMode.RoadNet && _road_net == null && !_loading) //开始下载道路网瓦片
{
_loading = true;
if (!_load_error)
((Action)(delegate ()
{
MapService ms = new MapService();
_road_net = ms.LoadMapTile(X, Y, Zoom, Mode, LoadMode);
_loading = false;
if (_road_net == null)
{
_load_error = true;
}
BMapControl.Invoke((Action)delegate ()
{
BMapControl.Invalidate();
});
})).BeginInvoke(null, null);
}
if (Mode == MapMode.Satellite && _sate == null && !_loading) //开始下载卫星图瓦片
{
_loading = true;
if (!_load_error)
((Action)(delegate ()
{
MapService ms = new MapService();
_sate = ms.LoadMapTile(X, Y, Zoom, Mode, LoadMode);
_loading = false;
if (_sate == null)
{
_load_error = true;
}
BMapControl.Invoke((Action)delegate ()
{
BMapControl.Invalidate();
});
})).BeginInvoke(null, null);
}
if (Mode == MapMode.Sate_RoadNet && _sate == null && !_loading) //开始下载卫星图瓦片
{
_loading = true;
if (!_load_error)
((Action)(delegate ()
{
MapService ms = new MapService();
_sate = ms.LoadMapTile(X, Y, Zoom, MapMode.Satellite, LoadMode);
_loading = false;
if (_sate == null)
{
_load_error = true;
}
BMapControl.Invoke((Action)delegate ()
{
BMapControl.Invalidate();
});
})).BeginInvoke(null, null);
}
if (Mode == MapMode.Sate_RoadNet && _road_net == null && !_loading) //开始下载道路网瓦片
{
_loading = true;
if (!_load_error)
((Action)(delegate ()
{
MapService ms = new MapService();
_road_net = ms.LoadMapTile(X, Y, Zoom, MapMode.RoadNet, LoadMode);
_loading = false;
if (_road_net == null)
{
_load_error = true;
}
BMapControl.Invoke((Action)delegate ()
{
BMapControl.Invalidate();
});
})).BeginInvoke(null, null);
}
string error = "正在加载图片...";
if (_load_error)
{
error = "图片加载失败...";
}
if (Mode == MapMode.Normal) //绘制普通地图
{
if (_normal == null)
{
g.FillRectangle(Brushes.LightGray, new RectangleF(p, new SizeF(256, 256)));
g.DrawRectangle(Pens.Gray, p.X, p.Y, 256, 256);
using (Font f = new Font("微软雅黑", 10))
{
g.DrawString(error, f, Brushes.Red, new PointF(p.X + 60, p.Y + 100));
}
}
else
{
g.DrawImage(_normal, new RectangleF(p, new SizeF(256, 256)));
}
}
if (Mode == MapMode.RoadNet) //绘制道路网
{
if (_road_net == null)
{
g.FillRectangle(Brushes.LightGray, new RectangleF(p, new SizeF(256, 256)));
g.DrawRectangle(Pens.Gray, p.X, p.Y, 256, 256);
using (Font f = new Font("微软雅黑", 10))
{
g.DrawString(error, f, Brushes.Red, new PointF(p.X + 60, p.Y + 100));
}
}
else
{
g.DrawImage(_road_net, new RectangleF(p, new SizeF(256, 256)));
}
}
if (Mode == MapMode.Satellite) //绘制卫星图
{
if (_sate == null)
{
g.FillRectangle(Brushes.LightGray, new RectangleF(p, new SizeF(256, 256)));
g.DrawRectangle(Pens.Gray, p.X, p.Y, 256, 256);
using (Font f = new Font("微软雅黑", 10))
{
g.DrawString(error, f, Brushes.Red, new PointF(p.X + 60, p.Y + 100));
}
}
else
{
g.DrawImage(_sate, new RectangleF(p, new SizeF(256, 256)));
}
}
if (Mode == MapMode.Sate_RoadNet) //绘制卫星图和道路网
{
if (_sate == null && _road_net == null)
{
g.FillRectangle(Brushes.LightGray, new RectangleF(p, new SizeF(256, 256)));
g.DrawRectangle(Pens.Gray, p.X, p.Y, 256, 256);
using (Font f = new Font("微软雅黑", 10))
{
g.DrawString(error, f, Brushes.Red, new PointF(p.X + 60, p.Y + 100));
}
}
else
{
//先绘制卫星图 再绘制道路网
if (_sate != null)
g.DrawImage(_sate, new RectangleF(p, new SizeF(256, 256)));
if (_road_net != null)
g.DrawImage(_road_net, new RectangleF(p, new SizeF(256, 256)));
}
}
}
}
} | 33.474926 | 166 | 0.394783 | [
"Apache-2.0"
] | baikangwang/SunPhotometer | SunPhotometerMap/BMap.NET.WindowsForm/BMapElements/BTile.cs | 11,748 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.