content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Quras.Core;
using Quras.Network;
using Quras.Wallets;
using System;
using System.IO;
using System.Linq;
namespace Quras.Consensus
{
internal class ConsensusWithPolicy : ConsensusService
{
private static string log_dictionary;
private static readonly object LOG_LOCK = new object();
public ConsensusWithPolicy(LocalNode localNode, Wallet wallet, string log_dictionary)
: base(localNode, wallet)
{
ConsensusWithPolicy.log_dictionary = log_dictionary;
}
protected override bool CheckPolicy(Transaction tx)
{
switch (Policy.Default.PolicyLevel)
{
case PolicyLevel.AllowAll:
return true;
case PolicyLevel.AllowList:
return tx.Scripts.All(p => Policy.Default.List.Contains(p.VerificationScript.ToScriptHash())) || tx.Outputs.All(p => Policy.Default.List.Contains(p.ScriptHash));
case PolicyLevel.DenyList:
return tx.Scripts.All(p => !Policy.Default.List.Contains(p.VerificationScript.ToScriptHash())) && tx.Outputs.All(p => !Policy.Default.List.Contains(p.ScriptHash));
default:
return base.CheckPolicy(tx);
}
}
protected override void Log(string message)
{
try
{
DateTime now = DateTime.Now;
string line = $"[{now.TimeOfDay:hh\\:mm\\:ss}] {message}";
Console.WriteLine(line);
if (string.IsNullOrEmpty(log_dictionary)) return;
lock (log_dictionary)
{
Directory.CreateDirectory(log_dictionary);
string path = Path.Combine(log_dictionary, $"{now:yyyy-MM-dd}.log");
lock (LOG_LOCK)
{
File.AppendAllLines(path, new[] { line });
}
}
}
catch
{
}
}
public void RefreshPolicy()
{
Policy.Default.Refresh();
}
}
}
| 31.955882 | 183 | 0.534284 | [
"MIT"
] | quras-official/quras-blockchain-csharp | Quras-cli/Consensus/ConsensusWithPolicy.cs | 2,175 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OdeToFood.Models;
namespace OdeToFood.Controllers
{
public class ReviewsController : Controller
{
//
// GET: /Reviews/
public ActionResult Index()
{
var model = _reviews.OrderBy(r => r.Country);
return View(model);
}
//
// GET: /Reviews/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Reviews/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Reviews/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Reviews/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /Reviews/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Reviews/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /Reviews/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// In memory review data for now.
private List<RestaurantReview> _reviews = new List<RestaurantReview>
{
new RestaurantReview
{
Id = 1,
Name = "Cinnamon Club",
City = "London",
Country = "UK",
Rating = 10
},
new RestaurantReview
{
Id = 2,
Name = "Marrakesh",
City = "D. C.",
Country = "USA",
Rating = 10
},
new RestaurantReview
{
Id = 2,
Name = "The House of Elliot",
City = "Ghent",
Country = "Belgium",
Rating = 10
}
};
}
}
| 21.782609 | 77 | 0.391218 | [
"Apache-2.0"
] | mrwizard82d1/bawan-mvc4 | OdeToFood/Controllers/ReviewsController.cs | 3,008 | C# |
using Microsoft.Extensions.Configuration;
using Nethereum.Microsoft.Configuration.Utils;
namespace Nethereum.BlockchainStore.CosmosCore.Bootstrap
{
public static class ConfigurationExtensions
{
public static void SetCosmosAccessKey(this IConfigurationRoot appConfig, string cosmosAccessKey)
{
appConfig[ConfigurationKeyNames.CosmosAccessKey] = cosmosAccessKey;
}
public static void SetCosmosEndpointUri(this IConfigurationRoot appConfig, string cosmosEndpointUri)
{
appConfig[ConfigurationKeyNames.CosmosEndpointUri] = cosmosEndpointUri;
}
public static string GetCosmosAccessKeyOrThrow(this IConfigurationRoot config)
{
return config.GetOrThrow(ConfigurationKeyNames.CosmosAccessKey);
}
public static string GetCosmosEndpointUrlOrThrow(this IConfigurationRoot config)
{
return config.GetOrThrow(ConfigurationKeyNames.CosmosEndpointUri);
}
public static string GetCosmosDbTag(this IConfigurationRoot config)
{
return config[ConfigurationKeyNames.CosmosDbTag];
}
}
}
| 33.285714 | 108 | 0.717597 | [
"MIT"
] | Dave-Whiffin/Nethereum.BlockchainStorage | src/Nethereum.BlockchainStore.CosmosCore/Bootstrap/ConfigurationExtensions.cs | 1,167 | C# |
/*
* 2010 Sizing Servers Lab, affiliated with IT bachelor degree NMCT
* University College of West-Flanders, Department GKG (www.sizingservers.be, www.nmct.be, www.howest.be/en)
*
* Author(s):
* Dieter Vandroemme
*/
using System;
using System.Windows.Forms;
namespace vApus.Util {
/// <summary>
/// If you want to be able to set a fixed duration, use ExtendedSchedule.
/// </summary>
public partial class ScheduleDialog : Form {
private DateTime _scheduledAt = DateTime.MinValue;
public DateTime ScheduledAt { get { return _scheduledAt; } }
public ScheduleDialog() { InitializeComponent(); }
public ScheduleDialog(DateTime scheduledAt)
: this() {
rdbLater.Checked = (scheduledAt > dtpTime.Value);
if (rdbLater.Checked)
dtpDate.Value = dtpTime.Value = scheduledAt;
}
private void dtp_ValueChanged(object sender, EventArgs e) { rdbLater.Checked = true; }
private void btnOK_Click(object sender, EventArgs e) {
_scheduledAt = (rdbNow.Checked) ? DateTime.Now : (dtpDate.Value.Date + dtpTime.Value.TimeOfDay);
if (ScheduledAt < DateTime.Now) _scheduledAt = DateTime.Now;
DialogResult = DialogResult.OK;
}
}
} | 34.153846 | 109 | 0.628378 | [
"MIT"
] | sizingservers/vApus | vApus.Util/Dialogs/ScheduleDialog.cs | 1,334 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Ptolemy
{
static class ArrayExtensions
{
public static double[] ScalarProduct(this double[] array, double scalar)
{
//Multiply each element by a scalar
double[] result = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = scalar * array[i];
}
return result;
}
public static double[] Product(this double[] array, double[] array2)
{
//Elementwise multiply
if (array.Length != array2.Length)
{
return null;
}
double[] result = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = array[i] * array2[i];
}
return result;
}
public static double[] Quotient(this double[] array, double[] array2)
{
//Elementwise divide
if (array.Length != array2.Length)
{
return null;
}
double[] result = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = array[i] / array2[i];
}
return result;
}
public static double[] Add(this double[] array, double[] array2)
{
//Elementwise addition
if (array.Length != array2.Length)
{
return null;
}
double[] result = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = array[i] + array2[i];
}
return result;
}
public static double[] Subtract(this double[] array, double[] array2)
{
//Elementwise subtraction
if (array.Length != array2.Length)
{
return null;
}
double[] result = new double[array.Length];
for (int i = 0; i < array.Length; i++)
{
result[i] = array[i] - array2[i];
}
return result;
}
public static double Norm(this double[] array)
{
double result = 0.0;
foreach (double element in array)
{
result += element * element;
}
return Math.Sqrt(result);
}
public static double Norm(this double[] array, double shorteningLength)
{
//Overload with optional shortening length
double result = 0.0;
foreach (double element in array)
{
result += element * element;
}
return Math.Sqrt(result + shorteningLength * shorteningLength);
}
public static double[] Push(this double[] array, double element)
{
double[] result = new double[array.Length];
//Move all elements in the array to the right and insert the new value
Array.Copy(array, 0, result, 1, (array.Length - 1));
result[0] = element;
return result;
}
public static double[][] Push(this double[][] array, double[] element)
{
//Overload for inserting into jagged array
double[][] result = new double[array.Length][];
//Move all elements in the array to the right and insert the new value
Array.Copy(array, 0, result, 1, (array.Length - 1));
result[0] = element;
return result;
}
public static uint[] ToUint(this double[] array)
{
//Overload for inserting into jagged array
uint[] result = new uint[array.Length];
for(int i = 0; i < array.Length; i++)
{
result[i] = (uint)array[i];
}
return result;
}
}
}
| 29.306122 | 83 | 0.466342 | [
"MIT"
] | Alex-Tremayne/Ptolemy | Ptolemy/Ptolemy/ArrayExtensions.cs | 4,310 | C# |
using CodingChallenge.Models;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CodingChallenge.Services
{
public class ConfigService : IConfigService
{
private IMemoryCache _cache;
public ConfigService(IMemoryCache cache)
{
_cache = cache;
}
public ViewConfig GetConfig()
{
return new ViewConfig()
{
Gender = GetGender(),
Nationalities = GetNationalities(),
Title = GetTitle()
};
}
private IEnumerable<Lov> GetTitle()
{
var title = _cache.Get<IEnumerable<Lov>>("title");
if (title == null || title.Count() == 0)
{
title = LovTitle.Get();
_cache.Set("title", title);
}
return title;
}
private IEnumerable<Lov> GetGender()
{
var gender = _cache.Get<IEnumerable<Lov>>("gender");
if (gender == null || gender.Count() == 0)
{
gender = LovGender.Get();
_cache.Set("gender", gender);
}
return gender;
}
private IEnumerable<Lov> GetNationalities()
{
var nat = _cache.Get<IEnumerable<Lov>>("nat");
if (nat == null || nat.Count() == 0)
{
nat = LovNationality.Get();
_cache.Set("nat", nat);
}
return nat;
}
}
}
| 24.953846 | 64 | 0.488903 | [
"Unlicense"
] | AndrzejSiedy/CodingChallenge | Services/ConfigService.cs | 1,624 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace Engine.EGUI {
/// <summary>
/// Класс-шина для всплывающих сообщений/подсказок
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
[RequireComponent(typeof(VerticalLayoutGroup))]
[RequireComponent(typeof(ContentSizeFitter))]
public abstract class UIHintMessage : MonoBehaviour, IHintMessage {
#region Shared Fields
[SerializeField] protected bool useMoveDirection = false;
[SerializeField] protected float moveDirectionSpeed = 1f;
[Caption("Текстовое поле")]
[Comments("Указывает ссылку на компонент текстового поля, в котором будет отображаться текст")]
[SerializeField] protected Text textField;
[Caption("Время жизни")]
[Comments("Время в секундах, в течение которого будет жить компонент")]
[SerializeField] protected float delay = 2f;
[Caption("Координаты")]
[Comments("Положение сообщения на экране")]
[SerializeField] protected Vector3 position;
[Caption("Размер")]
[Comments("Размер окна сообщения")]
[SerializeField] protected Vector2 size;
[Caption("Рамка")]
[Comments("Отступы от границы фона сообщения до текста")]
[SerializeField] protected Border border = new Border(0, 0, 0, 0);
#endregion
#region Hide Fields
private float timestamp;
private RectTransform textFieldRect;
private RectTransform rect;
private bool destroyFlag = false;
private bool destroyEventFlag = false;
#endregion
/// <summary>
/// Вызывается в момент, когда необходимо уничтожить сообщение
/// </summary>
public abstract void OnDestroyEvent();
/// <summary>
/// Продолжает метод Start у MonoBehaviour
/// </summary>
public virtual void OnStart() { }
/// <summary>
/// Продолжает метод Update у MonoBehaviour
/// </summary>
public virtual void OnUpdate() { }
private void Start() {
timestamp = Time.time;
textFieldRect = textField.GetComponent<RectTransform>();
OnStart();
}
private void Update() {
OnUpdate();
#if UNITY_EDITOR
if (!Application.isPlaying) {
return;
}
#endif
if (Time.time - timestamp < delay) {
return;
}
if (!destroyEventFlag) {
OnDestroyEvent();
destroyEventFlag = true;
}
if (isDestroy()) {
GameObject.Destroy(transform.gameObject);
}
}
/// <summary>
/// Возвращает true, если сообщение было помечено как уничтожено
/// </summary>
/// <returns></returns>
public bool isDestroy() {
return this.destroyFlag;
}
public bool isDestroyEvent() {
return this.destroyEventFlag;
}
/// <summary>
/// Устанавливает флаг необходимости уничтожить объект сообщения
/// </summary>
/// <param name="destroyFlag">Значение флага</param>
public void SetDestroy(bool destroyFlag){
this.destroyFlag = destroyFlag;
}
#region Properties
/// <summary>
/// Устанавливает время жизни сообщения
/// </summary>
public float Delay {
get {
return this.delay;
}
set {
this.delay = value;
}
}
/// <summary>
/// Устанавливает размер окна сообщения
/// </summary>
public Vector2 Size {
get {
return this.size;
}
set {
this.size = value;
Rect.sizeDelta = new Vector2(size.x, Rect.sizeDelta.y);
}
}
/// <summary>
/// Устанавливает положение на экране
/// </summary>
public virtual Vector3 Position {
get {
return this.position;
}
set {
this.position = value;
}
}
/// <summary>
/// Устанавливает текст сообщения
/// </summary>
public string Text {
get {
#if UNITY_EDITOR
if (this.textField == null) {
Debug.LogError("Не указана ссылка на текстовое поле!");
throw new MissingReferenceException();
}
#endif
return this.textField.text;
}
set {
#if UNITY_EDITOR
if (this.textField == null) {
Debug.LogError("Не указана ссылка на текстовое поле!");
throw new MissingReferenceException();
}
#endif
this.textField.text = value;
}
}
/// <summary>
/// Возвращает ссылку на RectTransform текстового поля
/// </summary>
public RectTransform TextFieldRect {
get {
return textFieldRect;
}
}
/// <summary>
/// Отступы границ виджета
/// </summary>
/// <value>Границы</value>
public IBorder Border {
get {
return border;
}
set {
this.border = value as Border;
VerticalLayoutGroup group = GetComponent<VerticalLayoutGroup>();
group.padding.left = (int)border.Left;
group.padding.right = (int)border.Right;
group.padding.top = (int)border.Top;
group.padding.bottom = (int)border.Bottom;
}
}
/// <summary>
/// RectTransform виджета
/// </summary>
/// <value>Возвращает объект RectTransform виджета</value>
public RectTransform Rect {
get {
return GetComponent<RectTransform>();
}
}
#endregion
#region Editor
private void OnValidate() {
Border = border;
Position = position;
Size = size;
if (textField != null) {
Text = Text;
}
}
#endregion
}
}
| 20.071713 | 97 | 0.656411 | [
"MIT"
] | vpcoder/7d1n | Assets/Packs/UnityAPI/sdon/Components/EGUI/UIHintMessage/Base/UIHintMessage.cs | 5,794 | 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/00022214", true, 0xE1FF)]
[Attributes(9)]
public class LteB24RxCalChan
{
[ElementsCount(16)]
[ElementType("uint16")]
[Description("")]
public ushort[] Value { get; set; }
}
}
| 21.52381 | 60 | 0.612832 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Efs/LteB24RxCalChanI.cs | 452 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace lm.Comol.Modules.EduPath.Domain
{
[Serializable]
public class dtoActivityUser : IRuleElement
{
public long Id { get; set; }
public Int64 UserCompletion { get; set; }
public short DisplayOrder { get; set; }
public short Duration { get; set; }
public DateTime? EndDate { get; set; }
public Int64 MinCompletion { get; set; }
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public Status Status { get; set; }
public Boolean MandatoryStepsCompleted { get; set; }
public short OverrideRuleCompletionMinValue { get; set; }
public short OverrideRuleCompletionMaxValue { get; set; }
public bool OverrideRules { get; set; }
public RuleRangeType OverrideRuleRangeType { get; set; }
//activity data
public Boolean Completed()
{
return this.MandatoryStepsCompleted && this.UserCompletion >= this.MinCompletion;
}
public short UserMark { get; set; }
public short OverrideRuleMarkMinValue { get; set; }
public short OverrideRuleMarkMaxValue { get; set; }
}
}
| 22.561404 | 93 | 0.630638 | [
"MIT"
] | EdutechSRL/Adevico | 3-Business/3-Modules/lm.Comol.Modules.EduPath/Domain/DTO/dtoActivityUser.cs | 1,288 | C# |
using HexUN.Events;
using UnityEngine;
using UnityEngine.Events;
namespace HexUN.UXUI
{
[System.Serializable]
public class SSwipeDataUnityEventListener : UnityEvent<SSwipeData>
{
}
[AddComponentMenu("HexUN/UX/Mobile/Events/SSwipeDataEventListener")]
public class SSwipeDataEventListener : ScriptableObjectEventListener<SSwipeData, SSwipeDataEvent, SSwipeDataUnityEventListener>
{
}
} | 25.5625 | 130 | 0.789731 | [
"MIT"
] | hexthedev/HexUN-UXUI | Runtime/Scripts/Mobile/SSwipeData.event/SSwipeDataEventListener.cs | 409 | C# |
using System;
using System.Diagnostics.Contracts;
using DKW.OwnTracks.Client.Messages;
using Marten;
using Serilog;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace DKW.OwnTracks.Client
{
public class Service : IDisposable
{
private readonly IDocumentStore _documentStore;
private readonly ILogger _logger;
private MqttClient _client;
private Boolean _isDisposed; // To detect redundant calls
public Service(IDocumentStore documentStore, ILogger logger)
{
Contract.Requires(documentStore != null);
Contract.Requires(logger != null);
if (documentStore == null) {
throw new ArgumentNullException(nameof(documentStore));
}
if (logger == null) {
throw new ArgumentNullException(nameof(logger));
}
_documentStore = documentStore;
_logger = logger;
}
public void Start()
{
EnsureNotDisposed();
// TODO: Put the magic strings in a config file or something. -dw
_client = new MqttClient("spartan.dkw.io");
_client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
_client.Connect("home.dkw.io-", "OwnTracks", "armageddon");
_client.Subscribe(new string[] { "owntracks.*.*" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
_client.Subscribe(new string[] { "owntracks.*.*.event" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
_client.Subscribe(new string[] { "owntracks.*.*.info" }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
}
public void Stop()
{
_client.Unsubscribe(new string[] { "owntracks.*.*" });
_client.Unsubscribe(new string[] { "owntracks.*.*.event" });
_client.Unsubscribe(new string[] { "owntracks.*.*.info" });
_client.Disconnect();
}
public void Dispose()
{
Dispose(true);
// TODO: uncomment the following line if the finalizer is implemented.
// GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed) {
if (disposing) {
if (_client.IsConnected) {
_client.Disconnect();
}
_client = null;
}
_isDisposed = true;
}
}
private void EnsureNotDisposed()
{
if (_isDisposed) {
throw new ObjectDisposedException(GetType().FullName, "The service is not reusable once it has been disposed.");
}
}
private void Client_MqttMsgPublishReceived(Object sender, MqttMsgPublishEventArgs e)
{
using (var session = _documentStore.LightweightSession()) {
var msg = System.Text.Encoding.ASCII.GetString(e.Message);
var location = Newtonsoft.Json.JsonConvert.DeserializeObject<Location>(msg);
_logger.Information($"{msg}");
}
}
}
}
| 28.311828 | 116 | 0.700342 | [
"MIT"
] | dougkwilson/DKW.OwnTracks.Client | DKW.OwnTracks.Client/Service.cs | 2,635 | C# |
// Copyright (c) 2018 Alachisoft
//
// 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.Text;
using System.Threading;
namespace Alachisoft.NCache.Common.Threading
{
public class ThrottlingManager
{
long _limit;
long _throtllingUnitMs = 1000;
long _currentInternval;
long _currentSize;
long _currentMilliSeconds;
DateTime _startTime;
public ThrottlingManager(long limit)
{
_limit = limit;
}
public ThrottlingManager(long limit, long unit)
{
_limit = limit;
_throtllingUnitMs = unit;
}
public void Start()
{
_startTime = DateTime.Now;
_currentMilliSeconds = GetMilliSecondDiff();
_currentInternval = _currentMilliSeconds / _throtllingUnitMs;
}
private long GetMilliSecondDiff()
{
return (long)(DateTime.Now - _startTime).TotalMilliseconds;
}
/// <summary>
/// Waits if throttling limit reaches
/// </summary>
/// <param name="size"></param>
public void Throttle(long size)
{
lock (this)
{
long msNow = GetMilliSecondDiff();
long currentInterval = msNow / _throtllingUnitMs;
if (currentInterval == _currentInternval)
{
_currentSize += size;
if (_currentSize >= _limit)
{
Thread.Sleep((int)(_throtllingUnitMs - (msNow - _currentMilliSeconds)));
}
}
else
{
_currentInternval = currentInterval;
_currentMilliSeconds = msNow;
_currentSize= size;
}
}
}
}
}
| 28.170455 | 96 | 0.557886 | [
"Apache-2.0"
] | abayaz61/NCache | Src/NCCommon/Threading/ThrottlingManager.cs | 2,481 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.470)
// Version 5.470.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Extends the ViewComposite by laying out children in horizontal/vertical stack.
/// </summary>
public class ViewLayoutStack : ViewComposite
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewLayoutStack class.
/// </summary>
public ViewLayoutStack(bool horizontal)
{
// Create child to dock style lookup
Horizontal = horizontal;
// By default we fill the remainder area with the last child
FillLastChild = true;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewLayoutStack:" + Id;
}
#endregion
#region Horizontal
/// <summary>
/// Gets and sets the stack orientation.
/// </summary>
public bool Horizontal { get; set; }
#endregion
#region FillLastChild
/// <summary>
/// Gets and sets if the last child fills the remainder of the space.
/// </summary>
public bool FillLastChild { get; set; }
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
Debug.Assert(context != null);
// Accumulate the stacked size
Size preferredSize = Size.Empty;
foreach (ViewBase child in this)
{
if (child.Visible)
{
// Get the preferred size of the child
Size childSize = child.GetPreferredSize(context);
// Depending on orientation, add up child sizes
if (Horizontal)
{
preferredSize.Height = Math.Max(preferredSize.Height, childSize.Height);
preferredSize.Width += childSize.Width;
}
else
{
preferredSize.Height += childSize.Height;
preferredSize.Width = Math.Max(preferredSize.Width, childSize.Width);
}
}
}
return preferredSize;
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Maximum space available for the next child
Rectangle childRectangle = ClientRectangle;
// Find the last visible child
ViewBase lastVisible = null;
foreach(ViewBase child in Reverse())
{
if (child.Visible)
{
lastVisible = child;
break;
}
}
// Position each entry, with last entry filling remaining of space
foreach (ViewBase child in this)
{
if (child.Visible)
{
// Provide the total space currently available
context.DisplayRectangle = childRectangle;
// Get the preferred size of the child
Size childSize = child.GetPreferredSize(context);
if (Horizontal)
{
// Ask child to fill the available height
childSize.Height = childRectangle.Height;
if ((child == lastVisible) && FillLastChild)
{
// This child takes all remainder width
childSize.Width = childRectangle.Width;
}
else
{
// Reduce remainder space to exclude this child
childRectangle.X += childSize.Width;
childRectangle.Width -= childSize.Width;
}
}
else
{
// Ask child to fill the available width
childSize.Width = childRectangle.Width;
if ((child == lastVisible) && FillLastChild)
{
// This child takes all remainder height
childSize.Height = childRectangle.Height;
}
else
{
// Reduce remainder space to exclude this child
childRectangle.Y += childSize.Height;
childRectangle.Height -= childSize.Height;
}
}
// Use the update child size as the actual space for layout
context.DisplayRectangle = new Rectangle(context.DisplayRectangle.Location, childSize);
// Layout child in the provided space
child.Layout(context);
}
}
// Put back the original display value now we have finished
context.DisplayRectangle = ClientRectangle;
}
#endregion
}
}
| 36.069149 | 157 | 0.497714 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-NET-5.470 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Layout/ViewLayoutStack.cs | 6,784 | C# |
using UnityEngine;
using UnityEngine.UI; //make sure to add this
using System.Collections;
public static class Utility
{
public static void ShowCG(CanvasGroup cg)
{
cg.alpha = 1;
cg.blocksRaycasts = true;
cg.interactable = true;
}
public static void HideCG(CanvasGroup cg)
{
cg.alpha = 0;
cg.blocksRaycasts = false;
cg.interactable = false;
}
} //end Utility.cs | 20.818182 | 46 | 0.59607 | [
"MIT"
] | kevin8667/The-Room-of-Alchemist | Assets/Scripts/DialogSystem/Utility.cs | 458 | C# |
namespace BuckarooSdk.Services.Giftcards.HuisTuinGiftcard
{
public class HuisTuinGiftcardRefundResponse
{
}
}
| 12.777778 | 57 | 0.817391 | [
"MIT"
] | buckaroo-it/BuckarooSdk_DotNet | BuckarooSdk/Services/Giftcards/HuisTuinGiftcard/HuisTuinGiftcardRefundResponse.cs | 115 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PersonViewModelWithModel.cs" company="Catel development team">
// Copyright (c) 2008 - 2014 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Test.Extensions.FluentValidation.ViewModels
{
using Catel.Data;
using Catel.MVVM;
using Catel.Test.Extensions.FluentValidation.Models;
/// <summary>
/// The person view model with model.
/// </summary>
public class PersonViewModelWithModel : ViewModelBase
{
#region Constants
/// <summary>Register the Person property so it is known in the class.</summary>
public static readonly PropertyData PersonProperty = RegisterProperty("Person", typeof(Person), default(Person), (s, e) => ((PersonViewModelWithModel)s).OnPersonChanged(e));
#endregion
#region Constructors
#endregion
#region Properties
/// <summary>
/// Gets or sets Person.
/// </summary>
[Model]
public Person Person
{
get { return GetValue<Person>(PersonProperty); }
set { SetValue(PersonProperty, value); }
}
#endregion
#region Methods
/// <summary>
/// Occurs when the value of the Person property is changed.
/// </summary>
/// <param name="e">
/// The event argument
/// </param>
private void OnPersonChanged(AdvancedPropertyChangedEventArgs e)
{
}
#endregion
}
} | 32.148148 | 181 | 0.52477 | [
"MIT"
] | gautamsi/Catel | src/Catel.Test/Catel.Test.NET40/Extensions/FluentValidation/ViewModels/PersonViewModelWithModel.cs | 1,738 | C# |
using System.Collections.Generic;
using CompResultPair = System.Tuple<Kelson.CSharp.Extensions.ComparableExtensions.Comparator<int>, bool>;
using NUnit.Framework;
namespace Kelson.CSharp.Extensions.Tests
{
[TestFixture]
public class ComparableExtensionsTests
{
[Test]
public void IsBetween_FromInclusive_AsExpected()
{
// ----------------------- Arrange -----------------------
// ----------------------- Act -----------------------
// ----------------------- Assert -----------------------
Assert.True(2.IsBetween<int>(0, 3));
Assert.False(3.IsBetween<int>(0, 3));
Assert.False(4.IsBetween<int>(0, 3));
Assert.True(0.IsBetween<int>(0, 3));
Assert.False((-1).IsBetween<int>(0, 3));
}
[Test]
public void IsBetween_Inclusive_AsExpected()
{
// ----------------------- Arrange -----------------------
// ----------------------- Act -----------------------
// ----------------------- Assert -----------------------
Assert.True(2.IsBetween<int>(0, 3, RangeFlags.Inclusive));
Assert.True(3.IsBetween<int>(0, 3, RangeFlags.Inclusive));
Assert.False(4.IsBetween<int>(0, 3, RangeFlags.Inclusive));
Assert.True(0.IsBetween<int>(0, 3, RangeFlags.Inclusive));
Assert.False((-1).IsBetween<int>(0, 3, RangeFlags.Inclusive));
}
[Test]
public void IsBetween_ToInclusive_AsExpected()
{
// ----------------------- Arrange -----------------------
// ----------------------- Act -----------------------
// ----------------------- Assert -----------------------
Assert.True(2.IsBetween<int>(0, 3, RangeFlags.ToInclusive));
Assert.True(3.IsBetween<int>(0, 3, RangeFlags.ToInclusive));
Assert.False(4.IsBetween<int>(0, 3, RangeFlags.ToInclusive));
Assert.False(0.IsBetween<int>(0, 3, RangeFlags.ToInclusive));
Assert.False((-1).IsBetween<int>(0, 3, RangeFlags.ToInclusive));
}
[Test]
public void IsBetween_Exclusive_AsExpected()
{
// ----------------------- Arrange -----------------------
// ----------------------- Act -----------------------
// ----------------------- Assert -----------------------
Assert.True(2.IsBetween<int>(0, 3, RangeFlags.Exclusive));
Assert.False(3.IsBetween<int>(0, 3, RangeFlags.Exclusive));
Assert.False(4.IsBetween<int>(0, 3, RangeFlags.Exclusive));
Assert.False(0.IsBetween<int>(0, 3, RangeFlags.Exclusive));
Assert.False((-1).IsBetween<int>(0, 3, RangeFlags.Exclusive));
}
[Test]
public void IsBetween_NumericTypes_AsExpected()
{
// ----------------------- Arrange -----------------------
// ----------------------- Act -----------------------
// ----------------------- Assert -----------------------
Assert.True(2l.IsBetween<long>(0l, 3l));
Assert.True(2ul.IsBetween<ulong>(0ul, 3ul));
Assert.True(2f.IsBetween<float>(0f, 3f));
Assert.True(2d.IsBetween<double>(0d, 3d));
Assert.True(2m.IsBetween<decimal>(0m, 3m));
}
private static IEnumerable<CompResultPair> ComparisonPairsRefLessThanComp()
{
yield return new CompResultPair(ComparableExtensions.IsGreaterThanOrEqualTo, false);
yield return new CompResultPair(ComparableExtensions.IsGreaterThan, false);
yield return new CompResultPair(ComparableExtensions.IsSameAs, false);
yield return new CompResultPair(ComparableExtensions.IsLessThanOrEqualTo, true);
yield return new CompResultPair(ComparableExtensions.IsLessThan, true);
}
[Test]
public void Comparator_RefLessThanComp_MatchesExpected([ValueSource(nameof(ComparisonPairsRefLessThanComp))] CompResultPair comparison)
{
//----------- Arrange -----------------------------
int reference = 1;
int comp = 2;
//----------- Act ---------------------------------
bool result = comparison.Item1(reference, comp);
//----------- Assert-------------------------------
Assert.True(result == comparison.Item2);
}
private static IEnumerable<CompResultPair> ComparisonPairsRefEqualsComp()
{
yield return new CompResultPair(ComparableExtensions.IsGreaterThanOrEqualTo, true);
yield return new CompResultPair(ComparableExtensions.IsGreaterThan, false);
yield return new CompResultPair(ComparableExtensions.IsSameAs, true);
yield return new CompResultPair(ComparableExtensions.IsLessThanOrEqualTo, true);
yield return new CompResultPair(ComparableExtensions.IsLessThan, false);
}
[Test]
public void Comparator_RefEqualsComp_MatchesExpected([ValueSource(nameof(ComparisonPairsRefEqualsComp))] CompResultPair comparison)
{
//----------- Arrange -----------------------------
int reference = 1;
int comp = 1;
//----------- Act ---------------------------------
bool result = comparison.Item1(reference, comp);
//----------- Assert-------------------------------
Assert.True(result == comparison.Item2);
}
private static IEnumerable<CompResultPair> ComparisonPairsRefGreaterThanComp()
{
yield return new CompResultPair(ComparableExtensions.IsGreaterThanOrEqualTo, true);
yield return new CompResultPair(ComparableExtensions.IsGreaterThan, true);
yield return new CompResultPair(ComparableExtensions.IsSameAs, false);
yield return new CompResultPair(ComparableExtensions.IsLessThanOrEqualTo, false);
yield return new CompResultPair(ComparableExtensions.IsLessThan, false);
}
[Test]
public void Comparator_RefGreaterThanComp_MatchesExpected([ValueSource(nameof(ComparisonPairsRefGreaterThanComp))] CompResultPair comparison)
{
//----------- Arrange -----------------------------
int reference = 2;
int comp = 1;
//----------- Act ---------------------------------
bool result = comparison.Item1(reference, comp);
//----------- Assert-------------------------------
Assert.True(result == comparison.Item2);
}
}
} | 44.746667 | 149 | 0.506704 | [
"MIT"
] | KelsonBall/KelsonBall.CSharp.Extensions | Kelson.CSharp.Extentions/Kelson.CSharp.Extensions.Tests/ComparableExtensionsTests.cs | 6,714 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml;
namespace SlnToCsv
{
class Program
{
static void Main(string[] args)
{
var fileEnding = "packages.config";
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("*************************************");
Console.WriteLine("Export 'packages.config' packages");
Console.WriteLine("*************************************");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Search directory: ");
Console.ForegroundColor = ConsoleColor.Gray;
var dir = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
Console.Write("Output file: ");
Console.ForegroundColor = ConsoleColor.Gray;
var output = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Notes: ");
Console.WriteLine("* Export as CSV");
Console.WriteLine("* Columns separated by ':'");
Console.WriteLine("* First column indicates column content.");
var files = Search(dir, fileEnding);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(files.Count + " " + fileEnding + " found.");
var packages = new Dictionary<string, PackageInformation>();
foreach (var file in files)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("Resolving file: " + file);
Resolve(file, packages);
}
using (var fs = new FileStream(output, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine("Package:Versions:Target Frameworks:Assemblies");
foreach (var packageInformation in packages.Values)
{
sw.WriteLine(packageInformation.ToString());
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Done.");
Console.ReadKey();
}
static ISet<string> Search(string dir, string fileEnding)
{
var files = new HashSet<string>();
try
{
foreach (var directory in Directory.GetDirectories(dir))
{
foreach (var file in Directory.GetFiles(directory))
{
if (file.EndsWith(fileEnding))
{
files.Add(file);
}
}
var result = Search(directory, fileEnding);
foreach (var foundFile in result)
{
files.Add(foundFile);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return files;
}
static void Resolve(string file, IDictionary<string, PackageInformation> packages)
{
var dir = Path.GetDirectoryName(file);
var filesInDir = Directory.GetFiles(dir);
var csproj = filesInDir.FirstOrDefault(x => x.EndsWith(".csproj"));
string assemblyName = string.Empty;
if (csproj != null)
{
var assemblyPattern = @"<AssemblyName>(.*)<\/AssemblyName>";
var csprojFile = File.ReadAllText(csproj);
assemblyName = Regex.Match(csprojFile, assemblyPattern).Groups[1].Value;
}
var packageXml = new XmlDocument();
packageXml.Load(file);
var packagesElement = packageXml.GetElementsByTagName("package");
foreach (XmlNode package in packagesElement)
{
var packageId = package.Attributes["id"].Value;
var packageVersion = package.Attributes["version"].Value;
var targetFramework = package.Attributes["targetFramework"]?.Value;
packages.TryGetValue(packageId, out var addedPackage);
if (addedPackage == null)
{
addedPackage = new PackageInformation(packageId);
packages.Add(packageId, addedPackage);
}
addedPackage.Versions.Add(packageVersion);
addedPackage.TargetFrameworks.Add(targetFramework);
addedPackage.Assemblies.Add(assemblyName);
}
}
class PackageInformation
{
private readonly string packageId;
public PackageInformation(string packageId)
{
this.Versions = new HashSet<string>();
this.Assemblies = new HashSet<string>();
this.TargetFrameworks = new HashSet<string>();
this.packageId = packageId;
}
public ISet<string> Versions { get; }
public ISet<string> TargetFrameworks { get; }
public ISet<string> Assemblies { get; }
public override string ToString()
{
var versions = string.Join(", ", this.Versions);
var assemblies = string.Join(", ", this.Assemblies);
var targetFrameworks = string.Join(", ", this.TargetFrameworks);
var formatted = string.Format("{0}:{1}:{2}:{3}", packageId, versions, targetFrameworks, assemblies);
return formatted;
}
}
}
}
| 34.435294 | 116 | 0.522378 | [
"MIT"
] | GixarIV/SlnToCsv | Source/Program.cs | 5,854 | C# |
using System;
using System.Web;
using System.Configuration;
using Neo4jClient;
using Ninject.Modules;
using Ninject.Activation;
namespace PracticalNeo4j_DotNet.App_Start.Modules
{
public class Neo4jModule : NinjectModule
{
/// <summary>Loads the module into the kernel.</summary>
public override void Load()
{
Bind<IGraphClient>().ToMethod(InitNeo4JClient).InSingletonScope();
}
private static IGraphClient InitNeo4JClient(IContext context)
{
var neo4JUri = new Uri(ConfigurationManager.ConnectionStrings["graphStory"].ConnectionString);
var graphClient = new GraphClient(neo4JUri);
graphClient.Connect();
return graphClient;
}
}
}
| 27.285714 | 106 | 0.668848 | [
"Apache-2.0"
] | dynamicdeploy/networkx | practical-neo4j-apress/practicalneo4j-dotnet-master/PracticalNeo4j-DotNet/App_Start/Modules/Neo4jModule.cs | 766 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Vpc.V20170312.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class ModifyNatGatewayDestinationIpPortTranslationNatRuleResponse : AbstractModel
{
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.477273 | 92 | 0.672632 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Vpc/V20170312/Models/ModifyNatGatewayDestinationIpPortTranslationNatRuleResponse.cs | 1,421 | C# |
using System;
namespace JetBrains.ReSharper.Plugins.FSharp.TypeProviders.Host
{
internal static class Program
{
public static void Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += RiderPluginAssemblyResolver.Resolve;
MainInternal(args);
}
private static void MainInternal(string[] args)
{
var endPoint = new TypeProvidersEndPoint();
var portValue = args[0];
var logPath = string.Empty;
if (args.Length > 1)
{
logPath = args[1];
}
endPoint.Start(portValue, logPath);
}
}
}
| 20.892857 | 85 | 0.644444 | [
"Apache-2.0"
] | JetBrains/fsharp-support | ReSharper.FSharp/src/FSharp.TypeProviders.Host/src/Program.cs | 587 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Linq;
namespace Microsoft.Azure.PowerShell.Cmdlets.ResourceGraph.Runtime.Json
{
internal class SerializationOptions
{
internal static readonly SerializationOptions Default = new SerializationOptions();
internal SerializationOptions() { }
internal SerializationOptions(
string[] include = null,
bool ingoreNullValues = false)
{
Include = include;
IgnoreNullValues = ingoreNullValues;
}
internal string[] Include { get; set; }
internal string[] Exclude { get; set; }
internal bool IgnoreNullValues { get; set; }
internal PropertyTransformation[] Transformations { get; set; }
internal Func<string, string> PropertyNameTransformer { get; set; }
internal int MaxDepth { get; set; } = 5;
internal bool IsIncluded(string name)
{
if (Exclude != null)
{
return !Exclude.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase));
}
else if (Include != null)
{
return Include.Any(exclude => exclude.Equals(name, StringComparison.OrdinalIgnoreCase));
}
return true;
}
internal PropertyTransformation GetTransformation(string propertyName)
{
if (Transformations == null) return null;
foreach (var t in Transformations)
{
if (t.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase))
{
return t;
}
}
return null;
}
}
} | 32.692308 | 106 | 0.516235 | [
"MIT"
] | 3quanfeng/azure-powershell | src/ResourceGraph/ResourceGraph.Autorest/generated/runtime/Serialization/SerializationOptions.cs | 2,063 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReactiveUI.Routing.Core.Tests.Presentation
{
public class TestViewModel
{
}
}
| 16.769231 | 52 | 0.761468 | [
"MIT"
] | KallynGowdy/ReactiveUI.Routing | src/ReactiveUI.Routing.Core.Tests/Presentation/TestViewModel.cs | 220 | C# |
/*
Copyright (c) 2008-2012 by the President and Fellows of Harvard College. All rights reserved.
Profiles Research Networking Software was developed under the supervision of Griffin M Weber, MD, PhD.,
and Harvard Catalyst: The Harvard Clinical and Translational Science Center, with support from the
National Center for Research Resources and Harvard University.
Code licensed under a BSD License.
For details, see: LICENSE.txt
*/
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Xml;
using Profiles.Framework.Utilities;
using Profiles.ORNG.Utilities;
namespace Profiles.ORNG.Modules.Gadgets
{
public partial class EditPersonalGadget : BaseModule
{
private OpenSocialManager om;
private string uri;
private int appId;
private PreparedGadget gadget;
private Profiles.ORNG.Utilities.DataIO data;
private bool hasGadget = false;
public Int64 SubjectID { get; set; }
public XmlDocument PropertyListXML { get; set; }
public string PredicateURI { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DrawProfilesModule();
}
public EditPersonalGadget() : base() { }
public EditPersonalGadget(XmlDocument pagedata, List<ModuleParams> moduleparams, XmlNamespaceManager pagenamespaces)
: base(pagedata, moduleparams, pagenamespaces)
{
SessionManagement sm = new SessionManagement();
base.BaseData = pagedata;
data = new Profiles.ORNG.Utilities.DataIO();
Profiles.Edit.Utilities.DataIO editdata = new Profiles.Edit.Utilities.DataIO();
Profiles.Profile.Utilities.DataIO propdata = new Profiles.Profile.Utilities.DataIO();
if (Request.QueryString["subject"] != null)
this.SubjectID = Convert.ToInt64(Request.QueryString["subject"]);
else if (base.GetRawQueryStringItem("subject") != null)
this.SubjectID = Convert.ToInt64(base.GetRawQueryStringItem("subject"));
else
Response.Redirect("~/search");
this.PredicateURI = Request.QueryString["predicateuri"].Replace("!", "#");
this.PropertyListXML = propdata.GetPropertyList(this.BaseData, base.PresentationXML, this.PredicateURI, false, true, false);
litBackLink.Text = "<a href='" + Brand.GetThemedDomain() + "/edit/" + this.SubjectID.ToString() + "'>Edit Menu</a> > <b>" + PropertyListXML.SelectSingleNode("PropertyList/PropertyGroup/Property/@Label").Value + "</b>";
//create a new network triple request.
base.RDFTriple = new RDFTriple(this.SubjectID, editdata.GetStoreNode(this.PredicateURI));
base.RDFTriple.Expand = true;
base.RDFTriple.ShowDetails = true;
base.GetDataByURI();//This will reset the data to a Network.
// Profiles OpenSocial Extension by UCSF
uri = this.BaseData.SelectSingleNode("rdf:RDF/rdf:Description/@rdf:about", base.Namespaces).Value;
uri = uri.Substring(0, uri.IndexOf(Convert.ToString(this.SubjectID)) + Convert.ToString(this.SubjectID).Length);
appId = Convert.ToInt32(base.GetModuleParamString("AppId"));
om = OpenSocialManager.GetOpenSocialManager(uri, Page, true);
if (om.IsEnabled())
{
gadget = om.AddOntologyGadget(appId, base.GetModuleParamString("View"), base.GetModuleParamString("OptParams"));
}
securityOptions.Subject = this.SubjectID;
securityOptions.PredicateURI = this.PredicateURI;
securityOptions.PrivacyCode = Convert.ToInt32(this.PropertyListXML.SelectSingleNode("PropertyList/PropertyGroup/Property/@ViewSecurityGroup").Value);
securityOptions.SecurityGroups = new XmlDataDocument();
securityOptions.SecurityGroups.LoadXml(base.PresentationXML.DocumentElement.LastChild.OuterXml);
hasGadget = Convert.ToInt32(this.PropertyListXML.SelectSingleNode("PropertyList/PropertyGroup/Property/@NumberOfConnections").Value) > 0;
}
private void DrawProfilesModule()
{
if (gadget == null || !om.IsVisible())
{
pnlSecurityOptions.Visible = false;
litGadget.Text = "This feature is currently turned off on your system";
return;
}
// We need to render the div even if we want to hide it, otherwise OpenSocial will not work
// so we use an ugly trick to turn it on and off in javascript
litGadget.Text = "<div id='" + gadget.GetChromeId() + "' class='gadgets-gadget-parent' style ='display: " + (hasGadget ? "block" : "none") + "'></div>";
om.LoadAssets();
if (hasGadget)
{
btnAddORNGApplication.Visible = false;
litDeleteORNGApplicationProperty.Text = "Remove " + gadget.GetLabel() + " gadget from your profile.";
lnkDelete.Visible = true;
}
else
{
litAddORNGApplicationProperty.Text = "Add " + gadget.GetLabel();
btnAddORNGApplication.Visible = true;
lnkDelete.Visible = false;
}
}
protected void btnAddORNGApplication_OnClick(object sender, EventArgs e)
{
// add the gadget to the person
data.AddPersonalGadget(this.SubjectID, this.PredicateURI, securityOptions.PrivacyCode);
hasGadget = true;
DrawProfilesModule();
upnlEditSection.Update();
string scriptstring = "document.getElementById('" + gadget.GetChromeId() + "').style.display = 'block';";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "hideshow", scriptstring, true);
}
protected void deleteOne_Onclick(object sender, EventArgs e)
{
data.RemovePersonalGadget(this.SubjectID, this.PredicateURI, securityOptions.PrivacyCode);
hasGadget = false;
DrawProfilesModule();
upnlEditSection.Update();
string scriptstring = "document.getElementById('" + gadget.GetChromeId() + "').style.display = 'none';";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "hideshow", scriptstring, true);
}
}
} | 45.626761 | 233 | 0.638987 | [
"BSD-3-Clause"
] | CTSIatUCSF/ProfilesRNS | Website/SourceCode/Profiles/Profiles/ORNG/Modules/EditPersonalGadget/EditPersonalGadget.ascx.cs | 6,481 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SASEBO_Measure_Lecroy.CipherModule
{
//================================================================ CipherInterface
public interface IBlockCipher
{
void open();
void close();
void setKey(byte[] key, int len);
void setEnc();
void setDec();
void writeText(byte[] text, int len);
void readText(byte[] text, int len);
void execute();
}
}
| 23.714286 | 86 | 0.528112 | [
"MIT"
] | gs1989/AcquisitionProject | SASEBO_Measure_Lecroy/CipherModule/IBlockCipher.cs | 500 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using Refit;
namespace Cake.BrowserStack.Services
{
internal class JsonPart : ByteArrayPart
{
public JsonPart(string fileName, object value) : base(Serialize(value), fileName, "application/json")
{
}
private static byte[] Serialize(object value)
{
var contents = JsonConvert.SerializeObject(value);
return Encoding.UTF8.GetBytes(contents);
}
}
}
| 23.73913 | 109 | 0.663004 | [
"MIT"
] | cake-contrib/Cake.BrowserStack | src/Cake.BrowserStack/Services/JsonPart.cs | 548 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using ProjectV.Models.Data;
using SteamWebApiLib.Models.AppDetails;
namespace ProjectV.SteamService.Mappers
{
public sealed class DataMapperSteamGame : IDataMapper<SteamApp, SteamGameInfo>
{
public DataMapperSteamGame()
{
}
#region IDataMapper<SteamApp, SteamGameInfo> Implementation
public SteamGameInfo Transform(SteamApp dataObject)
{
var releaseDate = DateTime.Parse(dataObject.ReleaseDate.Date);
decimal price = Convert.ToDecimal(dataObject.PriceOverview.Final);
IReadOnlyList<int> genreIds = dataObject.Genres.Select(genre => genre.Id).ToList();
return new SteamGameInfo(
thingId: dataObject.SteamAppId,
title: dataObject.Name,
voteCount: dataObject.PriceOverview.DiscountPercent,
voteAverage: dataObject.PriceOverview.Initial,
overview: dataObject.ShortDescription,
releaseDate: releaseDate,
price: price,
requiredAge: dataObject.RequiredAge,
genreIds: genreIds,
posterPath: dataObject.HeaderImage
);
}
#endregion
}
}
| 32.35 | 95 | 0.63524 | [
"Apache-2.0"
] | Vasar007/FilmsEvaluator | ProjectV/Libraries/ExternalServices/ProjectV.SteamService/Mappers/DataMapperSteamGame.cs | 1,296 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace ProjetoModeloDDD.MVC.Atributos
{
public static class T4Helpers
{
public static bool IsRequired(string viewDataTypeName, string propertyName)
{
bool IsRequired = false;
Attribute richText = null;
Type typeModel = Type.GetType(viewDataTypeName);
if (typeModel != null)
{
richText = (RequiredAttribute)Attribute.GetCustomAttribute(typeModel.GetProperty(propertyName), typeof(RequiredAttribute));
return richText != null;
}
return IsRequired;
}
}
} | 28.461538 | 139 | 0.640541 | [
"MIT"
] | LeonardoVanelli/Gest-oSpaca | PrismaWEB.MVC/Helpers/Atributos/T4Helpers.cs | 742 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AddressLabelUtilityCli.Arguments;
namespace AddressLabelUtilityCli.Helper
{
internal static class ArgumentHelper
{
private static readonly IReadOnlyCollection<Type> _argumentTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => !x.IsInterface && x.GetInterface(nameof(IArgument)) != null)
.ToList();
public static IEnumerable<IArgument> GetArguments()
{
return GetCommonArguments()
.Concat(GetCsvArguments())
.Concat(GetPdfArguments());
}
public static IEnumerable<IArgument> GetCommonArguments()
{
return _argumentTypes
.Where(x => x.Namespace == "AddressLabelUtilityCli.Arguments.Common")
.Select(x => Activator.CreateInstance(x) as IArgument);
}
public static IEnumerable<IArgument> GetCsvArguments()
{
return _argumentTypes
.Where(x => x.Namespace == "AddressLabelUtilityCli.Arguments.Csv")
.Select(x => Activator.CreateInstance(x) as IArgument);
}
public static IEnumerable<IArgument> GetPdfArguments()
{
return _argumentTypes
.Where(x => x.Namespace == "AddressLabelUtilityCli.Arguments.Pdf")
.Select(x => Activator.CreateInstance(x) as IArgument);
}
}
}
| 33.4 | 106 | 0.615436 | [
"Apache-2.0"
] | koktoh/address-label-utility | address-label-utility-cli/Helper/ArgumentHelper.cs | 1,505 | 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.Management.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A ExpressRouteResourceProvider object.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class ExpressRouteServiceProvider : Resource
{
/// <summary>
/// Initializes a new instance of the ExpressRouteServiceProvider
/// class.
/// </summary>
public ExpressRouteServiceProvider()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the ExpressRouteServiceProvider
/// class.
/// </summary>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="location">Resource location.</param>
/// <param name="tags">Resource tags.</param>
/// <param name="peeringLocations">Get a list of peering
/// locations.</param>
/// <param name="bandwidthsOffered">Gets bandwidths offered.</param>
/// <param name="provisioningState">Gets the provisioning state of the
/// resource.</param>
public ExpressRouteServiceProvider(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), IList<string> peeringLocations = default(IList<string>), IList<ExpressRouteServiceProviderBandwidthsOffered> bandwidthsOffered = default(IList<ExpressRouteServiceProviderBandwidthsOffered>), string provisioningState = default(string))
: base(id, name, type, location, tags)
{
PeeringLocations = peeringLocations;
BandwidthsOffered = bandwidthsOffered;
ProvisioningState = provisioningState;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets get a list of peering locations.
/// </summary>
[JsonProperty(PropertyName = "properties.peeringLocations")]
public IList<string> PeeringLocations { get; set; }
/// <summary>
/// Gets bandwidths offered.
/// </summary>
[JsonProperty(PropertyName = "properties.bandwidthsOffered")]
public IList<ExpressRouteServiceProviderBandwidthsOffered> BandwidthsOffered { get; set; }
/// <summary>
/// Gets the provisioning state of the resource.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; set; }
}
}
| 40.47619 | 476 | 0.654412 | [
"MIT"
] | azure-keyvault/azure-sdk-for-net | src/SDKs/Network/Management.Network/Generated/Models/ExpressRouteServiceProvider.cs | 3,400 | C# |
/* INFINITY CODE 2013-2016 */
/* http://www.infinity-code.com */
using System;
using UnityEngine;
/// <summary>
/// Instance of Billboard marker.
/// </summary>
[AddComponentMenu("")]
public class OnlineMapsMarkerBillboard : OnlineMapsMarkerInstanceBase
{
/// <summary>
/// Indicates whether to display the marker.
/// </summary>
public bool used;
public override OnlineMapsMarkerBase marker
{
get { return _marker; }
set { _marker = value as OnlineMapsMarker; }
}
[SerializeField]
private OnlineMapsMarker _marker;
/// <summary>
/// Creates a new instance of the billboard marker.
/// </summary>
/// <param name="marker">Marker</param>
/// <returns>Instance of billboard marker</returns>
public static OnlineMapsMarkerBillboard Create(OnlineMapsMarker marker)
{
GameObject billboardGO = new GameObject("Marker");
SpriteRenderer spriteRenderer = billboardGO.AddComponent<SpriteRenderer>();
OnlineMapsMarkerBillboard billboard = billboardGO.AddComponent<OnlineMapsMarkerBillboard>();
billboard.marker = marker;
Texture2D texture = marker.texture;
if (marker.texture == null) texture = OnlineMaps.instance.defaultMarkerTexture;
if (texture != null)
{
spriteRenderer.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0));
#if !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6 && !UNITY_4_7 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2
spriteRenderer.flipX = true;
#endif
}
return billboard;
}
/// <summary>
/// Dispose billboard instance
/// </summary>
public void Dispose()
{
if (gameObject != null) OnlineMapsUtils.DestroyImmediate(gameObject);
marker = null;
}
#if !UNITY_ANDROID
protected void OnMouseDown()
{
OnlineMapsControlBase.instance.InvokeBasePress();
}
protected void OnMouseUp()
{
OnlineMapsControlBase.instance.InvokeBaseRelease();
}
#endif
private void Start()
{
gameObject.AddComponent<BoxCollider>();
Update();
}
private void Update()
{
transform.LookAt(OnlineMapsControlBase3D.instance.activeCamera.transform.position);
Vector3 euler = transform.rotation.eulerAngles;
euler.y = 0;
transform.rotation = Quaternion.Euler(euler);
}
} | 28.627907 | 128 | 0.643379 | [
"CC0-1.0"
] | VisualSweden/Mixed | Assets/Infinity Code/Online maps/Scripts/Markers/OnlineMapsMarkerBillboard.cs | 2,464 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SoftFx.FxCalendar.Database;
using SoftFx.FxCalendar.Models;
namespace SoftFx.FxCalendar.Storage
{
public abstract class BaseStorage<TModel, TEntity> : IStorage<TModel, TEntity>
where TModel : INews, IModel<TEntity> where TEntity : class, INews
{
private static Dictionary<string, int> _storageAccessCnt = new Dictionary<string, int>();
private string _storagePath;
private int _storageVersion;
public string Location { get; protected set; }
public string CurrencyCode { get; protected set; }
public DbContextBase<TEntity> DbContext { get; protected set; }
public List<TModel> News { get; protected set; }
public DateTime EarliestDate { get; protected set; }
public DateTime LatestDate { get; protected set; }
protected BaseStorage(string location, string currencyCode)
{
Location = location;
CurrencyCode = currencyCode;
Initialize();
}
private void Initialize()
{
var dbDir = DbHelper.GetDbDirectory(Location);
if (!Directory.Exists(dbDir))
{
Directory.CreateDirectory(dbDir);
}
DbContext = CreateDbContext();
_storagePath = DbHelper.GetDbFilePath(DbContext.Location, DbContext.CalendarName, DbContext.CurrencyCode);
if (!_storageAccessCnt.ContainsKey(_storagePath))
_storageAccessCnt[_storagePath] = 1;
LoadNewsFromDb();
}
protected void LoadNewsFromDb()
{
News = new List<TModel>();
_storageVersion = _storageAccessCnt[_storagePath];
if (!DbContext.News.Any())
{
EarliestDate = DateTime.Now.ToUniversalTime();
LatestDate = DateTime.Now.ToUniversalTime();
}
else
{
EarliestDate = DbContext.News.First().DateUtc;
LatestDate = EarliestDate;
}
foreach (var entity in DbContext.News)
{
var model = CreateEmptyModel();
model.InitFromEntity(entity);
News.Add(model);
UpdateDatesRange(model);
}
}
protected void UpdateDatesRange(TModel model)
{
EarliestDate = model.DateUtc.Date < EarliestDate ? model.DateUtc.Date : EarliestDate;
LatestDate = model.DateUtc.Date >= LatestDate
? model.DateUtc.Date + TimeSpan.FromDays(1)
: LatestDate;
}
public abstract TModel CreateEmptyModel();
public abstract DbContextBase<TEntity> CreateDbContext();
public void AddNews(IEnumerable<TModel> news)
{
ReloadNewsIfNeeded();
foreach (var model in news)
{
News.Add(model);
DbContext.News.Add(model.ConvertToEntity());
UpdateDatesRange(model);
}
DbContext.SaveChanges();
_storageAccessCnt[_storagePath]++;
_storageVersion = _storageAccessCnt[_storagePath];
}
public void ReloadNewsIfNeeded()
{
if (_storageVersion != _storageAccessCnt[_storagePath])
{
LoadNewsFromDb();
}
}
public void UpdateDatesRange(DateTime start, DateTime end)
{
EarliestDate = start.Date < EarliestDate ? start.Date : EarliestDate;
LatestDate = end.Date >= LatestDate
? end.Date + TimeSpan.FromDays(1)
: LatestDate;
}
}
}
| 32 | 118 | 0.573358 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SoftFx/TTAlgo | src/csharp/lib/SoftFx.FxCalendar/Storage/BaseStorage.cs | 3,778 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace Analogy.LogViewer.RSSReader.Core
{
[Serializable]
public class RSSFeed : AbstractRSSFeed
{
#region Ctor
public RSSFeed(string url, bool isPersonal, bool dontKeepHistory, Encoding feedEncoding, string feedName = null,
int encodingCode = 0)
: base(url, isPersonal, dontKeepHistory, feedEncoding, feedName, encodingCode)
{
}
#endregion
#region Methods
public override string RSSNameWithCount
{
get
{
string name = RSSName;
if (UnreadItemsCount > 0)
{
name += string.Format(" ({0})", UnreadItemsCount);
}
return name;
}
}
protected override async Task<List<IRSSPost>> RefreshCurrentItems(bool suppressErrorDisplay)
{
TotalUpdates++;
try
{
//should be remove later on
if (FeedEncoding == null)
{
FeedEncoding = Encoding.UTF8;
}
if (Client == null)
{
Client = new WebClient
{
Encoding =
(FeedEncodingCodePage == 0)
? FeedEncoding
: Encoding.GetEncoding(FeedEncodingCodePage)
};
}
if (Client.Headers.Count == 0)
{
Client.Headers.Add("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
}
DateTime first = DateTime.Now;
var xmlData = await Client.DownloadStringTaskAsync(new Uri(RSSUrl));
DateTime last = DateTime.Now;
LastDownloadTime = last.Subtract(first);
LastDownloadSizeKb = (System.Text.Encoding.UTF8.GetByteCount(xmlData)) / 1024;
TotalDownloadedKB += (UInt64) LastDownloadSizeKb;
XDocument XMLDoc = XDocument.Parse(xmlData);
List<IRSSPost> newItems = (from post in XMLDoc.Descendants("item")
select new StandardRSSPost(post, this)).ToList<IRSSPost>();
if (IsPersonalFeed)
{
RSSItemsList = null;
return newItems;
//newItems.OrderByDescending(x => (x.Date.HasValue) ? x.Date.Value : DateTime.MinValue).ThenByDescending(x => x.AddedDate ).ToList();
}
if (RSSItemsList == null || RSSItemsList.Count() == 0)
{
RSSItemsList = newItems.ToList<IRSSPost>();
}
else
{
var newdistinctItems = (from newitm in newItems
where !RSSItemsList.Contains(newitm)
select newitm).ToList();
var browser = new PostHTMLStripperGenerator();
foreach (IRSSPost newdistinctItem in newdistinctItems)
{
//string HTMLToParse = newdistinctItem.Link + "<br>" + newdistinctItem.Title + "<br>" +
// newdistinctItem.Description + "<br>" + newdistinctItem.Content +"<br>" +
// newdistinctItem.Creator;
string HTMLToParse = newdistinctItem.Description + "<br>" + newdistinctItem.Content;
newdistinctItem.PlainTextPostContent = browser.GetPlainText(HTMLToParse);
}
LastNewPosts = newdistinctItems.ToList();
////get all read items
//var readitems = (from rssitem in RSSItemsList
// where rssitem.Read
// select rssitem).ToList();
//if (readitems.Count() > 0) //all were read: set new items to read
// foreach (var newitm in newItems)
// {
// if (readitems.Contains(newitm))
// {
// var olditem = readitems.Find(f => f.Equals(newitm ));
// newitm.Read = true;
// newitm.IgnoreThisPost = olditem.IgnoreThisPost;
// }
// }
RSSItemsList.AddRange(LastNewPosts);
//RSSItemsList = RSSItemsList.OrderByDescending(x => (x.Date.HasValue) ? x.Date.Value : DateTime.MinValue).ThenByDescending(x => x.AddedDate).ToList();
}
}
catch (Exception ex)
{
var exc = new ApplicationException("Feed Name: " + this.RSSName + " Feed URL: " + this.RSSUrl, ex);
OnRSSReadingError(new RSSErrorArgs(exc));
MessageShow.ShowException(this, exc, suppressErrorDisplay);
}
return RSSItemsList;
}
}
#endregion
}
| 37.62987 | 175 | 0.44918 | [
"MIT"
] | Analogy-LogViewer/Analogy.LogViewer.RSSReader | Analogy.LogViewer.RSSReader/Core/RSSFeed.cs | 5,797 | C# |
class Motorcycle : Vehicle
{
public Motorcycle(int horsePowers, double fuel) : base(horsePowers, fuel)
{
}
} | 20 | 77 | 0.675 | [
"MIT"
] | kaykayehnn/Uni | oop/2021-04-26/Vehicles/Motorcycle.cs | 120 | C# |
using _InputTest.Entity.Scripts.Input.Monobehaviours.Commands;
using UnityEngine;
using UnityEngine.InputSystem;
namespace _InputTest.Entity.Scripts.Input.Monobehaviours
{
public class CharacterInput : MonoBehaviour, IInteractInput, IMoveInput, IRotationInput, ISkillInput, IAttackInput
{
[Header("Input Commands")] public Command interactInput;
public Command movementInput;
public Command analogRotationInput;
public Command mouseRotationInput;
public Command skillInput;
public Command attackInput;
[Header("Input Values")] [Space(20)] [SerializeField]
private Vector3 rotationDirection;
[SerializeField] private Vector3 moveDirection;
[SerializeField] private bool isPressingInteract;
[SerializeField] private bool isUsingSkill;
[SerializeField] private bool isAttacking;
public Vector3 MoveDirection => moveDirection;
public Vector3 RotationDirection
{
get => rotationDirection;
set => rotationDirection = value;
}
public bool IsUsingSkill => isUsingSkill;
public bool IsPressingInteract => isPressingInteract;
public bool IsAttacking => isAttacking;
private PlayerInputActions _inputActions;
private const string LeftMouseButton = "Left Button";
private void Awake()
{
_inputActions = new PlayerInputActions();
}
private void OnEnable()
{
_inputActions.Enable();
if (movementInput)
_inputActions.Player.Movement.performed += OnMoveInput;
if (analogRotationInput)
_inputActions.Player.AnalogAim.performed += OnAnalogAimInput;
if (interactInput)
{
_inputActions.Player.Interact.started += OnInteractStart;
_inputActions.Player.Interact.canceled += OnInteractEnded;
}
if (skillInput)
{
_inputActions.Player.Skill.performed += OnSkillUse;
_inputActions.Player.Skill.canceled += OnSkillEnd;
}
if (attackInput)
{
_inputActions.Player.Attack.performed += OnAttackStart;
_inputActions.Player.Attack.canceled += OnAttackEnd;
}
}
private void OnMoveInput(InputAction.CallbackContext context)
{
var value = context.ReadValue<Vector2>();
moveDirection = new Vector3(value.x, 0, value.y);
if (movementInput != null)
movementInput.Execute();
}
private void OnAnalogAimInput(InputAction.CallbackContext context)
{
var value = context.ReadValue<Vector2>();
rotationDirection = new Vector3(value.x, 0, value.y);
if (analogRotationInput != null)
analogRotationInput.Execute();
}
private void OnInteractStart(InputAction.CallbackContext context)
{
if (context.control.displayName != LeftMouseButton) return;
isPressingInteract = true;
mouseRotationInput.Execute();
}
private void OnInteractEnded(InputAction.CallbackContext context)
{
if (interactInput != null)
interactInput.Execute();
isPressingInteract = false;
if (context.action.activeControl.device != Mouse.current) return;
rotationDirection = Vector3.zero;
}
private void OnSkillUse(InputAction.CallbackContext context)
{
isUsingSkill = true;
if (skillInput != null)
skillInput.Execute();
}
private void OnSkillEnd(InputAction.CallbackContext context)
{
isUsingSkill = false;
if (skillInput != null)
skillInput.Complete();
}
private void OnAttackStart(InputAction.CallbackContext context)
{
isAttacking = true;
if (attackInput)
attackInput?.Execute();
}
private void OnAttackEnd(InputAction.CallbackContext context)
{
isAttacking = false;
if (attackInput)
attackInput.Complete();
}
private void OnDisable()
{
_inputActions.Player.Movement.performed -= OnMoveInput;
_inputActions.Player.Interact.started -= OnInteractStart;
_inputActions.Player.Interact.canceled -= OnInteractEnded;
_inputActions.Player.AnalogAim.performed -= OnAnalogAimInput;
_inputActions.Player.Skill.performed -= OnSkillUse;
_inputActions.Disable();
}
}
} | 31.441558 | 118 | 0.597893 | [
"MIT"
] | Kodeman010/Input-System-Strategy-Pattern | Version 2 - Attack System/Assets/_InputTest/Entity/Scripts/Input/Monobehaviours/CharacterInput.cs | 4,844 | C# |
using System;
using UnityEngine;
public class KochSnowflakePattern : MonoBehaviour
{
public int numGenerations;
public float forward;
public int turn;
public float startX;
public float startY;
public double startHeading;
public float step;
Vector3 pos;
private RenderQueue word;
// Start is called before the first frame update
void Start()
{
pos = transform.localPosition;
step = 10 * Time.deltaTime; // calculate distance to move
forward = 2.0f;
turn = 60;
startX = pos.x;
startY = pos.y;
startHeading = 60;
setUp();
}
// Update is called once per frame
void Update()
{
float diff = Vector3.Distance(transform.position, pos);
//Debug.Log(diff);
if (diff < 0.001f)
{
//Debug.Log("X: " + pos.x + " Y: " + pos.y);
updatePosition();
//Debug.Log("X: " + pos.x + " Y: " + pos.y);
transform.position = Vector3.MoveTowards(transform.position, pos, step);
}
else
{
transform.position = Vector3.MoveTowards(transform.position, pos, step);
}
}
private void setUp()
{
numGenerations = 4;
word = getKochSnowflake(numGenerations);
}
/**
* Make a Koch Snowflake L-system.
* @param numGenerations number of rewrite generations
* @return the word for rendering
*/
private RenderQueue getKochSnowflake(int numGenerations)
{
// rule: F --> F-F++F-F
RenderCommand[] ruleFrom = { RenderCommand.FORWARD };
RenderQueue[] ruleTo = { RenderQueue.fromString("F-F++F-F") };
Rewriter rewriter = new Rewriter(ruleFrom, ruleTo);
RenderQueue seed = RenderQueue.fromString("F++F++F");
return rewriter.rewrite(seed, numGenerations);
}
private void updatePosition()
{
RenderCommand rc = RenderCommand.NONE;
bool updatedPos = false;
while (!(word.empty()) && !updatedPos)
{
rc = word.dequeue();
switch (rc)
{
case RenderCommand.FORWARD:
case RenderCommand.FORWARD2:
float x;
float y;
double theta = Math.Atan2(pos.y, pos.x);
x = (float)(forward * Math.Cos(theta));
y = (float)(forward * Math.Sin(theta));
//Debug.Log("THETA: X: " + x + " Y: " + y);
double r = Math.Sqrt(x * x + y * y);
x = (float)(r * Math.Cos(startHeading));
y = (float)(r * Math.Sin(startHeading));
//Debug.Log("R: X: " + x + " Y: " + y);
pos.x += x;
pos.y += y;
updatedPos = true;
break;
case RenderCommand.RIGHT:
startHeading += (turn * Math.PI / 180.0);
break;
case RenderCommand.LEFT:
startHeading += (-turn * Math.PI / 180.0);
break;
case RenderCommand.PUSH:
case RenderCommand.POP:
case RenderCommand.IGNORE:
default:
break;
}
word.enqueue(rc);
}
}
}
| 27.224 | 84 | 0.493682 | [
"MIT"
] | anamendes23/KochSnowflake | Assets/Scripts/KochSnowflakePattern.cs | 3,403 | 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
namespace Dnn.PersonaBar.SiteSettings.Services.Dto
{
using Newtonsoft.Json;
public class UpdateOtherSettingsRequest
{
public int? PortalId { get; set; }
public string CultureCode { get; set; }
public string AllowedExtensionsWhitelist { get; set; }
public bool EnablePopups { get; set; }
public bool InjectModuleHyperLink { get; set; }
public bool InlineEditorEnabled { get; set; }
public bool ShowQuickModuleAddMenu { get; set; }
}
}
| 29.16 | 72 | 0.673525 | [
"MIT"
] | Andy9999/Dnn.Platform | Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/SiteSettings/UpdateOtherSettingsRequest.cs | 731 | C# |
using Shinden.API;
using Shinden.Models.Initializers;
namespace Shinden.Models.Entities
{
public class Relation : IRelation
{
public Relation(InitRelation Init)
{
Id = Init.Id;
Title = Init.Title;
StaffId = Init.StaffId;
Language = Init.Language;
CharacterId = Init.CharacterId;
StaffPosition = Init.StaffPosition;
CharacterRole = Init.CharacterRole;
StaffLastName = Init.StaffLastName;
StaffFirstName = Init.StaffFirstName;
CharacterLastName = Init.CharacterLastName;
CharacterFirstName = Init.CharacterFirstName;
}
// IIndexable
public ulong Id { get; }
// IRelation
public string CharacterFirstName { get; }
public string CharacterLastName { get; }
public string StaffFirstName { get; }
public string StaffLastName { get; }
public string CharacterRole { get; }
public string StaffPosition { get; }
public ulong? CharacterId { get; }
public Language Language { get; }
public ulong? StaffId { get; }
public string Title { get; }
public override string ToString() => Title;
}
}
| 30.804878 | 57 | 0.598575 | [
"MIT"
] | MrZnake/Shinden.NET | src/Models/Entities/Relation.cs | 1,265 | C# |
using System;
namespace Main
{
class Program
{
static void Main(string[] args)
{
for(int i=1;i<20;i++){
if(i%15==0){
Console.WriteLine("FIZZ BUZZ");
}else if(i%3==0){
Console.WriteLine("FIZZ");
}else if(i%5==0){
Console.WriteLine("BUZZ");
}else{
Console.WriteLine(i.ToString());
}
}
}
}
}
| 22.173913 | 52 | 0.370588 | [
"MIT"
] | Kadoshita/OnedayOnelanguage | C-Sharp/FizzBuzz.cs | 510 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.IO;
using Microsoft.WindowsAzure.Storage.Blob; // Namespace for Blob storage types
//
namespace AzureUpload.Runner
{
public class AzureBlobUpload
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public CancellationToken cancellationToken;
// Blob
public string stringBlobUri = "";
// Storage queue
public string stringStorageQueueUri = "";
public async Task<bool> UploadAsync(string filePath)
{
try
{
// Create the blob client. TODO: add cancellationToken
CloudBlockBlob blobClient = new CloudBlockBlob(GenerateUriForFile(stringBlobUri, filePath));
// Upload the file
await blobClient.UploadFromFileAsync(filePath);
log.Info("Uploaded: " + filePath);
return true;
}
catch (Exception ex)
{
log.Error("Exception uploading file " + filePath, ex);
return false;
}
}
private Uri GenerateUriForFile(string url, string filePath)
{
// Get the file name (will be used to name the container i.e. files names must be unique or they will be overwritten)
string fileName = Path.GetFileName(filePath);
// Added the filename to the uri
var str = stringBlobUri.Split('?');
var newUri = str[0] + "/" + fileName + "?" + str[1];
// Generate Uri object
return new Uri(newUri);
}
}
}
| 22.263889 | 144 | 0.659389 | [
"MIT"
] | snitkjaer/AzureUpload | AzureUploadLib/AzureBlobUpload.cs | 1,609 | C# |
using System;
using Apizr.Requesting;
namespace Apizr.Mapping
{
/// <summary>
/// Tells Apizr to auto register an <see cref="IApizrManager{ICrudApi}"/> for the referenced api entity
/// and mapped to this decorated model entity (works only with IServiceCollection extensions registration)
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MappedCrudEntityAttribute : CrudEntityAttribute
{
/// <summary>
/// Define some crud api settings from this mapped model entity
/// </summary>
/// <param name="apiEntityBaseUri">The mapped api entity's base crud uri</param>
/// <param name="apiEntityType">The mapped api entity type</param>
/// <param name="apiEntityKeyType">The mapped api entity's crud key type (default: null = typeof(int))</param>
/// <param name="apiEntityReadAllResultType">The mapped api entity "ReadAll" query result type (default: null = typeof(IEnumerable{}))</param>
/// <param name="apiEntityReadAllParamsType">The mapped api entity ReadAll query parameters type (default: null = typeof(IDictionary{string, object}))</param>
public MappedCrudEntityAttribute(string apiEntityBaseUri, Type apiEntityType, Type apiEntityKeyType = null, Type apiEntityReadAllResultType = null, Type apiEntityReadAllParamsType = null) : base(apiEntityBaseUri, apiEntityKeyType, apiEntityReadAllResultType, apiEntityReadAllParamsType, apiEntityType)
{
}
public CrudEntityAttribute ToCrudEntityAttribute(Type modelEntityType)
{
var attribute = this as CrudEntityAttribute;
attribute.MappedEntityType = modelEntityType;
return attribute;
}
}
}
| 52.757576 | 309 | 0.705342 | [
"Apache-2.0"
] | Respawnsive/Apizr | Apizr/Apizr/Mapping/MappedCrudEntityAttribute.cs | 1,743 | C# |
using System;
using FluentAssertions;
using Newtonsoft.Json;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities;
using OmniSharp.Extensions.LanguageServer.Server.Messages;
using Serializer = OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Serializer;
using Xunit;
namespace Lsp.Tests.Messages
{
public class UnknownErrorCodeTests
{
[Theory, JsonFixture]
public void SimpleTest(string expected)
{
var model = new UnknownErrorCode();
var result = Fixture.SerializeObject(model);
result.Should().Be(expected);
var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject<RpcError>(expected);
deresult.Should().BeEquivalentTo(model);
}
}
}
| 31.035714 | 100 | 0.728423 | [
"MIT"
] | Bia10/csharp-language-server-protocol | test/Lsp.Tests/Messages/UnknownErrorCodeTests.cs | 869 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace OpenDart.Models
{
[XmlRoot("result")]
public class ResAlotMatterResult
{
[XmlElement("status")]
public string status { get; set; } // 에러 및 정보 코드 (※메시지 설명 참조)
[XmlElement("message")]
public string message { get; set; } // 에러 및 정보 메시지 (※메시지 설명 참조)
[XmlElement("list")]
public List<ResAlotMatterItem> list { get; set; } // 배당에 관한 사항 목록
public ResAlotMatterResult()
{
status = "";
message = "";
list = new List<ResAlotMatterItem>();
}
public void displayConsole()
{
Console.WriteLine("==================================================");
Console.WriteLine("ResAlotMatterResult Information");
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("corp_code: {0}", status);
Console.WriteLine("bgn_de: {0}", message);
foreach (ResAlotMatterItem item in list)
{
item.displayConsole();
}
Console.WriteLine("==================================================");
}
}
} | 33.736842 | 84 | 0.469579 | [
"MIT"
] | heenf22/OpenDart | OpenDart/ResAlotMatterResult.cs | 1,362 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebBrowserComponentWPF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("WebBrowserComponentWPF")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.178571 | 93 | 0.764889 | [
"MIT"
] | felixier/dotnet-windows | GUI_Tests/WebBrowserComponentTest/WebBrowserComponentWPF/Properties/AssemblyInfo.cs | 2,253 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Script.Middleware;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.HttpMiddleware
{
public class DefaultMiddlewarePipelineTests
{
[Fact]
public async Task RequestMiddleware_IsExecuted()
{
var pipeline = new DefaultMiddlewarePipeline(new List<IJobHostHttpMiddleware>());
var context = new DefaultHttpContext();
RequestDelegate requestDelegate = c =>
{
c.Items.Add(nameof(requestDelegate), string.Empty);
return Task.CompletedTask;
};
context.Items.Add(ScriptConstants.JobHostMiddlewarePipelineRequestDelegate, requestDelegate);
await pipeline.Pipeline(context);
Assert.Contains(nameof(requestDelegate), context.Items);
}
[Fact]
public async Task Middleware_IsExecutedInOrder()
{
var middleware = new List<IJobHostHttpMiddleware>
{
new TestMiddleware1(),
new TestMiddleware2()
};
var pipeline = new DefaultMiddlewarePipeline(middleware);
var context = new DefaultHttpContext();
context.Items["middlewarelist"] = string.Empty;
RequestDelegate requestDelegate = c =>
{
c.Items.Add(nameof(requestDelegate), string.Empty);
return Task.CompletedTask;
};
context.Items.Add(ScriptConstants.JobHostMiddlewarePipelineRequestDelegate, requestDelegate);
await pipeline.Pipeline(context);
Assert.Contains(nameof(TestMiddleware1) + nameof(TestMiddleware2), context.Items["middlewarelist"].ToString());
}
private class TestMiddleware1 : IJobHostHttpMiddleware
{
public async Task Invoke(HttpContext context, RequestDelegate next)
{
context.Items["middlewarelist"] += nameof(TestMiddleware1);
await next(context);
}
}
private class TestMiddleware2 : IJobHostHttpMiddleware
{
public async Task Invoke(HttpContext context, RequestDelegate next)
{
context.Items["middlewarelist"] += nameof(TestMiddleware2);
await next(context);
}
}
}
}
| 31.247059 | 123 | 0.622364 | [
"Apache-2.0",
"MIT"
] | AnatoliB/azure-functions-host | test/WebJobs.Script.Tests/HttpMiddleware/DefaultMiddlewarePipelineTests.cs | 2,658 | C# |
namespace Cryptofolio.Infrastructure.Entities
{
/// <summary>
/// Models a transaction of type "Transfer".
/// </summary>
public class TransferTransaction : Transaction
{
/// <summary>
/// The source.
/// </summary>
public string Source { get; set; }
/// <summary>
/// The destination.
/// </summary>
public string Destination { get; set; }
}
}
| 22.842105 | 50 | 0.536866 | [
"MIT"
] | fperronnet/cryptofolio | src/Cryptofolio.Infrastructure/Entities/TransferTransaction.cs | 434 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Connect;
using Amazon.Connect.Model;
namespace Amazon.PowerShell.Cmdlets.CONN
{
/// <summary>
/// Provides information about the hours of operation for the specified Amazon Connect
/// instance.
///
///
/// <para>
/// For more information about hours of operation, see <a href="https://docs.aws.amazon.com/connect/latest/adminguide/set-hours-operation.html">Set
/// the Hours of Operation for a Queue</a> in the <i>Amazon Connect Administrator Guide</i>.
/// </para><br/><br/>This cmdlet automatically pages all available results to the pipeline - parameters related to iteration are only needed if you want to manually control the paginated output. To disable autopagination, use -NoAutoIteration.
/// </summary>
[Cmdlet("Get", "CONNHoursOfOperationList")]
[OutputType("Amazon.Connect.Model.HoursOfOperationSummary")]
[AWSCmdlet("Calls the Amazon Connect Service ListHoursOfOperations API operation.", Operation = new[] {"ListHoursOfOperations"}, SelectReturnType = typeof(Amazon.Connect.Model.ListHoursOfOperationsResponse))]
[AWSCmdletOutput("Amazon.Connect.Model.HoursOfOperationSummary or Amazon.Connect.Model.ListHoursOfOperationsResponse",
"This cmdlet returns a collection of Amazon.Connect.Model.HoursOfOperationSummary objects.",
"The service call response (type Amazon.Connect.Model.ListHoursOfOperationsResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GetCONNHoursOfOperationListCmdlet : AmazonConnectClientCmdlet, IExecutor
{
#region Parameter InstanceId
/// <summary>
/// <para>
/// <para>The identifier of the Amazon Connect instance. You can find the instanceId in the
/// ARN of the instance.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String InstanceId { get; set; }
#endregion
#region Parameter MaxResult
/// <summary>
/// <para>
/// <para>The maximum number of results to return per page.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> In AWSPowerShell and AWSPowerShell.NetCore this parameter is used to limit the total number of items returned by the cmdlet.
/// <br/>In AWS.Tools this parameter is simply passed to the service to specify how many items should be returned by each service call.
/// <br/>Pipe the output of this cmdlet into Select-Object -First to terminate retrieving data pages early and control the number of items returned.
/// </para>
/// <para>If a value for this parameter is not specified the cmdlet will use a default value of '<b>100</b>'.</para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("MaxItems","MaxResults")]
public int? MaxResult { get; set; }
#endregion
#region Parameter NextToken
/// <summary>
/// <para>
/// <para>The token for the next set of results. Use the value returned in the previous response
/// in the next request to retrieve the next set of results.</para>
/// </para>
/// <para>
/// <br/><b>Note:</b> This parameter is only used if you are manually controlling output pagination of the service API call.
/// <br/>In order to manually control output pagination, use '-NextToken $null' for the first call and '-NextToken $AWSHistory.LastServiceResponse.NextToken' for subsequent calls.
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String NextToken { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is 'HoursOfOperationSummaryList'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Connect.Model.ListHoursOfOperationsResponse).
/// Specifying the name of a property of type Amazon.Connect.Model.ListHoursOfOperationsResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "HoursOfOperationSummaryList";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the InstanceId parameter.
/// The -PassThru parameter is deprecated, use -Select '^InstanceId' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^InstanceId' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter NoAutoIteration
/// <summary>
/// By default the cmdlet will auto-iterate and retrieve all results to the pipeline by performing multiple
/// service calls. If set, the cmdlet will retrieve only the next 'page' of results using the value of NextToken
/// as the start point.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoAutoIteration { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Connect.Model.ListHoursOfOperationsResponse, GetCONNHoursOfOperationListCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.InstanceId;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.InstanceId = this.InstanceId;
#if MODULAR
if (this.InstanceId == null && ParameterWasBound(nameof(this.InstanceId)))
{
WriteWarning("You are passing $null as a value for parameter InstanceId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.MaxResult = this.MaxResult;
#if MODULAR
if (!ParameterWasBound(nameof(this.MaxResult)))
{
WriteVerbose("MaxResult parameter unset, using default value of '100'");
context.MaxResult = 100;
}
#endif
#if !MODULAR
if (ParameterWasBound(nameof(this.MaxResult)) && this.MaxResult.HasValue)
{
WriteWarning("AWSPowerShell and AWSPowerShell.NetCore use the MaxResult parameter to limit the total number of items returned by the cmdlet." +
" This behavior is obsolete and will be removed in a future version of these modules. Pipe the output of this cmdlet into Select-Object -First to terminate" +
" retrieving data pages early and control the number of items returned. AWS.Tools already implements the new behavior of simply passing MaxResult" +
" to the service to specify how many items should be returned by each service call.");
}
#endif
context.NextToken = this.NextToken;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
#if MODULAR
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
// create request and set iteration invariants
var request = new Amazon.Connect.Model.ListHoursOfOperationsRequest();
if (cmdletContext.InstanceId != null)
{
request.InstanceId = cmdletContext.InstanceId;
}
if (cmdletContext.MaxResult != null)
{
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToServiceTypeInt32(cmdletContext.MaxResult.Value);
}
// Initialize loop variant and commence piping
var _nextToken = cmdletContext.NextToken;
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
_nextToken = response.NextToken;
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#else
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
var useParameterSelect = this.Select.StartsWith("^") || this.PassThru.IsPresent;
// create request and set iteration invariants
var request = new Amazon.Connect.Model.ListHoursOfOperationsRequest();
if (cmdletContext.InstanceId != null)
{
request.InstanceId = cmdletContext.InstanceId;
}
// Initialize loop variants and commence piping
System.String _nextToken = null;
int? _emitLimit = null;
int _retrievedSoFar = 0;
if (AutoIterationHelpers.HasValue(cmdletContext.NextToken))
{
_nextToken = cmdletContext.NextToken;
}
if (cmdletContext.MaxResult.HasValue)
{
// The service has a maximum page size of 100. If the user has
// asked for more items than page max, and there is no page size
// configured, we rely on the service ignoring the set maximum
// and giving us 100 items back. If a page size is set, that will
// be used to configure the pagination.
// We'll make further calls to satisfy the user's request.
_emitLimit = cmdletContext.MaxResult;
}
var _userControllingPaging = this.NoAutoIteration.IsPresent || ParameterWasBound(nameof(this.NextToken));
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
do
{
request.NextToken = _nextToken;
if (_emitLimit.HasValue)
{
int correctPageSize = Math.Min(100, _emitLimit.Value);
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(correctPageSize);
}
else if (!ParameterWasBound(nameof(this.MaxResult)))
{
request.MaxResults = AutoIterationHelpers.ConvertEmitLimitToInt32(100);
}
CmdletOutput output;
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
if (!useParameterSelect)
{
pipelineOutput = cmdletContext.Select(response, this);
}
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
int _receivedThisCall = response.HoursOfOperationSummaryList.Count;
_nextToken = response.NextToken;
_retrievedSoFar += _receivedThisCall;
if (_emitLimit.HasValue)
{
_emitLimit -= _receivedThisCall;
}
}
catch (Exception e)
{
if (_retrievedSoFar == 0 || !_emitLimit.HasValue)
{
output = new CmdletOutput { ErrorResponse = e };
}
else
{
break;
}
}
ProcessOutput(output);
} while (!_userControllingPaging && AutoIterationHelpers.HasValue(_nextToken) && (!_emitLimit.HasValue || _emitLimit.Value >= 1));
if (useParameterSelect)
{
WriteObject(cmdletContext.Select(null, this));
}
return null;
}
#endif
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Connect.Model.ListHoursOfOperationsResponse CallAWSServiceOperation(IAmazonConnect client, Amazon.Connect.Model.ListHoursOfOperationsRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Connect Service", "ListHoursOfOperations");
try
{
#if DESKTOP
return client.ListHoursOfOperations(request);
#elif CORECLR
return client.ListHoursOfOperationsAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String InstanceId { get; set; }
public int? MaxResult { get; set; }
public System.String NextToken { get; set; }
public System.Func<Amazon.Connect.Model.ListHoursOfOperationsResponse, GetCONNHoursOfOperationListCmdlet, object> Select { get; set; } =
(response, cmdlet) => response.HoursOfOperationSummaryList;
}
}
}
| 47.1475 | 281 | 0.585768 | [
"Apache-2.0"
] | QPC-database/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/Connect/Basic/Get-CONNHoursOfOperationList-Cmdlet.cs | 18,859 | C# |
using SoulsFormats;
using System.Collections.Generic;
using System.Numerics;
namespace HKX2
{
public partial class hclSceneDataSetupMeshSection : hkReferencedObject
{
public override uint Signature { get => 180466600; }
public hclSceneDataSetupMesh m_setupMesh;
public hkxMeshSection m_meshSection;
public bool m_skinnedSection;
public override void Read(PackFileDeserializer des, BinaryReaderEx br)
{
base.Read(des, br);
br.ReadUInt64();
m_setupMesh = des.ReadClassPointer<hclSceneDataSetupMesh>(br);
m_meshSection = des.ReadClassPointer<hkxMeshSection>(br);
m_skinnedSection = br.ReadBoolean();
br.ReadUInt32();
br.ReadUInt16();
br.ReadByte();
}
public override void Write(PackFileSerializer s, BinaryWriterEx bw)
{
base.Write(s, bw);
bw.WriteUInt64(0);
s.WriteClassPointer<hclSceneDataSetupMesh>(bw, m_setupMesh);
s.WriteClassPointer<hkxMeshSection>(bw, m_meshSection);
bw.WriteBoolean(m_skinnedSection);
bw.WriteUInt32(0);
bw.WriteUInt16(0);
bw.WriteByte(0);
}
}
}
| 32.025 | 78 | 0.60968 | [
"MIT"
] | SyllabusGames/DSMapStudio | HKX2/Autogen/hclSceneDataSetupMeshSection.cs | 1,281 | C# |
using UnityEngine;
using com.spacepuppy.Utils;
namespace com.spacepuppy.Tween.Curves
{
[CustomMemberCurve(typeof(Vector2))]
public class Vector2MemberCurve : MemberCurve, ISupportRedirectToMemberCurve
{
#region Fields
private Vector2 _start;
private Vector2 _end;
private bool _useSlerp;
#endregion
#region CONSTRUCTOR
protected Vector2MemberCurve()
{
}
public Vector2MemberCurve(string propName, float dur, Vector2 start, Vector2 end)
: base(propName, dur)
{
_start = start;
_end = end;
_useSlerp = false;
}
public Vector2MemberCurve(string propName, float dur, Vector2 start, Vector2 end, bool slerp)
: base(propName, dur)
{
_start = start;
_end = end;
_useSlerp = slerp;
}
public Vector2MemberCurve(string propName, Ease ease, float dur, Vector2 start, Vector2 end)
: base(propName, ease, dur)
{
_start = start;
_end = end;
_useSlerp = false;
}
public Vector2MemberCurve(string propName, Ease ease, float dur, Vector2 start, Vector2 end, bool slerp)
: base(propName, ease, dur)
{
_start = start;
_end = end;
_useSlerp = slerp;
}
protected override void ReflectiveInit(System.Type memberType, object start, object end, object option)
{
_start = ConvertUtil.ToVector2(start);
_end = ConvertUtil.ToVector2(end);
_useSlerp = ConvertUtil.ToBool(option);
}
void ISupportRedirectToMemberCurve.ConfigureAsRedirectTo(System.Type memberType, float totalDur, object current, object start, object end, object option)
{
_useSlerp = ConvertUtil.ToBool(option);
if (_useSlerp)
{
var c = ConvertUtil.ToVector2(current);
var s = ConvertUtil.ToVector2(start);
var e = ConvertUtil.ToVector2(end);
_start = c;
_end = e;
var at = Vector2.Angle(s, e);
if ((System.Math.Abs(at) < MathUtil.EPSILON))
{
this.Duration = 0f;
}
else
{
var ap = Vector2.Angle(c, e);
this.Duration = totalDur * ap / at;
}
}
else
{
var c = ConvertUtil.ToVector2(current);
var s = ConvertUtil.ToVector2(start);
var e = ConvertUtil.ToVector2(end);
_start = c;
_end = e;
c -= e;
s -= e;
if (VectorUtil.NearZeroVector(s))
{
this.Duration = 0f;
}
else
{
this.Duration = totalDur * Vector3.Dot(c, s.normalized) / Vector3.Dot(s, c.normalized);
}
}
}
#endregion
#region Properties
public Vector2 Start
{
get { return _start; }
set { _start = value; }
}
public Vector2 End
{
get { return _end; }
set { _end = value; }
}
public bool UseSlerp
{
get { return _useSlerp; }
set { _useSlerp = value; }
}
#endregion
#region MemberCurve Interface
protected override object GetValueAt(float dt, float t)
{
if (this.Duration == 0f) return _end;
t = this.Ease(t, 0f, 1f, this.Duration);
return (_useSlerp) ? VectorUtil.Slerp(_start, _end, t) : Vector2.LerpUnclamped(_start, _end, t);
}
#endregion
}
}
| 26.891156 | 161 | 0.494561 | [
"Unlicense"
] | dipique/spacepuppy-unity-framework-3.0 | SPTween/Tween/Curves/Vector2MemberCurve.cs | 3,955 | C# |
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace Tailwind.Traders.WebBff.Infrastructure
{
public class HttpClientAuthorizationDelegatingHandler
: DelegatingHandler
{
private readonly IHttpContextAccessor _httpContextAccesor;
private const string SCHEME = "Email";
public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccesor)
{
_httpContextAccesor = httpContextAccesor;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var authorizationHeader = _httpContextAccesor.HttpContext
.Request.Headers["Authorization"];
var authHeader = authorizationHeader[0].Split(" ");
if (!string.IsNullOrEmpty(authorizationHeader) && authHeader[0].Equals(SCHEME))
{
request.Headers.Authorization = new AuthenticationHeaderValue(SCHEME, authHeader[1]);
}
return await base.SendAsync(request, cancellationToken);
}
}
}
| 33 | 133 | 0.699301 | [
"MIT"
] | NileshGule/TailwindTraders-Backend | Source/ApiGWs/Tailwind.Traders.WebBff/Infrastructure/HttpClientAuthorizationDelegatingHandler.cs | 1,289 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
namespace DataProject4_Graphs
{
internal class Algorithms
{
private int minDistance(int[] dist, bool[] sptSet,int MAX)
{
int min = Int16.MaxValue, min_index=0;
for (int v = 0; v < MAX; v++)
if (sptSet[v] == false && dist[v] <= min)
{
min = dist[v];
min_index = v;
}
return min_index;
}
public int dijkstra(int[,] graph, int MAX, int src, int dest)
{
int[] dist = new int[MAX];
bool[] sptSet = new bool[MAX];
for (int i = 0; i < MAX; i++)
{
dist[i] = Int16.MaxValue;
sptSet[i] = false;
}
dist[src] = 0;
for (int count = 0; count < MAX-1; count++)
{
int u = minDistance(dist, sptSet,MAX);
sptSet[u] = true;
for (int v = 0; v < MAX; v++)
if (!sptSet[v] && (graph[u, v] != null) && dist[u] != Int16.MaxValue
&& dist[u]+graph[u,v] < dist[v])
dist[v] = dist[u] + graph[u,v];
}
return dist[dest];
}
public void DFS(int[,] graph, int MAX, int src)
{
bool[] visited = new bool[MAX];
DFS(graph, visited, MAX, src);
}
private void DFS(int[,] graph, bool[] visited, int MAX, int src)
{
Console.WriteLine("Şuan " + src + "nci tepeyi dolaştık.");
visited[src] = true;
for (int i = 0; i < MAX; i++)
if (graph[src, i] < Int16.MaxValue && !visited[i])//aradaki mesafe sonsuz değilse ve o köşe daha önce dolaşılmadıysa
DFS(graph, visited, MAX, i); //recursive olarak kökü o anki değer olarak fonksiyon tekrar çağırılır
}
public int[,] floydWarshell (int[,] graph, int MAX)
{
int[,] dist = new int[MAX,MAX];
int i, j, k;
for (i = 0; i < MAX; i++)
for (j = 0; j < MAX; j++)
dist[i,j] = graph[i,j];
for (k = 0; k < MAX; k++)
for (i = 0; i < MAX; i++)
for (j = 0; j < MAX; j++)
if (dist[i,k] + dist[k,j] < dist[i,j])
dist[i,j] = dist[i,k] + dist[k,j];
return dist;
}
public Queue<int> BFS(int[,] graph, int MAX, int src)//dolaşılacak elemanların sırasını kuyruk şeklinde döndürür
{ //src dolaşmaya başlanacak nokta
bool[] visited = new bool[MAX];
Queue<int> queue = new Queue<int>();
Queue<int> dolasmaSirasi = new Queue<int>();
queue.Enqueue(src);
visited[src] = true;
dolasmaSirasi.Enqueue(src);
while (queue.Count != 0)
{
int gecici=queue.Dequeue();
for (int i = 0; i < MAX; i++)
{
if (graph[gecici, i] < Int16.MaxValue && !visited[i])
{
dolasmaSirasi.Enqueue(i);
visited[i] = true;
queue.Enqueue(i);
}
}
}
return dolasmaSirasi;
}
}
} | 36 | 146 | 0.411897 | [
"BSD-3-Clause"
] | tolgahanakgun/School-Projects | Data Structures/Project 4A - [C#]/Social Network/DS_Project4/Algorithms.cs | 3,596 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
using tests.Clipping;
using tests.FontTest;
using tests.Extensions;
using Box2D.TestBed;
namespace tests
{
public class TestController : CCLayer
{
const int MENU_ITEM_Z_ORDER = 10000;
static int LINE_SPACE = 70;
static CCPoint curPos = CCPoint.Zero;
int currentItemIndex = 0;
CCPoint homePosition;
CCPoint lastPosition;
CCPoint beginTouchPos;
CCSprite menuIndicator;
CCLabelTtf versionLabel;
CCMenu testListMenu;
List<CCMenuItem> testListMenuItems = new List<CCMenuItem>();
CCMenu closeMenu;
CCMenuItem closeMenuItem;
#region Constructors
public TestController()
{
// Add close menu
closeMenuItem = new CCMenuItemImage(TestResource.s_pPathClose, TestResource.s_pPathClose, CloseCallback);
closeMenu = new CCMenu(closeMenuItem);
CCMenuItemFont.FontName = "MarkerFelt";
CCMenuItemFont.FontSize = 22;
#if !PSM && !WINDOWS_PHONE
#if NETFX_CORE
versionLabel = new CCLabelTtf("v" + this.GetType().GetAssemblyName().Version.ToString(), "arial", 30);
#else
versionLabel = new CCLabelTtf("v" + this.GetType().Assembly.GetName().Version.ToString(), "arial", 30);
#endif
AddChild(versionLabel, 20000);
#endif
// Add test list menu
testListMenu = new CCMenu();
for (int i = 0; i < (int)(TestCases.TESTS_COUNT); ++i)
{
CCLabelTtf label = new CCLabelTtf(Tests.g_aTestNames[i], "arial", 50);
CCMenuItem menuItem = new CCMenuItemLabelTTF(label, MenuCallback);
testListMenu.AddChild(menuItem, i + MENU_ITEM_Z_ORDER);
testListMenuItems.Add(menuItem);
}
#if XBOX || OUYA
CCSprite sprite = new CCSprite("Images/aButton");
AddChild(sprite, 10001);
menuIndicator = sprite;
#endif
AddChild(testListMenu);
AddChild(closeMenu, 1);
}
#endregion Constructors
#region Setup content
public override void OnEnter()
{
base.OnEnter();
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
// Laying out content based on window size
closeMenu.Position = CCPoint.Zero;
closeMenuItem.Position = new CCPoint(visibleBounds.Size.Width - 40, visibleBounds.Size.Height - 40);
#if !PSM && !WINDOWS_PHONE
versionLabel.HorizontalAlignment = CCTextAlignment.Left;
versionLabel.Position = new CCPoint (10.0f, visibleBounds.Size.Height - 40);
#endif
testListMenu.ContentSize = new CCSize(visibleBounds.Size.Width, ((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE);
int i = 0;
foreach (CCMenuItem testItem in testListMenuItems)
{
testItem.Position = new CCPoint(visibleBounds.Size.Width /2.0f, (visibleBounds.Size.Height - (i + 1) * LINE_SPACE));
i++;
}
#if XBOX || OUYA
// Center the menu on the first item so that it is
// in the center of the screen
homePosition = new CCPoint(0f, visibleBounds.Size.Height / 2f + LINE_SPACE / 2f);
lastPosition = new CCPoint(0f, homePosition.Y - (testListMenuItems.Count - 1) * LINE_SPACE);
#else
homePosition = curPos;
#endif
testListMenu.Position = homePosition;
// Add listeners
#if !XBOX && !OUYA
var touchListener = new CCEventListenerTouchOneByOne ();
touchListener.IsSwallowTouches = true;
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchMoved = OnTouchMoved;
AddEventListener(touchListener);
var mouseListener = new CCEventListenerMouse ();
mouseListener.OnMouseScroll = OnMouseScroll;
AddEventListener(mouseListener);
#endif
#if WINDOWS || WINDOWSGL || MACOS
EnableGamePad();
#endif
// set the first one to have the selection highlight
currentItemIndex = 0;
//SelectMenuItem();
}
#endregion Setup content
#region Menu item handling
void SelectMenuItem()
{
if (currentItemIndex < testListMenuItems.Count)
{
testListMenuItems [currentItemIndex].Selected = true;
if (menuIndicator != null) {
menuIndicator.Position = new CCPoint (
testListMenu.Position.X + testListMenuItems [currentItemIndex].Position.X
- testListMenuItems[currentItemIndex].ContentSize.Width / 2f - menuIndicator.ContentSize.Width / 2f - 5f,
testListMenu.Position.Y + testListMenuItems [currentItemIndex].Position.Y
);
}
}
}
void NextMenuItem()
{
testListMenuItems[currentItemIndex].Selected = false;
currentItemIndex = (currentItemIndex + 1) % testListMenuItems.Count;
CCSize winSize = Layer.VisibleBoundsWorldspace.Size;
testListMenu.Position = (new CCPoint(0, homePosition.Y + currentItemIndex * LINE_SPACE));
curPos = testListMenu.Position;
SelectMenuItem();
}
void PreviousMenuItem()
{
testListMenuItems[currentItemIndex].Selected = false;
currentItemIndex--;
if(currentItemIndex < 0) {
currentItemIndex = testListMenuItems.Count - 1;
}
CCSize winSize = Layer.VisibleBoundsWorldspace.Size;
testListMenu.Position = (new CCPoint(0, homePosition.Y + currentItemIndex * LINE_SPACE));
curPos = testListMenu.Position;
SelectMenuItem();
}
#endregion Menu item handling
void MenuCallback(object sender)
{
// get the userdata, it's the index of the menu item clicked
CCMenuItem menuItem = (CCMenuItem)sender;
var nIdx = menuItem.LocalZOrder - MENU_ITEM_Z_ORDER;
// create the test scene and run it
TestScene scene = CreateTestScene(nIdx);
if (scene != null)
{
scene.runThisTest();
}
}
void CloseCallback(object sender)
{
Application.ExitGame();
}
void EnableGamePad()
{
var AButtonWasPressed = false;
var gamePadListener = new CCEventListenerGamePad ();
gamePadListener.OnButtonStatus = (buttonStatus) =>
{
if (buttonStatus.A == CCGamePadButtonStatus.Pressed)
{
AButtonWasPressed = true;
}
else if (buttonStatus.A == CCGamePadButtonStatus.Released && AButtonWasPressed)
{
// Select the menu
testListMenuItems[currentItemIndex].Activate();
testListMenuItems[currentItemIndex].Selected = false;
}
};
long firstTicks = 0;
bool isDownPressed = false;
bool isUpPressed = false;
gamePadListener.OnDPadStatus = (dpadStatus) =>
{
// Down and Up only
if (dpadStatus.Down == CCGamePadButtonStatus.Pressed)
{
if (firstTicks == 0L)
{
firstTicks = DateTime.Now.Ticks;
isDownPressed = true;
}
}
else if (dpadStatus.Down == CCGamePadButtonStatus.Released && firstTicks > 0L && isDownPressed)
{
firstTicks = 0L;
NextMenuItem ();
isDownPressed = false;
}
if (dpadStatus.Up == CCGamePadButtonStatus.Pressed)
{
if (firstTicks == 0L) {
firstTicks = DateTime.Now.Ticks;
isUpPressed = true;
}
}
else if (dpadStatus.Up == CCGamePadButtonStatus.Released && firstTicks > 0L && isUpPressed)
{
firstTicks = 0L;
PreviousMenuItem ();
isUpPressed = false;
}
};
gamePadListener.OnConnectionStatus = (connectionStatus) =>
{
CCLog.Log("Player {0} is connected {1}", connectionStatus.Player, connectionStatus.IsConnected);
};
AddEventListener(gamePadListener);
}
#region Event handling
bool OnTouchBegan(CCTouch touch, CCEvent touchEvent)
{
beginTouchPos = touch.Location;
return true;
}
void OnTouchMoved(CCTouch touch, CCEvent touchEvent)
{
var touchLocation = touch.Location;
float nMoveY = touchLocation.Y - beginTouchPos.Y;
curPos = testListMenu.Position;
CCPoint nextPos = new CCPoint(curPos.X, curPos.Y + nMoveY);
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
if (nextPos.Y < 0.0f)
{
testListMenu.Position = new CCPoint(0, 0);
return;
}
if (nextPos.Y > (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height))
{
testListMenu.Position = (new CCPoint(0, (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height)));
return;
}
testListMenu.Position = nextPos;
beginTouchPos = touchLocation;
curPos = nextPos;
}
void OnMouseScroll(CCEventMouse mouseEvent)
{
// Due to a bug in MonoGame the menu will jump around on Mac when hitting the top element
// https://github.com/mono/MonoGame/issues/2276
var delta = mouseEvent.ScrollY;
CCRect visibleBounds = Layer.VisibleBoundsWorldspace;
curPos = testListMenu.Position;
var nextPos = curPos;
nextPos.Y -= (delta) / LINE_SPACE;
if (nextPos.Y < 0)
{
testListMenu.Position = CCPoint.Zero;
return;
}
if (nextPos.Y > (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height))
{
testListMenu.Position = (new CCPoint(0, (((int)TestCases.TESTS_COUNT + 1) * LINE_SPACE - visibleBounds.Size.Height)));
return;
}
testListMenu.Position = nextPos;
curPos = nextPos;
}
#endregion Event handling
public static TestScene CreateTestScene(int index)
{
//Application.PurgeAllCachedData();
TestScene scene = null;
switch(index)
{
case (int)TestCases.TEST_ACTIONS:
scene = new ActionsTestScene(); break;
case (int)TestCases.TEST_TRANSITIONS:
scene = new TransitionsTestScene(); break;
case (int)TestCases.TEST_PROGRESS_ACTIONS:
scene = new ProgressActionsTestScene(); break;
case (int)TestCases.TEST_EFFECTS:
scene = new EffectTestScene(); break;
case (int)TestCases.TEST_CLICK_AND_MOVE:
scene = new ClickAndMoveTest(); break;
case (int)TestCases.TEST_ROTATE_WORLD:
scene = new RotateWorldTestScene(); break;
case (int)TestCases.TEST_PARTICLE:
scene = new ParticleTestScene(); break;
case (int)TestCases.TEST_EASE_ACTIONS:
scene = new EaseActionsTestScene(); break;
case (int)TestCases.TEST_MOTION_STREAK:
scene = new MotionStreakTestScene(); break;
case (int)TestCases.TEST_DRAW_PRIMITIVES:
scene = new DrawPrimitivesTestScene(); break;
case (int)TestCases.TEST_COCOSNODE:
scene = new CocosNodeTestScene(); break;
case (int)TestCases.TEST_TOUCHES:
scene = new PongScene(); break;
case (int)TestCases.TEST_MENU:
scene = new MenuTestScene(); break;
case (int)TestCases.TEST_ACTION_MANAGER:
scene = new ActionManagerTestScene(); break;
case (int)TestCases.TEST_LAYER:
scene = new LayerTestScene(); break;
case (int)TestCases.TEST_SCENE:
scene = new SceneTestScene(); break;
case (int)TestCases.TEST_PARALLAX:
scene = new ParallaxTestScene(); break;
case (int)TestCases.TEST_TILE_MAP:
scene = new TileMapTestScene(); break;
case (int)TestCases.TEST_INTERVAL:
scene = new IntervalTestScene(); break;
case (int)TestCases.TEST_LABEL:
scene = new AtlasTestScene(); break;
case (int)TestCases.TEST_TEXT_INPUT:
scene = new TextInputTestScene(); break;
case (int)TestCases.TEST_SPRITE:
scene = new SpriteTestScene(); break;
case (int)TestCases.TEST_SCHEDULER:
scene = new SchedulerTestScene(); break;
case (int)TestCases.TEST_RENDERTEXTURE:
scene = new RenderTextureScene(); break;
case (int)TestCases.TEST_TEXTURE2D:
scene = new TextureTestScene(); break;
case (int)TestCases.TEST_BOX2D:
scene = new Box2DTestScene(); break;
case (int)TestCases.TEST_BOX2DBED2:
scene = new Box2D.TestBed.Box2dTestBedScene(); break;
case (int)TestCases.TEST_EFFECT_ADVANCE:
scene = new EffectAdvanceScene(); break;
case (int)TestCases.TEST_ACCELEROMRTER:
scene = new AccelerometerTestScene(); break;
case (int)TestCases.TEST_COCOSDENSHION:
scene = new CocosDenshionTestScene(); break;
case (int)TestCases.TEST_PERFORMANCE:
scene = new PerformanceTestScene(); break;
case (int)TestCases.TEST_ZWOPTEX:
scene = new ZwoptexTestScene(); break;
case (int)TestCases.TEST_FONTS:
scene = new FontTestScene(); break;
#if IPHONE || IOS || MACOS || WINDOWSGL || WINDOWS || (ANDROID && !OUYA) || NETFX_CORE
case (int)TestCases.TEST_SYSTEM_FONTS:
scene = new SystemFontTestScene(); break;
#endif
case (int)TestCases.TEST_CLIPPINGNODE:
scene = new ClippingNodeTestScene();
break;
case (int)TestCases.TEST_EXTENSIONS:
scene = new ExtensionsTestScene();
break;
case (int)TestCases.TEST_ORIENTATION:
scene = new OrientationTestScene();
break;
case(int)TestCases.TEST_MULTITOUCH:
scene = new MultiTouchTestScene();
break;
case(int)TestCases.TEST_EVENTDISPATCHER:
scene = new EventDispatcherTestScene();
break;
#if USE_PHYSICS
case(int)TestCases.TEST_PHYSICS:
scene = new PhysicsTestScene();
break;
#endif
default:
break;
}
return scene;
}
}
} | 36.724215 | 134 | 0.53764 | [
"MIT"
] | mhbsti/CocosSharp | tests/tests/classes/controller.cs | 16,379 | C# |
// +build android
// package android -- go2cs converted at 2020 October 09 05:45:46 UTC
// import "cmd/go/internal/imports/testdata/android" ==> using android = go.cmd.go.@internal.imports.testdata.android_package
// Original source: C:\Go\src\cmd\go\internal\imports\testdata\android\e.go
using _e_ = go.e_package; }
| 40.375 | 125 | 0.739938 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/cmd/go/internal/imports/testdata/android/e.cs | 323 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Com.Nostra13.Universalimageloader.Core;
using Windows.UI.Xaml.Media;
namespace $ext_safeprojectname$.Droid
{
[global::Android.App.ApplicationAttribute(
Label = "@string/ApplicationName",
LargeHeap = true,
HardwareAccelerated = true,
Theme = "@style/AppTheme"
)]
public class Application : Windows.UI.Xaml.NativeApplication
{
public Application(IntPtr javaReference, JniHandleOwnership transfer)
: base(new App(), javaReference, transfer)
{
ConfigureUniversalImageLoader();
}
private void ConfigureUniversalImageLoader()
{
// Create global configuration and initialize ImageLoader with this config
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(Context)
.Build();
ImageLoader.Instance.Init(config);
ImageSource.DefaultImageLoader = ImageLoader.Instance.LoadImageAsync;
}
}
}
| 24.386364 | 77 | 0.771668 | [
"Apache-2.0"
] | ATHULBABYKURIAN/uno | src/SolutionTemplate/UnoSolutionTemplate/Droid/Main.cs | 1,073 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.261
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ULib.Startup.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ULib.Startup.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 43.515625 | 178 | 0.612567 | [
"MIT"
] | mind0n/hive | History/Samples/Winform/platform/Winform.Startup/Properties/Resources.Designer.cs | 2,787 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace Blazui.Admin
{
[Resources]
public enum AdminResources
{
[Description("更新角色")]
UpdateRole,
[Description("删除角色")]
DeleteRole,
[Description("更新用户")]
UpdateUser,
[Description("删除用户")]
DeleteUser,
[Description("创建角色")]
CreateRole,
[Description("创建用户")]
CreateUser,
[Description("重置密码")]
ResetPassword,
[Description("修改密码")]
ModifyPassword
}
}
| 16.583333 | 33 | 0.569514 | [
"MIT"
] | 188867052/Element-Blazor | src/Admin/Admin/AdminResources.cs | 663 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Vpc.Model.V20160428
{
public class AddIPv6TranslatorAclListEntryResponse : AcsResponse
{
private string requestId;
private string aclEntryId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string AclEntryId
{
get
{
return aclEntryId;
}
set
{
aclEntryId = value;
}
}
}
}
| 22.947368 | 66 | 0.69419 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-vpc/Vpc/Model/V20160428/AddIPv6TranslatorAclListEntryResponse.cs | 1,308 | C# |
using Unity.Entities;
namespace ArcCore.Gameplay.Components
{
public struct ArcColorID : ISharedComponentData
{
/// <summary>
/// The colorId of this arc
/// </summary>
public int id;
public ArcColorID(int id)
{
this.id = id;
}
}
}
| 17.444444 | 51 | 0.531847 | [
"MIT"
] | 0thElement/ArcCore | Assets/Scripts/Gameplay/Components/Instance/ArcColorID.cs | 314 | C# |
using ObjCRuntime;
namespace Toggl.iOS.Intents
{
[Native]
public enum ContinueTimerIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch,
FailureNoApiToken = 100,
SuccessWithEntryDescription
}
[Native]
public enum ShowReportIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch
}
[Native]
public enum ShowReportPeriodReportPeriod : long
{
Unknown = 0,
Today = 1,
Yesterday = 2,
ThisWeek = 3,
LastWeek = 4,
ThisMonth = 5,
LastMonth = 6,
ThisYear = 7,
LastYear = 8
}
[Native]
public enum ShowReportPeriodIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch
}
[Native]
public enum StartTimerFromClipboardIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch,
FailureNoApiToken = 100,
FailureSyncConflict
}
[Native]
public enum StartTimerIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch,
FailureNoApiToken = 100,
FailureSyncConflict
}
[Native]
public enum StopTimerIntentResponseCode : long
{
Unspecified = 0,
Ready,
ContinueInApp,
InProgress,
Success,
Failure,
FailureRequiringAppLaunch,
FailureNoTimerRunning = 100,
FailureNoApiToken,
SuccessWithEmptyDescription,
FailureSyncConflict
}
}
| 15.782178 | 61 | 0.729611 | [
"BSD-3-Clause"
] | moljac/mobileapp | Toggl.iOS.IntentBinding/StructsAndEnums.cs | 1,594 | C# |
using System.Collections.Generic;
namespace Engine
{
public class Quest
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<QuestCompletionItem> QuestCompletionItems { get; set; }
public int RewardExperiencePoints { get; set; }
public int RewardGold { get; set; }
public Item RewardItem { get; set; }
/// <summary>
/// 任务
/// </summary>
/// <param name="id">唯一ID</param>
/// <param name="name">任务名</param>
/// <param name="description">任务描述</param>
/// <param name="rewardExperiencePoints">奖励经验值</param>
/// <param name="rewardGold">奖励金币</param>
public Quest(int id, string name, string description, int rewardExperiencePoints, int rewardGold)
{
ID = id;
Name = name;
Description = description;
RewardExperiencePoints = rewardExperiencePoints;
RewardGold = rewardGold;
QuestCompletionItems = new List<QuestCompletionItem>();
}
}
}
| 28.058824 | 99 | 0.68239 | [
"MIT"
] | Kingsmai/bug-fac-bugventure | Engine/Quest.cs | 996 | C# |
// ------------------------------------------------------------------------------
// <copyright file="CodeNamespaceCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ------------------------------------------------------------------------------
//
namespace System.CodeDom {
using System;
using System.Collections;
using System.Runtime.InteropServices;
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection"]/*' />
/// <devdoc>
/// <para>
/// A collection that stores <see cref='System.CodeDom.CodeNamespace'/> objects.
/// </para>
/// </devdoc>
[
ClassInterface(ClassInterfaceType.AutoDispatch),
ComVisible(true),
Serializable,
]
public class CodeNamespaceCollection : CollectionBase {
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.CodeNamespaceCollection"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.CodeNamespaceCollection'/>.
/// </para>
/// </devdoc>
public CodeNamespaceCollection() {
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.CodeNamespaceCollection1"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.CodeNamespaceCollection'/> based on another <see cref='System.CodeDom.CodeNamespaceCollection'/>.
/// </para>
/// </devdoc>
public CodeNamespaceCollection(CodeNamespaceCollection value) {
this.AddRange(value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.CodeNamespaceCollection2"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of <see cref='System.CodeDom.CodeNamespaceCollection'/> containing any array of <see cref='System.CodeDom.CodeNamespace'/> objects.
/// </para>
/// </devdoc>
public CodeNamespaceCollection(CodeNamespace[] value) {
this.AddRange(value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.this"]/*' />
/// <devdoc>
/// <para>Represents the entry at the specified index of the <see cref='System.CodeDom.CodeNamespace'/>.</para>
/// </devdoc>
public CodeNamespace this[int index] {
get {
return ((CodeNamespace)(List[index]));
}
set {
List[index] = value;
}
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.Add"]/*' />
/// <devdoc>
/// <para>Adds a <see cref='System.CodeDom.CodeNamespace'/> with the specified value to the
/// <see cref='System.CodeDom.CodeNamespaceCollection'/> .</para>
/// </devdoc>
public int Add(CodeNamespace value) {
return List.Add(value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.AddRange"]/*' />
/// <devdoc>
/// <para>Copies the elements of an array to the end of the <see cref='System.CodeDom.CodeNamespaceCollection'/>.</para>
/// </devdoc>
public void AddRange(CodeNamespace[] value) {
if (value == null) {
throw new ArgumentNullException("value");
}
for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) {
this.Add(value[i]);
}
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.AddRange1"]/*' />
/// <devdoc>
/// <para>
/// Adds the contents of another <see cref='System.CodeDom.CodeNamespaceCollection'/> to the end of the collection.
/// </para>
/// </devdoc>
public void AddRange(CodeNamespaceCollection value) {
if (value == null) {
throw new ArgumentNullException("value");
}
int currentCount = value.Count;
for (int i = 0; i < currentCount; i = ((i) + (1))) {
this.Add(value[i]);
}
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.Contains"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether the
/// <see cref='System.CodeDom.CodeNamespaceCollection'/> contains the specified <see cref='System.CodeDom.CodeNamespace'/>.</para>
/// </devdoc>
public bool Contains(CodeNamespace value) {
return List.Contains(value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.CopyTo"]/*' />
/// <devdoc>
/// <para>Copies the <see cref='System.CodeDom.CodeNamespaceCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the
/// specified index.</para>
/// </devdoc>
public void CopyTo(CodeNamespace[] array, int index) {
List.CopyTo(array, index);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.IndexOf"]/*' />
/// <devdoc>
/// <para>Returns the index of a <see cref='System.CodeDom.CodeNamespace'/> in
/// the <see cref='System.CodeDom.CodeNamespaceCollection'/> .</para>
/// </devdoc>
public int IndexOf(CodeNamespace value) {
return List.IndexOf(value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.Insert"]/*' />
/// <devdoc>
/// <para>Inserts a <see cref='System.CodeDom.CodeNamespace'/> into the <see cref='System.CodeDom.CodeNamespaceCollection'/> at the specified index.</para>
/// </devdoc>
public void Insert(int index, CodeNamespace value) {
List.Insert(index, value);
}
/// <include file='doc\CodeNamespaceCollection.uex' path='docs/doc[@for="CodeNamespaceCollection.Remove"]/*' />
/// <devdoc>
/// <para> Removes a specific <see cref='System.CodeDom.CodeNamespace'/> from the
/// <see cref='System.CodeDom.CodeNamespaceCollection'/> .</para>
/// </devdoc>
public void Remove(CodeNamespace value) {
List.Remove(value);
}
}
}
| 46.324503 | 177 | 0.549964 | [
"Unlicense"
] | bestbat/Windows-Server | com/netfx/src/framework/compmod/system/codedom/codenamespacecollection.cs | 6,995 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using StarkPlatform.CodeAnalysis.CommandLine;
namespace StarkPlatform.CodeAnalysis.Stark.CommandLine
{
internal sealed class Skc : CSharpCompiler
{
internal Skc(string responseFile, BuildPaths buildPaths, string[] args, IAnalyzerAssemblyLoader analyzerLoader)
: base(CSharpCommandLineParser.Default, responseFile, args, buildPaths, Environment.GetEnvironmentVariable("LIB"), analyzerLoader)
{
}
internal static int Run(string[] args, BuildPaths buildPaths, TextWriter textWriter, IAnalyzerAssemblyLoader analyzerLoader)
{
FatalError.Handler = FailFast.OnFatalException;
var responseFile = Path.Combine(buildPaths.ClientDirectory, CSharpCompiler.ResponseFileName);
var compiler = new Skc(responseFile, buildPaths, args, analyzerLoader);
return ConsoleUtil.RunWithUtf8Output(compiler.Arguments.Utf8Output, textWriter, tw => compiler.Run(tw));
}
}
}
| 43.814815 | 161 | 0.733728 | [
"Apache-2.0"
] | stark-lang/stark-roslyn | src/Compilers/Shared/Skc.cs | 1,185 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using WBrush = Microsoft.UI.Xaml.Media.Brush;
using WVisualStateManager = Microsoft.UI.Xaml.VisualStateManager;
using WVisualStateGroup = Microsoft.UI.Xaml.VisualStateGroup;
using WVisualState = Microsoft.UI.Xaml.VisualState;
using Microsoft.Maui.Graphics;
namespace Microsoft.Maui.Controls.Compatibility.Platform.UWP
{
public sealed class StepperControl : Control
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(StepperControl), new PropertyMetadata(default(double), OnValueChanged));
public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(StepperControl), new PropertyMetadata(default(double), OnMaxMinChanged));
public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(StepperControl), new PropertyMetadata(default(double), OnMaxMinChanged));
public static readonly DependencyProperty IncrementProperty = DependencyProperty.Register("Increment", typeof(double), typeof(StepperControl),
new PropertyMetadata(default(double), OnIncrementChanged));
public static readonly DependencyProperty ButtonBackgroundColorProperty = DependencyProperty.Register(nameof(ButtonBackgroundColor), typeof(Color), typeof(StepperControl), new PropertyMetadata(default(Color), OnButtonBackgroundColorChanged));
public static readonly DependencyProperty ButtonBackgroundProperty = DependencyProperty.Register(nameof(ButtonBackground), typeof(Brush), typeof(StepperControl), new PropertyMetadata(default(Brush), OnButtonBackgroundChanged));
Microsoft.UI.Xaml.Controls.Button _plus;
Microsoft.UI.Xaml.Controls.Button _minus;
VisualStateCache _plusStateCache;
VisualStateCache _minusStateCache;
public StepperControl()
{
DefaultStyleKey = typeof(StepperControl);
}
public double Increment
{
get { return (double)GetValue(IncrementProperty); }
set { SetValue(IncrementProperty, value); }
}
public double Maximum
{
get { return (double)GetValue(MaximumProperty); }
set { SetValue(MaximumProperty, value); }
}
public double Minimum
{
get { return (double)GetValue(MinimumProperty); }
set { SetValue(MinimumProperty, value); }
}
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public Color ButtonBackgroundColor
{
get { return (Color)GetValue(ButtonBackgroundColorProperty); }
set { SetValue(ButtonBackgroundColorProperty, value); }
}
public Brush ButtonBackground
{
get { return (Brush)GetValue(ButtonBackgroundProperty); }
set { SetValue(ButtonBackgroundProperty, value); }
}
public event EventHandler ValueChanged;
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_plus = GetTemplateChild("Plus") as Microsoft.UI.Xaml.Controls.Button;
if (_plus != null)
_plus.Click += OnPlusClicked;
_minus = GetTemplateChild("Minus") as Microsoft.UI.Xaml.Controls.Button;
if (_minus != null)
_minus.Click += OnMinusClicked;
UpdateEnabled(Value);
UpdateButtonBackgroundColor(ButtonBackgroundColor);
}
static void OnButtonBackgroundColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var stepper = (StepperControl)d;
stepper.UpdateButtonBackgroundColor(stepper.ButtonBackgroundColor);
}
static void OnButtonBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var stepper = (StepperControl)d;
stepper.UpdateButtonBackground(stepper.ButtonBackground);
}
static void OnIncrementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var stepper = (StepperControl)d;
stepper.UpdateEnabled(stepper.Value);
}
static void OnMaxMinChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var stepper = (StepperControl)d;
stepper.UpdateEnabled(stepper.Value);
}
void OnMinusClicked(object sender, RoutedEventArgs e)
{
UpdateValue(-Increment);
}
void OnPlusClicked(object sender, RoutedEventArgs e)
{
UpdateValue(+Increment);
}
static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var stepper = (StepperControl)d;
stepper.UpdateEnabled((double)e.NewValue);
EventHandler changed = stepper.ValueChanged;
if (changed != null)
changed(d, EventArgs.Empty);
}
VisualStateCache PseudoDisable(Control control)
{
if (VisualTreeHelper.GetChildrenCount(control) == 0)
control.ApplyTemplate();
WVisualStateManager.GoToState(control, "Disabled", true);
var rootElement = (FrameworkElement)VisualTreeHelper.GetChild(control, 0);
var cache = new VisualStateCache();
IList<WVisualStateGroup> groups = WVisualStateManager.GetVisualStateGroups(rootElement);
WVisualStateGroup common = null;
foreach (var group in groups)
{
if (group.Name == "CommonStates")
common = group;
else if (group.Name == "FocusStates")
cache.FocusStates = group;
else if (cache.FocusStates != null && common != null)
break;
}
if (cache.FocusStates != null)
groups.Remove(cache.FocusStates);
if (common != null)
{
foreach (WVisualState state in common.States)
{
if (state.Name == "Normal")
cache.Normal = state;
else if (state.Name == "Pressed")
cache.Pressed = state;
else if (state.Name == "PointerOver")
cache.PointerOver = state;
}
if (cache.Normal != null)
common.States.Remove(cache.Normal);
if (cache.Pressed != null)
common.States.Remove(cache.Pressed);
if (cache.PointerOver != null)
common.States.Remove(cache.PointerOver);
}
return cache;
}
/*
The below serves as a way to disable the button visually, rather than using IsEnabled. It's a hack
but should remain stable as long as the user doesn't change the WinRT Button template too much.
The reason we're not using IsEnabled is that the buttons have a click radius that overlap about 40%
of the next button. This doesn't cause a problem until one button becomes disabled, then if you think
you're still hitting + (haven't noticed its disabled), you will actually hit -. This hack doesn't
completely solve the problem, but it drops the overlap to something like 20%. I haven't found the root
cause, so this will have to suffice for now.
*/
void PsuedoEnable(Control control, ref VisualStateCache cache)
{
if (cache == null || VisualTreeHelper.GetChildrenCount(control) == 0)
return;
var rootElement = (FrameworkElement)VisualTreeHelper.GetChild(control, 0);
IList<WVisualStateGroup> groups = WVisualStateManager.GetVisualStateGroups(rootElement);
if (cache.FocusStates != null)
groups.Add(cache.FocusStates);
var commonStates = groups.FirstOrDefault(g => g.Name == "CommonStates");
if (commonStates == null)
return;
if (cache.Normal != null)
commonStates.States.Insert(0, cache.Normal); // defensive
if (cache.Pressed != null)
commonStates.States.Add(cache.Pressed);
if (cache.PointerOver != null)
commonStates.States.Add(cache.PointerOver);
WVisualStateManager.GoToState(control, "Normal", true);
cache = null;
}
void UpdateButtonBackgroundColor(Color value)
{
WBrush brush = value.ToBrush();
_minus = GetTemplateChild("Minus") as Microsoft.UI.Xaml.Controls.Button;
_plus = GetTemplateChild("Plus") as Microsoft.UI.Xaml.Controls.Button;
if (_minus != null)
_minus.Background = brush;
if (_plus != null)
_plus.Background = brush;
}
void UpdateButtonBackground(Brush value)
{
var brush = value.ToBrush();
_minus = GetTemplateChild("Minus") as Microsoft.UI.Xaml.Controls.Button;
_plus = GetTemplateChild("Plus") as Microsoft.UI.Xaml.Controls.Button;
if (_minus != null)
_minus.Background = brush;
if (_plus != null)
_plus.Background = brush;
}
void UpdateEnabled(double value)
{
double increment = Increment;
if (_plus != null)
{
if (value + increment > Maximum && _plusStateCache is null)
_plusStateCache = PseudoDisable(_plus);
else if (value + increment <= Maximum)
PsuedoEnable(_plus, ref _plusStateCache);
}
if (_minus != null)
{
if (value - increment < Minimum && _minusStateCache is null)
_minusStateCache = PseudoDisable(_minus);
else if (value - increment >= Minimum)
PsuedoEnable(_minus, ref _minusStateCache);
}
}
void UpdateValue(double delta)
{
double newValue = Value + delta;
if (newValue > Maximum || newValue < Minimum)
return;
Value = newValue;
}
class VisualStateCache
{
public WVisualStateGroup FocusStates;
public WVisualState Normal, PointerOver, Pressed;
}
}
} | 31.696113 | 244 | 0.73456 | [
"MIT"
] | gilnicki/maui-linux | src/Compatibility/Core/src/Windows/StepperControl.cs | 8,970 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using Microsoft.Quantum.Qir.Runtime.Tools.Driver;
#nullable enable
namespace Microsoft.Quantum.Qir.Runtime.Tools.Executable
{
/// <summary>
/// Class to create and run QIR-based executables that use the full-state simulator.
/// </summary>
public class QirFullStateExecutable : QirExecutable
{
public override string DriverFileExtension => "cpp";
public override IList<string> LinkLibraries => new List<string> {
"Microsoft.Quantum.Qir.Runtime",
"Microsoft.Quantum.Qir.QSharp.Foundation",
"Microsoft.Quantum.Qir.QSharp.Core"
};
public override IList<DirectoryInfo> HeaderDirectories { get; } = new List<DirectoryInfo>();
public override IList<DirectoryInfo> LibraryDirectories { get; } = new List<DirectoryInfo>();
public QirFullStateExecutable(FileInfo executableFile, byte[] qirBitcode, ILogger? logger = null)
: base(executableFile,
qirBitcode,
new QirFullStateDriverGenerator(),
logger)
{
var thisModulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (string.IsNullOrWhiteSpace(thisModulePath))
{
throw new InvalidOperationException("Could not get a path for the current assembly location.");
}
HeaderDirectories.Add(new DirectoryInfo(Path.Combine(thisModulePath, "runtimes", "any", "native", "include")));
HeaderDirectories.Add(new DirectoryInfo(Path.Combine(thisModulePath, "Externals", "CLI11")));
var osID = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "win-x64"
: RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "linux-x64"
: RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "osx-x64"
: throw new ArgumentException("Unsupported operating system architecture.");
LibraryDirectories.Add(new DirectoryInfo(Path.Combine(thisModulePath, "runtimes", osID, "native")));
LibraryDirectories.Add(new DirectoryInfo(Path.Combine(thisModulePath, "Libraries", osID)));
}
}
}
| 42.77193 | 123 | 0.668581 | [
"MIT"
] | matuhinal/qsharp-runtime | src/Qir/Tools/Executable/QirFullStateExecutable.cs | 2,440 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using beaverNet.POS.WebApp.Models;
namespace beaverNet.POS.WebApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
| 24.710526 | 112 | 0.643237 | [
"MIT"
] | JulioMelchorPinto/beaverNet.POS | beaverNet.POS.WebApp/Controllers/HomeController.cs | 941 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.ProjectSystem
{
[ExcludeFromCodeCoverage]
[SuppressMessage("Style", "IDE0016:Use 'throw' expression")]
internal partial class ResolvedProjectReference
{
}
}
| 31.769231 | 161 | 0.757869 | [
"Apache-2.0"
] | M-Lipin/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Rules/ResolvedProjectReference.cs | 415 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ASCompletion.Completion;
using ASCompletion.Context;
using ASCompletion.Model;
using CodeRefactor.Commands;
using CodeRefactor.Controls;
using CodeRefactor.Provider;
using PluginCore;
using PluginCore.Helpers;
using PluginCore.Localization;
using PluginCore.Managers;
using PluginCore.Utilities;
using ProjectManager;
using ProjectManager.Actions;
using ProjectManager.Controls.TreeView;
using ProjectManager.Helpers;
using CodeRefactor.Managers;
namespace CodeRefactor
{
public class PluginMain : IPlugin
{
const string REG_IDENTIFIER = "^[a-zA-Z_$][a-zA-Z0-9_$]*$";
private ToolStripMenuItem editorReferencesItem;
private ToolStripMenuItem viewReferencesItem;
private SurroundMenu surroundContextMenu;
private RefactorMenu refactorContextMenu;
private RefactorMenu refactorMainMenu;
private Settings settingObject;
private string settingFilename;
TreeView projectTreeView;
public const string TraceGroup = nameof(CodeRefactor);
#region Required Properties
/// <summary>
/// Api level of the plugin
/// </summary>
public int Api => 1;
/// <summary>
/// Name of the plugin
/// </summary>
public string Name { get; } = nameof(CodeRefactor);
/// <summary>
/// GUID of the plugin
/// </summary>
public string Guid { get; } = "5c0d3740-a6f2-11de-8a39-0800200c9a66";
/// <summary>
/// Author of the plugin
/// </summary>
public string Author { get; } = "FlashDevelop Team";
/// <summary>
/// Description of the plugin
/// </summary>
public string Description { get; set; } = "Adds refactoring capabilities to FlashDevelop.";
/// <summary>
/// Web address for help
/// </summary>
public string Help { get; } = "www.flashdevelop.org/community/";
/// <summary>
/// Object that contains the settings
/// </summary>
[Browsable(false)]
public object Settings => settingObject;
#endregion
#region Required Methods
/// <summary>
/// Initializes the plugin
/// </summary>
public void Initialize()
{
InitBasics();
LoadSettings();
CreateMenuItems();
RegisterMenuItems();
RegisterTraceGroups();
}
/// <summary>
/// Disposes the plugin
/// </summary>
public void Dispose() => SaveSettings();
/// <summary>
/// Handles the incoming events
/// </summary>
public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority)
{
switch (e.Type)
{
case EventType.FileSwitch:
GenerateSurroundMenuItems();
UpdateMenuItems();
break;
case EventType.UIStarted:
// Expose plugin's refactor main menu & context menu...
EventManager.DispatchEvent(this, new DataEvent(EventType.Command, "CodeRefactor.Menu", refactorMainMenu));
EventManager.DispatchEvent(this, new DataEvent(EventType.Command, "CodeRefactor.ContextMenu", refactorContextMenu));
// Watch resolved context for menu item updating...
ASComplete.OnResolvedContextChanged += OnResolvedContextChanged;
DirectoryNode.OnDirectoryNodeRefresh += OnDirectoryNodeRefresh;
UpdateMenuItems();
break;
case EventType.Command:
var de = (DataEvent)e;
string[] args;
string oldPath;
string newPath;
switch (de.Action)
{
case ProjectFileActionsEvents.FileRename:
if (settingObject.DisableMoveRefactoring) break;
args = (string[]) de.Data;
oldPath = args[0];
newPath = args[1];
if (Directory.Exists(oldPath) && IsValidForMove(oldPath, newPath))
{
MovingHelper.AddToQueue(new Dictionary<string, string> { { oldPath, newPath } }, true, true);
e.Handled = true;
}
else if (IsValidForRename(oldPath, newPath))
{
MoveFile(oldPath, newPath);
e.Handled = true;
}
break;
case ProjectFileActionsEvents.FileMove:
if (settingObject.DisableMoveRefactoring) break;
args = (string[]) de.Data;
oldPath = args[0];
newPath = args[1];
if (IsValidForMove(oldPath, newPath))
{
MovingHelper.AddToQueue(new Dictionary<string, string> { { oldPath, newPath } }, true);
e.Handled = true;
}
break;
case "ASCompletion.ContextualGenerator.AddOptions":
OnAddRefactorOptions(de.Data as List<ICompletionListItem>);
break;
case ProjectManagerEvents.TreeSelectionChanged:
OnTreeSelectionChanged();
break;
}
break;
}
}
/// <summary>
/// Checks if the file is valid for rename file command
/// </summary>
static bool IsValidForRename(string oldPath, string newPath)
{
return PluginBase.CurrentProject != null
&& Path.GetExtension(oldPath) is string oldExt && File.Exists(oldPath)
&& Path.GetExtension(newPath) is string newExt && oldExt == newExt
&& IsValidFile(oldPath)
&& Path.GetFileNameWithoutExtension(newPath) is string newPathWithoutExtension
&& Regex.Match(newPathWithoutExtension, REG_IDENTIFIER, RegexOptions.Singleline).Success;
}
/// <summary>
/// Checks if the file or directory is valid for move command
/// </summary>
static bool IsValidForMove(string oldPath)
{
return PluginBase.CurrentProject != null
&& !RefactoringHelper.IsUnderSDKPath(oldPath)
&& (File.Exists(oldPath) || Directory.Exists(oldPath))
&& IsValidFile(oldPath);
}
/// <summary>
/// Checks if the file or directory is valid for move command
/// </summary>
static bool IsValidForMove(string oldPath, string newPath)
{
return IsValidForMove(oldPath)
&& Path.GetFileNameWithoutExtension(newPath) is string newPathWithoutExtension
&& Regex.Match(newPathWithoutExtension, REG_IDENTIFIER, RegexOptions.Singleline).Success;
}
/// <summary>
/// Checks if the file or directory is ok for refactoring
/// </summary>
static bool IsValidFile(string file)
{
return PluginBase.CurrentProject is IProject project
&& RefactoringHelper.IsProjectRelatedFile(project, file)
&& Path.GetFileNameWithoutExtension(file) is string fileNameWithoutExtension
&& Regex.Match(fileNameWithoutExtension, REG_IDENTIFIER, RegexOptions.Singleline).Success
&& ((Directory.Exists(file) && !IsEmpty(file, project.DefaultSearchFilter)) || FileHelper.FileMatchesSearchFilter(file, project.DefaultSearchFilter));
// Utils
bool IsEmpty(string directoryPath, string searchPattern)
{
return searchPattern.Split(';').All(pattern => !Directory.EnumerateFiles(directoryPath, pattern, SearchOption.AllDirectories).Any());
}
}
#endregion
#region Event Handling
/// <summary>
/// Initializes important variables
/// </summary>
private void InitBasics()
{
EventManager.AddEventHandler(this, EventType.UIStarted | EventType.FileSwitch | EventType.Command);
var dataPath = Path.Combine(PathHelper.DataDir, nameof(CodeRefactor));
if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath);
settingFilename = Path.Combine(dataPath, "Settings.fdb");
Description = TextHelper.GetString("Info.Description");
BatchProcessManager.AddBatchProcessor(new BatchProcessors.FormatCodeProcessor());
BatchProcessManager.AddBatchProcessor(new BatchProcessors.OrganizeImportsProcessor());
BatchProcessManager.AddBatchProcessor(new BatchProcessors.TruncateImportsProcessor());
BatchProcessManager.AddBatchProcessor(new BatchProcessors.ConsistentEOLProcessor());
}
/// <summary>
/// Creates the required menu items
/// </summary>
private void CreateMenuItems()
{
refactorMainMenu = new RefactorMenu(true);
refactorMainMenu.RenameMenuItem.Click += RenameClicked;
refactorMainMenu.MoveMenuItem.Click += MoveClicked;
refactorMainMenu.OrganizeMenuItem.Click += OrganizeImportsClicked;
refactorMainMenu.TruncateMenuItem.Click += TruncateImportsClicked;
refactorMainMenu.ExtractMethodMenuItem.Click += ExtractMethodClicked;
refactorMainMenu.DelegateMenuItem.Click += DelegateMethodsClicked;
refactorMainMenu.ExtractLocalVariableMenuItem.Click += ExtractLocalVariableClicked;
refactorMainMenu.CodeGeneratorMenuItem.Click += CodeGeneratorMenuItemClicked;
refactorMainMenu.BatchMenuItem.Click += BatchMenuItemClicked;
refactorContextMenu = new RefactorMenu(false);
refactorContextMenu.RenameMenuItem.Click += RenameClicked;
refactorContextMenu.MoveMenuItem.Click += MoveClicked;
refactorContextMenu.OrganizeMenuItem.Click += OrganizeImportsClicked;
refactorContextMenu.TruncateMenuItem.Click += TruncateImportsClicked;
refactorContextMenu.DelegateMenuItem.Click += DelegateMethodsClicked;
refactorContextMenu.ExtractMethodMenuItem.Click += ExtractMethodClicked;
refactorContextMenu.ExtractLocalVariableMenuItem.Click += ExtractLocalVariableClicked;
refactorContextMenu.CodeGeneratorMenuItem.Click += CodeGeneratorMenuItemClicked;
refactorContextMenu.BatchMenuItem.Click += BatchMenuItemClicked;
ContextMenuStrip editorMenu = PluginBase.MainForm.EditorMenu;
surroundContextMenu = new SurroundMenu();
editorMenu.Items.Insert(3, refactorContextMenu);
editorMenu.Items.Insert(4, surroundContextMenu);
PluginBase.MainForm.MenuStrip.Items.Insert(5, refactorMainMenu);
ToolStripMenuItem searchMenu = PluginBase.MainForm.FindMenuItem("SearchMenu") as ToolStripMenuItem;
viewReferencesItem = new ToolStripMenuItem(TextHelper.GetString("Label.FindAllReferences"), null, FindAllReferencesClicked);
editorReferencesItem = new ToolStripMenuItem(TextHelper.GetString("Label.FindAllReferences"), null, FindAllReferencesClicked);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.SurroundWith", refactorMainMenu.SurroundMenu);
PluginBase.MainForm.RegisterShortcutItem("SearchMenu.ViewReferences", viewReferencesItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.SurroundWith", surroundContextMenu);
PluginBase.MainForm.RegisterSecondaryItem("SearchMenu.ViewReferences", editorReferencesItem);
searchMenu.DropDownItems.Add(new ToolStripSeparator());
searchMenu.DropDownItems.Add(viewReferencesItem);
editorMenu.Items.Insert(8, editorReferencesItem);
}
/// <summary>
/// Registers the menu items with the shortcut manager
/// </summary>
private void RegisterMenuItems()
{
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.Rename", refactorMainMenu.RenameMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.Move", refactorMainMenu.MoveMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.ExtractMethod", refactorMainMenu.ExtractMethodMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.ExtractLocalVariable", refactorMainMenu.ExtractLocalVariableMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.GenerateDelegateMethods", refactorMainMenu.DelegateMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.OrganizeImports", refactorMainMenu.OrganizeMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.TruncateImports", refactorMainMenu.TruncateMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.CodeGenerator", refactorMainMenu.CodeGeneratorMenuItem);
PluginBase.MainForm.RegisterShortcutItem("RefactorMenu.BatchProcess", refactorMainMenu.BatchMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.Rename", refactorContextMenu.RenameMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.Move", refactorContextMenu.MoveMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.ExtractMethod", refactorContextMenu.ExtractMethodMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.ExtractLocalVariable", refactorContextMenu.ExtractLocalVariableMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.GenerateDelegateMethods", refactorContextMenu.DelegateMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.OrganizeImports", refactorContextMenu.OrganizeMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.TruncateImports", refactorContextMenu.TruncateMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.CodeGenerator", refactorContextMenu.CodeGeneratorMenuItem);
PluginBase.MainForm.RegisterSecondaryItem("RefactorMenu.BatchProcess", refactorContextMenu.BatchMenuItem);
}
private void RegisterTraceGroups()
{
TraceManager.RegisterTraceGroup(TraceGroup, TextHelper.GetStringWithoutMnemonics("Label.Refactor"), false);
TraceManager.RegisterTraceGroup(FindAllReferences.TraceGroup, TextHelper.GetString("Label.FindAllReferencesResult"), false, true);
}
/// <summary>
/// Cursor position changed and word at this position was resolved
/// </summary>
private void OnResolvedContextChanged(ResolvedContext resolved) => UpdateMenuItems(resolved);
/// <summary>
/// Updates the state of the menu items
/// </summary>
private void UpdateMenuItems() => UpdateMenuItems(ASComplete.CurrentResolvedContext);
private void UpdateMenuItems(ResolvedContext resolved)
{
try
{
var document = PluginBase.MainForm.CurrentDocument;
var curFileName = document != null ? document.FileName : string.Empty;
var langIsValid = RefactoringHelper.GetLanguageIsValid();
var isValid = langIsValid && resolved != null && resolved.Position >= 0;
var result = isValid ? resolved.Result : null;
if (result != null && !result.IsNull())
{
// Rename
var validator = CommandFactoryProvider.GetFactory(result)?.GetValidator(typeof(Rename))
?? CommandFactoryProvider.DefaultFactory.GetValidator(typeof(Rename));
var enabled = validator(result);
refactorContextMenu.RenameMenuItem.Enabled = enabled;
refactorMainMenu.RenameMenuItem.Enabled = enabled;
// Find All References
enabled = !result.IsPackage && (File.Exists(curFileName) || curFileName.Contains("[model]"));
editorReferencesItem.Enabled = enabled;
viewReferencesItem.Enabled = enabled;
// Generate Delegate Methods
validator = CommandFactoryProvider.GetFactoryForCurrentDocument().GetValidator(typeof(DelegateMethods))
?? CommandFactoryProvider.DefaultFactory.GetValidator(typeof(DelegateMethods));
enabled = validator(result);
refactorContextMenu.DelegateMenuItem.Enabled = enabled;
refactorMainMenu.DelegateMenuItem.Enabled = enabled;
}
else
{
refactorMainMenu.RenameMenuItem.Enabled = false;
refactorContextMenu.RenameMenuItem.Enabled = false;
editorReferencesItem.Enabled = false;
viewReferencesItem.Enabled = false;
refactorMainMenu.DelegateMenuItem.Enabled = false;
refactorContextMenu.DelegateMenuItem.Enabled = false;
}
var context = ASContext.Context;
if (context?.CurrentModel != null)
{
var enabled = false;
if (RefactoringHelper.GetLanguageIsValid())
{
var validator = CommandFactoryProvider.GetFactoryForCurrentDocument().GetValidator(typeof(OrganizeImports))
?? CommandFactoryProvider.DefaultFactory.GetValidator(typeof(OrganizeImports));
enabled = validator(new ASResult {InFile = context.CurrentModel});
}
refactorContextMenu.OrganizeMenuItem.Enabled = enabled;
refactorContextMenu.TruncateMenuItem.Enabled = enabled;
refactorMainMenu.OrganizeMenuItem.Enabled = enabled;
refactorMainMenu.TruncateMenuItem.Enabled = enabled;
}
refactorMainMenu.MoveMenuItem.Enabled = false;
refactorContextMenu.MoveMenuItem.Enabled = false;
surroundContextMenu.Enabled = false;
refactorMainMenu.SurroundMenu.Enabled = false;
refactorMainMenu.ExtractMethodMenuItem.Enabled = false;
refactorContextMenu.ExtractMethodMenuItem.Enabled = false;
refactorMainMenu.ExtractLocalVariableMenuItem.Enabled = false;
refactorContextMenu.ExtractLocalVariableMenuItem.Enabled = false;
if (document != null && document.IsEditable && langIsValid)
{
var isValidFile = IsValidForMove(curFileName);
refactorMainMenu.MoveMenuItem.Enabled = isValidFile;
refactorContextMenu.MoveMenuItem.Enabled = isValidFile;
var sci = document.SciControl;
if (sci.SelTextSize > 0)
{
if (!sci.PositionIsOnComment(sci.SelectionStart) || !sci.PositionIsOnComment(sci.SelectionEnd))
{
surroundContextMenu.Enabled = true;
refactorMainMenu.SurroundMenu.Enabled = true;
refactorMainMenu.ExtractMethodMenuItem.Enabled = true;
refactorContextMenu.ExtractMethodMenuItem.Enabled = true;
}
if (context != null)
{
var declAtSelStart = context.GetDeclarationAtLine(sci.LineFromPosition(sci.SelectionStart));
var declAtSelEnd = context.GetDeclarationAtLine(sci.LineFromPosition(sci.SelectionEnd));
if (declAtSelStart?.Member != null && (declAtSelStart.Member.Flags & FlagType.Function) > 0
&& declAtSelEnd != null && declAtSelStart.Member.Equals(declAtSelEnd.Member))
{
refactorMainMenu.ExtractLocalVariableMenuItem.Enabled = true;
refactorContextMenu.ExtractLocalVariableMenuItem.Enabled = true;
}
}
}
}
refactorMainMenu.CodeGeneratorMenuItem.Enabled = isValid;
refactorContextMenu.CodeGeneratorMenuItem.Enabled = isValid;
}
catch { }
}
/// <summary>
/// Generate surround main menu and context menu items
/// </summary>
private void GenerateSurroundMenuItems()
{
var document = PluginBase.MainForm.CurrentDocument;
if (document != null && document.IsEditable && RefactoringHelper.GetLanguageIsValid())
{
surroundContextMenu.GenerateSnippets(document.SciControl);
refactorMainMenu.SurroundMenu.GenerateSnippets(document.SciControl);
}
else
{
surroundContextMenu.Clear();
refactorMainMenu.SurroundMenu.Clear();
}
}
/// <summary>
/// Invoked when the user selects the "Rename" command
/// </summary>
private void RenameClicked(object sender, EventArgs e)
{
if (InlineRename.InProgress) return;
try
{
var factory = CommandFactoryProvider.GetFactoryForCurrentDocument() ?? CommandFactoryProvider.DefaultFactory;
factory.CreateRenameCommandAndExecute(true, settingObject.UseInlineRenaming);
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Move" command
/// </summary>
static void MoveClicked(object sender, EventArgs e) => MoveFile(PluginBase.MainForm.CurrentDocument.FileName);
static void MoveFile(string fileName)
{
var dialog = new MoveDialog(fileName);
if (dialog.ShowDialog() != DialogResult.OK) return;
var oldPathToNewPath = new Dictionary<string, string>();
foreach (var file in dialog.MovingFiles)
{
oldPathToNewPath[file] = dialog.SelectedDirectory;
}
MovingHelper.AddToQueue(oldPathToNewPath, true, false, dialog.FixPackages);
}
/// <summary>
///
/// </summary>
private void MoveFile(string oldPath, string newPath)
{
try
{
var factory = CommandFactoryProvider.GetFactoryForCurrentDocument() ?? CommandFactoryProvider.DefaultFactory;
var command = factory.CreateRenameFileCommand(oldPath, newPath);
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Find All References" command
/// </summary>
private void FindAllReferencesClicked(object sender, EventArgs e)
{
ASComplete.OnResolvedContextChanged -= OnResolvedContextChanged;
EventManager.RemoveEventHandler(this, EventType.FileSwitch, HandlingPriority.Normal);
try
{
var command = CommandFactoryProvider.GetFactoryForCurrentDocument().CreateFindAllReferencesCommand(true);
command.Execute();
command.OnRefactorComplete += (o, args) =>
{
ASComplete.OnResolvedContextChanged += OnResolvedContextChanged;
EventManager.AddEventHandler(this, EventType.FileSwitch);
};
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
ASComplete.OnResolvedContextChanged += OnResolvedContextChanged;
EventManager.AddEventHandler(this, EventType.FileSwitch);
}
}
/// <summary>
/// Invoked when the user selects the "Organize Imports" command
/// </summary>
private void OrganizeImportsClicked(object sender, EventArgs e)
{
try
{
var command = (OrganizeImports)CommandFactoryProvider.GetFactoryForCurrentDocument().CreateOrganizeImportsCommand();
command.SeparatePackages = settingObject.SeparatePackages;
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Truncate Imports" command
/// </summary>
private void TruncateImportsClicked(object sender, EventArgs e)
{
try
{
var command = (OrganizeImports)CommandFactoryProvider.GetFactoryForCurrentDocument().CreateOrganizeImportsCommand();
command.SeparatePackages = settingObject.SeparatePackages;
command.TruncateImports = true;
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Delegate Method" command
/// </summary>
private void DelegateMethodsClicked(object sender, EventArgs e)
{
try
{
var result = ASComplete.CurrentResolvedContext.Result;
var members = new Dictionary<MemberModel, ClassModel>();
var memberNames = new List<string>();
var cm = result.Type;
cm.ResolveExtends();
while (!cm.IsVoid() && cm.Type != "Object")
{
cm.Members.Sort();
foreach (MemberModel m in cm.Members)
{
if (((m.Flags & FlagType.Function) > 0 || (m.Flags & FlagType.Getter) > 0 || (m.Flags & FlagType.Setter) > 0)
&& (m.Access & Visibility.Public) > 0
&& (m.Flags & FlagType.Constructor) == 0
&& (m.Flags & FlagType.Static) == 0)
{
var name = m.Name;
if ((m.Flags & FlagType.Getter) > 0) name = "get " + name;
if ((m.Flags & FlagType.Setter) > 0) name = "set " + name;
if (!memberNames.Contains(name))
{
memberNames.Add(name);
members[m] = cm;
}
}
}
cm = cm.Extends;
}
var dialog = new DelegateMethodsDialog();
dialog.FillData(members, result.Type);
if (dialog.ShowDialog() != DialogResult.OK || dialog.checkedMembers.Count <= 0) return;
var command = CommandFactoryProvider.GetFactoryForCurrentDocument().CreateDelegateMethodsCommand(result, dialog.checkedMembers);
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Extract Method" command
/// </summary>
private void ExtractMethodClicked(object sender, EventArgs e)
{
try
{
var newName = "newMethod";
var label = TextHelper.GetString("Label.NewName");
var title = TextHelper.GetString("Title.ExtractMethodDialog");
var askName = new LineEntryDialog(title, label, newName);
var result = askName.ShowDialog();
if (result != DialogResult.OK) return;
if (askName.Line.Trim().Length > 0 && askName.Line.Trim() != newName)
{
newName = askName.Line.Trim();
}
var command = CommandFactoryProvider.GetFactoryForCurrentDocument().CreateExtractMethodCommand(newName);
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invoked when the user selects the "Extract Local Variable" command
/// </summary>
private void ExtractLocalVariableClicked(object sender, EventArgs e)
{
try
{
var command = CommandFactoryProvider.GetFactoryForCurrentDocument().CreateExtractLocalVariableCommand();
command.Execute();
}
catch (Exception ex)
{
ErrorManager.ShowError(ex);
}
}
/// <summary>
/// Invokes the batch processing dialog
/// </summary>
private void BatchMenuItemClicked(object sender, EventArgs e)
{
var dialog = new BatchProcessDialog();
dialog.ShowDialog();
}
/// <summary>
/// Invokes the ASCompletion contextual generator
/// </summary>
private void CodeGeneratorMenuItemClicked(object sender, EventArgs e)
{
var de = new DataEvent(EventType.Command, "ASCompletion.ContextualGenerator", null);
EventManager.DispatchEvent(this, de);
}
/// <summary>
/// Loads the plugin settings
/// </summary>
void LoadSettings()
{
settingObject = new Settings();
if (!File.Exists(settingFilename)) SaveSettings();
else settingObject = (Settings) ObjectSerializer.Deserialize(settingFilename, settingObject);
}
/// <summary>
/// Saves the plugin settings
/// </summary>
void SaveSettings() => ObjectSerializer.Serialize(settingFilename, settingObject);
void OnAddRefactorOptions(List<ICompletionListItem> list)
{
if (list is null) return;
RefactorItem.AddItemToList(refactorMainMenu.RenameMenuItem, list);
RefactorItem.AddItemToList(refactorMainMenu.ExtractMethodMenuItem, list);
RefactorItem.AddItemToList(refactorMainMenu.ExtractLocalVariableMenuItem, list);
RefactorItem.AddItemToList(refactorMainMenu.DelegateMenuItem, list);
RefactorItem.AddItemToList(refactorMainMenu.SurroundMenu, list);
var features = ASContext.Context.Features;
if (!features.hasImports) return;
var sci = ASContext.CurSciControl;
var line = sci.GetLine(sci.CurrentLine).TrimStart();
if (line.StartsWithOrdinal(features.importKey)
|| !string.IsNullOrEmpty(features.importKeyAlt) && line.StartsWithOrdinal(features.importKeyAlt))
{
RefactorItem.AddItemToList(refactorMainMenu.OrganizeMenuItem, list);
if (features.hasImportsWildcard)
RefactorItem.AddItemToList(refactorMainMenu.TruncateMenuItem, list);
}
}
void OnDirectoryNodeRefresh(DirectoryNode node) => projectTreeView = node.TreeView;
void OnTreeSelectionChanged()
{
if (projectTreeView is null) return;
string path = null;
if (projectTreeView.SelectedNode is GenericNode node) path = node.BackingPath;
if (string.IsNullOrEmpty(path) || !IsValidForMove(path)) return;
var menu = (ProjectContextMenu) projectTreeView.ContextMenuStrip;
var index = menu.Items.IndexOf(menu.Rename);
if (index == -1) return;
var item = new ToolStripMenuItem(TextHelper.GetString("Label.Move"));
item.ShortcutKeys = PluginBase.MainForm.GetShortcutItemKeys("RefactorMenu.Move");
item.Click += OnMoveItemClick;
menu.Items.Insert(index + 1, item);
}
void OnMoveItemClick(object sender, EventArgs eventArgs)
{
string path = null;
if (projectTreeView.SelectedNode is GenericNode node) path = node.BackingPath;
if (string.IsNullOrEmpty(path) || !IsValidForMove(path)) return;
MoveFile(path);
}
#endregion
}
} | 47.365651 | 167 | 0.576788 | [
"MIT"
] | R32/flashdevelop | External/Plugins/CodeRefactor/PluginMain.cs | 33,477 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Microsoft.Extensions.DependencyInjection;
#pragma warning disable RCS1102 // Make class static.
namespace Microsoft.EntityFrameworkCore
{
public class ProxyGraphUpdatesInMemoryTest
{
public abstract class ProxyGraphUpdatesInMemoryTestBase<TFixture> : ProxyGraphUpdatesTestBase<TFixture>
where TFixture : ProxyGraphUpdatesInMemoryTestBase<TFixture>.ProxyGraphUpdatesInMemoryFixtureBase, new()
{
protected ProxyGraphUpdatesInMemoryTestBase(TFixture fixture)
: base(fixture)
{
}
// #11552
public override void Save_required_one_to_one_changed_by_reference(ChangeMechanism changeMechanism)
{
}
public override void Optional_one_to_one_relationships_are_one_to_one()
{
}
public override void Optional_one_to_one_with_AK_relationships_are_one_to_one()
{
}
public override void Optional_many_to_one_dependents_with_alternate_key_are_orphaned_in_store(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Optional_many_to_one_dependents_are_orphaned_in_store(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_one_to_one_are_cascade_detached_when_Added(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_one_to_one_relationships_are_one_to_one()
{
}
public override void Required_one_to_one_with_AK_relationships_are_one_to_one()
{
}
public override void Required_one_to_one_with_alternate_key_are_cascade_detached_when_Added(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_one_to_one_with_alternate_key_are_cascade_deleted_in_store(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_many_to_one_dependents_are_cascade_deleted_in_store(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_many_to_one_dependents_with_alternate_key_are_cascade_deleted_in_store(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_non_PK_one_to_one_are_cascade_detached_when_Added(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
public override void Required_non_PK_one_to_one_with_alternate_key_are_cascade_detached_when_Added(
CascadeTiming cascadeDeleteTiming,
CascadeTiming deleteOrphansTiming)
{
}
protected override void ExecuteWithStrategyInTransaction(
Action<DbContext> testOperation,
Action<DbContext> nestedTestOperation1 = null,
Action<DbContext> nestedTestOperation2 = null,
Action<DbContext> nestedTestOperation3 = null)
{
base.ExecuteWithStrategyInTransaction(testOperation, nestedTestOperation1, nestedTestOperation2, nestedTestOperation3);
Fixture.Reseed();
}
public abstract class ProxyGraphUpdatesInMemoryFixtureBase : ProxyGraphUpdatesFixtureBase
{
protected override ITestStoreFactory TestStoreFactory => InMemoryTestStoreFactory.Instance;
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
}
}
public class LazyLoading : ProxyGraphUpdatesInMemoryTestBase<LazyLoading.ProxyGraphUpdatesWithLazyLoadingInMemoryFixture>
{
public LazyLoading(ProxyGraphUpdatesWithLazyLoadingInMemoryFixture fixture)
: base(fixture)
{
}
protected override bool DoesLazyLoading => true;
protected override bool DoesChangeTracking => false;
public class ProxyGraphUpdatesWithLazyLoadingInMemoryFixture : ProxyGraphUpdatesInMemoryFixtureBase
{
protected override string StoreName { get; } = "ProxyGraphLazyLoadingUpdatesTest";
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder.UseLazyLoadingProxies());
protected override IServiceCollection AddServices(IServiceCollection serviceCollection)
=> base.AddServices(serviceCollection.AddEntityFrameworkProxies());
}
}
public class ChangeTracking : ProxyGraphUpdatesInMemoryTestBase<ChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture>
{
public ChangeTracking(ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture)
: base(fixture)
{
}
protected override bool DoesLazyLoading => false;
protected override bool DoesChangeTracking => true;
public class ProxyGraphUpdatesWithChangeTrackingInMemoryFixture : ProxyGraphUpdatesInMemoryFixtureBase
{
protected override string StoreName { get; } = "ProxyGraphChangeTrackingUpdatesTest";
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(builder.UseChangeDetectionProxies());
protected override IServiceCollection AddServices(IServiceCollection serviceCollection)
=> base.AddServices(serviceCollection.AddEntityFrameworkProxies());
}
}
public class LazyLoadingAndChangeTracking : ProxyGraphUpdatesInMemoryTestBase<LazyLoadingAndChangeTracking.ProxyGraphUpdatesWithChangeTrackingInMemoryFixture>
{
public LazyLoadingAndChangeTracking(ProxyGraphUpdatesWithChangeTrackingInMemoryFixture fixture)
: base(fixture)
{
}
protected override bool DoesLazyLoading => true;
protected override bool DoesChangeTracking => true;
public class ProxyGraphUpdatesWithChangeTrackingInMemoryFixture : ProxyGraphUpdatesInMemoryFixtureBase
{
protected override string StoreName { get; } = "ProxyGraphLazyLoadingAndChangeTrackingUpdatesTest";
public override DbContextOptionsBuilder AddOptions(DbContextOptionsBuilder builder)
=> base.AddOptions(
builder
.UseChangeDetectionProxies()
.UseLazyLoadingProxies());
protected override IServiceCollection AddServices(IServiceCollection serviceCollection)
=> base.AddServices(serviceCollection.AddEntityFrameworkProxies());
}
}
}
}
| 42.347594 | 166 | 0.664225 | [
"Apache-2.0"
] | EricStG/efcore | test/EFCore.InMemory.FunctionalTests/GraphUpdates/ProxyGraphUpdatesInMemoryTest.cs | 7,921 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Gear.Domain.AppEntities;
using Gear.Domain.Infrastructure;
using Gear.Domain.PmEntities.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Gear.ProjectManagement.Manager.Domain.Projects.Queries.GetProjectMembers
{
public class GetProjectMembersQueryHandler : IRequestHandler<GetProjectMembersQuery, ApplicationUserListViewModel>
{
private readonly IGearContext _context;
public GetProjectMembersQueryHandler(IGearContext context)
{
_context = context;
}
public async Task<ApplicationUserListViewModel> Handle(GetProjectMembersQuery request, CancellationToken cancellationToken)
{
var users = await _context.ApplicationUsers
.Include(u => u.Activities).ThenInclude(a => a.Activity).ThenInclude(a => a.LoggedTimes)
.Where(u => u.Projects.Any(p => p.ProjectId == request.Id))
.ToListAsync(cancellationToken);
var applicationUsers = users.Select(x => new ApplicationUser
{
Activities = x.Activities.Where(a => a.Activity.ProjectId == request.Id).ToList(),
FirstName = x.FirstName,
LastName = x.LastName,
JobPosition = x.JobPosition,
Id = x.Id
});
return await Task.FromResult(new ApplicationUserListViewModel
{
Users = applicationUsers.Select(user => ProjectMemberLookupModel.Create(user, request.Filter)).ToList()
});
}
}
}
| 37.930233 | 131 | 0.653587 | [
"MIT"
] | indrivo/bizon360_pm | IndrivoPM/Gear.ProjectManagement.Application/Domain/Projects/Queries/GetProjectMembers/GetProjectMembersQueryHandler.cs | 1,633 | C# |
namespace Tokens.Operators
{
/// <summary>
/// Defines an operation that can be performed on a token
/// </summary>
public interface ITokenOperator
{
/// <summary>
/// Performs the operation on the specified value.
/// </summary>
/// <param name="function"></param>
/// <param name="token">The token.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
object Perform(Function function, Token token, object value);
}
}
| 29.5 | 69 | 0.572505 | [
"MIT"
] | BerndK/tokenizer | Tokenizer/Operators/ITokenOperator.cs | 533 | C# |
// This file is provided under The MIT License as part of Steamworks.NET.
// Copyright (c) 2013-2015 Riley Labrecque
// Please see the included LICENSE.txt for additional information.
// This file is automatically generated.
// Changes to this file will be reverted when you update Steamworks.NET
namespace Steamworks
{
public static class SteamVideo
{
/// <summary>
/// <para> Get a URL suitable for streaming the given Video app ID's video</para>
/// </summary>
public static void GetVideoURL(AppId_t unVideoAppID)
{
InteropHelp.TestIfAvailableClient();
NativeMethods.ISteamVideo_GetVideoURL(unVideoAppID);
}
/// <summary>
/// <para> returns true if user is uploading a live broadcast</para>
/// </summary>
public static bool IsBroadcasting(out int pnNumViewers)
{
InteropHelp.TestIfAvailableClient();
return NativeMethods.ISteamVideo_IsBroadcasting(out pnNumViewers);
}
}
} | 34.5 | 89 | 0.657971 | [
"MIT"
] | KingBranBran/Time-Signatures | Assets/Editor/Steamworks.NET/autogen/isteamvideo.cs | 1,035 | C# |
using IM.Lib.Descriptor.LocalPatternDescriptor.NeighborTopo;
using IM.Lib.Descriptor.LocalPatternDescriptor.LocalPatternImage;
// Reference:
// D. Kim, J. Jung, T. T. Nguyen, D. Kim, M. Kim, K. H. Kwon, J. W. Jeon, "An FPGA-based Parallel Hardware Architecture for Real-time Eye Detection,"
// J. Semiconductor Technology and Science, vol. 12, no. 2, pp. 150-161, 2012
namespace IM.Lib.Descriptor.LocalPatternDescriptor.LocalPattern.ModifiedLocalPattern
{
public class ModifiedLBP : AModifiedLocalPattern
{
public ModifiedLBP(ANeighborTopo neighborTopo)
: base(neighborTopo)
{
this._lengthOfEncoding = this._neighborTopo.NPointsOnBorder();
}
public override void DoTransform(int x, int y, int encodingIdx, float avg, float valOfNeighbor, LPImage lpImg)
{
if (avg <= valOfNeighbor)
lpImg.Set(x, y, encodingIdx, BinaryValueOne.Singleton);
else
lpImg.Set(x, y, encodingIdx, BinaryValueZero.Singleton);
}
}
}
| 40.185185 | 150 | 0.651613 | [
"MIT"
] | ntthuy11/ImageDescriptorsExtraction_CSharp | LocalPatternDescriptor/LocalPattern/ModifiedLocalPattern/ModifiedLBP.cs | 1,087 | C# |
using System;
using Alipay.AopSdk.Domain;
using System.Collections.Generic;
using Alipay.AopSdk.Response;
namespace Alipay.AopSdk.Request
{
/// <summary>
/// AOP API: alipay.data.dataservice.userlevel.zrank.get
/// </summary>
public class AlipayDataDataserviceUserlevelZrankGetRequest : IAopRequest<AlipayDataDataserviceUserlevelZrankGetResponse>
{
/// <summary>
/// 通用的活跃高价值用户等级,支持EMAIL,PHONE,BANKCARD,CERTNO,IMEI,MAC,TBID维度查询用户活跃高价值等级。等级从Z0-Z7,等级越高价值越高,Z0表示未实名认证或者用户信息不全。
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.data.dataservice.userlevel.zrank.get";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 24.954545 | 124 | 0.622222 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk/Request/AlipayDataDataserviceUserlevelZrankGetRequest.cs | 2,863 | C# |
using System;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using RestSharp;
using certdognet.model;
using CredentialManagement;
using System.Collections.Generic;
namespace certdognet
{
public class Certdog
{
public static String CERTDOGCREDS = "CERTDOGCREDS";
#region Public Static Calls
/// <summary>
/// Given a certificate DN can generate a CSR and return a PKCS#12
/// This is a one hit static method which performs logon, cert request and logoff
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="certIssuer">The name of the certificate issuer</param>
/// <param name="dn">The requested Distinguished Name</param>
/// <param name="generator">The name of the CSR Generator</param>
/// <param name="p12Password">The password to protect the returned PKCS#12</param>
/// <param name="sans">Subject Alternative Names. E.g. ["DNS:domain.com","IP:10.11.1.2"]</param>
/// <param name="teamName">The name of the team to associate this certificate with</param>
/// <param name="username">The certdog API Username</param>
/// <param name="password">The certdog API Password</param>
/// <returns>Base64 encoded PKCS#12</returns>
public static String GetCert(String url, String certIssuer, String dn, String generator,
String p12Password, List<String> sans, String teamName, String username, String password)
{
RestClient client = GetClient(url);
String jwt = Login(client, username, password);
if (sans == null)
sans = new List<String>();
var request = new RestRequest("/certs/request", Method.POST);
request.AddHeader("Authorization", "Bearer " + jwt);
request.AddJsonBody(
new GetCertRequest { caName = certIssuer, dn = dn, csrGeneratorName = generator,
subjectAltNames = sans.ToArray(), p12Password = p12Password, teamName = teamName });
IRestResponse<GetCertResponse> response = client.Execute<GetCertResponse>(request);
CheckError(response, "Get Certificate");
String p12Data = response.Data.p12Data;
Logout(client, jwt);
return p12Data;
}
/// <summary>
/// Given a certificate DN can generate a CSR and return a PKCS#12
/// Using the credentials stored in the windows credential manager
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="certIssuer">The name of the certificate issuer</param>
/// <param name="dn">The requested Distinguished Name</param>
/// <param name="generator">The name of the CSR Generator</param>
/// <param name="p12Password">The password to protect the returned PKCS#12</param>
/// <param name="sans">Subject Alternative Names. E.g. ["DNS:domain.com","IP:10.11.1.2"]</param>
/// <param name="teamName">The name of the team to associate this certificate with</param>
/// <returns>Base64 encoded PKCS#12</returns>
public static String GetCert(String url, String certIssuer, String dn, String generator,
String p12Password, List<String> sans, String teamName)
{
var credManager = new Credential { Target = CERTDOGCREDS };
credManager.Load();
if (credManager == null || credManager.Username == null || credManager.Password == null)
throw new Exception("Unable to obtain credentials from the credential store. Ensure that a Generic credential has been saved called " + CERTDOGCREDS + " set by the same user running this application");
return GetCert(url, certIssuer, dn, generator, p12Password, sans, teamName, credManager.Username, credManager.Password);
}
/// <summary>
/// Issues a certificate from a CSR
/// This is a one hit static method which performs logon, cert request and logoff
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="certIssuer">The name of the certificate issuer</param>
/// <param name="csrData">The csr data in PEM format</param>
/// <param name="teamName">The name of the team to associate this certificate with</param>
/// <param name="username">The certdog API Username</param>
/// <param name="password">The certdog API Password</param>
/// <returns>The issued certificate in PEM format</returns>
public static String GetCertFromCsr(String url, String certIssuer, String csrData, String teamName, String username, String password)
{
RestClient client = GetClient(url);
String jwt = Login(client, username, password);
var request = new RestRequest("/certs/requestp10", Method.POST);
request.AddHeader("Authorization", "Bearer " + jwt);
request.AddJsonBody(new GetCertFromCsrRequest { caName = certIssuer, csr = csrData, teamName = teamName });
IRestResponse<GetCertFromCsrResponse> response = client.Execute<GetCertFromCsrResponse>(request);
CheckError(response, "Get Certificate");
String certData = response.Data.pemCert;
Logout(client, jwt);
return certData;
}
/// <summary>
/// Issues a certificate from a CSR using the credentials stored in the windows credential manager
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="certIssuer">The name of the certificate issuer</param>
/// <param name="csrData">The csr data in PEM format</param>
/// <param name="teamName">The name of the team to associate this certificate with</param>
/// <returns>The issued certificate in PEM format</returns>
public static String GetCertFromCsr(String url, String certIssuer, String csrData, String teamName)
{
var credManager = new Credential { Target = CERTDOGCREDS };
credManager.Load();
if (credManager == null || credManager.Username == null || credManager.Password == null)
throw new Exception("Unable to obtain credentials from the credential store. Ensure that a Generic credential has been saved called " + CERTDOGCREDS + " set by the same user running this application");
return GetCertFromCsr(url, certIssuer, csrData, teamName, credManager.Username, credManager.Password);
}
/// <summary>
/// Returns the available certificate issuers
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="username">The certdog API Username</param>
/// <param name="password">The certdog API Password</param>
/// <returns>A list of CertDogCertIssuer</returns>
public static List<CertDogCertIssuer> GetCertIssuers(String url, String username, String password)
{
RestClient client = GetClient(url);
String jwt = Login(client, username, password);
var request = new RestRequest("/admin/ca", Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + jwt);
IRestResponse response = client.Execute(request);
var issuers = SimpleJson.DeserializeObject<List<CertDogCertIssuer>>(response.Content);
CheckError(response, "Getting Issuers");
Logout(client, jwt);
return issuers;
}
/// <summary>
/// Returns the available certificate issuers using the credentials stored in the windows credential manager
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <returns>A list of CertDogCertIssuer</returns>
public static List<CertDogCertIssuer> GetCertIssuers(String url)
{
var credManager = new Credential { Target = CERTDOGCREDS };
credManager.Load();
if (credManager == null || credManager.Username == null || credManager.Password == null)
throw new Exception("Unable to obtain credentials from the credential store. Ensure that a Generic credential has been saved called " + CERTDOGCREDS + " set by the same user running this application");
return GetCertIssuers(url, credManager.Username, credManager.Password);
}
/// <summary>
/// Returns the available CSR Generators
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <param name="username">The certdog API Username</param>
/// <param name="password">The certdog API Password</param>
/// <returns>A list of CertDogCsrGenerator</returns>
public static List<CertDogCsrGenerator> GetCsrGenerators(String url, String username, String password)
{
RestClient client = GetClient(url);
String jwt = Login(client, username, password);
var request = new RestRequest("/admin/generators", Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + jwt);
IRestResponse response = client.Execute(request);
var generators = SimpleJson.DeserializeObject<List<CertDogCsrGenerator>>(response.Content);
CheckError(response, "Getting CSR Generators");
Logout(client, jwt);
return generators;
}
/// <summary>
/// Returns the available CSR Generators using the credentials stored in the windows credential manager
/// </summary>
/// <param name="url">The certdog API URL</param>
/// <returns>A list of CertDogCsrGenerator</returns>
public static List<CertDogCsrGenerator> GetCsrGenerators(String url)
{
var credManager = new Credential { Target = CERTDOGCREDS };
credManager.Load();
if (credManager == null || credManager.Username == null || credManager.Password == null)
throw new Exception("Unable to obtain credentials from the credential store. Ensure that a Generic credential has been saved called " + CERTDOGCREDS + " set by the same user running this application");
return GetCsrGenerators(url, credManager.Username, credManager.Password);
}
#endregion
#region Private Static Calls
/// <summary>
/// If the error code is anything other than 200 OK, throws an exception
/// Attempts to obtain the error message
/// </summary>
/// <param name="response"></param>
/// <param name="requestName"></param>
private static void CheckError(IRestResponse response, String requestName)
{
if (response == null)
throw new Exception(requestName + " failed. No response was returned from the server");
if (response.StatusCode != HttpStatusCode.OK)
{
String errorMessage = requestName + " failed with error code ";
try
{
ErrorResponse err = SimpleJson.DeserializeObject<ErrorResponse>(response.Content);
errorMessage += err.status + ". Details: " + err.message;
}
catch (Exception e)
{
errorMessage += response.StatusCode + (response.Content != null ? ". Details: " + response.Content : "");
}
throw new Exception(errorMessage);
}
}
/// <summary>
/// Gets the Rest Sharp client
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static RestClient GetClient(String url)
{
var client = new RestClient(url);
client.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
client.Timeout = -1;
return client;
}
/// <summary>
/// Logs the user in and returns the auth (JWT) token
/// </summary>
/// <param name="client"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
private static String Login(RestClient client, String username, String password)
{
var request = new RestRequest("/login", Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(new LoginRequest { username = username, password = password });
IRestResponse<LoginResponse> response = client.Execute<LoginResponse>(request);
CheckError(response, "Logging In");
String tok = response.Data.token;
return tok;
}
/// <summary>
/// Logs out the user
/// </summary>
/// <param name="client"></param>
/// <param name="token"></param>
private static void Logout(RestClient client, String token)
{
var request = new RestRequest("/logouthere", Method.GET);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + token);
client.Execute(request);
}
#endregion
}
}
| 46.479452 | 217 | 0.616932 | [
"BSD-2-Clause"
] | krestfield/certdog-dotnet-client | Certdog.cs | 13,574 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.MultiTenancy;
using Abp.Timing;
namespace Abp.Authorization.Users
{
/// <summary>
/// Used to save a login attempt of a user.
/// </summary>
[Table("AbpUserLoginAttempts")]
public class UserLoginAttempt : Entity<long>, IHasCreationTime, IMayHaveTenant
{
/// <summary>
/// Max length of the <see cref="TenancyName"/> property.
/// </summary>
public const int MaxTenancyNameLength = AbpTenantBase.MaxTenancyNameLength;
/// <summary>
/// Max length of the <see cref="TenancyName"/> property.
/// </summary>
public const int MaxUserNameOrEmailAddressLength = 255;
/// <summary>
/// Maximum length of <see cref="ClientIpAddress"/> property.
/// </summary>
public const int MaxClientIpAddressLength = 64;
/// <summary>
/// Maximum length of <see cref="ClientName"/> property.
/// </summary>
public const int MaxClientNameLength = 128;
/// <summary>
/// Maximum length of <see cref="BrowserInfo"/> property.
/// </summary>
public const int MaxBrowserInfoLength = 512;
/// <summary>
/// Tenant's Id, if <see cref="TenancyName"/> was a valid tenant name.
/// </summary>
public virtual int? TenantId { get; set; }
/// <summary>
/// Tenancy name.
/// </summary>
[StringLength(MaxTenancyNameLength)]
public virtual string TenancyName { get; set; }
/// <summary>
/// User's Id, if <see cref="UserNameOrEmailAddress"/> was a valid username or email address.
/// </summary>
public virtual long? UserId { get; set; }
/// <summary>
/// User name or email address
/// </summary>
[StringLength(MaxUserNameOrEmailAddressLength)]
public virtual string UserNameOrEmailAddress { get; set; }
/// <summary>
/// IP address of the client.
/// </summary>
[StringLength(MaxClientIpAddressLength)]
public virtual string ClientIpAddress { get; set; }
/// <summary>
/// Name (generally computer name) of the client.
/// </summary>
[StringLength(MaxClientNameLength)]
public virtual string ClientName { get; set; }
/// <summary>
/// Browser information if this method is called in a web request.
/// </summary>
[StringLength(MaxBrowserInfoLength)]
public virtual string BrowserInfo { get; set; }
/// <summary>
/// Login attempt result.
/// </summary>
public virtual AbpLoginResultType Result { get; set; }
public virtual DateTime CreationTime { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="UserLoginAttempt"/> class.
/// </summary>
public UserLoginAttempt()
{
CreationTime = Clock.Now;
}
}
}
| 32.05102 | 101 | 0.592486 | [
"MIT"
] | 12321/aspnetboilerplate | src/Abp.Zero.Common/Authorization/Users/UserLoginAttempt.cs | 3,143 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/ocidl.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IEnumOleUndoUnits" /> struct.</summary>
public static unsafe partial class IEnumOleUndoUnitsTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IEnumOleUndoUnits" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IEnumOleUndoUnits).GUID, Is.EqualTo(IID_IEnumOleUndoUnits));
}
/// <summary>Validates that the <see cref="IEnumOleUndoUnits" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IEnumOleUndoUnits>(), Is.EqualTo(sizeof(IEnumOleUndoUnits)));
}
/// <summary>Validates that the <see cref="IEnumOleUndoUnits" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IEnumOleUndoUnits).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IEnumOleUndoUnits" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IEnumOleUndoUnits), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IEnumOleUndoUnits), Is.EqualTo(4));
}
}
}
}
| 37.211538 | 145 | 0.638243 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/ocidl/IEnumOleUndoUnitsTests.cs | 1,937 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Compute.Outputs
{
[OutputType]
public sealed class WindowsVirtualMachineScaleSetDataDisk
{
/// <summary>
/// The type of Caching which should be used for this Data Disk. Possible values are `None`, `ReadOnly` and `ReadWrite`.
/// </summary>
public readonly string Caching;
/// <summary>
/// The create option which should be used for this Data Disk. Possible values are `Empty` and `FromImage`. Defaults to `Empty`. (`FromImage` should only be used if the source image includes data disks).
/// </summary>
public readonly string? CreateOption;
/// <summary>
/// The ID of the Disk Encryption Set which should be used to encrypt this Data Disk.
/// </summary>
public readonly string? DiskEncryptionSetId;
/// <summary>
/// Specifies the Read-Write IOPS for this Data Disk. Only settable for UltraSSD disks.
/// </summary>
public readonly int? DiskIopsReadWrite;
/// <summary>
/// Specifies the bandwidth in MB per second for this Data Disk. Only settable for UltraSSD disks.
/// </summary>
public readonly int? DiskMbpsReadWrite;
/// <summary>
/// The size of the Data Disk which should be created.
/// </summary>
public readonly int DiskSizeGb;
/// <summary>
/// The Logical Unit Number of the Data Disk, which must be unique within the Virtual Machine.
/// </summary>
public readonly int Lun;
/// <summary>
/// The Type of Storage Account which should back this Data Disk. Possible values include `Standard_LRS`, `StandardSSD_LRS`, `Premium_LRS` and `UltraSSD_LRS`.
/// </summary>
public readonly string StorageAccountType;
/// <summary>
/// Should Write Accelerator be enabled for this Data Disk? Defaults to `false`.
/// </summary>
public readonly bool? WriteAcceleratorEnabled;
[OutputConstructor]
private WindowsVirtualMachineScaleSetDataDisk(
string caching,
string? createOption,
string? diskEncryptionSetId,
int? diskIopsReadWrite,
int? diskMbpsReadWrite,
int diskSizeGb,
int lun,
string storageAccountType,
bool? writeAcceleratorEnabled)
{
Caching = caching;
CreateOption = createOption;
DiskEncryptionSetId = diskEncryptionSetId;
DiskIopsReadWrite = diskIopsReadWrite;
DiskMbpsReadWrite = diskMbpsReadWrite;
DiskSizeGb = diskSizeGb;
Lun = lun;
StorageAccountType = storageAccountType;
WriteAcceleratorEnabled = writeAcceleratorEnabled;
}
}
}
| 37.082353 | 211 | 0.629124 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/Compute/Outputs/WindowsVirtualMachineScaleSetDataDisk.cs | 3,152 | C# |
#region License
// =================================================================================================
// Copyright 2018 DataArt, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.
// =================================================================================================
#endregion
#if NET452
using System.Collections.Generic;
using DataArt.Atlas.Configuration.Impl;
using DataArt.Atlas.Configuration.Settings;
namespace DataArt.Atlas.Configuration
{
public interface IConfigurationClient
{
List<SettingsSection> SettingsSections { get; }
T GetSettings<T>()
where T : new();
ApplicationSettings GetApplicationSettings();
string GetConfigurationFolderPath();
}
}
#endif | 37.432432 | 100 | 0.574007 | [
"Apache-2.0"
] | DamirAinullin/Atlas | core/Configuration/DataArt.Atlas.Configuration/IConfigurationClient.cs | 1,385 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
namespace reCAPTCHA.AspNetCore
{
public class RecaptchaService : IRecaptchaService
{
public static bool UseRecaptchaNet { get; set; } = false;
public static HttpClient Client { get; private set; }
public readonly RecaptchaSettings RecaptchaSettings;
public RecaptchaService(RecaptchaSettings options)
{
RecaptchaSettings = options;
if (Client == null)
Client = new HttpClient();
}
public RecaptchaService(IOptions<RecaptchaSettings> options)
{
RecaptchaSettings = options.Value;
if(Client == null)
Client = new HttpClient();
}
public RecaptchaService(IOptions<RecaptchaSettings> options, HttpClient client)
{
RecaptchaSettings = options.Value;
Client = client;
}
public RecaptchaService(RecaptchaSettings options, HttpClient client)
{
RecaptchaSettings = options;
Client = client;
}
public async Task<RecaptchaResponse> Validate(HttpRequest request, bool antiForgery = true)
{
if (!request.Form.ContainsKey("g-recaptcha-response")) // error if no reason to do anything, this is to alert developers they are calling it without reason.
throw new ValidationException("Google recaptcha response not found in form. Did you forget to include it?");
var domain = UseRecaptchaNet ? "www.recaptcha.net" : "www.google.com";
var response = request.Form["g-recaptcha-response"];
var result = await Client.GetStringAsync($"https://{domain}/recaptcha/api/siteverify?secret={RecaptchaSettings.SecretKey}&response={response}");
var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result);
if (captchaResponse.success && antiForgery)
if (captchaResponse.hostname?.ToLower() != request.Host.Host?.ToLower())
throw new ValidationException("Recaptcha host, and request host do not match. Forgery attempt?");
return captchaResponse;
}
public async Task<RecaptchaResponse> Validate(string responseCode)
{
if (string.IsNullOrEmpty(responseCode))
throw new ValidationException("Google recaptcha response is empty?");
var domain = UseRecaptchaNet ? "www.recaptcha.net" : "www.google.com";
var result = await Client.GetStringAsync($"https://{domain}/recaptcha/api/siteverify?secret={RecaptchaSettings.SecretKey}&response={responseCode}");
var captchaResponse = JsonConvert.DeserializeObject<RecaptchaResponse>(result);
return captchaResponse;
}
}
}
| 39.907895 | 168 | 0.659083 | [
"MIT"
] | BionStt/reCAPTCHA.AspNetCore | reCAPTCHA.AspNetCore/RecaptchaService.cs | 3,035 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Podler.Responses
{
public class AddComicResponse : IResponse
{
public bool IsSuccess { get; }
public string Message { get; }
public AddComicResponse(bool isSuccess, string message)
{
IsSuccess = isSuccess;
Message = message;
}
}
}
| 20.85 | 63 | 0.633094 | [
"MIT"
] | icegabriel/podler | src/Podler/Responses/AddComicResponse.cs | 419 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CodeGenerator.Example
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class OnlineJudgeSystemEntities : DbContext
{
public OnlineJudgeSystemEntities()
: base("name=OnlineJudgeSystemEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<C__MigrationHistory> C__MigrationHistory { get; set; }
public virtual DbSet<AccessLog> AccessLogs { get; set; }
public virtual DbSet<AspNetRole> AspNetRoles { get; set; }
public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual DbSet<AspNetUser> AspNetUsers { get; set; }
public virtual DbSet<Checker> Checkers { get; set; }
public virtual DbSet<ContestCategory> ContestCategories { get; set; }
public virtual DbSet<ContestQuestionAnswer> ContestQuestionAnswers { get; set; }
public virtual DbSet<ContestQuestion> ContestQuestions { get; set; }
public virtual DbSet<Contest> Contests { get; set; }
public virtual DbSet<Event> Events { get; set; }
public virtual DbSet<FeedbackReport> FeedbackReports { get; set; }
public virtual DbSet<News> News { get; set; }
public virtual DbSet<ParticipantAnswer> ParticipantAnswers { get; set; }
public virtual DbSet<Participant> Participants { get; set; }
public virtual DbSet<ProblemResource> ProblemResources { get; set; }
public virtual DbSet<Problem> Problems { get; set; }
public virtual DbSet<Setting> Settings { get; set; }
public virtual DbSet<SourceCode> SourceCodes { get; set; }
public virtual DbSet<Submission> Submissions { get; set; }
public virtual DbSet<SubmissionType> SubmissionTypes { get; set; }
public virtual DbSet<Tag> Tags { get; set; }
public virtual DbSet<TestRun> TestRuns { get; set; }
public virtual DbSet<Test> Tests { get; set; }
}
}
| 47.818182 | 88 | 0.63346 | [
"MIT"
] | BogdanDimov/HQC-2-HW | Topics/05. Development-Tools/demos/CodeGenerator.Example/Entities.Context.cs | 2,632 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>E2A Network Mapping fabric specific settings.</summary>
public partial class VmmToAzureNetworkMappingSettings :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVmmToAzureNetworkMappingSettings,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IVmmToAzureNetworkMappingSettingsInternal,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IValidates
{
/// <summary>
/// Backing field for Inherited model <see cref= "Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettings"
/// />
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettings __networkMappingFabricSpecificSettings = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.NetworkMappingFabricSpecificSettings();
/// <summary>Gets the Instance type.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inherited)]
public string InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettingsInternal)__networkMappingFabricSpecificSettings).InstanceType; }
/// <summary>Internal Acessors for InstanceType</summary>
string Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettingsInternal.InstanceType { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettingsInternal)__networkMappingFabricSpecificSettings).InstanceType; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettingsInternal)__networkMappingFabricSpecificSettings).InstanceType = value; }
/// <summary>Validates that this object meets the validation criteria.</summary>
/// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener" /> instance that will receive validation
/// events.</param>
/// <returns>
/// A < see cref = "global::System.Threading.Tasks.Task" /> that will be complete when validation is completed.
/// </returns>
public async global::System.Threading.Tasks.Task Validate(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IEventListener eventListener)
{
await eventListener.AssertNotNull(nameof(__networkMappingFabricSpecificSettings), __networkMappingFabricSpecificSettings);
await eventListener.AssertObjectIsValid(nameof(__networkMappingFabricSpecificSettings), __networkMappingFabricSpecificSettings);
}
/// <summary>Creates an new <see cref="VmmToAzureNetworkMappingSettings" /> instance.</summary>
public VmmToAzureNetworkMappingSettings()
{
}
}
/// E2A Network Mapping fabric specific settings.
public partial interface IVmmToAzureNetworkMappingSettings :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettings
{
}
/// E2A Network Mapping fabric specific settings.
internal partial interface IVmmToAzureNetworkMappingSettingsInternal :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.INetworkMappingFabricSpecificSettingsInternal
{
}
} | 67.581818 | 490 | 0.764595 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/VmmToAzureNetworkMappingSettings.cs | 3,663 | C# |
//namespace Web.Middleware
//{
// using System;
// using Microsoft.AspNetCore.Mvc;
// using Microsoft.AspNetCore.Mvc.Filters;
// using Microsoft.AspNetCore.Mvc.ModelBinding;
// using Microsoft.AspNetCore.Mvc.ViewFeatures;
// public class CustomExceptionFilter : ExceptionFilterAttribute
// {
// public override void OnException(ExceptionContext context)
// {
// string message;
// if (context.Exception is BindingException)
// {
// var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(y => y.ErrorMessage));
// message = string.Join(Environment.NewLine, errors);
// var result = new ViewResult { ViewName = "CustomError" };
// var modelMetadata = new EmptyModelMetadataProvider();
// result.ViewData = new ViewDataDictionary(
// modelMetadata,
// context.ModelState)
// {
// Model = message,
// };
// context.ExceptionHandled = true;
// context.Result = result;
// base.OnException(context);
// }
// else if (context.Exception is NotEnoughTickets)
// {
// message = context.Exception.Message;
// var result = new ViewResult { ViewName = "CustomError" };
// var modelMetadata = new EmptyModelMetadataProvider();
// result.ViewData = new ViewDataDictionary(
// modelMetadata,
// context.ModelState)
// {
// Model = message,
// };
// context.ExceptionHandled = true;
// context.Result = result;
// base.OnException(context);
// }
// }
// }
//}
| 27.622642 | 99 | 0.663934 | [
"MIT"
] | bMedarski/BettingWebApp | Web/Middleware/CustomExceptionFilter.cs | 1,466 | C# |
using Assets.scripts;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
private const int NUM_COLS = 4;
private const int NUM_ROWS = 4;
public GameObject plugPrefab;
public GameObject callPanelPrefab;
public GameObject commandPanel;
public GameObject gameOverPanel;
public Text scoreText;
public Text gameOverText;
private int score = 0;
public Fuckup bad_thing_happened;
// Text Shit
public GameObject topLabel;
public GameObject leftLabel;
public GameObject rightLabel;
// symbols for the rows and columns
public char[] rowSyms;
public char[] colSyms;
// x- and y-spacing for the plugs
public float colSpace;
public float rowSpace;
private GameObject startPlug;
private GameObject endPlug;
public Cord cord;
private List<CallRequest> requestEnds;
private List<GameObject> plugs = new List<GameObject>();
static System.Random rand = new System.Random();
// Use this for initialization
void Start () {
requestEnds = new List<CallRequest>();
rowSyms = GenerateCipher() ;
colSyms = GenerateCipher();
topLabel.GetComponent<TextMesh>().text = colSyms[0] + " " + colSyms[1] + " " + colSyms[2] + " " + colSyms[3];
leftLabel.GetComponent<TextMesh>().text = rowSyms[0] + "\n" + rowSyms[1] + "\n" + rowSyms[2] + "\n" + rowSyms[3];
rightLabel.GetComponent<TextMesh>().text = rowSyms[0] + "\n" + rowSyms[1] + "\n" + rowSyms[2] + "\n" + rowSyms[3];
}
private void ShouldShowPlug(GameObject plug, bool show)
{
plug.GetComponent<MeshRenderer>().enabled = show;
}
private void InstantiatePlugs() {
for (var col = 0 ; col < NUM_COLS; ++col) {
for (var row = 0; row < NUM_ROWS; ++row) {
var position = new Vector3(-4.254f + colSpace * col, 3.223f + -1 * rowSpace * row, 2.571f);
var plug = Instantiate(plugPrefab, position, Quaternion.Euler(90, 0, 0));
ShouldShowPlug(plug, false);
plug.GetComponent<Plug>().setPosition(col, row);
plugs.Add(plug);
}
}
}
private void CreatePlugGoal()
{
var goalPlug = new PlugEnds();
print("Okay, now connect " + goalPlug.first.CoordString() + " to " + goalPlug.second.CoordString());
GameObject newCallPanel = Instantiate(callPanelPrefab, commandPanel.transform);
CallRequest call = newCallPanel.GetComponent<CallRequest>();
call.StartRequest(goalPlug, colSyms, rowSyms, 20f);
requestEnds.Add(call);
}
public void TriggerPlug(GameObject plug)
{ // was GameObject instead of Plug
if (plug == startPlug)
{
startPlug = null;
ShouldShowPlug(plug, false);
cord.RemoveStart();
}
else if (plug == endPlug)
{
endPlug = null;
ShouldShowPlug(plug, false);
cord.RemoveEnd();
}
else if (!(startPlug != null && endPlug != null)) // i.e. only one plug is null and we're about to finish a connection
{
if (startPlug == null)
{
startPlug = plug;
ShouldShowPlug(plug, true);
cord.SetStart(plug.transform);
}
else // endPlug == null; there's no other option
{
endPlug = plug;
ShouldShowPlug(plug, true);
cord.SetEnd(plug.transform);
}
// connection is completed, let's see if the player got it right...
if (startPlug != null && endPlug != null) // !(plugs == null) will always return true
{
var plugs = ToPlugEnds();
tryTransmission (plugs);
}
}
var _startPlug = (startPlug != null) ? startPlug.GetComponent<Plug>().ToString() : "null";
var _endPlug = (endPlug != null) ? endPlug.GetComponent<Plug>().ToString() : "null";
Debug.Log("startPlug: " + _startPlug + "| endPlug: " + _endPlug);
}
// Update is called once per frame
void Update () {}
private PlugEnds ToPlugEnds()
{
return new PlugEnds(startPlug.GetComponent<Plug>().getCol(),
startPlug.GetComponent<Plug>().getRow(),
endPlug.GetComponent<Plug>().getCol(),
endPlug.GetComponent<Plug>().getRow());
}
private IEnumerator<WaitForSeconds> removeBothPlugs() {
yield return new WaitForSeconds(0.5f);
TriggerPlug (startPlug);
TriggerPlug (endPlug);
}
private bool tryTransmission(PlugEnds attemptedPlugCoordinates) {
foreach (CallRequest curRequest in requestEnds)
{
if (curRequest.getSolution().Equals(attemptedPlugCoordinates))
{
requestEnds.Remove(curRequest);
var waitTime = curRequest.CompleteCall();
print("Well done.");
score += Mathf.FloorToInt(10f + 50 * waitTime);
scoreText.text = "Score: " + score;
CreatePlugGoal();
StartCoroutine(removeBothPlugs ());
Debug.Log (score);
}
else
{
var startString = (startPlug != null) ? startPlug.GetComponent<Plug>().ToString() : "null";
var endString = (endPlug != null) ? endPlug.GetComponent<Plug>().ToString() : "null";
print("You silly goose, look what you've done! You've connected " + startString + " and " + endString);
bad_thing_happened.gameObject.SetActive(true);
bad_thing_happened.DisplayFuckup(attemptedPlugCoordinates, curRequest.getSolution(), colSyms, rowSyms);
GameOver("You made a bad connection. Jimmy ended up calling his ex and now things are awkward.");
}
// to do: remove curPlugCoordinate, kill the CallRequest UI element.
// and play a ding ding sound
}
return false;
}
public void TimeOver(CallRequest unhappyCustomer)
{
print("Time over, you lazy fool");
requestEnds.Remove(unhappyCustomer);
if (rand.Next(0,1000) == 69)
{
GameOver("You have died of dysentery");
}
GameOver("You ran out of time. Martha couldn't order her pizza and starved to death.");
}
public void StartGameSinglePlayer()
{
InstantiatePlugs();
commandPanel.SetActive(true);
CreatePlugGoal();
}
public void StartGameMultiPlayer()
{
CreatePlugGoal();
}
public char[] GenerateCipher()
{
HashSet<char> cipher = new HashSet<char>();
var i = 0;
while(i < 4)
{
char thing = (char)(rand.Next(65, 91));
if (!cipher.Contains(thing))
{
cipher.Add(thing);
i++;
}
}
char[] returnThis = new char[4];
cipher.CopyTo(returnThis);
return returnThis;
}
public void GameOver(string message)
{
gameOverText.text = message;
gameOverPanel.SetActive(true);
commandPanel.SetActive(false);
foreach(GameObject plug in plugs)
{
Destroy(plug);
}
foreach(CallRequest request in requestEnds)
{
Destroy(request.gameObject);
}
}
}
| 31.491304 | 126 | 0.595886 | [
"MIT"
] | saaqibz/SmoothOperator | Assets/scripts/GameController.cs | 7,245 | C# |
using System.Runtime.Serialization;
namespace Signicat.Express.Notification
{
public enum DeliveryLogging
{
[EnumMember(Value = "never")]
Never = 0,
[EnumMember(Value = "failed")]
Failed = 1,
[EnumMember(Value = "always")]
Always = 2
}
} | 19.75 | 39 | 0.550633 | [
"Apache-2.0"
] | Signereno/idfy-sdk-net | src/Signicat.Express.SDK/Services/Notification/Entities/DeliveryLogging.cs | 316 | C# |
using System;
using System.Runtime.CompilerServices;
using StirlingLabs.Utilities;
namespace BigBuffers
{
public sealed class UnsafeByteSpanManager : ByteBufferManager
{
private byte[] _buffer;
private unsafe void* _spanPtr;
private nuint _spanSize;
private bool _isFixedSize;
internal unsafe UnsafeByteSpanManager(BigSpan<byte> buffer, bool growable = false)
{
_spanPtr = buffer.GetUnsafePointer();
_spanSize = buffer.Length;
_isFixedSize = !growable;
}
internal unsafe UnsafeByteSpanManager(ReadOnlyBigSpan<byte> buffer, bool growable = false)
{
_spanPtr = buffer.GetUnsafePointer();
_spanSize = buffer.Length;
_isFixedSize = !growable;
}
public override bool Growable
{
get => _buffer is not null || !_isFixedSize;
set => _isFixedSize = !value;
}
public override unsafe void GrowFront(ulong newSize)
{
if (newSize < LongLength)
throw new("ByteBuffer: cannot truncate buffer.");
if (_buffer is null && _isFixedSize)
throw new InvalidOperationException("Growing the buffer was not permitted.");
var newBuffer = new byte[newSize];
Span.CopyTo(new BigSpan<byte>(newBuffer)
.Slice(0, Span.Length));
_buffer = newBuffer;
_spanPtr = default;
_spanSize = default;
}
public override unsafe BigSpan<byte> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get {
if (_buffer is not null) return (BigSpan<byte>)_buffer;
return new(_spanPtr, _spanSize);
}
}
public override unsafe ReadOnlyBigSpan<byte> ReadOnlySpan
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get {
if (_buffer is not null) return (ReadOnlyBigSpan<byte>)_buffer;
return new(_spanPtr, _spanSize);
}
}
}
}
| 26.985507 | 94 | 0.664876 | [
"Apache-2.0"
] | StirlingLabs/BigBuffers | net/BigBuffers.Runtime/UnsafeByteSpanManager.cs | 1,862 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using RAGE;
using System.Threading.Tasks;
namespace main_client.Player.Character
{
/*class Vehicule : Events.Script
{
public Vehicule()
{
/*Events.Add("OpenDoor", openDoor);
//Events.Add("AnimationSyncLaunch", AnimationSyncLaunch);
//Events.Add("AnimationSyncClose", AnimationSyncClose);
Events.Add("MecanoSetActive", MecanoSetActive);
Events.Add("InclinVehiculeMecano", InclinVehiculeMecano);
Events.Add("RepairVehiculeMecano", RepairVehiculeMecano);
Events.Add("GetDoorPos", GetDoorPos);
Events.OnEntityStreamIn += OnEntityStreamIn;
Events.Tick += tick;
}
RAGE.Elements.MapObject obj = null;
bool[] actives = new bool[4] { false, false, false , false };
public void tick(List<Events.TickNametagData> nametags)
{
if (Input.IsDown((int)ConsoleKey.M) && actives[0] == false)
{
Events.CallRemote("MecanoRepair");
actives[0] = !actives[0];
}
if (Input.IsDown((int)ConsoleKey.W) && actives[0] == false)
{
Events.CallRemote("MecanoRemoveVehicule");
actives[0] = !actives[0];
}
}
public void GetDoorPos(object[] args)
{
RAGE.Elements.Vehicle vehicle = (RAGE.Elements.Vehicle)args[0];
//Vector3 tmp = new Vector3(vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Z);
//vehicle.SetData<Vector3>("DoorPos0", new Vector3(vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Z));
//vehicle.SetData<Vector3>("DoorPos1", new Vector3(vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_rf")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_rf")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_rf")).Z));
//Chat.Output("TEST " + vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")));
//Chat.Output("TEST 2 " + new Vector3(vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_lf")).Z));
Events.CallRemote("SetDataVehiculeValue", vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("door_dside_f")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("door_dside_f")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("door_dside_f")).Z, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("door_pside_f")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("wheel_rf")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("door_pside_f")).Z, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("bumper_f")).X, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("bumper_f")).Y, vehicle.GetWorldPositionOfBone(vehicle.GetBoneIndexByName("bumper_f")).Z);
}
public void InclinVehiculeMecano(object[] args)
{
RAGE.Elements.Vehicle vehicle = (RAGE.Elements.Vehicle)args[0];
RAGE.Elements.MapObject obj = (RAGE.Elements.MapObject)args[1];
int side = (int)args[2];
vehicle.Position += new Vector3(0, 0, side == -1 ? -0.1f : 0.1f);
vehicle.SetHeading(0f);
vehicle.SetRotation(0, side == 1 ? 15 : side == -1 ? 0 : -15, 1, 1, true);
vehicle.FreezePosition(side == -1 ? false : true);
}
public void RepairVehiculeMecano(object[] args)
{
RAGE.Elements.Vehicle vehicle = (RAGE.Elements.Vehicle)args[0];
vehicle.SetFixed();
vehicle.SetHealth(10);
vehicle.FreezePosition(false);
}
public void MecanoSetActive(object[] args)
{
actives[(int)args[0]] = (bool)args[1];
}
public void openDoor(object[] args)
{
RAGE.Elements.Vehicle vehicle = (RAGE.Elements.Vehicle)args[0];
string doorId = (string)args[1];
float angle = (float)args[2];
Chat.Output("Test Test");
vehicle.SetDoorOpen(Convert.ToInt32(doorId), angle == 0 ? false : true, angle == 0 ? false : true);
vehicle.SetDoorControl(Convert.ToInt32(doorId), 1, angle);
vehicle.FreezePosition(angle == 0 ? false : true);
}
public void AnimationSyncLaunch(object[] args)
{
Chat.Output("Salut");
RAGE.Elements.Player _player = (RAGE.Elements.Player)args[0];
//RAGE.Game.Streaming.RequestAnimDict((string)args[1]);
_player.PlaySynchronizedAnim((int)args[3], (string)args[1], (string)args[2], 8.0f, -8.0f, -1, 1);
//_player.PlayAnim((string)args[1], (string)args[2], 8.0f, true, true, false, 0, 0);
/*Task.Run(() =>
{
//while (!RAGE.Game.Streaming.HasAnimDictLoaded((string)args[1])) { RAGE.Game.Utils.Wait(0); };
//_player.PlaySynchronizedAnim((int)args[3], (string)args[1], (string)args[2], 8.0f, -8.0f, -1, 1);
});
}
public void AnimationSyncClose(object[] args)
{
RAGE.Elements.Player _player = (RAGE.Elements.Player)args[0];
_player.StopSynchronizedAnim((int)args[1], true);
}
public void OnEntityStreamIn(RAGE.Elements.Entity entity)
{
if (entity.Type == RAGE.Elements.Type.Vehicle)
{
RAGE.Elements.Vehicle vehicle = (RAGE.Elements.Vehicle)entity;
vehicle.FreezePosition(true);
for (int i = 0; i < 7; i++)
{
if (vehicle.GetSharedData(i.ToString()) != null)
{
//vehicle.SetDoorOpen(i, true, true);
//vehicle.Position += new Vector3(0, 0, 0.1f);
//vehicle.SetRotation(0, 15, 1, 1, true);
//vehicle.SetDoorControl(i, 2, (float)vehicle.GetSharedData(i.ToString()));
vehicle.FreezePosition(false);
}
}
}
else if (entity.Type == RAGE.Elements.Type.Ped)
{
RAGE.Elements.Ped ped = (RAGE.Elements.Ped)entity;
if (ped.GetSharedData("Animation") != null)
{
RAGE.Game.Streaming.RequestAnimDict("amb@world_human_vehicle_mechanic@male@idle_a");
ped.TaskPlayAnim("amb@world_human_vehicle_mechanic@male@idle_a", "idle_a", 8.0f, -8.0f, -1, 1, 0.0f, false, false, false);
}
}
else if (entity.Type == RAGE.Elements.Type.Player)
{
RAGE.Elements.Player _player = (RAGE.Elements.Player)entity;
if (_player.GetSharedData("AnimationSyncLaunch") != null)
{
Chat.Output("Animation 2");
object[] objs = (object[])_player.GetSharedData("AnimationSyncLaunch");
RAGE.Game.Streaming.RequestAnimDict((string)objs[0]);
while (!RAGE.Game.Streaming.HasAnimDictLoaded((string)objs[0])) { RAGE.Game.Utils.Wait(0); };
//_player.PlaySynchronizedAnim(0, (string)objs[0], (string)objs[1], 8.0f, -8.0f, -1, 1);
_player.TaskPlayAnim((string)objs[0], (string)objs[1], 8.0f, -8.0f, -1, 1, 0.0f, false, false, false);
//_player.TaskPlayAnim(objs[0], objs[1], -8, 8, -1, );
}
else if (_player.GetSharedData("AnimationSyncClose") != null)
{
_player.StopSynchronizedAnim((int)_player.GetSharedData("AnimationSyncClose"), true);
}
}
/*else if (entity.Type == RAGE.Elements.Type.Object)
{
RAGE.Elements.MapObject objects = (RAGE.Elements.MapObject)entity;
if (objects.GetSharedData("AttachElement") != null)
{
objects.FreezePosition(false);
objects.SetCollision(false, true);
objects.SetDynamic(true);
}
}
}
}*/
}
| 48.805405 | 741 | 0.576254 | [
"MIT"
] | Stolym/RAGEMP | Server/server-files/server-files/client_workspace/main_client/Player/Character/Vehicule.cs | 9,031 | C# |
using NUnit.Framework;
using Wikiled.Text.Analysis.Dictionary;
namespace Wikiled.Text.Analysis.Tests.Dictionary
{
[TestFixture]
public class BasicEnglishDictionaryTests
{
[Test]
public void Test()
{
var instance = new BasicEnglishDictionary();
var data = instance.GetWords();
Assert.AreEqual(44323, data.Length);
Assert.IsTrue(instance.IsKnown("mother"));
Assert.IsFalse(instance.IsKnown("motherzzz"));
}
}
}
| 25.95 | 58 | 0.618497 | [
"MIT"
] | AndMu/Wikiled.Text.Analysis | src/Wikiled.Text.Analysis.Tests/Dictionary/BasicEnglishDictionaryTests.cs | 521 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PackageBuilder.Models
{
public class CodePackage
{
public string Code { get; set; }
public byte[] OutputBinary { get; set; }
}
}
| 17.8 | 48 | 0.677903 | [
"MIT"
] | tenor/CSharpAWSLambdaFunctions | src/PackageBuilder/Models/CodePackage.cs | 269 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cofoundry.Domain.Data;
using Microsoft.AspNetCore.Identity;
namespace Cofoundry.Domain.Internal
{
/// <summary>
/// Shared user authentication methods
/// </summary>
public class UserAuthenticationHelper
{
private readonly IPasswordCryptographyService _cryptographyService;
private readonly IUserAreaDefinitionRepository _userAreaRepository;
public UserAuthenticationHelper(
IPasswordCryptographyService cryptographyService,
IUserAreaDefinitionRepository userAreaRepository
)
{
_cryptographyService = cryptographyService;
_userAreaRepository = userAreaRepository;
}
public PasswordVerificationResult VerifyPassword(User user, string password)
{
if (user == null) return PasswordVerificationResult.Failed;
var userArea = _userAreaRepository.GetByCode(user.UserAreaCode);
if (!userArea.AllowPasswordLogin)
{
throw new InvalidOperationException("This user is not permitted to log in with a password.");
}
if (String.IsNullOrWhiteSpace(user.Password) || !user.PasswordHashVersion.HasValue)
{
throw new InvalidOperationException("Cannot authenticate via password because the specified account does not have a password set.");
}
var result = _cryptographyService.Verify(password, user.Password, user.PasswordHashVersion.Value);
return result;
}
}
}
| 33.77551 | 148 | 0.67855 | [
"MIT"
] | aTiKhan/cofoundry | src/Cofoundry.Domain/Domain/Users/Helpers/UserAuthenticationHelper.cs | 1,657 | C# |
// Copyright 2021-2022 The SeedV Lab.
//
// 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 FluentAssertions;
using SeedLang.Common;
using SeedLang.Runtime;
using Xunit;
namespace SeedLang.Visualization.Tests {
internal class MockupBinaryVisualizer : IVisualizer<Event.Binary> {
public Event.Binary BinaryEvent { get; private set; }
public void On(Event.Binary be, IVM vm) {
BinaryEvent = be;
}
}
internal class AnotherMockupBinaryVisualizer : IVisualizer<Event.Binary> {
public Event.Binary BinaryEvent { get; private set; }
public void On(Event.Binary be, IVM vm) {
BinaryEvent = be;
}
}
internal class MockupVariableDefinedVisualizer : IVisualizer<Event.VariableDefined> {
public Event.VariableDefined VariableDefined { get; private set; }
public void On(Event.VariableDefined vde, IVM vm) {
VariableDefined = vde;
}
}
internal class MockupVariableDeletedVisualizer : IVisualizer<Event.VariableDeleted> {
public Event.VariableDeleted VariableDeleted { get; private set; }
public void On(Event.VariableDeleted vde, IVM vm) {
VariableDeleted = vde;
}
}
internal class MockupVM : IVM {
public void Pause() {
throw new NotImplementedException();
}
public void Stop() {
throw new NotImplementedException();
}
public bool GetGlobals(out IReadOnlyList<IVM.VariableInfo> globals) {
throw new NotImplementedException();
}
public bool GetLocals(out IReadOnlyList<IVM.VariableInfo> locals) {
throw new NotImplementedException();
}
}
public class VisualizerCenterTests {
[Fact]
public void TestIsVariableTrackingEnabled() {
var vc = new VisualizerCenter();
vc.IsVariableTrackingEnabled.Should().Be(false);
vc.IsVariableTrackingEnabled = true;
vc.IsVariableTrackingEnabled.Should().Be(true);
vc.IsVariableTrackingEnabled = false;
vc.Register(new MockupVariableDefinedVisualizer());
vc.IsVariableTrackingEnabled.Should().Be(true);
vc.IsVariableTrackingEnabled = false;
vc.Register(new MockupVariableDeletedVisualizer());
vc.IsVariableTrackingEnabled.Should().Be(true);
}
[Fact]
public void TestRegisterVisualizer() {
(var visualizerCenter, var binaryVisualizer) = NewBinaryVisualizerCenter();
Assert.Null(binaryVisualizer.BinaryEvent);
visualizerCenter.Notify(NewBinaryEvent(), new MockupVM());
Assert.NotNull(binaryVisualizer.BinaryEvent);
}
[Fact]
public void TestRegisterMultipleVisualizers() {
(var visualizerCenter, var binaryVisualizer, var multipleVisualizer) =
NewMultipleVisualizerCenter();
Assert.Null(binaryVisualizer.BinaryEvent);
Assert.Null(multipleVisualizer.BinaryEvent);
visualizerCenter.Notify(NewBinaryEvent(), new MockupVM());
Assert.NotNull(binaryVisualizer.BinaryEvent);
Assert.NotNull(multipleVisualizer.BinaryEvent);
}
[Fact]
public void TestUnregisterVisualizer() {
(var visualizerCenter, var binaryVisualizer) = NewBinaryVisualizerCenter();
visualizerCenter.Unregister(binaryVisualizer);
visualizerCenter.Notify(NewBinaryEvent(), new MockupVM());
Assert.Null(binaryVisualizer.BinaryEvent);
}
private static (VisualizerCenter, MockupBinaryVisualizer) NewBinaryVisualizerCenter() {
var binaryVisualizer = new MockupBinaryVisualizer();
var visualizerCenter = new VisualizerCenter();
visualizerCenter.Register(binaryVisualizer);
return (visualizerCenter, binaryVisualizer);
}
private static (VisualizerCenter, MockupBinaryVisualizer, AnotherMockupBinaryVisualizer)
NewMultipleVisualizerCenter() {
var binaryVisualizer = new MockupBinaryVisualizer();
var anotherBinaryVisualizer = new AnotherMockupBinaryVisualizer();
var visualizerCenter = new VisualizerCenter();
visualizerCenter.Register(binaryVisualizer);
visualizerCenter.Register(anotherBinaryVisualizer);
return (visualizerCenter, binaryVisualizer, anotherBinaryVisualizer);
}
private static Event.Binary NewBinaryEvent() {
return new Event.Binary(new Value(1), BinaryOperator.Add, new Value(2), new Value(3),
new TextRange(0, 1, 2, 3));
}
}
}
| 36.289855 | 93 | 0.702276 | [
"Apache-2.0"
] | SeedV/SeedLang | csharp/tests/SeedLang.Tests/Visualization/VisualizerCenterTests.cs | 5,008 | 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("WPCordovaClassLib")]
[assembly: AssemblyDescription("2.9.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Apache Cordova")]
[assembly: AssemblyProduct("WPCordovaClassLib")]
[assembly: AssemblyCopyright("")]
[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("633ee7ad-9a75-4b68-96e9-281528c50275")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.9.0.0")]
[assembly: AssemblyFileVersion("2.9.0.0")]
| 38.027778 | 84 | 0.751644 | [
"MIT"
] | AKJ1/Code4Bulgaria | Frontend/libs/phone-gap/windows-phone/wp8/framework/Properties/AssemblyInfo.cs | 1,371 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor;
using OpenHardwareMonitor.Hardware;
namespace Echo
{
public class SystemMonitor
{
public static SystemMonitor Instance = new SystemMonitor();
private SystemMonitor()
{
myComputer.Open();
}
static MySettings settings = new MySettings(new Dictionary<string, string>
{
{ "/intelcpu/0/temperature/0/values", "H4sIAAAAAAAEAOy9B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Iu6//MH37x79i9/+NX6N3/TJm9/5f/01fw1+fosnv+A/+OlfS37/jZ/s/Lpv9fff6Ml/NTef/yZPnozc5679b+i193//TQZ+/w2Dd+P9/sZeX/67v/GTf/b3iP3u4/ObBL//73+i+f039+D8Zk/+xz/e/P6beu2TQZju8yH8f6OgzcvPv/U3/Rb8+z/0f/9b/+yfaOn8079X6fr6Cws7ln/iHzNwflPv99/wyS/+xY4+v/evcJ+733+jJ5//Cw7/4ndy9Im3+U2e/Fbnrk31C93vrt/fyPvdb+N//hsF7/4/AQAA//9NLZZ8WAIAAA==" }
});
Computer myComputer = new Computer(settings)
{
MainboardEnabled = true,
CPUEnabled = true,
RAMEnabled = true,
GPUEnabled = true,
FanControllerEnabled = true,
HDDEnabled = true
};
public Single GetCPU0Speed()
{
Single result = 0f;
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.CPU)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
{
subHardware.Update();
}
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Clock)
{
result = (float)sensor.Value;
return result;
}
}
}
}
return result;
}
public Single GetCPU0Temp()
{
Single result = 0f;
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.CPU)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
{
subHardware.Update();
}
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
result = (float)sensor.Value;
return result;
}
}
}
}
return result;
}
public Single GetGPU0Speed()
{
Single result = 0f;
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.GpuAti || hardwareItem.HardwareType == HardwareType.GpuNvidia)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
{
subHardware.Update();
}
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Clock)
{
result = (float)sensor.Value;
return result;
}
}
}
}
return result;
}
public Single GetGPU0Temp()
{
Single result = 0f;
foreach (var hardwareItem in myComputer.Hardware)
{
if (hardwareItem.HardwareType == HardwareType.GpuAti || hardwareItem.HardwareType == HardwareType.GpuNvidia)
{
hardwareItem.Update();
foreach (IHardware subHardware in hardwareItem.SubHardware)
{
subHardware.Update();
}
foreach (var sensor in hardwareItem.Sensors)
{
if (sensor.SensorType == SensorType.Temperature)
{
result = (float)sensor.Value;
return result;
}
}
}
}
return result;
}
}
public class MySettings : ISettings
{
private IDictionary<string, string> settings = new Dictionary<string, string>();
public MySettings(IDictionary<string, string> settings)
{
this.settings = settings;
}
public bool Contains(string name)
{
return settings.ContainsKey(name);
}
public string GetValue(string name, string value)
{
string result;
if (settings.TryGetValue(name, out result))
return result;
else
return value;
}
public void Remove(string name)
{
settings.Remove(name);
}
public void SetValue(string name, string value)
{
settings[name] = value;
}
}
//public class OHW
//{
// private static OHW m_Instance;
// public static OHW Instance
// {
// get
// {
// if (m_Instance == null)
// m_Instance = new OHW();
// return m_Instance;
// }
// }
// private OHW()
// {
// m_Instance = this;
// }
//}
}
| 28.980952 | 522 | 0.469602 | [
"Apache-2.0"
] | edwin-jones/Echo | Echo/SystemMonitor.cs | 6,088 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace MijnSauna.Backend.Api
{
[ExcludeFromCodeCoverage]
public class Program
{
public static void Main(string[] args)
{
var certificateFileName = Environment.GetEnvironmentVariable("CERTIFICATE_FILENAME");
var certificatePassword = Environment.GetEnvironmentVariable("CERTIFICATE_PASSWORD");
CreateHostBuilder(args, certificateFileName, certificatePassword).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args, string certificateFileName, string certificatePassword) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
//webBuilder.UseIISIntegration();
webBuilder.UseKestrel();
webBuilder.ConfigureKestrel((context, options) =>
{
if (string.IsNullOrEmpty(certificateFileName) || string.IsNullOrEmpty(certificatePassword))
{
options.Listen(IPAddress.Any, 5000);
}
else
{
options.Listen(IPAddress.Any, 5000,
listenOptions => { listenOptions.UseHttps(certificateFileName, certificatePassword); });
}
});
webBuilder.UseStartup<Startup>();
});
}
} | 40.925 | 126 | 0.565669 | [
"Unlicense"
] | Djohnnie/BuildCloudNativeApplicationsWithDotNet5-DotNetDeveloperDays-2020 | mijnsauna/MijnSauna.Backend.Api/Program.cs | 1,639 | C# |
//
// Copyright (c) Seal Report, Eric Pfirsch (sealreport@gmail.com), http://www.sealreport.org.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. http://www.apache.org/licenses/LICENSE-2.0..
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Windows.Forms;
using Seal.Model;
using System.Data.OleDb;
using System.Data;
using System.Drawing;
using Seal.Helpers;
using System.Collections;
using System.Data.Common;
using System.Data.Odbc;
namespace Seal.Forms
{
public interface ITreeSort
{
int GetSort();
}
public class SourceFolder : ITreeSort { public int GetSort() { return 0; } }
public class ModelFolder : ITreeSort { public int GetSort() { return 2; } }
public class OutputFolder : ITreeSort { public int GetSort() { return 4; } }
public class ScheduleFolder : ITreeSort { public int GetSort() { return 5; } }
public class ConnectionFolder : ITreeSort { public int GetSort() { return 0; } }
public class TableFolder : ITreeSort { public int GetSort() { return 1; } }
public class JoinFolder : ITreeSort { public int GetSort() { return 2; } }
public class EnumFolder : ITreeSort { public int GetSort() { return 3; } }
public class LabelFolder : ITreeSort { public int GetSort() { return 1; } }
// Create a node sorter that implements the IComparer interface.
public class NodeSorter : IComparer
{
// Compare the length of the strings, or the strings
// themselves, if they are the same length.
public int Compare(object x, object y)
{
TreeNode tx = x as TreeNode;
TreeNode ty = y as TreeNode;
//Category folder bottom
if (tx.Tag is CategoryFolder && ty.Tag is CategoryFolder) return (string.Compare(((CategoryFolder)tx.Tag).Path, ((CategoryFolder)ty.Tag).Path));
if (tx.Tag is CategoryFolder) return 1;
if (ty.Tag is CategoryFolder) return -1;
//Master table top
if (tx.Tag is MetaTable && ((MetaTable)tx.Tag).IsMasterTable) return -1;
if (ty.Tag is MetaTable && ((MetaTable)ty.Tag).IsMasterTable) return 1;
if (tx.Tag is ITreeSort && ty.Tag is ITreeSort)
{
ITreeSort viewx = tx.Tag as ITreeSort;
ITreeSort viewy = ty.Tag as ITreeSort;
if (viewx.GetSort() == viewy.GetSort()) return string.Compare(tx.Text, ty.Text);
if (viewx.GetSort() > viewy.GetSort()) return 1;
return -1;
}
return string.Compare(tx.Text, ty.Text);
}
}
public class TreeViewEditorHelper
{
public ContextMenuStrip treeContextMenuStrip;
public TreeView mainTreeView;
public ToolStripMenuItem addToolStripMenuItem;
public ToolStripMenuItem removeToolStripMenuItem;
public ToolStripMenuItem addFromToolStripMenuItem;
public ToolStripMenuItem removeRootToolStripMenuItem;
public ToolStripMenuItem copyToolStripMenuItem;
public ToolStripMenuItem sortColumnAlphaOrderToolStripMenuItem;
public ToolStripMenuItem sortColumnSQLOrderToolStripMenuItem;
public bool ForReport = false;
public Report Report = null;
public void AfterSelect(object sender, TreeViewEventArgs e)
{
//Expand by default
if (mainTreeView.SelectedNode != null && !mainTreeView.SelectedNode.IsExpanded && mainTreeView.SelectedNode.Tag is MetaSource)
{
MetaSource metaSource = mainTreeView.SelectedNode.Tag as MetaSource;
if (metaSource != null) mainTreeView.SelectedNode.Expand();
}
}
private MetaSource GetSource(TreeNode node)
{
MetaSource result;
TreeNode currentNode = node;
while (currentNode != null && !(currentNode.Tag is MetaSource))
{
currentNode = currentNode.Parent;
}
result = (MetaSource)(currentNode != null ? currentNode.Tag : null);
return result;
}
public void addSource(TreeNodeCollection nodes, MetaSource source, int noSQLIndex)
{
int index = source.IsNoSQL ? noSQLIndex : 0;
TreeNode mainTN = new TreeNode() { Tag = source, Text = source.Name, ImageIndex = index, SelectedImageIndex = index };
nodes.Add(mainTN);
TreeNode sourceConnectionTN = new TreeNode("Connections") { Tag = source.ConnectionFolder, ImageIndex = 2, SelectedImageIndex = 2 };
mainTN.Nodes.Add(sourceConnectionTN);
foreach (var item in source.Connections.OrderByDescending(i => i.IsEditable).ThenBy(i => i.Name))
{
TreeNode tn = new TreeNode(item.Name + (!item.IsEditable ? " (Repository)" : "")) { Tag = item, ImageIndex = 1, SelectedImageIndex = 1 };
sourceConnectionTN.Nodes.Add(tn);
}
if (!ForReport) sourceConnectionTN.ExpandAll();
TreeNode sourceTableTN = new TreeNode("Tables") { Tag = source.TableFolder, ImageIndex = 2, SelectedImageIndex = 2 };
mainTN.Nodes.Add(sourceTableTN);
foreach (var table in source.MetaData.Tables.OrderByDescending(i => i.IsEditable).ThenBy(i => i.AliasName))
{
TreeNode tableTN = new TreeNode(table.AliasName + (!table.IsEditable ? " (Repository)" : "")) { Tag = table, ImageIndex = 4, SelectedImageIndex = 4 };
sourceTableTN.Nodes.Add(tableTN);
//Add elements
foreach (var column in table.Columns.OrderBy(i => i.DisplayOrder))
{
TreeNode columnTN = new TreeNode(column.DisplayName) { Tag = column, ImageIndex = 7, SelectedImageIndex = 7 };
tableTN.Nodes.Add(columnTN);
}
}
sourceTableTN.Expand();
//Columns by category
TreeNode categoryTN = new TreeNode("Columns by categories") { Tag = source.CategoryFolder, ImageIndex = 2, SelectedImageIndex = 2 };
sourceTableTN.Nodes.Add(categoryTN);
TreeViewHelper.InitCategoryTreeNode(categoryTN.Nodes, source.MetaData.Tables);
categoryTN.Expand();
if (!source.IsNoSQL)
{
TreeNode sourceJoinTN = new TreeNode("Joins") { Tag = source.JoinFolder, ImageIndex = 2, SelectedImageIndex = 2 };
mainTN.Nodes.Add(sourceJoinTN);
foreach (var item in source.MetaData.Joins.OrderByDescending(i => i.IsEditable).ThenBy(i => i.Name))
{
TreeNode tn = new TreeNode(item.Name + (!item.IsEditable ? " (Repository)" : "")) { Tag = item, ImageIndex = 5, SelectedImageIndex = 5 };
sourceJoinTN.Nodes.Add(tn);
}
if (!ForReport) sourceJoinTN.ExpandAll();
}
TreeNode sourceEnumTN = new TreeNode("Enumerated Lists") { Tag = source.EnumFolder, ImageIndex = 2, SelectedImageIndex = 2 };
mainTN.Nodes.Add(sourceEnumTN);
foreach (var item in source.MetaData.Enums.OrderByDescending(i => i.IsEditable).ThenBy(i => i.Name))
{
TreeNode tn = new TreeNode(item.Name + (!item.IsEditable ? " (Repository)" : "")) { Tag = item, ImageIndex = 6, SelectedImageIndex = 6 };
sourceEnumTN.Nodes.Add(tn);
}
if (!ForReport) sourceEnumTN.ExpandAll();
mainTreeView.TreeViewNodeSorter = new NodeSorter();
}
public void sortColumns_Click(object sender, EventArgs e, bool byPosition)
{
if (mainTreeView.SelectedNode == null) return;
if (mainTreeView.SelectedNode.Tag is MetaTable)
{
MetaTable table = mainTreeView.SelectedNode.Tag as MetaTable;
table.SortColumns(byPosition);
}
if (mainTreeView.SelectedNode.Tag is CategoryFolder)
{
CategoryFolder folder = mainTreeView.SelectedNode.Tag as CategoryFolder;
List<MetaColumn> cols = new List<MetaColumn>();
List<string> colNames = new List<string>();
foreach (TreeNode child in mainTreeView.SelectedNode.Nodes)
{
if (child.Tag is MetaColumn)
{
cols.Add(child.Tag as MetaColumn);
}
}
int position = 0;
foreach (var col in cols.OrderBy(i => i.DisplayName))
{
col.DisplayOrder = position++;
}
folder.SetInformation("Columns have been sorted by Name");
}
}
public object addToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mainTreeView.SelectedNode == null) return null;
object entity = mainTreeView.SelectedNode.Tag;
object newEntity = null;
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (entity is ConnectionFolder && source != null)
{
newEntity = source.AddConnection();
}
else if (entity is TableFolder && source != null)
{
newEntity = source.AddTable(ForReport);
}
else if (entity is JoinFolder && source != null)
{
newEntity = source.AddJoin();
}
else if (entity is MetaTable && source != null)
{
newEntity = source.AddColumn((MetaTable)entity);
}
else if (entity is EnumFolder && source != null)
{
newEntity = source.AddEnum();
}
return newEntity;
}
public object copyToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mainTreeView.SelectedNode == null) return null;
object entity = mainTreeView.SelectedNode.Tag;
object newEntity = null;
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (entity is MetaConnection && source != null)
{
newEntity = Helper.Clone(entity);
source.Connections.Add((MetaConnection)newEntity);
source.InitReferences(source.Repository);
((RootComponent)newEntity).GUID = Guid.NewGuid().ToString();
((RootComponent)newEntity).Name = Helper.GetUniqueName(((RootComponent)entity).Name + " - Copy", (from i in source.Connections select i.Name).ToList());
}
else if (entity is MetaTable && source != null)
{
MetaTable table = entity as MetaTable;
newEntity = Helper.Clone(entity);
source.MetaData.Tables.Add((MetaTable)newEntity);
source.InitReferences(source.Repository);
((RootComponent)newEntity).GUID = Guid.NewGuid().ToString();
//Set a table alias
string oldName = !string.IsNullOrEmpty(table.Alias) ? table.Alias : table.Name;
string newName = oldName + "Copy";
((MetaTable)newEntity).Alias = newName;
//Change the table name in the columns
changeTableColumnNames((MetaTable)newEntity, oldName, newName);
foreach (MetaColumn col in ((MetaTable)newEntity).Columns)
{
col.GUID = Guid.NewGuid().ToString();
col.Category = col.Category + " - Copy";
}
}
else if (entity is MetaColumn && source != null)
{
newEntity = Helper.Clone(entity);
((MetaColumn)entity).MetaTable.Columns.Add((MetaColumn)newEntity);
source.InitReferences(source.Repository);
((RootComponent)newEntity).GUID = Guid.NewGuid().ToString();
((MetaColumn)newEntity).DisplayName = ((MetaColumn)entity).DisplayName + " - Copy";
}
else if (entity is MetaJoin && source != null)
{
newEntity = Helper.Clone(entity);
source.MetaData.Joins.Add((MetaJoin)newEntity);
source.InitReferences(source.Repository);
((RootComponent)newEntity).GUID = Guid.NewGuid().ToString();
((RootComponent)newEntity).Name = Helper.GetUniqueName(((RootComponent)entity).Name + " - Copy", (from i in source.MetaData.Joins select i.Name).ToList());
}
else if (entity is MetaEnum && source != null)
{
newEntity = Helper.Clone(entity);
source.MetaData.Enums.Add((MetaEnum)newEntity);
source.InitReferences(source.Repository);
((RootComponent)newEntity).GUID = Guid.NewGuid().ToString();
((RootComponent)newEntity).Name = Helper.GetUniqueName(((RootComponent)entity).Name + " - Copy", (from i in source.MetaData.Enums select i.Name).ToList());
}
return newEntity;
}
public object removeRootToolStripMenuItem_Click(object sender, EventArgs e)
{
if (mainTreeView.SelectedNode == null) return null;
object entity = mainTreeView.SelectedNode.Tag;
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (entity is MetaConnection && source != null)
{
source.RemoveConnection((MetaConnection)entity);
}
else if (entity is MetaTable && source != null)
{
source.RemoveTable((MetaTable)entity);
}
else if (entity is MetaColumn && source != null)
{
((MetaColumn)entity).MetaTable.Columns.Remove((MetaColumn)entity);
}
else if (entity is MetaJoin && source != null)
{
source.RemoveJoin((MetaJoin)entity);
}
else if (entity is MetaEnum && source != null)
{
source.RemoveEnum((MetaEnum)entity);
}
return mainTreeView.SelectedNode.Parent.Tag;
}
public IList getRemoveSource(ref string displayName)
{
IList selectSource = null;
object entity = mainTreeView.SelectedNode.Tag;
MetaSource source = GetSource(mainTreeView.SelectedNode);
ReportView parentView = null;
if (entity is SourceFolder && Report != null)
{
selectSource = Report.Sources.OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is ConnectionFolder && source != null)
{
selectSource = source.Connections.Where(i => i.IsEditable).OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is TableFolder && source != null)
{
selectSource = source.MetaData.Tables.Where(i => i.IsEditable).OrderBy(i => i.AliasName).ToList();
displayName = "DisplayName";
}
else if (entity is JoinFolder && source != null)
{
selectSource = source.MetaData.Joins.Where(i => i.IsEditable).OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is EnumFolder && source != null)
{
selectSource = source.MetaData.Enums.Where(i => i.IsEditable).OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is MetaTable && source != null)
{
selectSource = ((MetaTable)entity).Columns.OrderBy(i => i.DisplayName2).ToList();
displayName = "DisplayName2";
}
else if (entity is ModelFolder)
{
selectSource = Report.Models.OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is ViewFolder)
{
selectSource = Report.Views.OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is ReportView)
{
parentView = (ReportView)entity;
}
else if (entity is TasksFolder)
{
selectSource = Report.Tasks.OrderBy(i => i.SortOrder).ToList();
displayName = "Name";
}
else if (entity is OutputFolder)
{
selectSource = Report.Outputs.OrderBy(i => i.Name).ToList();
displayName = "Name";
}
else if (entity is ScheduleFolder)
{
selectSource = Report.Schedules.OrderBy(i => i.Name).ToList();
displayName = "Name";
}
if (parentView != null)
{
selectSource = parentView.Views.OrderBy(i => i.SortOrder).ToList();
displayName = "Name";
}
return selectSource;
}
public bool removeToolStripMenuItem_Click(object sender, EventArgs e)
{
bool isModified = false;
string displayName = "";
IList selectSource = getRemoveSource(ref displayName);
try
{
Cursor.Current = Cursors.WaitCursor;
if (selectSource != null)
{
MultipleSelectForm frm = new MultipleSelectForm("Please select objects to remove", selectSource, displayName);
if (frm.ShowDialog() == DialogResult.OK)
{
object entity = mainTreeView.SelectedNode.Tag;
MetaSource source = GetSource(mainTreeView.SelectedNode);
Cursor.Current = Cursors.WaitCursor;
isModified = true;
foreach (var item in frm.CheckedItems)
{
if (item is ReportSource)
{
Report.RemoveSource((ReportSource)item);
}
else if (item is MetaConnection)
{
source.RemoveConnection((MetaConnection)item);
}
else if (item is MetaTable)
{
source.RemoveTable((MetaTable)item);
}
else if (item is MetaJoin)
{
source.RemoveJoin((MetaJoin)item);
}
else if (item is MetaColumn)
{
((MetaTable)entity).Columns.Remove((MetaColumn)item);
}
else if (item is MetaEnum)
{
source.RemoveEnum((MetaEnum)item);
}
else if (item is ReportModel)
{
Report.RemoveModel((ReportModel)item);
}
else if (entity is ViewFolder && item is ReportView)
{
Report.RemoveView(null, (ReportView)item);
}
else if (item is ReportView)
{
Report.RemoveView(((ReportView)entity), (ReportView)item);
}
else if (item is ReportTask)
{
Report.RemoveTask((ReportTask)item);
}
else if (item is ReportOutput)
{
Report.RemoveOutput((ReportOutput)item);
}
else if (item is ReportSchedule)
{
Report.RemoveSchedule((ReportSchedule)item);
}
}
}
}
}
finally
{
Cursor.Current = Cursors.Default;
}
return isModified;
}
public void treeContextMenuStrip_Opening(object sender, CancelEventArgs e)
{
string entityName = null, copyEntityName = null;
object entity = mainTreeView.SelectedNode.Tag;
MetaSource metaSource = null;
if (entity is ConnectionFolder) entityName = "Connection";
else if (entity is TableFolder)
{
entityName = "Table";
metaSource = mainTreeView.SelectedNode.Parent.Tag as MetaSource;
}
else if (entity is JoinFolder) entityName = "Join";
else if (entity is EnumFolder) entityName = "Enum";
else if (entity is MetaConnection)
{
copyEntityName = ((MetaConnection)entity).Name;
}
else if (entity is MetaTable)
{
entityName = "Column";
copyEntityName = ((MetaTable)entity).DisplayName;
metaSource = ((MetaTable)entity).Source;
}
else if (entity is MetaColumn)
{
copyEntityName = ((MetaColumn)entity).Name;
metaSource = ((MetaColumn)entity).Source;
}
else if (entity is MetaJoin)
{
copyEntityName = ((MetaJoin)entity).Name;
}
else if (entity is MetaEnum)
{
copyEntityName = ((MetaEnum)entity).Name;
}
bool isNoSQL = (metaSource != null && metaSource.IsNoSQL);
treeContextMenuStrip.Items.Clear();
if (!string.IsNullOrEmpty(entityName) && !isNoSQL)
{
addToolStripMenuItem.Text = string.Format("Add {0}", entityName);
treeContextMenuStrip.Items.Add(addToolStripMenuItem);
treeContextMenuStrip.Items.Add(new ToolStripSeparator());
removeToolStripMenuItem.Text = string.Format("Remove {0}s...", entityName);
treeContextMenuStrip.Items.Add(removeToolStripMenuItem);
string displayName = "";
IList selectSource = getRemoveSource(ref displayName);
removeToolStripMenuItem.Enabled = (selectSource.Count > 0);
if (entity is TableFolder || entity is JoinFolder || entity is MetaTable)
{
treeContextMenuStrip.Items.Add(new ToolStripSeparator());
addFromToolStripMenuItem.Text = string.Format("Add {0}s from Catalog...", entityName);
treeContextMenuStrip.Items.Add(addFromToolStripMenuItem);
}
}
//Disable menu for repository tables in report designer
if (entity is MetaTable && !((MetaTable)entity).IsEditable) treeContextMenuStrip.Items.Clear();
//Copy....
if (!string.IsNullOrEmpty(copyEntityName) && !isNoSQL)
{
if (treeContextMenuStrip.Items.Count > 0) treeContextMenuStrip.Items.Add(new ToolStripSeparator());
copyToolStripMenuItem.Text = string.Format("Copy {0}", Helper.QuoteSingle(copyEntityName));
treeContextMenuStrip.Items.Add(copyToolStripMenuItem);
}
//Disable remove for repository elements in Report Designer
if (entity is MetaTable && !((MetaTable)entity).IsEditable) copyEntityName = null;
if (entity is MetaJoin && !((MetaJoin)entity).IsEditable) copyEntityName = null;
if (entity is MetaEnum && !((MetaEnum)entity).IsEditable) copyEntityName = null;
//Remove....
if (!string.IsNullOrEmpty(copyEntityName) && !isNoSQL)
{
if (treeContextMenuStrip.Items.Count > 0) treeContextMenuStrip.Items.Add(new ToolStripSeparator());
removeRootToolStripMenuItem.Text = string.Format("Remove {0}", Helper.QuoteSingle(copyEntityName));
treeContextMenuStrip.Items.Add(removeRootToolStripMenuItem);
}
//Disable menu for repository columns in report designer
if (entity is MetaColumn && !((MetaColumn)entity).MetaTable.IsEditable) treeContextMenuStrip.Items.Clear();
//Special menus
if (entity is MetaTable && ((MetaTable)entity).IsEditable)
{
if (treeContextMenuStrip.Items.Count > 0) treeContextMenuStrip.Items.Add(new ToolStripSeparator());
treeContextMenuStrip.Items.Add(sortColumnAlphaOrderToolStripMenuItem);
treeContextMenuStrip.Items.Add(sortColumnSQLOrderToolStripMenuItem);
}
if (entity is CategoryFolder && mainTreeView.SelectedNode.Parent != null && mainTreeView.SelectedNode.Parent.Tag is CategoryFolder)
{
bool canSort = true;
foreach (TreeNode child in mainTreeView.SelectedNode.Nodes)
{
if (child.Tag is MetaColumn && !((MetaColumn)child.Tag).MetaTable.IsEditable)
{
canSort = false;
break;
}
}
if (canSort)
{
if (treeContextMenuStrip.Items.Count > 0) treeContextMenuStrip.Items.Add(new ToolStripSeparator());
treeContextMenuStrip.Items.Add(sortColumnAlphaOrderToolStripMenuItem);
}
}
e.Cancel = (treeContextMenuStrip.Items.Count == 0);
}
List<MetaJoin> GetJoins(DbConnection connection, MetaSource source)
{
List<MetaJoin> joins = new List<MetaJoin>();
if (!(connection is OleDbConnection)) return joins;
DataTable schemaTables = ((OleDbConnection)connection).GetOleDbSchemaTable(OleDbSchemaGuid.Foreign_Keys, null);
foreach (DataRow row in schemaTables.Rows)
{
string table1Name = source.GetTableName(row["PK_TABLE_NAME"].ToString());
string table2Name = source.GetTableName(row["FK_TABLE_NAME"].ToString());
MetaTable table1 = source.MetaData.Tables.FirstOrDefault(i => i.Name == source.GetTableName(table1Name));
MetaTable table2 = source.MetaData.Tables.FirstOrDefault(i => i.Name == source.GetTableName(table2Name));
if (table1 == null)
{
string pkschema = "";
if (schemaTables.Columns.Contains("PK_TABLE_SCHEMA")) pkschema = row["PK_TABLE_SCHEMA"].ToString();
else if (schemaTables.Columns.Contains("PK_TABLE_SCHEM")) pkschema = row["PK_TABLE_SCHEM"].ToString();
if (!string.IsNullOrEmpty(pkschema)) table1 = source.MetaData.Tables.FirstOrDefault(i => i.Name == pkschema + "." + table1Name);
}
if (table2 == null)
{
string fkschema = "";
if (schemaTables.Columns.Contains("FK_TABLE_SCHEMA")) fkschema = row["FK_TABLE_SCHEMA"].ToString();
else if (schemaTables.Columns.Contains("FK_TABLE_SCHEM")) fkschema = row["FK_TABLE_SCHEM"].ToString();
if (!string.IsNullOrEmpty(fkschema)) table2 = source.MetaData.Tables.FirstOrDefault(i => i.Name == fkschema + "." + table2Name);
}
if (table1 != null && table2 != null && table1.Name != table2.Name && !source.MetaData.Joins.Exists(i => i.LeftTableGUID == table1.GUID && i.RightTableGUID == table2.GUID))
{
MetaJoin join = joins.FirstOrDefault(i => i.LeftTableGUID == table1.GUID && i.RightTableGUID == table2.GUID);
if (join == null)
{
join = MetaJoin.Create();
join.Name = table1.Name + " - " + table2.Name;
join.LeftTableGUID = table1.GUID;
join.RightTableGUID = table2.GUID;
join.Source = source;
joins.Add(join);
}
if (!string.IsNullOrEmpty(join.Clause)) join.Clause += " AND ";
join.Clause += string.Format("{0}.{1} = {2}.{3}\r\n", table1.Name, source.GetColumnName(row["PK_COLUMN_NAME"].ToString()), table2.Name, source.GetColumnName(row["FK_COLUMN_NAME"].ToString()));
join.JoinType = JoinType.Inner;
}
}
return joins;
}
void addSchemaTables(DataTable schemaTables, List<MetaTable> tables, MetaSource source)
{
//Helper.DisplayDataTable(schemaTables);
foreach (DataRow row in schemaTables.Rows)
{
//if (row["TABLE_TYPE"].ToString() == "SYSTEM TABLE" || row["TABLE_TYPE"].ToString() == "SYSTEM VIEW") continue;
MetaTable table = MetaTable.Create();
string schema = "";
if (schemaTables.Columns.Contains("TABLE_SCHEMA")) schema = row["TABLE_SCHEMA"].ToString();
else if (schemaTables.Columns.Contains("TABLE_SCHEM")) schema = row["TABLE_SCHEM"].ToString();
table.Name = (!string.IsNullOrEmpty(schema) ? source.GetTableName(schema) + "." : "") + source.GetTableName(row["TABLE_NAME"].ToString());
table.Type = row["TABLE_TYPE"].ToString();
table.Source = source;
tables.Add(table);
}
}
public bool addFromToolStripMenuItem_Click(object sender, EventArgs e)
{
bool isModified = false;
object entity = mainTreeView.SelectedNode.Tag;
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (source == null) return isModified;
DbConnection connection = source.GetOpenConnection();
object selectSource = null;
string name = "";
List<CheckBox> options = new List<CheckBox>();
CheckBox autoCreateColumns = new CheckBox() { Text = "Auto create table columns", Checked = true, AutoSize = true };
CheckBox autoCreateJoins = new CheckBox() { Text = "Auto create joins", Checked = true, AutoSize = true };
CheckBox useTableSchemaName = new CheckBox() { Text = "Use schema name", Checked = false, AutoSize = true };
CheckBox keepColumnNames = new CheckBox() { Text = "Keep column names", Checked = false, AutoSize = true };
try
{
Cursor.Current = Cursors.WaitCursor;
if (entity is TableFolder)
{
DataTable schemaTables = connection.GetSchema("Tables");
List<MetaTable> tables = new List<MetaTable>();
addSchemaTables(connection.GetSchema("Tables"), tables, source);
if (connection is OdbcConnection)
{
//Add views for odbc connections..
addSchemaTables(connection.GetSchema("Views"), tables, source);
}
selectSource = tables.OrderBy(i => i.AliasName).ToList();
name = "DisplayName";
options.Add(autoCreateColumns);
options.Add(autoCreateJoins);
if (tables.Count > 0 && tables[0].Name.Contains(".")) options.Add(useTableSchemaName);
if (tables.Count > 0) options.Add(keepColumnNames);
}
else if (entity is MetaTable)
{
options.Add(autoCreateJoins);
autoCreateJoins.Checked = false;
List<MetaColumn> columns = new List<MetaColumn>();
source.AddColumnsFromCatalog(columns, connection, ((MetaTable)entity));
selectSource = columns.OrderBy(i => i.Name).ToList();
name = "Name";
}
else if (entity is JoinFolder)
{
List<MetaJoin> joins = GetJoins(connection, source);
if (joins.Count == 0)
{
MessageBox.Show(connection is OleDbConnection ? "All Joins have been defined for the existing tables" : "Joins cannot be read from the database for 'Microsoft OleDB provider for ODBC drivers'...\r\nIf possible, use another OleDB provider for your connection.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
return isModified;
}
selectSource = joins.OrderBy(i => i.Name).ToList();
name = "Name";
}
if (source != null && selectSource != null)
{
MultipleSelectForm frm = new MultipleSelectForm("Please select objects to add", selectSource, name);
int index = 10;
foreach (var checkbox in options)
{
checkbox.Location = new Point(index, 5);
frm.optionPanel.Controls.Add(checkbox);
index += checkbox.Width + 10;
frm.Width = Math.Max(index + 5, frm.Width);
}
frm.optionPanel.Visible = (options.Count > 0);
if (frm.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
isModified = true;
foreach (var item in frm.CheckedItems)
{
if (item is MetaTable)
{
MetaTable table = (MetaTable)item;
if (!useTableSchemaName.Checked)
{
string[] names = table.Name.Split('.');
if (names.Length == 2) table.Name = names[1];
}
if (source.MetaData.Tables.Exists(i => i.AliasName == table.AliasName))
{
table.Alias = Helper.GetUniqueName(table.Name, (from i in source.MetaData.Tables select i.AliasName).ToList());
}
if (keepColumnNames.Checked)
{
table.KeepColumnNames = true;
}
if (autoCreateColumns.Checked)
{
source.AddColumnsFromCatalog(table.Columns, connection, table);
}
source.MetaData.Tables.Add(table);
}
else if (item is MetaColumn)
{
MetaColumn column = (MetaColumn)item;
((MetaTable)entity).Columns.Add(column);
}
else if (item is MetaJoin)
{
MetaJoin join = (MetaJoin)item;
join.Name = Helper.GetUniqueName(join.Name, (from i in source.MetaData.Joins select i.Name).ToList());
source.MetaData.Joins.Add(join);
}
}
if (autoCreateJoins.Checked)
{
foreach (var join in GetJoins(connection, source))
{
join.Name = Helper.GetUniqueName(join.Name, (from i in source.MetaData.Joins select i.Name).ToList());
source.MetaData.Joins.Add(join);
}
}
}
}
}
finally
{
Cursor.Current = Cursors.Default;
}
return isModified;
}
private void changeTableColumnNames(MetaTable table, string oldValue, string newValue)
{
if (!string.IsNullOrEmpty(newValue) && newValue != oldValue)
{
//Change the table name in the columns
foreach (var col in table.Columns)
{
col.Name = col.Name.Replace(oldValue + ".", newValue + ".");
col.Name = col.Name.Replace(oldValue.ToLower() + ".", newValue + ".");
}
}
}
public static void CheckPropertyValue(object selectedEntity, PropertyValueChangedEventArgs e)
{
//bug 47, if double click in property editor, values are not translated by the converter...
//no better way so far to disable double click...
//-> regression gave bug 50...
string propertyName = e.ChangedItem.PropertyDescriptor.Name;
if (e.ChangedItem.Value == null) return;
var newValue = e.ChangedItem.Value.ToString();
if (string.IsNullOrEmpty(newValue)) return;
if (selectedEntity is MetaSource && propertyName == "ConnectionGUID")
{
var entity = selectedEntity as MetaSource;
if (e.OldValue != null && newValue != ReportSource.DefaultRepositoryConnectionGUID &&
newValue != ReportSource.DefaultReportConnectionGUID &&
!entity.Connections.Exists(i => i.GUID == newValue)) entity.ConnectionGUID = e.OldValue.ToString();
}
if (selectedEntity is ReportModel && propertyName == "ConnectionGUID")
{
var entity = selectedEntity as ReportModel;
if (e.OldValue != null && newValue != ReportSource.DefaultRepositoryConnectionGUID &&
newValue != ReportSource.DefaultReportConnectionGUID &&
!entity.Source.Connections.Exists(i => i.GUID == newValue)) entity.ConnectionGUID = e.OldValue.ToString();
}
if (selectedEntity is ReportTask && propertyName == "ConnectionGUID")
{
var entity = selectedEntity as ReportTask;
if (e.OldValue != null && newValue != ReportSource.DefaultRepositoryConnectionGUID &&
newValue != ReportSource.DefaultReportConnectionGUID &&
!entity.Source.Connections.Exists(i => i.GUID == newValue)) entity.ConnectionGUID = e.OldValue.ToString();
}
else if (selectedEntity is MetaColumn && propertyName == "EnumGUID")
{
var entity = selectedEntity as MetaColumn;
if (e.OldValue != null && !entity.Source.MetaData.Enums.Exists(i => i.GUID == newValue)) entity.EnumGUID = e.OldValue.ToString();
}
else if (selectedEntity is ReportModel && propertyName == "SourceGUID")
{
var entity = selectedEntity as ReportModel;
if (e.OldValue != null && !entity.Report.Sources.Exists(i => i.GUID == newValue)) entity.SourceGUID = e.OldValue.ToString();
}
else if (selectedEntity is ReportTask && propertyName == "SourceGUID")
{
var entity = selectedEntity as ReportTask;
if (e.OldValue != null && !entity.Report.Sources.Exists(i => i.GUID == newValue)) entity.SourceGUID = e.OldValue.ToString();
}
else if (selectedEntity is ReportView && propertyName == "ModelGUID")
{
var entity = selectedEntity as ReportView;
if (e.OldValue != null && !entity.Report.Models.Exists(i => i.GUID == newValue)) entity.ModelGUID = e.OldValue.ToString();
}
else if (selectedEntity is ViewFolder && propertyName == "ViewGUID")
{
var entity = selectedEntity as ViewFolder;
if (e.OldValue != null && !entity.Report.Views.Exists(i => i.GUID == newValue)) entity.ViewGUID = e.OldValue.ToString();
}
else if (selectedEntity is ReportOutput && propertyName == "ViewGUID")
{
var entity = selectedEntity as ReportOutput;
if (e.OldValue != null && !entity.Report.Views.Exists(i => i.GUID == newValue)) entity.ViewGUID = e.OldValue.ToString();
}
else if (selectedEntity is MetaJoin && propertyName == "LeftTableGUID")
{
var entity = selectedEntity as MetaJoin;
if (e.OldValue != null && !entity.Source.MetaData.Tables.Exists(i => i.GUID == newValue)) entity.LeftTableGUID = e.OldValue.ToString();
}
else if (selectedEntity is MetaJoin && propertyName == "RightTableGUID")
{
var entity = selectedEntity as MetaJoin;
if (e.OldValue != null && !entity.Source.MetaData.Tables.Exists(i => i.GUID == newValue)) entity.RightTableGUID = e.OldValue.ToString();
}
}
public bool mainPropertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
if (mainTreeView.SelectedNode == null) return false;
bool mustInit = false;
object selectedEntity = mainTreeView.SelectedNode.Tag;
CheckPropertyValue(selectedEntity, e);
string propertyName = e.ChangedItem.PropertyDescriptor.Name;
if (selectedEntity is ReportTask && propertyName == "Enabled")
{
ReportTask entity = (ReportTask)selectedEntity;
mainTreeView.SelectedNode.ImageIndex = entity.Enabled ? 12 : 14;
mainTreeView.SelectedNode.SelectedImageIndex = mainTreeView.SelectedNode.ImageIndex;
}
else
{
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (source == null) return mustInit;
if (selectedEntity is ReportSource && propertyName == "ConnectionGUID")
{
((ReportSource)selectedEntity).RefreshEnumsOnDbConnection();
}
else if (selectedEntity is MetaConnection && propertyName == "Name")
{
MetaConnection entity = (MetaConnection)selectedEntity;
entity.Name = Helper.GetUniqueName(entity.Name, (from i in source.Connections where i != entity select i.Name).ToList());
mainTreeView.SelectedNode.Text = entity.Name;
}
else if (selectedEntity is MetaTable)
{
MetaTable table = (MetaTable)selectedEntity;
if (propertyName == "Name" && string.IsNullOrEmpty(table.Alias)) table.Name = Helper.GetUniqueName(table.Name, (from i in source.MetaData.Tables where i != table select i.AliasName).ToList());
if (propertyName == "Alias") table.Alias = Helper.GetUniqueName(table.Alias, (from i in source.MetaData.Tables where i != table select i.AliasName).ToList());
mainTreeView.SelectedNode.Text = table.AliasName;
if (table.DynamicColumns && (propertyName == "Name" || propertyName == "Sql" || propertyName == "DefinitionScript"))
{
table.Refresh();
mustInit = true;
}
string newValue = null;
string oldValue = null;
if (e.OldValue != null)
{
oldValue = e.OldValue.ToString();
if (propertyName == "Name") newValue = table.Name;
else if (propertyName == "Alias") newValue = table.Alias;
if (!string.IsNullOrEmpty(newValue) && newValue != oldValue)
{
//Change the table name in the columns and the joins...
changeTableColumnNames(table, oldValue, newValue);
foreach (var join in source.MetaData.Joins.Where(i => i.LeftTableGUID == table.GUID || i.RightTableGUID == table.GUID))
{
join.Clause = join.Clause.Replace(oldValue + ".", newValue + ".");
join.Clause = join.Clause.Replace(oldValue.ToLower() + ".", newValue + ".");
}
}
}
}
else if (selectedEntity is MetaJoin && (propertyName == "Name" || propertyName == "LeftTableGUID" || propertyName == "RightTableGUID"))
{
MetaJoin entity = (MetaJoin)selectedEntity;
entity.Name = Helper.GetUniqueName(entity.Name, (from i in source.MetaData.Joins where i != entity select i.Name).ToList());
mainTreeView.SelectedNode.Text = entity.Name;
}
else if (selectedEntity is MetaColumn)
{
MetaColumn entity = (MetaColumn)selectedEntity;
if (propertyName == "DisplayName")
{
//MetaColumn can be edited in several nodes...
List<TreeNode> nodes = new List<TreeNode>();
TreeViewHelper.NodesFromEntity(mainTreeView.Nodes, selectedEntity, nodes);
foreach (var node in nodes) node.Text = entity.DisplayName;
}
else if (propertyName == "Category")
{
//Rebuild category nodes...
TreeNode rootNode = TreeViewHelper.GetRootCategoryNode(mainTreeView.SelectedNode);
TreeViewHelper.InitCategoryTreeNode(rootNode.Nodes, source.MetaData.Tables);
TreeViewHelper.SelectNode(mainTreeView, rootNode.Nodes, selectedEntity);
}
else if (propertyName == "DisplayOrder")
{
mainTreeView.Sort();
}
}
else if (selectedEntity is CategoryFolder)
{
CategoryFolder entity = (CategoryFolder)selectedEntity;
if (propertyName == "Path")
{
int cnt = 0;
//Change all categories having this name
foreach (MetaTable table in source.MetaData.Tables.Where(i => i.IsEditable))
{
foreach (MetaColumn column in table.Columns)
{
if (column.Category.StartsWith(e.OldValue.ToString()))
{
cnt++;
column.Category = entity.Path + column.Category.Substring(e.OldValue.ToString().Length);
}
}
}
//Rebuild category nodes...
TreeNode rootNode = TreeViewHelper.GetRootCategoryNode(mainTreeView.SelectedNode);
TreeViewHelper.InitCategoryTreeNode(rootNode.Nodes, source.MetaData.Tables);
TreeNode newFolderNode = TreeViewHelper.SelectCategoryNode(mainTreeView, rootNode.Nodes, entity.Path);
if (newFolderNode == null) newFolderNode = rootNode;
CategoryFolder newFolder = (CategoryFolder)newFolderNode.Tag;
newFolder.Information = string.Format("{0} column categories have been updated.", cnt);
if (ForReport) newFolder.Information += " Note that columns defined in Repository Sources cannot be updated from the Report Designer.";
mainTreeView.SelectedNode = null;
mainTreeView.SelectedNode = newFolderNode;
}
}
else if (selectedEntity is MetaEnum && propertyName == "Name")
{
MetaEnum entity = (MetaEnum)selectedEntity;
entity.Name = Helper.GetUniqueName(entity.Name, (from i in source.MetaData.Enums where i != entity select i.Name).ToList());
mainTreeView.SelectedNode.Text = entity.Name;
}
}
TreeNode previous = mainTreeView.SelectedNode;
mainTreeView.Sort();
mainTreeView.SelectedNode = previous;
return mustInit;
}
public void dynamicColumnsToolStripMenuItem_Click(object sender, EventArgs e)
{
object entity = mainTreeView.SelectedNode.Tag;
MetaSource source = GetSource(mainTreeView.SelectedNode);
if (source == null) return;
MetaTable table = entity as MetaTable;
if (table != null && table.DynamicColumns)
{
table.Refresh();
}
}
}
}
| 48.329491 | 350 | 0.527082 | [
"Apache-2.0"
] | 2644783865/Seal-Report | Projects/SealLibrary/Helpers/TreeViewEditorHelper.cs | 50,313 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using MirrorSharp.Testing;
using Newtonsoft.Json.Linq;
using Xunit;
using Xunit.Abstractions;
using SharpLab.Server.Common;
using SharpLab.Tests.Internal;
namespace SharpLab.Tests {
public class DecompilationTests {
private readonly ITestOutputHelper _output;
public DecompilationTests(ITestOutputHelper output) {
_output = output;
}
[Theory]
[InlineData("class C { void M((int, string) t) {} }")] // Tuples, https://github.com/ashmind/SharpLab/issues/139
public async Task SlowUpdate_DecompilesSimpleCodeWithoutErrors(string code) {
var driver = TestEnvironment.NewDriver().SetText(code);
await driver.SendSetOptionsAsync(LanguageNames.CSharp, LanguageNames.CSharp);
var result = await driver.SendSlowUpdateAsync<string>();
var errors = result.JoinErrors();
Assert.True(string.IsNullOrEmpty(errors), errors);
Assert.NotNull(result.ExtensionResult);
Assert.NotEmpty(result.ExtensionResult);
}
[Theory]
[InlineData("Constructor.BaseCall.cs2cs")]
[InlineData("NullPropagation.ToTernary.cs2cs")]
[InlineData("Simple.cs2il")]
[InlineData("Simple.vb2cs")]
[InlineData("Module.vb2cs")]
[InlineData("Lambda.CallInArray.cs2cs")] // https://github.com/ashmind/SharpLab/issues/9
[InlineData("Cast.ExplicitOperatorOnNull.cs2cs")] // https://github.com/ashmind/SharpLab/issues/20
[InlineData("Goto.TryWhile.cs2cs")] // https://github.com/ashmind/SharpLab/issues/123
[InlineData("Nullable.OperatorLifting.cs2cs")] // https://github.com/ashmind/SharpLab/issues/159
[InlineData("Finalizer.Exception.cs2il")] // https://github.com/ashmind/SharpLab/issues/205
[InlineData("Parameters.Optional.Decimal.cs2cs")] // https://github.com/ashmind/SharpLab/issues/316
[InlineData("Unsafe.FixedBuffer.cs2cs")] // https://github.com/ashmind/SharpLab/issues/398
public async Task SlowUpdate_ReturnsExpectedDecompiledCode(string resourceName) {
var data = TestCode.FromResource(resourceName);
var driver = await NewTestDriverAsync(data);
var result = await driver.SendSlowUpdateAsync<string>();
var errors = result.JoinErrors();
var decompiledText = result.ExtensionResult?.Trim();
Assert.True(string.IsNullOrEmpty(errors), errors);
data.AssertIsExpected(decompiledText, _output);
}
[Theory]
[InlineData("Condition.SimpleSwitch.cs2cs")] // https://github.com/ashmind/SharpLab/issues/25
//[InlineData("Variable.FromArgumentToCall.cs2cs")] // https://github.com/ashmind/SharpLab/issues/128
[InlineData("Preprocessor.IfDebug.cs2cs")] // https://github.com/ashmind/SharpLab/issues/161
[InlineData("Preprocessor.IfDebug.vb2cs")] // https://github.com/ashmind/SharpLab/issues/161
[InlineData("FSharp.Preprocessor.IfDebug.fs2cs")] // https://github.com/ashmind/SharpLab/issues/161
[InlineData("Using.Simple.cs2cs")] // https://github.com/ashmind/SharpLab/issues/185
[InlineData("StringInterpolation.Simple.cs2cs")]
public async Task SlowUpdate_ReturnsExpectedDecompiledCode_InDebug(string resourceName) {
var data = TestCode.FromResource(resourceName);
var driver = await NewTestDriverAsync(data, Optimize.Debug);
var result = await driver.SendSlowUpdateAsync<string>();
var errors = result.JoinErrors();
var decompiledText = result.ExtensionResult?.Trim();
Assert.True(string.IsNullOrEmpty(errors), errors);
data.AssertIsExpected(decompiledText, _output);
}
[Theory]
[InlineData(LanguageNames.CSharp,"/// <summary><see cref=\"Incorrect\"/></summary>\r\npublic class C {}", "CS1574")] // https://github.com/ashmind/SharpLab/issues/219
[InlineData(LanguageNames.VisualBasic, "''' <summary><see cref=\"Incorrect\"/></summary>\r\nPublic Class C\r\nEnd Class", "BC42309")]
public async Task SlowUpdate_ReturnsExpectedWarnings_ForXmlDocumentation(string sourceLanguageName, string code, string expectedWarningId) {
var driver = TestEnvironment.NewDriver().SetText(code);
await driver.SendSetOptionsAsync(sourceLanguageName, TargetNames.IL);
var result = await driver.SendSlowUpdateAsync<string>();
Assert.Equal(
new[] { new { Severity = "warning", Id = expectedWarningId } },
result.Diagnostics.Select(d => new { d.Severity, d.Id }).ToArray()
);
}
[Theory]
[InlineData(LanguageNames.CSharp, "public class C {}")]
[InlineData(LanguageNames.VisualBasic, "Public Class C\r\nEnd Class")]
public async Task SlowUpdate_DoesNotReturnWarnings_ForCodeWithoutXmlDocumentation(string sourceLanguageName, string code) {
var driver = TestEnvironment.NewDriver().SetText(code);
await driver.SendSetOptionsAsync(sourceLanguageName, TargetNames.IL);
var result = await driver.SendSlowUpdateAsync<string>();
Assert.Empty(result.Diagnostics);
}
[Theory]
[InlineData("FSharp.EmptyType.fs2il")]
[InlineData("FSharp.SimpleMethod.fs2cs")] // https://github.com/ashmind/SharpLab/issues/119
[InlineData("FSharp.NotNull.fs2cs")]
public async Task SlowUpdate_ReturnsExpectedDecompiledCode_ForFSharp(string resourceName) {
var data = TestCode.FromResource(resourceName);
var driver = await NewTestDriverAsync(data);
var result = await driver.SendSlowUpdateAsync<string>();
var errors = result.JoinErrors();
var decompiledText = result.ExtensionResult?.Trim();
Assert.True(string.IsNullOrEmpty(errors), errors);
data.AssertIsExpected(decompiledText, _output);
}
[Theory]
[InlineData("JitAsm.Simple.cs2asm")]
[InlineData("JitAsm.MultipleReturns.cs2asm")]
[InlineData("JitAsm.ArrayElement.cs2asm")]
[InlineData("JitAsm.AsyncRegression.cs2asm")]
[InlineData("JitAsm.ConsoleWrite.cs2asm")]
[InlineData("JitAsm.JumpBack.cs2asm")] // https://github.com/ashmind/SharpLab/issues/229
[InlineData("JitAsm.Delegate.cs2asm")]
[InlineData("JitAsm.Nested.Simple.cs2asm")]
[InlineData("JitAsm.Generic.Open.Multiple.cs2asm")]
[InlineData("JitAsm.Generic.MethodWithAttribute.cs2asm")]
[InlineData("JitAsm.Generic.ClassWithAttribute.cs2asm")]
#if !NETCOREAPP
// TODO: Diagnose later
// [InlineData("JitAsm.Generic.MethodWithAttribute.fs2asm")]
#endif
[InlineData("JitAsm.Generic.Nested.AttributeOnTop.cs2asm")]
[InlineData("JitAsm.Generic.Nested.AttributeOnNested.cs2asm")]
[InlineData("JitAsm.Generic.Nested.AttributeOnBoth.cs2asm")]
public async Task SlowUpdate_ReturnsExpectedDecompiledCode_ForJitAsm(string resourceName) {
var data = TestCode.FromResource(resourceName);
var driver = await NewTestDriverAsync(data);
var result = await driver.SendSlowUpdateAsync<string>();
var errors = result.JoinErrors();
var decompiledText = result.ExtensionResult?.Trim();
Assert.True(string.IsNullOrEmpty(errors), errors);
data.AssertIsExpected(decompiledText, _output);
}
[Theory]
[InlineData("class C { static int F = 0; }")]
[InlineData("class C { static C() {} }")]
[InlineData("class C { class N { static N() {} } }")]
public async Task SlowUpdate_ReturnsNotSupportedError_ForJitAsmWithStaticConstructors(string code) {
var driver = TestEnvironment.NewDriver().SetText(code);
await driver.SendSetOptionsAsync(LanguageNames.CSharp, TargetNames.JitAsm);
await Assert.ThrowsAsync<NotSupportedException>(() => driver.SendSlowUpdateAsync<string>());
}
[Theory]
[InlineData("Ast.EmptyClass.cs2ast")]
[InlineData("Ast.StructuredTrivia.cs2ast")]
[InlineData("Ast.LiteralTokens.cs2ast")]
[InlineData("Ast.EmptyType.fs2ast")]
[InlineData("Ast.LiteralTokens.fs2ast")]
public async Task SlowUpdate_ReturnsExpectedResult_ForAst(string resourceName) {
var data = TestCode.FromResource(resourceName);
var driver = await NewTestDriverAsync(data);
var result = await driver.SendSlowUpdateAsync<JArray>();
var json = result.ExtensionResult?.ToString();
data.AssertIsExpected(json, _output);
}
private static async Task<MirrorSharpTestDriver> NewTestDriverAsync(TestCode code, string optimize = Optimize.Release) {
var driver = TestEnvironment.NewDriver();
await driver.SendSetOptionsAsync(code.SourceLanguageName, code.TargetName, optimize);
driver.SetText(code.Original);
return driver;
}
}
}
| 50.251337 | 175 | 0.655848 | [
"BSD-2-Clause"
] | Youssef1313/SharpLab | source/NetFramework/Tests/DecompilationTests.cs | 9,397 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.Maui.Controls.Internals;
namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.GalleryPages.CollectionViewGalleries.GroupingGalleries
{
[Preserve(AllMembers = true)]
class Team : List<Member>
{
public Team(string name, List<Member> members) : base(members)
{
Name = name;
}
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
[Preserve(AllMembers = true)]
class Member
{
public Member(string name) => Name = name;
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
[Preserve(AllMembers = true)]
class SuperTeams : List<Team>
{
public SuperTeams()
{
Add(new Team("Avengers",
new List<Member>
{
new Member("Thor"),
new Member("Captain America"),
new Member("Iron Man"),
new Member("The Hulk"),
new Member("Ant-Man"),
new Member("Wasp"),
new Member("Hawkeye"),
new Member("Black Panther"),
new Member("Black Widow"),
new Member("Doctor Druid"),
new Member("She-Hulk"),
new Member("Mockingbird"),
}
));
Add(new Team("Fantastic Four",
new List<Member>
{
new Member("The Thing"),
new Member("The Human Torch"),
new Member("The Invisible Woman"),
new Member("Mr. Fantastic"),
}
));
Add(new Team("Defenders",
new List<Member>
{
new Member("Doctor Strange"),
new Member("Namor"),
new Member("Hulk"),
new Member("Silver Surfer"),
new Member("Hellcat"),
new Member("Nighthawk"),
new Member("Yellowjacket"),
}
));
Add(new Team("Heroes for Hire",
new List<Member>
{
new Member("Luke Cage"),
new Member("Iron Fist"),
new Member("Misty Knight"),
new Member("Colleen Wing"),
new Member("Shang-Chi"),
}
));
Add(new Team("West Coast Avengers",
new List<Member>
{
new Member("Hawkeye"),
new Member("Mockingbird"),
new Member("War Machine"),
new Member("Wonder Man"),
new Member("Tigra"),
}
));
Add(new Team("Great Lakes Avengers",
new List<Member>
{
new Member("Squirrel Girl"),
new Member("Dinah Soar"),
new Member("Mr. Immortal"),
new Member("Flatman"),
new Member("Doorman"),
}
));
}
}
[Preserve(AllMembers = true)]
class ObservableTeam : ObservableCollection<Member>
{
public ObservableTeam(string name, List<Member> members) : base(members)
{
Name = name;
}
public string Name { get; set; }
public override string ToString()
{
return Name;
}
}
[Preserve(AllMembers = true)]
class ObservableSuperTeams : ObservableCollection<ObservableTeam>
{
public ObservableSuperTeams()
{
Add(new ObservableTeam("Avengers",
new List<Member>
{
new Member("Thor"),
new Member("Captain America"),
new Member("Iron Man"),
new Member("The Hulk"),
new Member("Ant-Man"),
new Member("Wasp"),
new Member("Hawkeye"),
new Member("Black Panther"),
new Member("Black Widow"),
new Member("Doctor Druid"),
new Member("She-Hulk"),
new Member("Mockingbird"),
}
));
Add(new ObservableTeam("Fantastic Four",
new List<Member>
{
new Member("The Thing"),
new Member("The Human Torch"),
new Member("The Invisible Woman"),
new Member("Mr. Fantastic"),
}
));
Add(new ObservableTeam("Defenders",
new List<Member>
{
new Member("Doctor Strange"),
new Member("Namor"),
new Member("Hulk"),
new Member("Silver Surfer"),
new Member("Hellcat"),
new Member("Nighthawk"),
new Member("Yellowjacket"),
}
));
Add(new ObservableTeam("Heroes for Hire",
new List<Member>
{
new Member("Luke Cage"),
new Member("Iron Fist"),
new Member("Misty Knight"),
new Member("Colleen Wing"),
new Member("Shang-Chi"),
}
));
Add(new ObservableTeam("West Coast Avengers",
new List<Member>
{
new Member("Hawkeye"),
new Member("Mockingbird"),
new Member("War Machine"),
new Member("Wonder Man"),
new Member("Tigra"),
}
));
Add(new ObservableTeam("Great Lakes Avengers",
new List<Member>
{
new Member("Squirrel Girl"),
new Member("Dinah Soar"),
new Member("Mr. Immortal"),
new Member("Flatman"),
new Member("Doorman"),
}
));
}
}
}
| 21.084112 | 117 | 0.600842 | [
"MIT"
] | 10088/maui | src/Compatibility/ControlGallery/src/Core/GalleryPages/CollectionViewGalleries/GroupingGalleries/ViewModel.cs | 4,514 | 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("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("ea6759d1-1115-4340-a2b2-b44a23523b7f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.747697 | [
"MIT"
] | vesko24/MyRepository-VZ | ListSortNumbers/ListSortNumbers/Properties/AssemblyInfo.cs | 1,414 | C# |
using System.Web.Mvc;
namespace DevOpsPortal
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 21.416667 | 81 | 0.622568 | [
"MIT"
] | alexhaynes32/DevOpsPortal | DevOpsPortal/App_Start/FilterConfig.cs | 259 | C# |
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace NHSCovidPassVerifier.Views.Elements
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MenuItem : Grid
{
public MenuItem()
{
InitializeComponent();
}
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if (propertyName == TextProperty.PropertyName)
{
TextLabel.Text = Text;
}
else if (propertyName == CommandProperty.PropertyName)
{
CommandGestureRecognizer.Command = Command;
}
}
public static readonly BindableProperty TextProperty =
BindableProperty.Create(nameof(TextProperty), typeof(string), typeof(Grid), null, BindingMode.OneWay);
public string Text
{
get => (string)GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly BindableProperty CommandProperty =
BindableProperty.Create(nameof(CommandProperty), typeof(ICommand), typeof(Grid), null, BindingMode.OneWay);
public ICommand Command
{
get => (ICommand)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
}
} | 30.833333 | 119 | 0.621622 | [
"MIT"
] | 0x00null/covid-pass-verifier | NHSCovidPassVerifier/Views/Elements/MenuItem.xaml.cs | 1,482 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.