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 |
|---|---|---|---|---|---|---|---|---|
#region Using Directives
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
#endregion
namespace System.CommandLine.ValueConverters
{
/// <summary>
/// Represents a value converter, which is able to convert strings to integers.
/// </summary>
public class IntegerConverter : IValueConverter
{
#region Private Static Fields
/// <summary>
/// Contains a list of all the types that are supported by this value converter.
/// </summary>
private static List<Type> supportedTypes = new List<Type> { typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong) };
/// <summary>
/// Contains the number style that is used to parse the integer literals.
/// </summary>
private static readonly NumberStyles numberStyles = NumberStyles.Integer | NumberStyles.AllowThousands | NumberStyles.AllowExponent;
#endregion
#region IValueConverter Implementation
/// <summary>
/// Determines whether this value converter is able to convert the specified string.
/// </summary>
/// <param name="value">The value that is to be tested.</param>
/// <returns>Returns <c>true</c> if the value converter is able to convert the specified type and <c>false</c> otherwise.</returns>
public bool CanConvertFrom(string value)
{
Regex hexNumberRegex = new Regex(@"^[ ]*[\+\-]?(0x)", RegexOptions.IgnoreCase);
if (hexNumberRegex.IsMatch(value))
return long.TryParse(hexNumberRegex.Replace(value, string.Empty, 1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _);
return long.TryParse(value, numberStyles, CultureInfo.InvariantCulture, out _);
}
/// <summary>
/// Determines whether this value converter is able to convert a string to the specified type.
/// </summary>
/// <param name="resultType">The type which is to be tested.</param>
/// <returns>Returns <c>true</c> if the value converter can convert to the specified type and <c>false</c> otherwise.</returns>
public bool CanConvertTo(Type resultType) => IntegerConverter.supportedTypes.Contains(resultType);
/// <summary>
/// Converts the specified value to the specified destination type.
/// </summary>
/// <param name="value">The value that is to be converted to the specified destination type.</param>
/// <param name="resultType">The type to which the value is to be converted.</param>
/// <exception cref="ArgumentNullException">If the type or the value is <c>null</c>, empty, or only consists of white spaces, then an <see cref="ArgumentNullException"/> is thrown.
/// <exception cref="InvalidOperationException">If the specified type is not supported or the value could not be converted, then an <see cref="InvalidOperationException"/> is thrown.
/// <returns>Returns a new instance of the specified type, that contains the converted value.</returns>
public object Convert(Type resultType, string value)
{
// Validates the arguments
if (resultType == null)
throw new ArgumentNullException(nameof(resultType));
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException(nameof(value));
// Tries to convert the specified value to the specified type
try
{
Regex hexNumberRegex = new Regex(@"^[ ]*[\+\-]?(0x)", RegexOptions.IgnoreCase);
if (hexNumberRegex.IsMatch(value))
{
int sign = value.Contains("-") ? -1 : 1;
value = hexNumberRegex.Replace(value, string.Empty, 1);
if (resultType == typeof(byte) && sign == 1)
return byte.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
if (resultType == typeof(sbyte))
return (sbyte)(sbyte.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture) * sign);
if (resultType == typeof(short))
return (short)(short.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture) * sign);
if (resultType == typeof(ushort) && sign == 1)
return ushort.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
if (resultType == typeof(int))
return (int)(int.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture) * sign);
if (resultType == typeof(uint) && sign == 1)
return uint.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
if (resultType == typeof(long) || resultType == typeof(object))
return (long)(long.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture) * sign);
if (resultType == typeof(ulong) && sign == 1)
return ulong.Parse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
else
{
if (resultType == typeof(byte))
return byte.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(sbyte))
return sbyte.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(short))
return short.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(ushort))
return ushort.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(int))
return int.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(uint))
return uint.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(long) || resultType == typeof(object))
return long.Parse(value, numberStyles, CultureInfo.InvariantCulture);
if (resultType == typeof(ulong))
return ulong.Parse(value, numberStyles, CultureInfo.InvariantCulture);
}
}
catch (FormatException) {}
catch (OverflowException) {}
// If this code is reached it means, that either the specified type is not supported or the value could not be converted, in that case an exception is thrown
throw new InvalidOperationException($"The value \"{value}\" cannot be converted to \"{resultType.Name}\".");
}
#endregion
}
}
| 56.362903 | 190 | 0.608814 | [
"MIT"
] | JTOne123/command-line-parser | source/ValueConverters/IntegerCoverter.cs | 6,989 | C# |
namespace WFw.IEntity
{
/// <summary>
/// 备注
/// </summary>
public interface IRemark
{
/// <summary>
/// 备注信息
/// </summary>
string Remark { get; set; }
}
}
| 14.333333 | 35 | 0.432558 | [
"MIT"
] | litesz/WFw | WFw/IEntity/IRemark.cs | 229 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace FIFOAnimalShelter.Classes
{
public class Animal
{
public string Type { get; set; }
public Animal Next { get; set; }
public Animal(string type)
{
Type = type;
}
}
}
| 17.111111 | 40 | 0.581169 | [
"MIT"
] | ericsingletonjr/Data-Structures-and-Algorithms | First_Iteration/Challenges/FIFOAnimalShelter/FIFOAnimalShelter/Classes/Animal.cs | 310 | C# |
using System;
using System.Linq;
namespace Books_Store_Lesson.Memory
{
public class BookRepository : IBookRepository
{
/// <summary>
/// Жаңа кітап қосамыз
/// </summary>
private readonly Book[] books = new[]
{
new Book(1, "ISBN 12345-54321","D. Knuth", "Art Of Programming", "Description: Art Of Programming", 7.19m),
new Book(2, "ISBN 12345-54322","M. Fowler", "Refactoring", "Description: Refactoring", 12.45m),
new Book(3, "ISBN 12345-54323","B. Kernighan, D. Ritchie", "C Programming Language", "Description: C Programming Language", 14.98m),
};
public Book[] GetAllByIsbn(string isbn)
{
return books.Where(book => book.Isbn == isbn)
.ToArray();
}
/// <summary>
/// Табылған кітаптарды қайтарады
/// </summary>
/// <param name="query">Іздеу сөзі</param>
/// <returns>Тізбек - Array</returns>
public Book[] GetAllByTitleOrAuthor(string query)
{
// Where(book => book.Title.Contains(titlePart)) - true немесе false қайтарады
// Where(book => book.Title.Contains(titlePart)) - егер Programming сөзі біррет немесе оданда көп кезіксе true қайтарады
// .ToArray(); - қайтадан тізбек түрінде қайтарады
return books.Where(book => book.Author.Contains(query)
|| book.Title.Contains(query))
.ToArray();
}
public Book GetById(int id)
{
//Single - Ешқашан null қайтармайды
//Single - 1 немесе оданда көп элемент болғанда ғана іске қосылады
//Single - Ештеңе таппаған жағдайда ........
return books.Single(book => book.Id == id);
}
}
}
| 35.326923 | 144 | 0.557431 | [
"Unlicense"
] | berkut001kz/books_store_lesson | infrastructure/Books_Store_Lesson.Memory/BookRepository.cs | 2,073 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LevelPropertyEditor.Models {
/// <summary>
/// Модель поведения.
/// </summary>
public class BehaviourModel {
/// <summary>
/// События.
/// </summary>
public IEnumerable<EventModel> Events {
get;
set;
}
/// <summary>
/// Состояния.
/// </summary>
public IEnumerable<StateModel> States {
get;
set;
}
/// <summary>
/// Действия.
/// </summary>
public IEnumerable<ActionModel> Actions {
get;
set;
}
}
}
| 14.95 | 44 | 0.573579 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | trueromanus/ShineGame | src/LevelPropertyEditor/Models/BehaviourModel.cs | 639 | C# |
using System;
using System.Linq;
using Terraria.ID;
using Terraria.ModLoader.Default;
namespace Terraria.ModLoader.IO
{
public class TileEntry : ModEntry
{
public static Func<TagCompound, TileEntry> DESERIALIZER = tag => new TileEntry(tag);
public bool frameImportant;
public TileEntry(ModTile tile) : base(tile) {
frameImportant = Main.tileFrameImportant[tile.Type];
}
public TileEntry(TagCompound tag) : base(tag) {
frameImportant = tag.GetBool("framed");
}
public override string DefaultUnloadedType => ModContent.GetInstance<UnloadedSolidTile>().FullName;
public override TagCompound SerializeData() {
var tag = base.SerializeData();
tag["framed"] = frameImportant;
return tag;
}
protected override string GetUnloadedType(ushort type) {
if (TileID.Sets.BasicChest[type])
return ModContent.GetInstance<UnloadedChest>().FullName;
if (TileID.Sets.BasicDresser[type])
return ModContent.GetInstance<UnloadedDresser>().FullName;
if (TileID.Sets.RoomNeeds.CountsAsChair.Contains(type) ||
TileID.Sets.RoomNeeds.CountsAsDoor.Contains(type) ||
TileID.Sets.RoomNeeds.CountsAsTable.Contains(type) ||
TileID.Sets.RoomNeeds.CountsAsTorch.Contains(type)) {
return ModContent.GetInstance<UnloadedSupremeFurniture>().FullName;
}
if (Main.tileSolidTop[type])
return ModContent.GetInstance<UnloadedSemiSolidTile>().FullName;
if (!Main.tileSolid[type])
return ModContent.GetInstance<UnloadedNonSolidTile>().FullName;
return DefaultUnloadedType;
}
}
}
| 28.537037 | 101 | 0.746918 | [
"MIT"
] | Aang099/tModLoader | patches/tModLoader/Terraria/ModLoader/IO/TileEntry.cs | 1,543 | 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("Unity Networking Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Unity Networking Server")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[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("834f1b6a-6f26-4fc4-8e40-ed569307b82c")]
// 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.216216 | 84 | 0.748939 | [
"MIT"
] | dh-cfo/unity-networking-server | Unity Networking Server/Properties/AssemblyInfo.cs | 1,417 | C# |
using NailGun.Objects;
using System;
using XwMaxLib.Diagnostics;
using XwMaxLib.DNS;
namespace Tester
{
partial class Program
{
//***********************************************************************************
static public void MenuMLS()
{
while (true)
{
Console.ResetColor();
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("------------------------- MLS ---------------------------");
Console.WriteLine("0 - Main Menu");
Console.WriteLine("1 - Test");
Console.ResetColor();
Console.Write("Select option: ");
string option = Console.ReadLine().Trim();
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("--------------------------- Run Test ----------------------------");
Console.ResetColor();
switch (option)
{
case "0":
return;
case "1":
TEST_MLS();
break;
default:
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Unknown option");
}
break;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("----------------------------- DONE ------------------------------");
Console.ReadKey();
}
}
//***********************************************************************************
static public void TEST_MLS()
{
Profiler profiler = new Profiler();
profiler.Setup(true, 0, "Test");
//warmup
MLS wmls = new MLS();
XwMLS wxwmls = new XwMLS();
profiler.Start("NEW");
for (long i = 0; i < 50000; i++)
{
XwMLS mls = new XwMLS("[PT-PT]String de Teste #[/PT-PT][EN-GB]Test String #[/EN-GB][FR-FR]chaîne de test #[/FR-FR][ES-ES]cadena de prueba #[/ES-ES]");
string PTPT = mls.GetTranslation("PT-PT");
string ENGB = mls.GetTranslation("EN-GB");
string FRFR = mls.GetTranslation("FR-FR");
string ESES = mls.GetTranslation("ES-ES");
mls.SetTranslation("PT-PT", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("EN-GB", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("FR-FR", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("ES-ES", PTPT.Replace("#", i.ToString()));
string s = mls;
}
profiler.Stop("NEW");
profiler.Start("OLD");
for (long i = 0; i < 50000; i++)
{
MLS mls = new MLS("[PT-PT]String de Teste #[/PT-PT][EN-GB]Test String #[/EN-GB][FR-FR]chaîne de test #[/FR-FR][ES-ES]cadena de prueba #[/ES-ES]");
string PTPT = mls.GetTranslation("PT-PT");
string ENGB = mls.GetTranslation("EN-GB");
string FRFR = mls.GetTranslation("FR-FR");
string ESES = mls.GetTranslation("ES-ES");
mls.SetTranslation("PT-PT", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("EN-GB", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("FR-FR", PTPT.Replace("#", i.ToString()));
mls.SetTranslation("ES-ES", PTPT.Replace("#", i.ToString()));
string s = mls;
}
profiler.Stop("OLD");
Console.Write(profiler.Print());
}
}
}
| 40.142857 | 166 | 0.417641 | [
"MIT"
] | maxsnts/XwMaxLib | Tester/Test-MLS.cs | 3,938 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type ReferencedObject.
/// </summary>
[JsonConverter(typeof(DerivedTypeConverter<ReferencedObject>))]
public partial class ReferencedObject
{
/// <summary>
/// Gets or sets referencedObjectName.
/// Name of the referenced object. Must match one of the objects in the directory definition.
/// </summary>
[JsonPropertyName("referencedObjectName")]
public string ReferencedObjectName { get; set; }
/// <summary>
/// Gets or sets referencedProperty.
/// Currently not supported. Name of the property in the referenced object, the value for which is used as the reference.
/// </summary>
[JsonPropertyName("referencedProperty")]
public string ReferencedProperty { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonPropertyName("@odata.type")]
public string ODataType { get; set; }
}
}
| 34.769231 | 153 | 0.577434 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/ReferencedObject.cs | 1,808 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SkunkLab.Channels;
using VirtualRtu.Communications.Channels;
using VirtualRtu.Communications.Modbus;
using VirtualRtu.Communications.Pipelines;
using VirtualRtu.Configuration;
namespace VirtualRtu.Communications.Tcp
{
public class ScadaClientListener
{
private readonly VrtuConfig config;
private TcpListener listener;
private readonly ILogger logger;
private Dictionary<string, Pipeline> pipelines;
public ScadaClientListener(VrtuConfig config, ILogger logger = null)
{
this.config = config;
this.logger = logger;
pipelines = new Dictionary<string, Pipeline>();
}
public async Task RunAsync()
{
#if DEBUG
listener = new TcpListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 502));
#else
listener = new TcpListener(new IPEndPoint(GetIPAddress(Dns.GetHostName()), 502));
#endif
listener.ExclusiveAddressUse = false;
listener.Start();
logger?.LogInformation("SCADA client listener started.");
while (true)
{
try
{
TcpClient tcpClient = await listener.AcceptTcpClientAsync();
tcpClient.LingerState = new LingerOption(true, 0);
tcpClient.NoDelay = true;
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
CancellationTokenSource cts = new CancellationTokenSource();
logger?.LogDebug("SCADA client connection acquired.");
IChannel inputChannel = ChannelFactory.Create(false, tcpClient, 1024, 1024 * 100, cts.Token);
logger?.LogDebug("SCADA client created TCP input channel");
IChannel outputChannel = new VirtualRtuChannel(config, logger);
logger?.LogDebug("SCADA client created VRTU output channel");
MbapMapper mapper = new MbapMapper(Guid.NewGuid().ToString());
PipelineBuilder builder = new PipelineBuilder(logger);
Pipeline pipeline = builder.AddConfig(config)
.AddInputChannel(inputChannel)
.AddOutputChannel(outputChannel)
.AddInputFilter(new InputMapFilter(mapper))
.AddOutputFilter(new OutputMapFilter(mapper))
.Build();
logger?.LogDebug("SCADA client pipeline built.");
pipeline.OnPipelineError += Pipeline_OnPipelineError;
pipelines.Add(pipeline.Id, pipeline);
pipeline.Execute();
logger?.LogDebug("SCADA client pipeline executed.");
}
catch (Exception ex)
{
logger?.LogError(ex, "Fault creating pipeline.");
}
}
}
public async Task Shutdown()
{
try
{
pipelines.Clear();
pipelines = null;
listener = null;
}
catch (Exception ex)
{
logger?.LogError(ex, "Not so gracefull scada client listener shutdown.");
}
await Task.CompletedTask;
}
private IPAddress GetIPAddress(string hostname)
{
IPHostEntry hostInfo = Dns.GetHostEntry(hostname);
for (int index = 0; index < hostInfo.AddressList.Length; index++)
{
if (hostInfo.AddressList[index].AddressFamily == AddressFamily.InterNetwork)
{
return hostInfo.AddressList[index];
}
}
return null;
}
private void Pipeline_OnPipelineError(object sender, PipelineErrorEventArgs e)
{
if (e.Error != null)
{
logger?.LogError(e.Error, "Pipe error.");
logger?.LogWarning("Disposing pipeline.");
}
if (pipelines.ContainsKey(e.Id))
{
Pipeline pipeline = pipelines[e.Id];
pipelines.Remove(e.Id);
try
{
pipeline.Dispose();
}
catch (Exception ex)
{
logger?.LogError(ex, "Fault disposing pipeline.");
}
}
else
{
logger?.LogWarning("Pipeline not identified to dispose.");
}
}
}
} | 34.935252 | 116 | 0.541392 | [
"MIT"
] | skunklab/virtualrtu | src/VirtualRtu.Communications/Tcp/ScadaClientListener.cs | 4,858 | C# |
using SpaceShipWarBa.Abstracts.Movements;
using SpaceShipWarBa.Controllers;
using UnityEngine;
namespace SpaceShipWarBa.Movements
{
public class PlayerTransformMovement : IMover
{
readonly PlayerController _playerController;
Vector2 _direction;
public PlayerTransformMovement(PlayerController playerController)
{
_playerController = playerController;
}
public void Tick()
{
_direction = _playerController.InputReader.Direction;
}
public void FixedTick()
{
//yurutme
_playerController.transform.position += (Vector3)_direction * Time.deltaTime;
}
}
} | 25.035714 | 89 | 0.653352 | [
"Unlicense"
] | berkterek/SpaceShipWarBa | SpaceShipWarBA/Assets/_GameFolders/Scripts/Concretes/Movements/PlayerTransformMovement.cs | 701 | C# |
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Xml.Serialization;
namespace TMFileParser.Models.tm7
{
[ExcludeFromCodeCoverage]
public class TM7BordersKeyValueOfguidanyType
{
[XmlElement("Key")]
public string key { get; set; }
[XmlElement("Value")]
public TM7BordersValue value { get; set; }
}
} | 25.6 | 50 | 0.692708 | [
"MIT"
] | microsoft/tm-file-parser | TMFileParser/TMFileParser/Models/tm7/TM7BordersKeyValueOfguidanyType.cs | 386 | 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.
==================================================================== */
namespace Zephyr.Utils.NPOI.SS.Formula.Functions
{
using System;
using System.Text;
using Zephyr.Utils.NPOI.SS.Formula;
using Zephyr.Utils.NPOI.SS.Formula.Eval;
using System.Globalization;
/**
* Common functionality used by VLOOKUP, HLOOKUP, LOOKUP and MATCH
*
* @author Josh Micich
*/
internal class LookupUtils
{
internal class RowVector : ValueVector
{
private AreaEval _tableArray;
private int _size;
private int _rowIndex;
public RowVector(AreaEval tableArray, int rowIndex)
{
_rowIndex = rowIndex;
int _rowAbsoluteIndex = tableArray.FirstRow + rowIndex;
if (!tableArray.ContainsRow(_rowAbsoluteIndex))
{
int lastRowIx = tableArray.LastRow - tableArray.FirstRow;
throw new ArgumentException("Specified row index (" + rowIndex
+ ") is outside the allowed range (0.." + lastRowIx + ")");
}
_tableArray = tableArray;
_size = tableArray.Width;
}
public ValueEval GetItem(int index)
{
if (index > _size)
{
throw new IndexOutOfRangeException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size - 1) + ")");
}
return _tableArray.GetRelativeValue(_rowIndex, index);
}
public int Size
{
get
{
return _size;
}
}
}
internal class ColumnVector : ValueVector
{
private AreaEval _tableArray;
private int _size;
private int _columnIndex;
public ColumnVector(AreaEval tableArray, int columnIndex)
{
_columnIndex = columnIndex;
int _columnAbsoluteIndex = tableArray.FirstColumn + columnIndex;
if (!tableArray.ContainsColumn((short)_columnAbsoluteIndex))
{
int lastColIx = tableArray.LastColumn - tableArray.FirstColumn;
throw new ArgumentException("Specified column index (" + columnIndex
+ ") is outside the allowed range (0.." + lastColIx + ")");
}
_tableArray = tableArray;
_size = _tableArray.Height;
}
public ValueEval GetItem(int index)
{
if (index > _size)
{
throw new IndexOutOfRangeException("Specified index (" + index
+ ") is outside the allowed range (0.." + (_size - 1) + ")");
}
return _tableArray.GetRelativeValue(index, _columnIndex);
}
public int Size
{
get
{
return _size;
}
}
}
public static ValueVector CreateRowVector(TwoDEval tableArray, int relativeRowIndex)
{
return new RowVector((AreaEval)tableArray, relativeRowIndex);
}
public static ValueVector CreateColumnVector(TwoDEval tableArray, int relativeColumnIndex)
{
return new ColumnVector((AreaEval)tableArray, relativeColumnIndex);
}
/**
* @return <c>null</c> if the supplied area is neither a single row nor a single colum
*/
public static ValueVector CreateVector(TwoDEval ae)
{
if (ae.IsColumn)
{
return CreateColumnVector(ae, 0);
}
if (ae.IsRow)
{
return CreateRowVector(ae, 0);
}
return null;
}
private class StringLookupComparer : LookupValueComparerBase
{
private String _value;
public StringLookupComparer(StringEval se)
: base(se)
{
_value = se.StringValue;
}
protected override CompareResult CompareSameType(ValueEval other)
{
StringEval se = (StringEval)other;
return CompareResult.ValueOf(String.Compare(_value, se.StringValue, StringComparison.OrdinalIgnoreCase));
}
protected override String GetValueAsString()
{
return _value;
}
}
private class NumberLookupComparer : LookupValueComparerBase
{
private double _value;
public NumberLookupComparer(NumberEval ne)
: base(ne)
{
_value = ne.NumberValue;
}
protected override CompareResult CompareSameType(ValueEval other)
{
NumberEval ne = (NumberEval)other;
return CompareResult.ValueOf(_value.CompareTo(ne.NumberValue));
}
protected override String GetValueAsString()
{
return _value.ToString(CultureInfo.InvariantCulture);
}
}
/**
* Processes the third argument to VLOOKUP, or HLOOKUP (<b>col_index_num</b>
* or <b>row_index_num</b> respectively).<br/>
* Sample behaviour:
* <table border="0" cellpAdding="1" cellspacing="2" summary="Sample behaviour">
* <tr><th>Input Return</th><th>Value </th><th>Thrown Error</th></tr>
* <tr><td>5</td><td>4</td><td> </td></tr>
* <tr><td>2.9</td><td>2</td><td> </td></tr>
* <tr><td>"5"</td><td>4</td><td> </td></tr>
* <tr><td>"2.18e1"</td><td>21</td><td> </td></tr>
* <tr><td>"-$2"</td><td>-3</td><td>*</td></tr>
* <tr><td>FALSE</td><td>-1</td><td>*</td></tr>
* <tr><td>TRUE</td><td>0</td><td> </td></tr>
* <tr><td>"TRUE"</td><td> </td><td>#REF!</td></tr>
* <tr><td>"abc"</td><td> </td><td>#REF!</td></tr>
* <tr><td>""</td><td> </td><td>#REF!</td></tr>
* <tr><td><blank></td><td> </td><td>#VALUE!</td></tr>
* </table><br/>
*
* * Note - out of range errors (both too high and too low) are handled by the caller.
* @return column or row index as a zero-based value
*
*/
public static int ResolveRowOrColIndexArg(ValueEval rowColIndexArg, int srcCellRow, int srcCellCol)
{
if(rowColIndexArg == null) {
throw new ArgumentException("argument must not be null");
}
ValueEval veRowColIndexArg;
try {
veRowColIndexArg = OperandResolver.GetSingleValue(rowColIndexArg, srcCellRow, (short)srcCellCol);
} catch (EvaluationException) {
// All errors get translated to #REF!
throw EvaluationException.InvalidRef();
}
int oneBasedIndex;
if(veRowColIndexArg is StringEval) {
StringEval se = (StringEval) veRowColIndexArg;
String strVal = se.StringValue;
Double dVal = OperandResolver.ParseDouble(strVal);
if(Double.IsNaN(dVal)) {
// String does not resolve to a number. Raise #REF! error.
throw EvaluationException.InvalidRef();
// This includes text booleans "TRUE" and "FALSE". They are not valid.
}
// else - numeric value parses OK
}
// actual BoolEval values get interpreted as FALSE->0 and TRUE->1
oneBasedIndex = OperandResolver.CoerceValueToInt(veRowColIndexArg);
if (oneBasedIndex < 1) {
// note this is asymmetric with the errors when the index is too large (#REF!)
throw EvaluationException.InvalidValue();
}
return oneBasedIndex - 1; // convert to zero based
}
/**
* The second argument (table_array) should be an area ref, but can actually be a cell ref, in
* which case it Is interpreted as a 1x1 area ref. Other scalar values cause #VALUE! error.
*/
public static AreaEval ResolveTableArrayArg(ValueEval eval)
{
if (eval is AreaEval)
{
return (AreaEval)eval;
}
if(eval is RefEval) {
RefEval refEval = (RefEval) eval;
// Make this cell ref look like a 1x1 area ref.
// It doesn't matter if eval is a 2D or 3D ref, because that detail is never asked of AreaEval.
return refEval.Offset(0, 0, 0, 0);
}
throw EvaluationException.InvalidValue();
}
/**
* Resolves the last (optional) parameter (<b>range_lookup</b>) to the VLOOKUP and HLOOKUP functions.
* @param rangeLookupArg
* @param srcCellRow
* @param srcCellCol
* @return
* @throws EvaluationException
*/
public static bool ResolveRangeLookupArg(ValueEval rangeLookupArg, int srcCellRow, int srcCellCol)
{
if (rangeLookupArg == null)
{
// range_lookup arg not provided
return true; // default Is TRUE
}
ValueEval valEval = OperandResolver.GetSingleValue(rangeLookupArg, srcCellRow, srcCellCol);
if (valEval is BlankEval)
{
// Tricky:
// fourth arg supplied but Evaluates to blank
// this does not Get the default value
return false;
}
if (valEval is BoolEval)
{
// Happy day flow
BoolEval boolEval = (BoolEval)valEval;
return boolEval.BooleanValue;
}
if (valEval is StringEval)
{
String stringValue = ((StringEval)valEval).StringValue;
if (stringValue.Length < 1)
{
// More trickiness:
// Empty string Is not the same as BlankEval. It causes #VALUE! error
throw EvaluationException.InvalidValue();
}
// TODO move parseBoolean to OperandResolver
bool? b = Countif.ParseBoolean(stringValue);
if (b!=null)
{
// string Converted to bool OK
return b==true?true:false;
}
//// Even more trickiness:
//// Note - even if the StringEval represents a number value (for example "1"),
//// Excel does not resolve it to a bool.
throw EvaluationException.InvalidValue();
//// This Is in contrast to the code below,, where NumberEvals values (for
//// example 0.01) *do* resolve to equivalent bool values.
}
if (valEval is NumericValueEval)
{
NumericValueEval nve = (NumericValueEval)valEval;
// zero Is FALSE, everything else Is TRUE
return 0.0 != nve.NumberValue;
}
throw new Exception("Unexpected eval type (" + valEval.GetType().Name + ")");
}
public static int LookupIndexOfValue(ValueEval lookupValue, ValueVector vector, bool IsRangeLookup)
{
LookupValueComparer lookupComparer = CreateLookupComparer(lookupValue);
int result;
if (IsRangeLookup)
{
result = PerformBinarySearch(vector, lookupComparer);
}
else
{
result = LookupIndexOfExactValue(lookupComparer, vector);
}
if (result < 0)
{
throw new EvaluationException(ErrorEval.NA);
}
return result;
}
/**
* Finds first (lowest index) exact occurrence of specified value.
* @param lookupValue the value to be found in column or row vector
* @param vector the values to be searched. For VLOOKUP this Is the first column of the
* tableArray. For HLOOKUP this Is the first row of the tableArray.
* @return zero based index into the vector, -1 if value cannot be found
*/
private static int LookupIndexOfExactValue(LookupValueComparer lookupComparer, ValueVector vector)
{
// Find first occurrence of lookup value
int size = vector.Size;
for (int i = 0; i < size; i++)
{
if (lookupComparer.CompareTo(vector.GetItem(i)).IsEqual)
{
return i;
}
}
return -1;
}
/**
* Excel has funny behaviour when the some elements in the search vector are the wrong type.
*
*/
private static int PerformBinarySearch(ValueVector vector, LookupValueComparer lookupComparer)
{
// both low and high indexes point to values assumed too low and too high.
BinarySearchIndexes bsi = new BinarySearchIndexes(vector.Size);
while (true)
{
int midIx = bsi.GetMidIx();
if (midIx < 0)
{
return bsi.GetLowIx();
}
CompareResult cr = lookupComparer.CompareTo(vector.GetItem(midIx));
if (cr.IsTypeMismatch)
{
int newMidIx = HandleMidValueTypeMismatch(lookupComparer, vector, bsi, midIx);
if (newMidIx < 0)
{
continue;
}
midIx = newMidIx;
cr = lookupComparer.CompareTo(vector.GetItem(midIx));
}
if (cr.IsEqual)
{
return FindLastIndexInRunOfEqualValues(lookupComparer, vector, midIx, bsi.GetHighIx());
}
bsi.narrowSearch(midIx, cr.IsLessThan);
}
}
/**
* Excel seems to handle mismatched types initially by just stepping 'mid' ix forward to the
* first compatible value.
* @param midIx 'mid' index (value which has the wrong type)
* @return usually -1, signifying that the BinarySearchIndex has been narrowed to the new mid
* index. Zero or greater signifies that an exact match for the lookup value was found
*/
private static int HandleMidValueTypeMismatch(LookupValueComparer lookupComparer, ValueVector vector,
BinarySearchIndexes bsi, int midIx)
{
int newMid = midIx;
int highIx = bsi.GetHighIx();
while (true)
{
newMid++;
if (newMid == highIx)
{
// every element from midIx to highIx was the wrong type
// move highIx down to the low end of the mid values
bsi.narrowSearch(midIx, true);
return -1;
}
CompareResult cr = lookupComparer.CompareTo(vector.GetItem(newMid));
if (cr.IsLessThan && newMid == highIx - 1)
{
// move highIx down to the low end of the mid values
bsi.narrowSearch(midIx, true);
return -1;
// but only when "newMid == highIx-1"? slightly weird.
// It would seem more efficient to always do this.
}
if (cr.IsTypeMismatch)
{
// keep stepping over values Until the right type Is found
continue;
}
if (cr.IsEqual)
{
return newMid;
}
// Note - if moving highIx down (due to lookup<vector[newMid]),
// this execution path only moves highIx it down as far as newMid, not midIx,
// which would be more efficient.
bsi.narrowSearch(newMid, cr.IsLessThan);
return -1;
}
}
/**
* Once the binary search has found a single match, (V/H)LOOKUP steps one by one over subsequent
* values to choose the last matching item.
*/
private static int FindLastIndexInRunOfEqualValues(LookupValueComparer lookupComparer, ValueVector vector,
int firstFoundIndex, int maxIx)
{
for (int i = firstFoundIndex + 1; i < maxIx; i++)
{
if (!lookupComparer.CompareTo(vector.GetItem(i)).IsEqual)
{
return i - 1;
}
}
return maxIx - 1;
}
public static LookupValueComparer CreateLookupComparer(ValueEval lookupValue)
{
if (lookupValue == BlankEval.instance)
{
// blank eval translates to zero
// Note - a blank eval in the lookup column/row never matches anything
// empty string in the lookup column/row can only be matched by explicit emtpty string
return new NumberLookupComparer(NumberEval.ZERO);
}
if (lookupValue is StringEval)
{
return new StringLookupComparer((StringEval)lookupValue);
}
if (lookupValue is NumberEval)
{
return new NumberLookupComparer((NumberEval)lookupValue);
}
if (lookupValue is BoolEval)
{
return new BooleanLookupComparer((BoolEval)lookupValue);
}
throw new ArgumentException("Bad lookup value type (" + lookupValue.GetType().Name + ")");
}
}
/**
* Enumeration to support <b>4</b> valued comparison results.<p/>
* Excel lookup functions have complex behaviour in the case where the lookup array has mixed
* types, and/or Is Unordered. Contrary to suggestions in some Excel documentation, there
* does not appear to be a Universal ordering across types. The binary search algorithm used
* Changes behaviour when the Evaluated 'mid' value has a different type to the lookup value.<p/>
*
* A simple int might have done the same job, but there Is risk in confusion with the well
* known <c>Comparable.CompareTo()</c> and <c>Comparator.Compare()</c> which both use
* a ubiquitous 3 value result encoding.
*/
public class CompareResult
{
private bool _isTypeMismatch;
private bool _isLessThan;
private bool _isEqual;
private bool _isGreaterThan;
private CompareResult(bool IsTypeMismatch, int simpleCompareResult)
{
if (IsTypeMismatch)
{
_isTypeMismatch = true;
_isLessThan = false;
_isEqual = false;
_isGreaterThan = false;
}
else
{
_isTypeMismatch = false;
_isLessThan = simpleCompareResult < 0;
_isEqual = simpleCompareResult == 0;
_isGreaterThan = simpleCompareResult > 0;
}
}
public static CompareResult TYPE_MISMATCH = new CompareResult(true, 0);
public static CompareResult LESS_THAN = new CompareResult(false, -1);
public static CompareResult EQUAL = new CompareResult(false, 0);
public static CompareResult GREATER_THAN = new CompareResult(false, +1);
public static CompareResult ValueOf(int simpleCompareResult)
{
if (simpleCompareResult < 0)
{
return LESS_THAN;
}
if (simpleCompareResult > 0)
{
return GREATER_THAN;
}
return EQUAL;
}
public bool IsTypeMismatch
{
get { return _isTypeMismatch; }
}
public bool IsLessThan
{
get { return _isLessThan; }
}
public bool IsEqual
{
get { return _isEqual; }
}
public bool IsGreaterThan
{
get { return _isGreaterThan; }
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(FormatAsString);
sb.Append("]");
return sb.ToString();
}
private String FormatAsString
{
get
{
if (_isTypeMismatch)
{
return "TYPE_MISMATCH";
}
if (_isLessThan)
{
return "LESS_THAN";
}
if (_isEqual)
{
return "EQUAL";
}
if (_isGreaterThan)
{
return "GREATER_THAN";
}
// toString must be reliable
return "error";
}
}
}
/**
* Encapsulates some standard binary search functionality so the Unusual Excel behaviour can
* be clearly distinguished.
*/
internal class BinarySearchIndexes
{
private int _lowIx;
private int _highIx;
public BinarySearchIndexes(int highIx)
{
_lowIx = -1;
_highIx = highIx;
}
/**
* @return -1 if the search range Is empty
*/
public int GetMidIx()
{
int ixDiff = _highIx - _lowIx;
if (ixDiff < 2)
{
return -1;
}
return _lowIx + (ixDiff / 2);
}
public int GetLowIx()
{
return _lowIx;
}
public int GetHighIx()
{
return _highIx;
}
public void narrowSearch(int midIx, bool IsLessThan)
{
if (IsLessThan)
{
_highIx = midIx;
}
else
{
_lowIx = midIx;
}
}
}
internal class BooleanLookupComparer : LookupValueComparerBase
{
private bool _value;
public BooleanLookupComparer(BoolEval be)
: base(be)
{
_value = be.BooleanValue;
}
protected override CompareResult CompareSameType(ValueEval other)
{
BoolEval be = (BoolEval)other;
bool otherVal = be.BooleanValue;
if (_value == otherVal)
{
return CompareResult.EQUAL;
}
// TRUE > FALSE
if (_value)
{
return CompareResult.GREATER_THAN;
}
return CompareResult.LESS_THAN;
}
protected override String GetValueAsString()
{
return _value.ToString();
}
}
/**
* Represents a single row or column within an <c>AreaEval</c>.
*/
public interface ValueVector
{
ValueEval GetItem(int index);
int Size { get; }
}
public interface LookupValueComparer
{
/**
* @return one of 4 instances or <c>CompareResult</c>: <c>LESS_THAN</c>, <c>EQUAL</c>,
* <c>GREATER_THAN</c> or <c>TYPE_MISMATCH</c>
*/
CompareResult CompareTo(ValueEval other);
}
internal abstract class LookupValueComparerBase : LookupValueComparer
{
private Type _tarGetType;
protected LookupValueComparerBase(ValueEval tarGetValue)
{
if (tarGetValue == null)
{
throw new Exception("tarGetValue cannot be null");
}
_tarGetType = tarGetValue.GetType();
}
public CompareResult CompareTo(ValueEval other)
{
if (other == null)
{
throw new Exception("Compare to value cannot be null");
}
if (_tarGetType != other.GetType())
{
return CompareResult.TYPE_MISMATCH;
}
if (_tarGetType == typeof(StringEval))
{
}
return CompareSameType(other);
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
sb.Append(GetValueAsString());
sb.Append("]");
return sb.ToString();
}
protected abstract CompareResult CompareSameType(ValueEval other);
/** used only for debug purposes */
protected abstract String GetValueAsString();
}
} | 35.443228 | 121 | 0.522212 | [
"MIT"
] | zhupangithub/WEBERP | Code/Zephyr.Net/Zephyr.Utils/Document/Excel/NPOI/SS/Formula/Functions/LookupUtils.cs | 25,909 | C# |
using UnityEditor;
using UnityEngine;
namespace VCI
{
public sealed class UnitySettingsLayerValidator : IUnitySettingsValidator
{
public bool IsValid => IsCompleteLayers();
public string ValidationDescription => string.Format("Layer Settings (current = {0})", (IsValid) ? "Valid" : "Invalid");
public string ValidationButtonText => "Use recommended Layer Settings";
public void OnValidate()
{
var tagManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
OverwriteLayers(tagManager);
tagManager.ApplyModifiedProperties();
}
private static readonly string[] requiredLayers =
{
VciDefaultLayerSettings.LocationLayerName,
VciDefaultLayerSettings.PickUpLayerName,
VciDefaultLayerSettings.AccessoryLayerName,
VciDefaultLayerSettings.ItemLayerName,
};
private static readonly int[] requiredLayerIds =
{
24,
25,
26,
27,
};
private static void OverwriteLayers(SerializedObject tagManager)
{
var layersProp = tagManager.FindProperty("layers");
var index = 0;
foreach (var layerId in requiredLayerIds)
{
if (layersProp.arraySize > layerId)
{
var sp = layersProp.GetArrayElementAtIndex(layerId);
if (sp != null && sp.stringValue != requiredLayers[index])
{
sp.stringValue = requiredLayers[index];
Debug.Log("Adding layer " + requiredLayers[index]);
}
}
index++;
}
}
private static bool IsCompleteLayers()
{
for (int i = 0; i < requiredLayers.Length; i++)
{
if (LayerMask.NameToLayer(requiredLayers[i]) == -1)
{
return false;
}
}
return true;
}
}
} | 32.575758 | 128 | 0.53814 | [
"MIT"
] | amamagi/VCI | Assets/VCI/UniVCI/Editor/Utils/UnitySettingsWindow/UnitySettingsLayerValidator.cs | 2,152 | C# |
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Diagnostics;
using System.Threading;
namespace WebService
{
internal static class Program
{
/// <summary>
/// This is the entry point of the service host process.
/// </summary>
private static void Main()
{
try
{
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime.RegisterServiceAsync("WebServiceType",
context => new WebService(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(WebService).Name);
// Prevents this host process from terminating so services keeps running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
}
}
| 34.5 | 122 | 0.594966 | [
"MIT"
] | guyrt/routefinder | src/RouteFinder/WebService/Program.cs | 1,311 | C# |
// =============================================================================
// MIT License
//
// Copyright (c) 2018 Valeriya Pudova (hww.github.io)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// =============================================================================
using UnityEngine;
namespace XiDebugMenu
{
public abstract class DebugMenuItem
{
public DebugMenu parentMenu; //< the menu of this item
public int order; //< sorting menu items and group them by similarities
public readonly string label; //< at left side of menu item
public string value; //< at right side of menu item
public string labelColor; //< label color
public string valueColor; //< value color
public enum EvenTag
{
Null, //< Nothing
Render, //< Render item, update label, value and colors
Up, //< Go to previous item
Down, //< Go to next item
Left, //< Go to previous menu or decrease value or call action
Right, //< Go to next menu or increase value or call action
Reset, //< Reset value to default
OpenMenu, //< When menu open
CloseMenu, //< When menu closed
ToggleMenu, //< Show/Hide menu
ToggleQuickMenu, //< Show/Hide exact menu
}
public enum EventResult
{
Null,
Reset,
Modified,
Called,
}
protected DebugMenuItem(string path, int order)
{
var pathOnly = DebugMenuTools.GetDirectoryName(path);
label = DebugMenuTools.GetFileName(path);
parentMenu = DebugMenuSystem.RootDebugMenu.GetOrCreateMenu(pathOnly);
this.order = order;
labelColor = Colors.ToggleLabelDisabled;
valueColor = Colors.ToggleLabelDisabled;
parentMenu.AddItem(this);
}
protected DebugMenuItem(DebugMenu parentMenu, string label, int order)
{
this.label = label;
this.parentMenu = parentMenu;
this.order = order;
labelColor = Colors.ToggleLabelDisabled;
valueColor = Colors.ToggleLabelDisabled;
parentMenu?.AddItem(this);
}
public virtual void OnEvent(EvenTag tag)
{
// override this method to make specific menu item
}
public override string ToString() { return $"MenuItem[{label}]"; }
protected int KeyboardModificationSpeed
{
get => Input.GetKey(KeyCode.LeftShift) ? (Input.GetKey(KeyCode.LeftControl) ? 100 : 10) : 1;
}
// =============================================================================================================
// Syntax sugar (Can be removed)
// =============================================================================================================
/// <summary>
/// Menu will group items with equal or +1 difference to single block
/// </summary>
public DebugMenuItem Order(int order)
{
this.order = order;
parentMenu.Sort();
return this;
}
public DebugMenuItem AddToMenu(DebugMenu menu)
{
parentMenu?.RemoveItem(this);
parentMenu = menu;
menu.AddItem(this);
return this;
}
public DebugMenuItem Value(string value)
{
this.value = value;
return this;
}
public DebugMenuItem LabelColor(string value)
{
labelColor = value;
return this;
}
public DebugMenuItem ValueColor(string value)
{
valueColor = value;
return this;
}
}
}
| 38.286765 | 117 | 0.520645 | [
"MIT"
] | hww/XiDebugMenu | Assets/XiDebugMenu/Scripts/DebugMenuItem.cs | 5,209 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 0.1.0-559
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = intersight.Client.SwaggerDateConverter;
namespace intersight.Model
{
/// <summary>
/// Storage Enclosure for physical disks
/// </summary>
[DataContract]
public partial class StorageEnclosure : IEquatable<StorageEnclosure>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="StorageEnclosure" /> class.
/// </summary>
/// <param name="Ancestors">Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. .</param>
/// <param name="Moid">A unique identifier of this Managed Object instance. .</param>
/// <param name="Owners">An array of owners which represent effective ownership of this object. .</param>
/// <param name="Parent">The direct ancestor of this managed object in the containment hierarchy. .</param>
/// <param name="Tags">An array of tags, which allow to add key, value meta-data to managed objects. .</param>
/// <param name="ComputeBlade">ComputeBlade.</param>
/// <param name="ComputeRackUnit">ComputeRackUnit.</param>
/// <param name="EquipmentChassis">EquipmentChassis.</param>
/// <param name="PhysicalDisks">PhysicalDisks.</param>
/// <param name="RegisteredDevice">RegisteredDevice.</param>
public StorageEnclosure(List<MoBaseMoRef> Ancestors = default(List<MoBaseMoRef>), string Moid = default(string), List<string> Owners = default(List<string>), MoBaseMoRef Parent = default(MoBaseMoRef), List<MoTag> Tags = default(List<MoTag>), ComputeBladeRef ComputeBlade = default(ComputeBladeRef), ComputeRackUnitRef ComputeRackUnit = default(ComputeRackUnitRef), EquipmentChassisRef EquipmentChassis = default(EquipmentChassisRef), List<StoragePhysicalDiskRef> PhysicalDisks = default(List<StoragePhysicalDiskRef>), AssetDeviceRegistrationRef RegisteredDevice = default(AssetDeviceRegistrationRef))
{
this.Ancestors = Ancestors;
this.Moid = Moid;
this.Owners = Owners;
this.Parent = Parent;
this.Tags = Tags;
this.ComputeBlade = ComputeBlade;
this.ComputeRackUnit = ComputeRackUnit;
this.EquipmentChassis = EquipmentChassis;
this.PhysicalDisks = PhysicalDisks;
this.RegisteredDevice = RegisteredDevice;
}
/// <summary>
/// The Account ID for this managed object.
/// </summary>
/// <value>The Account ID for this managed object. </value>
[DataMember(Name="AccountMoid", EmitDefaultValue=false)]
public string AccountMoid { get; private set; }
/// <summary>
/// Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy.
/// </summary>
/// <value>Ancestors is an array containing the MO references of the ancestors in the object containment hierarchy. </value>
[DataMember(Name="Ancestors", EmitDefaultValue=false)]
public List<MoBaseMoRef> Ancestors { get; set; }
/// <summary>
/// The time when this managed object was created.
/// </summary>
/// <value>The time when this managed object was created. </value>
[DataMember(Name="CreateTime", EmitDefaultValue=false)]
public DateTime? CreateTime { get; private set; }
/// <summary>
/// The time when this managed object was last modified.
/// </summary>
/// <value>The time when this managed object was last modified. </value>
[DataMember(Name="ModTime", EmitDefaultValue=false)]
public DateTime? ModTime { get; private set; }
/// <summary>
/// A unique identifier of this Managed Object instance.
/// </summary>
/// <value>A unique identifier of this Managed Object instance. </value>
[DataMember(Name="Moid", EmitDefaultValue=false)]
public string Moid { get; set; }
/// <summary>
/// The fully-qualified type of this managed object, e.g. the class name.
/// </summary>
/// <value>The fully-qualified type of this managed object, e.g. the class name. </value>
[DataMember(Name="ObjectType", EmitDefaultValue=false)]
public string ObjectType { get; private set; }
/// <summary>
/// An array of owners which represent effective ownership of this object.
/// </summary>
/// <value>An array of owners which represent effective ownership of this object. </value>
[DataMember(Name="Owners", EmitDefaultValue=false)]
public List<string> Owners { get; set; }
/// <summary>
/// The direct ancestor of this managed object in the containment hierarchy.
/// </summary>
/// <value>The direct ancestor of this managed object in the containment hierarchy. </value>
[DataMember(Name="Parent", EmitDefaultValue=false)]
public MoBaseMoRef Parent { get; set; }
/// <summary>
/// An array of tags, which allow to add key, value meta-data to managed objects.
/// </summary>
/// <value>An array of tags, which allow to add key, value meta-data to managed objects. </value>
[DataMember(Name="Tags", EmitDefaultValue=false)]
public List<MoTag> Tags { get; set; }
/// <summary>
/// Gets or Sets DeviceMoId
/// </summary>
[DataMember(Name="DeviceMoId", EmitDefaultValue=false)]
public string DeviceMoId { get; private set; }
/// <summary>
/// Gets or Sets Dn
/// </summary>
[DataMember(Name="Dn", EmitDefaultValue=false)]
public string Dn { get; private set; }
/// <summary>
/// Gets or Sets Rn
/// </summary>
[DataMember(Name="Rn", EmitDefaultValue=false)]
public string Rn { get; private set; }
/// <summary>
/// Gets or Sets Model
/// </summary>
[DataMember(Name="Model", EmitDefaultValue=false)]
public string Model { get; private set; }
/// <summary>
/// Gets or Sets Revision
/// </summary>
[DataMember(Name="Revision", EmitDefaultValue=false)]
public string Revision { get; private set; }
/// <summary>
/// Gets or Sets Serial
/// </summary>
[DataMember(Name="Serial", EmitDefaultValue=false)]
public string Serial { get; private set; }
/// <summary>
/// Gets or Sets Vendor
/// </summary>
[DataMember(Name="Vendor", EmitDefaultValue=false)]
public string Vendor { get; private set; }
/// <summary>
/// Gets or Sets ChassisId
/// </summary>
[DataMember(Name="ChassisId", EmitDefaultValue=false)]
public long? ChassisId { get; private set; }
/// <summary>
/// Gets or Sets ComputeBlade
/// </summary>
[DataMember(Name="ComputeBlade", EmitDefaultValue=false)]
public ComputeBladeRef ComputeBlade { get; set; }
/// <summary>
/// Gets or Sets ComputeRackUnit
/// </summary>
[DataMember(Name="ComputeRackUnit", EmitDefaultValue=false)]
public ComputeRackUnitRef ComputeRackUnit { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="Description", EmitDefaultValue=false)]
public string Description { get; private set; }
/// <summary>
/// Gets or Sets EnclosureId
/// </summary>
[DataMember(Name="EnclosureId", EmitDefaultValue=false)]
public long? EnclosureId { get; private set; }
/// <summary>
/// Gets or Sets EquipmentChassis
/// </summary>
[DataMember(Name="EquipmentChassis", EmitDefaultValue=false)]
public EquipmentChassisRef EquipmentChassis { get; set; }
/// <summary>
/// Gets or Sets NumSlots
/// </summary>
[DataMember(Name="NumSlots", EmitDefaultValue=false)]
public long? NumSlots { get; private set; }
/// <summary>
/// Gets or Sets PhysicalDisks
/// </summary>
[DataMember(Name="PhysicalDisks", EmitDefaultValue=false)]
public List<StoragePhysicalDiskRef> PhysicalDisks { get; set; }
/// <summary>
/// Gets or Sets Presence
/// </summary>
[DataMember(Name="Presence", EmitDefaultValue=false)]
public string Presence { get; private set; }
/// <summary>
/// Gets or Sets RegisteredDevice
/// </summary>
[DataMember(Name="RegisteredDevice", EmitDefaultValue=false)]
public AssetDeviceRegistrationRef RegisteredDevice { get; set; }
/// <summary>
/// Gets or Sets ServerId
/// </summary>
[DataMember(Name="ServerId", EmitDefaultValue=false)]
public long? ServerId { get; private set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="Type", EmitDefaultValue=false)]
public string Type { get; private set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class StorageEnclosure {\n");
sb.Append(" AccountMoid: ").Append(AccountMoid).Append("\n");
sb.Append(" Ancestors: ").Append(Ancestors).Append("\n");
sb.Append(" CreateTime: ").Append(CreateTime).Append("\n");
sb.Append(" ModTime: ").Append(ModTime).Append("\n");
sb.Append(" Moid: ").Append(Moid).Append("\n");
sb.Append(" ObjectType: ").Append(ObjectType).Append("\n");
sb.Append(" Owners: ").Append(Owners).Append("\n");
sb.Append(" Parent: ").Append(Parent).Append("\n");
sb.Append(" Tags: ").Append(Tags).Append("\n");
sb.Append(" DeviceMoId: ").Append(DeviceMoId).Append("\n");
sb.Append(" Dn: ").Append(Dn).Append("\n");
sb.Append(" Rn: ").Append(Rn).Append("\n");
sb.Append(" Model: ").Append(Model).Append("\n");
sb.Append(" Revision: ").Append(Revision).Append("\n");
sb.Append(" Serial: ").Append(Serial).Append("\n");
sb.Append(" Vendor: ").Append(Vendor).Append("\n");
sb.Append(" ChassisId: ").Append(ChassisId).Append("\n");
sb.Append(" ComputeBlade: ").Append(ComputeBlade).Append("\n");
sb.Append(" ComputeRackUnit: ").Append(ComputeRackUnit).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" EnclosureId: ").Append(EnclosureId).Append("\n");
sb.Append(" EquipmentChassis: ").Append(EquipmentChassis).Append("\n");
sb.Append(" NumSlots: ").Append(NumSlots).Append("\n");
sb.Append(" PhysicalDisks: ").Append(PhysicalDisks).Append("\n");
sb.Append(" Presence: ").Append(Presence).Append("\n");
sb.Append(" RegisteredDevice: ").Append(RegisteredDevice).Append("\n");
sb.Append(" ServerId: ").Append(ServerId).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as StorageEnclosure);
}
/// <summary>
/// Returns true if StorageEnclosure instances are equal
/// </summary>
/// <param name="other">Instance of StorageEnclosure to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(StorageEnclosure other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AccountMoid == other.AccountMoid ||
this.AccountMoid != null &&
this.AccountMoid.Equals(other.AccountMoid)
) &&
(
this.Ancestors == other.Ancestors ||
this.Ancestors != null &&
this.Ancestors.SequenceEqual(other.Ancestors)
) &&
(
this.CreateTime == other.CreateTime ||
this.CreateTime != null &&
this.CreateTime.Equals(other.CreateTime)
) &&
(
this.ModTime == other.ModTime ||
this.ModTime != null &&
this.ModTime.Equals(other.ModTime)
) &&
(
this.Moid == other.Moid ||
this.Moid != null &&
this.Moid.Equals(other.Moid)
) &&
(
this.ObjectType == other.ObjectType ||
this.ObjectType != null &&
this.ObjectType.Equals(other.ObjectType)
) &&
(
this.Owners == other.Owners ||
this.Owners != null &&
this.Owners.SequenceEqual(other.Owners)
) &&
(
this.Parent == other.Parent ||
this.Parent != null &&
this.Parent.Equals(other.Parent)
) &&
(
this.Tags == other.Tags ||
this.Tags != null &&
this.Tags.SequenceEqual(other.Tags)
) &&
(
this.DeviceMoId == other.DeviceMoId ||
this.DeviceMoId != null &&
this.DeviceMoId.Equals(other.DeviceMoId)
) &&
(
this.Dn == other.Dn ||
this.Dn != null &&
this.Dn.Equals(other.Dn)
) &&
(
this.Rn == other.Rn ||
this.Rn != null &&
this.Rn.Equals(other.Rn)
) &&
(
this.Model == other.Model ||
this.Model != null &&
this.Model.Equals(other.Model)
) &&
(
this.Revision == other.Revision ||
this.Revision != null &&
this.Revision.Equals(other.Revision)
) &&
(
this.Serial == other.Serial ||
this.Serial != null &&
this.Serial.Equals(other.Serial)
) &&
(
this.Vendor == other.Vendor ||
this.Vendor != null &&
this.Vendor.Equals(other.Vendor)
) &&
(
this.ChassisId == other.ChassisId ||
this.ChassisId != null &&
this.ChassisId.Equals(other.ChassisId)
) &&
(
this.ComputeBlade == other.ComputeBlade ||
this.ComputeBlade != null &&
this.ComputeBlade.Equals(other.ComputeBlade)
) &&
(
this.ComputeRackUnit == other.ComputeRackUnit ||
this.ComputeRackUnit != null &&
this.ComputeRackUnit.Equals(other.ComputeRackUnit)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.EnclosureId == other.EnclosureId ||
this.EnclosureId != null &&
this.EnclosureId.Equals(other.EnclosureId)
) &&
(
this.EquipmentChassis == other.EquipmentChassis ||
this.EquipmentChassis != null &&
this.EquipmentChassis.Equals(other.EquipmentChassis)
) &&
(
this.NumSlots == other.NumSlots ||
this.NumSlots != null &&
this.NumSlots.Equals(other.NumSlots)
) &&
(
this.PhysicalDisks == other.PhysicalDisks ||
this.PhysicalDisks != null &&
this.PhysicalDisks.SequenceEqual(other.PhysicalDisks)
) &&
(
this.Presence == other.Presence ||
this.Presence != null &&
this.Presence.Equals(other.Presence)
) &&
(
this.RegisteredDevice == other.RegisteredDevice ||
this.RegisteredDevice != null &&
this.RegisteredDevice.Equals(other.RegisteredDevice)
) &&
(
this.ServerId == other.ServerId ||
this.ServerId != null &&
this.ServerId.Equals(other.ServerId)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.AccountMoid != null)
hash = hash * 59 + this.AccountMoid.GetHashCode();
if (this.Ancestors != null)
hash = hash * 59 + this.Ancestors.GetHashCode();
if (this.CreateTime != null)
hash = hash * 59 + this.CreateTime.GetHashCode();
if (this.ModTime != null)
hash = hash * 59 + this.ModTime.GetHashCode();
if (this.Moid != null)
hash = hash * 59 + this.Moid.GetHashCode();
if (this.ObjectType != null)
hash = hash * 59 + this.ObjectType.GetHashCode();
if (this.Owners != null)
hash = hash * 59 + this.Owners.GetHashCode();
if (this.Parent != null)
hash = hash * 59 + this.Parent.GetHashCode();
if (this.Tags != null)
hash = hash * 59 + this.Tags.GetHashCode();
if (this.DeviceMoId != null)
hash = hash * 59 + this.DeviceMoId.GetHashCode();
if (this.Dn != null)
hash = hash * 59 + this.Dn.GetHashCode();
if (this.Rn != null)
hash = hash * 59 + this.Rn.GetHashCode();
if (this.Model != null)
hash = hash * 59 + this.Model.GetHashCode();
if (this.Revision != null)
hash = hash * 59 + this.Revision.GetHashCode();
if (this.Serial != null)
hash = hash * 59 + this.Serial.GetHashCode();
if (this.Vendor != null)
hash = hash * 59 + this.Vendor.GetHashCode();
if (this.ChassisId != null)
hash = hash * 59 + this.ChassisId.GetHashCode();
if (this.ComputeBlade != null)
hash = hash * 59 + this.ComputeBlade.GetHashCode();
if (this.ComputeRackUnit != null)
hash = hash * 59 + this.ComputeRackUnit.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.EnclosureId != null)
hash = hash * 59 + this.EnclosureId.GetHashCode();
if (this.EquipmentChassis != null)
hash = hash * 59 + this.EquipmentChassis.GetHashCode();
if (this.NumSlots != null)
hash = hash * 59 + this.NumSlots.GetHashCode();
if (this.PhysicalDisks != null)
hash = hash * 59 + this.PhysicalDisks.GetHashCode();
if (this.Presence != null)
hash = hash * 59 + this.Presence.GetHashCode();
if (this.RegisteredDevice != null)
hash = hash * 59 + this.RegisteredDevice.GetHashCode();
if (this.ServerId != null)
hash = hash * 59 + this.ServerId.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 42.734082 | 608 | 0.523926 | [
"Apache-2.0"
] | CiscoUcs/intersight-powershell | csharp/swaggerClient/src/intersight/Model/StorageEnclosure.cs | 22,820 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BlogApiDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "BlogApiDemo", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "BlogApiDemo v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 29.133333 | 106 | 0.629291 | [
"MIT"
] | Escan-DNMZ/AspNetCoreMvc5-Blog | WebProject/BlogApiDemo/Startup.cs | 1,748 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Project2JAGV.DataAccess.Entities
{
public partial class Ingredients
{
public Ingredients()
{
PizzaIngredients = new HashSet<PizzaIngredients>();
}
public int Id { get; set; }
public int TypeId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public virtual IngredientTypes IngredientType { get; set; }
public virtual ICollection<PizzaIngredients> PizzaIngredients { get; set; }
}
}
| 25.782609 | 83 | 0.634064 | [
"MIT"
] | JAGV-Project2/Project2 | Project2JAGV.DataAccess/Entities/Ingredients.cs | 595 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
namespace Amazon.StorageGateway.Model
{
/// <summary>
/// Returns information about the DescribeBandwidthRateLimitResult response and response metadata.
/// </summary>
public class DescribeBandwidthRateLimitResponse : AmazonWebServiceResponse
{
private DescribeBandwidthRateLimitResult describeBandwidthRateLimitResult;
/// <summary>
/// Gets and sets the DescribeBandwidthRateLimitResult property.
/// A JSON object containing the following fields: GatewayARN DescribeBandwidthRateLimitOutput$AverageDownloadRateLimitInBitsPerSec
/// DescribeBandwidthRateLimitOutput$AverageDownloadRateLimitInBitsPerSec
/// </summary>
public DescribeBandwidthRateLimitResult DescribeBandwidthRateLimitResult
{
get
{
if(this.describeBandwidthRateLimitResult == null)
{
this.describeBandwidthRateLimitResult = new DescribeBandwidthRateLimitResult();
}
return this.describeBandwidthRateLimitResult;
}
set { this.describeBandwidthRateLimitResult = value; }
}
}
}
| 36.403846 | 139 | 0.701004 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.StorageGateway/Model/DescribeBandwidthRateLimitResponse.cs | 1,893 | C# |
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EasyPost {
public class Resource : IResource {
public static T Load<T>(string json) where T : Resource {
return JsonConvert.DeserializeObject<T>(json);
}
public static T LoadFromDictionary<T>(Dictionary<string, object> attributes) where T : Resource {
Type type = typeof(T);
T resource = (T)Activator.CreateInstance(type);
foreach (PropertyInfo property in type.GetProperties()) {
if (attributes.TryGetValue(property.Name, out object attribute) == false)
continue;
if (property.PropertyType.GetInterfaces().Contains(typeof(IResource))) {
MethodInfo method = property.PropertyType
.GetMethod("LoadFromDictionary", BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(new Type[] { property.PropertyType });
property.SetValue(resource, method.Invoke(resource, new object[] { attribute }), null);
} else if (typeof(IEnumerable<IResource>).IsAssignableFrom(property.PropertyType)) {
property.SetValue(resource, Activator.CreateInstance(property.PropertyType), null);
Type genericType = property.PropertyType.GetGenericArguments()[0];
MethodInfo method = genericType.GetMethod("LoadFromDictionary", BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(new Type[] { genericType });
foreach (Dictionary<string, object> attr in (List<Dictionary<string, object>>)attribute) {
((IList)property.GetValue(resource, null)).Add(method.Invoke(resource, new object[] { attr }));
}
} else {
property.SetValue(resource, attribute, null);
}
}
return resource;
}
public void Merge(object source) {
foreach (PropertyInfo property in source.GetType().GetProperties()) {
property.SetValue(this, property.GetValue(source, null), null);
}
}
public Dictionary<string, object> AsDictionary() {
return this.GetType()
.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Where(info => GetValue(info) != null) // only include parameters that are not null
.ToDictionary(info => info.Name, info => GetValue(info));
}
private object GetValue(PropertyInfo info) {
object value = info.GetValue(this, null);
if (value is IResource) {
return ((IResource)value).AsDictionary();
}
else if (value is IEnumerable<IResource>) {
List<Dictionary<string, object>> values = new List<Dictionary<string, object>>();
foreach (IResource IResource in (IEnumerable<IResource>)value) {
values.Add(IResource.AsDictionary());
}
return values;
}
else {
return value;
}
}
}
}
| 43.395062 | 158 | 0.570697 | [
"MIT"
] | roehnan/easypost-csharp | EasyPost/Resource.cs | 3,517 | C# |
/// <summary>
/// The status events.
/// </summary>
namespace bg3_modders_multitool.Enums.ValueLists
{
public enum StatusEvent
{
None,
OnTurn,
OnSpellCast,
OnAttack,
OnAttacked,
OnApply,
OnRemove,
OnApplyAndTurn,
OnDamage,
OnEquip,
OnUnequip,
OnHeal,
OnObscurityChanged,
OnSightRelationsChanged,
OnSurfaceEnter,
OnStatusApplied,
OnStatusRemoved
}
}
| 18.444444 | 48 | 0.558233 | [
"MIT"
] | ShinyHobo/bg3-mod-packer | bg3-modders-multitool/bg3-modders-multitool/Enums/ValueLists/StatusEvent.cs | 500 | C# |
namespace Graphviz4Net
{
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Windows;
using Dot;
using Dot.AntlrParser;
using Graphs;
/// <summary>
/// Directs the process of building a layout.
/// </summary>
/// <remarks>
/// <para>
/// LayoutDirector delegates all the work to individual components,
/// which are
/// <list type="dot">
/// <item><see cref="IGraphToDotConverter"/></item>
/// <item><see cref="IDotRunner"/></item>
/// <item><see cref="IDotParser{TVertexId}"/></item>
/// <item><see cref="ILayoutBuilder{TVertexId}"/></item>
/// </list>
/// </para>
/// <para>
/// The process of building a graph is divided up into three stages: <see cref="StartBuilder"/>,
/// <see cref="RunDot"/>, <see cref="BuildGraph"/>.
/// Only the <see cref="BuildGraph"/> and <see cref="StartBuilder"/> stages invokes the <see cref="ILayoutBuilder{TVertexId}"/>;
/// therefore, if the graph is built from GUI elements (e.g. WPF controls) these has to be
/// run in the dispatcher thread. On contrary, the <see cref="RunDot"/> phase
/// invokes only the <see cref="ILayoutBuilder{TVertexId}.GetSize"/> method so, if this method
/// can run outsize the dispatcher thread (e.g., one can calculate the size in advance),
/// then the invocation of <see cref="RunDot"/> (the actual layouting, which might be slow) can
/// be run in parallel.
/// </para>
/// </remarks>
public class LayoutDirector
{
private readonly ILayoutBuilder<int> builder;
private readonly IDotParser<int> parser;
private readonly IGraphToDotConverter converter;
private readonly IDotRunner dotRunner;
private IGraph originalGraph = null;
private DotGraph<int> dotGraph = null;
private object[] originalGraphElementsMap = null;
/// <summary>
/// Factory method: provides convenient way to construct <see cref="LayoutDirector"/>.
/// </summary>
/// <remarks>
/// <para>If an argument value is not provided (i.e., it's null), then
/// default implementation of required interface is provided. See the
/// documentation of the constructor of this class for the list of
/// default implementations of these interfaces.</para>
/// </remarks>
public static LayoutDirector GetLayoutDirector(
ILayoutBuilder<int> builder,
IDotParser<int> parser = null,
IGraphToDotConverter converter = null,
IDotRunner dotRunner = null)
{
Contract.Requires(builder != null);
Contract.Ensures(Contract.Result<LayoutDirector>() != null);
if (parser == null)
parser = AntlrParserAdapter<int>.GetParser();
if (converter == null)
converter = new GraphToDotConverter();
if (dotRunner == null)
{
#if SILVERLIGHT
dotRunner = new DotAutomationFactoryRunner();
#else
dotRunner = new DotExeRunner();
#endif
}
return new LayoutDirector(builder, parser, converter, dotRunner);
}
/// <summary>
/// Initializes a new instance of the <see cref="LayoutDirector"/> class.
/// </summary>
/// <param name="builder">The builder is responsible for building the actual graphical output.</param>
/// <param name="parser">The parser pases DOT output, default
/// implementation is <see cref="AntlrParserAdapter{T}"/>.
/// Use factory method <see cref="AntlrParserAdapter{T}.GetParser()"/></param>
/// <param name="converter">The converter converts the .NET graph into a
/// GraphViz representation. Default implementation is <see cref="GraphToDotConverter"/>.</param>
/// <param name="dotRunner">The dot runner runs the DOT utility.
/// Default implementation is <see cref="DotExeRunner"/></param>
private LayoutDirector(
ILayoutBuilder<int> builder,
IDotParser<int> parser,
IGraphToDotConverter converter,
IDotRunner dotRunner)
{
Contract.Requires(parser != null);
Contract.Requires(converter != null);
Contract.Requires(builder != null);
Contract.Requires(dotRunner != null);
this.builder = builder;
this.parser = parser;
this.converter = converter;
this.dotRunner = dotRunner;
}
/// <summary>
/// Starts the builder. If the builder requires to be run
/// in the dispatcher thread, this method must be run in it.
/// </summary>
/// <param name="graph">The graph to be layouted.</param>
public void StartBuilder(IGraph graph)
{
this.dotGraph = null;
this.originalGraph = graph;
builder.Start(graph);
}
/// <summary>
/// Runs the dot program and parses it's output.
/// An invocation of <see cref="StartBuilder"/> must precede by a call to this method.
/// </summary>
/// <param name="engine">Layout engine to use.</param>
/// <remarks>
/// This method uses <see cref="IDotRunner"/> and <see cref="IDotParser{TVertexId}"/>,
/// it does not invoke any method on <see cref="ILayoutBuilder{TVertexId}"/>.
/// So in case the <see cref="ILayoutBuilder{TVertexId}"/> requires to run in dispatcher thread,
/// this method does not have to do so, unless the <see cref="IDotRunner"/> or
/// <see cref="IDotParser{TVertexId}"/> require it.
/// </remarks>
public void RunDot(LayoutEngine engine = LayoutEngine.Dot)
{
if (this.originalGraph == null)
{
throw new InvalidOperationException(
"LayoutDirector: the RunDot method must be invoked before call to BuildGraph");
}
var reader = this.dotRunner.RunDot(
writer =>
this.originalGraphElementsMap =
this.converter.Convert(
writer,
this.originalGraph,
new AttributesProvider(builder)),
engine);
this.dotGraph = this.parser.Parse(reader);
}
/// <summary>
/// Processes the graph parsed by <see cref="RunDot"/> and invokes methods on <see cref="ILayoutBuilder"/>
/// to build the actual layout. An invocation of <see cref="RunDot"/> must precede by a call to this method.
/// </summary>
/// <exception cref="InvalidOperationException"/>
/// <exception cref="InvalidFormatException"/>
public void BuildGraph()
{
if (this.dotGraph == null)
{
throw new InvalidOperationException(
"LayoutDirector: the RunDot method must be invoked before call to BuildGraph");
}
if (this.dotGraph.Width.HasValue == false ||
this.dotGraph.Height.HasValue == false)
{
throw new InvalidFormatException("Graph in dot output does not have width or height value set up.");
}
this.builder.BuildGraph(dotGraph.Width.Value, dotGraph.Height.Value, this.originalGraph, dotGraph);
this.BuildVertices();
this.BuildSubGraphs();
this.BuildEdges();
this.builder.Finish();
}
private void BuildEdges()
{
foreach (var edge in dotGraph.Edges)
{
if (edge is DotEdge<int>)
{
var dotEdge = (DotEdge<int>) edge;
Contract.Assert(
0 <= dotEdge.Id && dotEdge.Id < this.originalGraphElementsMap.Length,
"The id of an edge is not in the range of originalGraphElementsMap.");
Contract.Assert(
this.originalGraphElementsMap[dotEdge.Id] is IEdge,
"The id of an edge does not point to an IEdge in originalGraphElementsMap.");
builder.BuildEdge(dotEdge.Path, (IEdge)this.originalGraphElementsMap[dotEdge.Id], dotEdge);
}
}
}
private void BuildSubGraphs()
{
foreach (var subGraph in dotGraph.SubGraphs)
{
if (subGraph.BoundingBox.HasAllValues)
{
Contract.Assert(
0 <= subGraph.Id && subGraph.Id < this.originalGraphElementsMap.Length,
"The id of a subGraph is not in the range of originalGraphElementsMap.");
Contract.Assert(
this.originalGraphElementsMap[subGraph.Id] is ISubGraph,
"The id of an edge does not point to an IEdge in originalGraphElementsMap.");
builder.BuildSubGraph(
subGraph.BoundingBox.LeftX.Value,
subGraph.BoundingBox.UpperY.Value,
subGraph.BoundingBox.RightX.Value,
subGraph.BoundingBox.LowerY.Value,
(ISubGraph)this.originalGraphElementsMap[subGraph.Id],
subGraph);
}
else
{
throw new InvalidFormatException(
string.Format(
"SubGraph '{0}' in dot layout output does not have bounding box (bb) set up.",
subGraph.Label));
}
}
}
private void BuildVertices()
{
foreach (var vertex in dotGraph.AllVertices)
{
if (vertex.Position.HasValue &&
vertex.Width.HasValue &&
vertex.Height.HasValue)
{
Contract.Assert(
0 <= vertex.Id && vertex.Id < this.originalGraphElementsMap.Length,
"The id of a vertex is not in the range of originalGraphElementsMap.");
builder.BuildVertex(
vertex.Position.Value,
vertex.Width.Value,
vertex.Height.Value,
this.originalGraphElementsMap[vertex.Id],
vertex);
}
else
{
throw new InvalidFormatException(
string.Format(
"Vertex '{0}' in dot layout output does not have position, width or height set.",
vertex));
}
}
}
public class InvalidFormatException : Graphviz4NetException
{
public InvalidFormatException(string message, Exception inner = null)
: base(message, inner)
{
}
}
private class AttributesProvider : IAttributesProvider
{
private readonly ILayoutBuilder<int> builder;
public AttributesProvider(ILayoutBuilder<int> builder)
{
this.builder = builder;
}
public IDictionary<string, string> GetVertexAttributes(object vertex)
{
var result = new Dictionary<string, string>();
Size size = this.builder.GetSize(vertex);
result.Add("width", size.Width.ToInvariantString());
result.Add("height", size.Height.ToInvariantString());
result.Add("shape", "rect");
result.Add("fixedsize", "true");
foreach (var attribute in this.builder.GetAdditionalAttributes(vertex))
{
result.Add(attribute.Key, attribute.Value);
}
return result;
}
}
}
}
| 41.22408 | 137 | 0.540889 | [
"BSD-2-Clause"
] | DeafLight/Graphviz4Net | src/Graphviz4Net.Core/LayoutDirector.cs | 12,326 | C# |
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using WMenuItem = Microsoft.Phone.Controls.MenuItem;
using WApplication = System.Windows.Application;
namespace Xamarin.Forms.Platform.WinPhone
{
public sealed class CustomContextMenu : ContextMenu
{
protected override DependencyObject GetContainerForItemOverride()
{
var item = new WMenuItem();
item.SetBinding(HeaderedItemsControl.HeaderProperty, new System.Windows.Data.Binding("Text") { Converter = (System.Windows.Data.IValueConverter)WApplication.Current.Resources["LowerConverter"] });
item.Click += (sender, args) =>
{
IsOpen = false;
var menuItem = item.DataContext as MenuItem;
if (menuItem != null)
menuItem.Activate();
};
return item;
}
}
} | 29.074074 | 199 | 0.745223 | [
"MIT"
] | Acidburn0zzz/Xamarin.Forms | Xamarin.Forms.Platform.WP8/CustomContextMenu.cs | 787 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
// Start is called before the first frame update
public Transform target;
public Vector3 offset;
// Update is called once per frame
void Update()
{
transform.position = Vector3.Lerp(transform.position, target.position + offset, 2 * Time.deltaTime);
}
}
| 23.333333 | 108 | 0.714286 | [
"MIT"
] | atakanhbk/Bag-Master | Assets/Scripts/CameraController.cs | 422 | C# |
// Copyright (c) to owners found in https://github.com/arlm/WinApi/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
using System;
namespace Sandbox
{
[Flags]
public enum SetWindowPosFlags : uint
{
// ReSharper disable InconsistentNaming
/// <summary>
/// If the calling thread and the thread that owns the window are attached to different input
/// queues, the system posts the request to the thread that owns the window. This prevents
/// the calling thread from blocking its execution while other threads process the request.
/// </summary>
SWP_ASYNCWINDOWPOS = 0x4000,
/// <summary>
/// Prevents generation of the WM_SYNCPAINT message.
/// </summary>
SWP_DEFERERASE = 0x2000,
/// <summary>
/// Draws a frame (defined in the window's class description) around the window.
/// </summary>
SWP_DRAWFRAME = 0x0020,
/// <summary>
/// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE
/// message to the window, even if the window's size is not being changed. If this flag is
/// not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
/// </summary>
SWP_FRAMECHANGED = 0x0020,
/// <summary>
/// Hides the window.
/// </summary>
SWP_HIDEWINDOW = 0x0080,
/// <summary>
/// Does not activate the window. If this flag is not set, the window is activated and moved
/// to the top of either the topmost or non-topmost group (depending on the setting of the
/// hWndInsertAfter parameter).
/// </summary>
SWP_NOACTIVATE = 0x0010,
/// <summary>
/// Discards the entire contents of the client area. If this flag is not specified, the valid
/// contents of the client area are saved and copied back into the client area after the
/// window is sized or repositioned.
/// </summary>
SWP_NOCOPYBITS = 0x0100,
/// <summary>
/// Retains the current position (ignores X and Y parameters).
/// </summary>
SWP_NOMOVE = 0x0002,
/// <summary>
/// Does not change the owner window's position in the Z order.
/// </summary>
SWP_NOOWNERZORDER = 0x0200,
/// <summary>
/// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This
/// applies to the client area, the non-client area (including the title bar and scroll
/// bars), and any part of the parent window uncovered as a result of the window being moved.
/// When this flag is set, the application must explicitly invalidate or redraw any parts of
/// the window and parent window that need redrawing.
/// </summary>
SWP_NOREDRAW = 0x0008,
/// <summary>
/// Same as the SWP_NOOWNERZORDER flag.
/// </summary>
SWP_NOREPOSITION = 0x0200,
/// <summary>
/// Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
/// </summary>
SWP_NOSENDCHANGING = 0x0400,
/// <summary>
/// Retains the current size (ignores the cx and cy parameters).
/// </summary>
SWP_NOSIZE = 0x0001,
/// <summary>
/// Retains the current Z order (ignores the hWndInsertAfter parameter).
/// </summary>
SWP_NOZORDER = 0x0004,
/// <summary>
/// Displays the window.
/// </summary>
SWP_SHOWWINDOW = 0x0040,
// ReSharper restore InconsistentNaming
}
} | 37.058824 | 114 | 0.610847 | [
"MIT"
] | arlm/WinApi | src/Sandbox/DisplayApi/SetWindowPosFlags.cs | 3,782 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CefSharp.Puppeteer.Messaging;
namespace CefSharp.Puppeteer.PageAccessibility
{
/// <summary>
/// The Accessibility class provides methods for inspecting Chromium's accessibility tree.
/// The accessibility tree is used by assistive technology such as screen readers or switches.
///
/// Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.
/// Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is than translated into different platform-specific APIs.
/// Accessibility namespace gives users access to the Blink Accessibility Tree.
/// Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves.
/// By default, Puppeteer tries to approximate this filtering, exposing only the "interesting" nodes of the tree.
/// </summary>
public class Accessibility
{
private readonly Connection _client;
/// <summary>
/// Initializes a new instance of the <see cref="PageAccessibility.Accessibility"/> class.
/// </summary>
/// <param name="client">Client.</param>
public Accessibility(Connection client) => _client = client;
/// <summary>
/// Snapshots the async.
/// </summary>
/// <returns>The async.</returns>
/// <param name="options">Options.</param>
public async Task<SerializedAXNode> SnapshotAsync(AccessibilitySnapshotOptions options = null)
{
var response = await _client.SendAsync<AccessibilityGetFullAXTreeResponse>("Accessibility.getFullAXTree").ConfigureAwait(false);
var nodes = response.Nodes;
object backendNodeId = null;
if (options?.Root != null)
{
var node = await _client.SendAsync<DomDescribeNodeResponse>("DOM.describeNode", new DomDescribeNodeRequest
{
ObjectId = options.Root.RemoteObject.ObjectId
}).ConfigureAwait(false);
backendNodeId = node.Node.BackendNodeId;
}
var defaultRoot = AXNode.CreateTree(nodes);
var needle = defaultRoot;
if (backendNodeId != null)
{
needle = defaultRoot.Find(node => node.Payload.BackendDOMNodeId.Equals(backendNodeId));
if (needle == null)
{
return null;
}
}
if (options?.InterestingOnly == false)
{
return SerializeTree(needle)[0];
}
var interestingNodes = new List<AXNode>();
CollectInterestingNodes(interestingNodes, defaultRoot, false);
if (!interestingNodes.Contains(needle))
{
return null;
}
return SerializeTree(needle, interestingNodes)[0];
}
private void CollectInterestingNodes(List<AXNode> collection, AXNode node, bool insideControl)
{
if (node.IsInteresting(insideControl))
{
collection.Add(node);
}
if (node.IsLeafNode())
{
return;
}
insideControl = insideControl || node.IsControl();
foreach (var child in node.Children)
{
CollectInterestingNodes(collection, child, insideControl);
}
}
private SerializedAXNode[] SerializeTree(AXNode node, List<AXNode> whitelistedNodes = null)
{
var children = new List<SerializedAXNode>();
foreach (var child in node.Children)
{
children.AddRange(SerializeTree(child, whitelistedNodes));
}
if (whitelistedNodes?.Contains(node) == false)
{
return children.ToArray();
}
var serializedNode = node.Serialize();
if (children.Count > 0)
{
serializedNode.Children = children.ToArray();
}
return new[] { serializedNode };
}
}
}
| 39.834862 | 161 | 0.592123 | [
"MIT"
] | isabella232/Puppeteer-1 | lib/PuppeteerSharp/PageAccessibility/Accessibility.cs | 4,342 | C# |
using UnityEngine;
using System.Collections;
public class lockCursor : MonoBehaviour {
// Use this for initialization
void Start ()
{
Cursor.lockState = CursorLockMode.Confined;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKey(KeyCode.Escape))
{
Cursor.visible = !Cursor.visible;
Cursor.lockState= CursorLockMode.None;
}
}
}
| 18.708333 | 45 | 0.703786 | [
"MIT"
] | htw6174/LaborJam | LaborJam/Assets/Scripts/lockCursor.cs | 451 | C# |
//
// AVCaptureDeviceInput.cs
//
// Authors:
// Miguel de Icaza
//
// Copyright 2009, Novell, Inc.
// Copyright 2010, Novell, Inc.
// Copyright 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !TVOS && !WATCH
using System;
using Foundation;
using ObjCRuntime;
#nullable enable
namespace AVFoundation {
public partial class AVCaptureDeviceInput {
static public AVCaptureDeviceInput? FromDevice (AVCaptureDevice device)
{
return FromDevice (device, out var error);
}
}
}
#endif
| 32.122449 | 73 | 0.749047 | [
"BSD-3-Clause"
] | stephen-hawley/xamarin-macios | src/AVFoundation/AVCaptureDeviceInput.cs | 1,574 | C# |
using WeifenLuo.WinFormsUI.Docking.Skins;
using System.ComponentModel;
namespace WeifenLuo.WinFormsUI.Docking
{
public partial class DockPanel
{
private DockPanelSkin m_dockPanelSkin = DockPanelSkinBuilder.Create(Style.VisualStudio2005);
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockPanelSkin")]
public DockPanelSkin Skin
{
get { return m_dockPanelSkin; }
set { m_dockPanelSkin = value; }
}
private Style m_dockPanelSkinStyle = Style.VisualStudio2005;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockPanelSkinStyle")]
[DefaultValue(Style.VisualStudio2005)]
public Style SkinStyle
{
get { return m_dockPanelSkinStyle; }
set
{
if (m_dockPanelSkinStyle == value)
return;
m_dockPanelSkinStyle = value;
Skin = DockPanelSkinBuilder.Create(m_dockPanelSkinStyle);
}
}
}
}
| 31.138889 | 101 | 0.604817 | [
"MIT"
] | zdomokos/dockpanelsuite | WinFormsUI/Docking/DockPanel.Appearance.cs | 1,123 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace ES2.Amplitude.Unity.Simulation
{
/// <remarks/>
[GeneratedCode("xsd", "2.0.50727.3038")]
[Serializable]
[DebuggerStepThrough]
[DesignerCategory("code")]
public class QuestExecutionTreeAction_RemoveCuriosity : QuestExecutionTreeAction
{
private QuestInputArgument input_CuriosityGUIDField;
/// <remarks/>
[XmlElement(Form = XmlSchemaForm.Unqualified)]
public QuestInputArgument Input_CuriosityGUID
{
get
{
return this.input_CuriosityGUIDField;
}
set
{
this.input_CuriosityGUIDField = value;
this.RaisePropertyChanged("Input_CuriosityGUID");
}
}
}
} | 21.333333 | 81 | 0.755208 | [
"MIT"
] | Scrivener07/Endless-Studio | Source/Studio.ES2/Amplitude/Unity/Simulation/quest/QuestExecutionTreeAction_RemoveCuriosity.cs | 768 | C# |
/*
* CHANGE LOG - keep only last 5 threads
*
* on-line resources
*/
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Gravity.Services.ActionPlugins.Extensions
{
public static class TypeExtensions
{
/// <summary>
/// Gets the first method in this type with the specified <see cref="DescriptionAttribute"/> description.
/// </summary>
/// <param name="t">This <see cref="Type"/> instance.</param>
/// <param name="regex">A pattern by which to find the method.</param>
/// <returns>MethodInfo instance if found or null if not.</returns>
public static MethodInfo GetMethodByDescription(this Type t, string regex)
{
return GetMethodByDescription(
t,
regex,
flags: BindingFlags.Instance | BindingFlags.NonPublic);
}
/// <summary>
/// Gets the first method in this type with the specified <see cref="DescriptionAttribute"/> description.
/// </summary>
/// <param name="t">This <see cref="Type"/> instance.</param>
/// <param name="regex">A pattern by which to find the method.</param>
/// <param name="flags">Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.</param>
/// <returns>MethodInfo instance if found or null if not.</returns>
public static MethodInfo GetMethodByDescription(this Type t, string regex, BindingFlags flags)
{
return GetMethodByDescription(t, regex, flags, comparison: RegexOptions.IgnoreCase);
}
/// <summary>
/// Gets the first method in this type with the specified <see cref="DescriptionAttribute"/> description.
/// </summary>
/// <param name="t">This <see cref="Type"/> instance.</param>
/// <param name="regex">A pattern by which to find the method.</param>
/// <param name="flags">Specifies flags that control binding and the way in which the search for members and types is conducted by reflection.</param>
/// <param name="comparison">Specifies the culture, case, and sort rules to be used by this search.</param>
/// <returns>MethodInfo instance if found or null if not.</returns>
public static MethodInfo GetMethodByDescription(this Type t, string regex, BindingFlags flags, RegexOptions comparison)
{
// shortcuts
var d = regex;
var c = comparison;
// get method
var methods = t.GetMethods(flags).Where(i => i.GetCustomAttribute<DescriptionAttribute>() != null);
return methods.FirstOrDefault(i => Regex.IsMatch(i.GetCustomAttribute<DescriptionAttribute>().Description, d, c));
}
}
} | 47.081967 | 158 | 0.642758 | [
"MIT"
] | gravity-api/gravity-actions | src/csharp/Gravity.Actions/Gravity.Actions/Extensions/TypeExtensions.cs | 2,874 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CsvGui
{
public partial class FormLoader : Form
{
public FormLoader()
{
InitializeComponent();
}
private void LoadButton_Click(object sender, EventArgs e)
{
string filePath = FilePathTextBox.Text;
bool hasHead = HeadCheckBox.Checked;
ApplicationQueue.InstanceAddFormQueue(LoadingScreen.ConstructForm<FormInfo>(filePath,hasHead));
}
private void FilePathOpenDialog_Click(object sender, EventArgs e)
{
if (FilePathDialog.ShowDialog() == DialogResult.OK)
{
FilePathTextBox.Text = FilePathDialog.FileName;
}
}
private void FilePathOpenFolder_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("explorer", "/select, \""+FilePathTextBox.Text+"\"");
}
}
}
| 27.219512 | 107 | 0.637993 | [
"MIT"
] | CodingWolves/CsvGui | CsvGui/CsvGui/FormLoader.cs | 1,118 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Threading;
using CommunityToolkit.Mvvm.Messaging.Internals;
namespace CommunityToolkit.Mvvm.Messaging;
/// <summary>
/// A class providing a reference implementation for the <see cref="IMessenger"/> interface.
/// </summary>
/// <remarks>
/// This <see cref="IMessenger"/> implementation uses strong references to track the registered
/// recipients, so it is necessary to manually unregister them when they're no longer needed.
/// </remarks>
public sealed class StrongReferenceMessenger : IMessenger
{
// This messenger uses the following logic to link stored instances together:
// --------------------------------------------------------------------------------------------------------
// Dictionary2<Recipient, HashSet<IMapping>> recipientsMap;
// | \________________[*]IDictionary2<Recipient, IDictionary2<TToken>>
// | \_______________[*]IDictionary2<Recipient, object?> /
// | \_________/_________/___ /
// |\ _(recipients registrations)_/ / \ /
// | \__________________ / _____(channel registrations)_____/______\____/
// | \ / / __________________________/ \
// | / / / \
// | Dictionary2<Recipient, object?> mapping = Mapping________________\
// | __________________/ / | / \
// |/ / | / \
// Dictionary2<Recipient, Dictionary2<TToken, object?>> mapping = Mapping<TToken>____________\
// / / / /
// ___(Type2.TToken)____/ / / /
// /________________(Type2.TMessage)_______/_______/__/
// / ________________________________/
// / /
// Dictionary2<Type2, IMapping> typesMap;
// --------------------------------------------------------------------------------------------------------
// Each combination of <TMessage, TToken> results in a concrete Mapping type (if TToken is Unit) or Mapping<Token> type,
// which holds the references from registered recipients to handlers. Mapping is used when the default channel is being
// requested, as in that case there will only ever be up to a handler per recipient, per message type. In that case,
// each recipient will only track the message dispatcher (stored as an object?, see notes below), instead of a dictionary
// mapping each TToken value to the corresponding dispatcher for that recipient. When a custom channel is used, the
// dispatchers are stored in a <TToken, object?> dictionary, so that each recipient can have up to one registered handler
// for a given token, for each message type. Note that the registered dispatchers are only stored as object references, as
// they can either be null or a MessageHandlerDispatcher.For<TRecipient, TMessage> instance.
//
// The first case happens if the handler was registered through an IRecipient<TMessage> instance, while the second one is
// used to wrap input MessageHandler<TRecipient, TMessage> instances. The MessageHandlerDispatcher.For<TRecipient, TMessage>
// instances will just be cast to MessageHandlerDispatcher when invoking it. This allows users to retain type information on
// each registered recipient, instead of having to manually cast each recipient to the right type within the handler
// (additionally, using double dispatch here avoids the need to alias delegate types). The type conversion is guaranteed to be
// respected due to how the messenger type itself works - as registered handlers are always invoked on their respective recipients.
//
// Each mapping is stored in the types map, which associates each pair of concrete types to its mapping instance. Mapping instances
// are exposed as IMapping items, as each will be a closed type over a different combination of TMessage and TToken generic type
// parameters (or just of TMessage, for the default channel). Each existing recipient is also stored in the main recipients map,
// along with a set of all the existing (dictionaries of) handlers for that recipient (for all message types and token types, if any).
//
// A recipient is stored in the main map as long as it has at least one registered handler in any of the existing mappings for every
// message/token type combination. The shared map is used to access the set of all registered handlers for a given recipient, without
// having to know in advance the type of message or token being used for the registration, and without having to use reflection. This
// is the same approach used in the types map, as we expose saved items as IMapping values too.
//
// Note that each mapping stored in the associated set for each recipient also indirectly implements either IDictionary2<Recipient, Token>
// or IDictionary2<Recipient>, with any token type currently in use by that recipient (or none, if using the default channel). This allows
// to retrieve the type-closed mappings of registered handlers with a given token type, for any message type, for every receiver, again
// without having to use reflection. This shared map is used to unregister messages from a given recipients either unconditionally, by
// message type, by token, or for a specific pair of message type and token value.
/// <summary>
/// The collection of currently registered recipients, with a link to their linked message receivers.
/// </summary>
/// <remarks>
/// This collection is used to allow reflection-free access to all the existing
/// registered recipients from <see cref="UnregisterAll"/> and other methods in this type,
/// so that all the existing handlers can be removed without having to dynamically create
/// the generic types for the containers of the various dictionaries mapping the handlers.
/// </remarks>
private readonly Dictionary2<Recipient, HashSet<IMapping>> recipientsMap = new();
/// <summary>
/// The <see cref="Mapping"/> and <see cref="Mapping{TToken}"/> instance for types combination.
/// </summary>
/// <remarks>
/// The values are just of type <see cref="IDictionary2{T}"/> as we don't know the type parameters in advance.
/// Each method relies on <see cref="GetOrAddMapping{TMessage,TToken}"/> to get the type-safe instance of the
/// <see cref="Mapping"/> or <see cref="Mapping{TToken}"/> class for each pair of generic arguments in use.
/// </remarks>
private readonly Dictionary2<Type2, IMapping> typesMap = new();
/// <summary>
/// Gets the default <see cref="StrongReferenceMessenger"/> instance.
/// </summary>
public static StrongReferenceMessenger Default { get; } = new();
/// <inheritdoc/>
public bool IsRegistered<TMessage, TToken>(object recipient, TToken token)
where TMessage : class
where TToken : IEquatable<TToken>
{
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.For<TToken>.ThrowIfNull(token);
lock (this.recipientsMap)
{
if (typeof(TToken) == typeof(Unit))
{
if (!TryGetMapping<TMessage>(out Mapping? mapping))
{
return false;
}
Recipient key = new(recipient);
return mapping.ContainsKey(key);
}
else
{
if (!TryGetMapping<TMessage, TToken>(out Mapping<TToken>? mapping))
{
return false;
}
Recipient key = new(recipient);
return
mapping.TryGetValue(key, out Dictionary2<TToken, object?>? handlers) &&
handlers.ContainsKey(token);
}
}
}
/// <inheritdoc/>
public void Register<TRecipient, TMessage, TToken>(TRecipient recipient, TToken token, MessageHandler<TRecipient, TMessage> handler)
where TRecipient : class
where TMessage : class
where TToken : IEquatable<TToken>
{
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.For<TToken>.ThrowIfNull(token);
ArgumentNullException.ThrowIfNull(handler);
Register<TMessage, TToken>(recipient, token, new MessageHandlerDispatcher.For<TRecipient, TMessage>(handler));
}
/// <inheritdoc cref="WeakReferenceMessenger.Register{TMessage, TToken}(IRecipient{TMessage}, TToken)"/>
internal void Register<TMessage, TToken>(IRecipient<TMessage> recipient, TToken token)
where TMessage : class
where TToken : IEquatable<TToken>
{
Register<TMessage, TToken>(recipient, token, null);
}
/// <summary>
/// Registers a recipient for a given type of message.
/// </summary>
/// <typeparam name="TMessage">The type of message to receive.</typeparam>
/// <typeparam name="TToken">The type of token to use to pick the messages to receive.</typeparam>
/// <param name="recipient">The recipient that will receive the messages.</param>
/// <param name="token">A token used to determine the receiving channel to use.</param>
/// <param name="dispatcher">The input <see cref="MessageHandlerDispatcher"/> instance to register, or null.</param>
/// <exception cref="InvalidOperationException">Thrown when trying to register the same message twice.</exception>
private void Register<TMessage, TToken>(object recipient, TToken token, MessageHandlerDispatcher? dispatcher)
where TMessage : class
where TToken : IEquatable<TToken>
{
lock (this.recipientsMap)
{
Recipient key = new(recipient);
IMapping mapping;
// Fast path for unit tokens
if (typeof(TToken) == typeof(Unit))
{
// Get the <TMessage> registration list for this recipient
Mapping underlyingMapping = GetOrAddMapping<TMessage>();
ref object? registeredHandler = ref underlyingMapping.GetOrAddValueRef(key);
if (registeredHandler is not null)
{
ThrowInvalidOperationExceptionForDuplicateRegistration();
}
// Store the input handler
registeredHandler = dispatcher;
mapping = underlyingMapping;
}
else
{
// Get the <TMessage, TToken> registration list for this recipient
Mapping<TToken> underlyingMapping = GetOrAddMapping<TMessage, TToken>();
ref Dictionary2<TToken, object?>? map = ref underlyingMapping.GetOrAddValueRef(key);
map ??= new Dictionary2<TToken, object?>();
// Add the new registration entry
ref object? registeredHandler = ref map.GetOrAddValueRef(token);
if (registeredHandler is not null)
{
ThrowInvalidOperationExceptionForDuplicateRegistration();
}
registeredHandler = dispatcher;
mapping = underlyingMapping;
}
// Make sure this registration map is tracked for the current recipient
ref HashSet<IMapping>? set = ref this.recipientsMap.GetOrAddValueRef(key);
set ??= new HashSet<IMapping>();
_ = set.Add(mapping);
}
}
/// <inheritdoc/>
public void UnregisterAll(object recipient)
{
ArgumentNullException.ThrowIfNull(recipient);
lock (this.recipientsMap)
{
// If the recipient has no registered messages at all, ignore
Recipient key = new(recipient);
if (!this.recipientsMap.TryGetValue(key, out HashSet<IMapping>? set))
{
return;
}
// Removes all the lists of registered handlers for the recipient
foreach (IMapping mapping in set)
{
if (mapping.TryRemove(key) &&
mapping.Count == 0)
{
// Maps here are really of type Mapping<,> and with unknown type arguments.
// If after removing the current recipient a given map becomes empty, it means
// that there are no registered recipients at all for a given pair of message
// and token types. In that case, we also remove the map from the types map.
// The reason for keeping a key in each mapping is that removing items from a
// dictionary (a hashed collection) only costs O(1) in the best case, while
// if we had tried to iterate the whole dictionary every time we would have
// paid an O(n) minimum cost for each single remove operation.
_ = this.typesMap.TryRemove(mapping.TypeArguments);
}
}
// Remove the associated set in the recipients map
_ = this.recipientsMap.TryRemove(key);
}
}
/// <inheritdoc/>
public void UnregisterAll<TToken>(object recipient, TToken token)
where TToken : IEquatable<TToken>
{
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.For<TToken>.ThrowIfNull(token);
// This method is never called with the unit type, so this path is not implemented. This
// exception should not ever be thrown, it's here just to double check for regressions in
// case a bug was introduced that caused this path to somehow be invoked with the Unit type.
// This type is internal, so consumers of the library would never be able to pass it here,
// and there are (and shouldn't be) any APIs publicly exposed from the library that would
// cause this path to be taken either. When using the default channel, only UnregisterAll(object)
// is supported, which would just unregister all recipients regardless of the selected channel.
if (typeof(TToken) == typeof(Unit))
{
throw new NotImplementedException();
}
bool lockTaken = false;
object[]? maps = null;
int i = 0;
// We use an explicit try/finally block here instead of the lock syntax so that we can use a single
// one both to release the lock and to clear the rented buffer and return it to the pool. The reason
// why we're declaring the buffer here and clearing and returning it in this outer finally block is
// that doing so doesn't require the lock to be kept, and releasing it before performing this last
// step reduces the total time spent while the lock is acquired, which in turn reduces the lock
// contention in multi-threaded scenarios where this method is invoked concurrently.
try
{
Monitor.Enter(this.recipientsMap, ref lockTaken);
// Get the shared set of mappings for the recipient, if present
Recipient key = new(recipient);
if (!this.recipientsMap.TryGetValue(key, out HashSet<IMapping>? set))
{
return;
}
// Copy the candidate mappings for the target recipient to a local array, as we can't modify the
// contents of the set while iterating it. The rented buffer is oversized and will also include
// mappings for handlers of messages that are registered through a different token. Note that
// we're using just an object array to minimize the number of total rented buffers, that would
// just remain in the shared pool unused, other than when they are rented here. Instead, we're
// using a type that would possibly also be used by the users of the library, which increases
// the opportunities to reuse existing buffers for both. When we need to reference an item
// stored in the buffer with the type we know it will have, we use Unsafe.As<T> to avoid the
// expensive type check in the cast, since we already know the assignment will be valid.
maps = ArrayPool<object>.Shared.Rent(set.Count);
foreach (IMapping item in set)
{
// Select all mappings using the same token type
if (item is IDictionary2<Recipient, IDictionary2<TToken>> mapping)
{
maps[i++] = mapping;
}
}
// Iterate through all the local maps. These are all the currently
// existing maps of handlers for messages of any given type, with a token
// of the current type, for the target recipient. We heavily rely on
// interfaces here to be able to iterate through all the available mappings
// without having to know the concrete type in advance, and without having
// to deal with reflection: we can just check if the type of the closed interface
// matches with the token type currently in use, and operate on those instances.
foreach (object obj in maps.AsSpan(0, i))
{
IDictionary2<Recipient, IDictionary2<TToken>>? handlersMap = Unsafe.As<IDictionary2<Recipient, IDictionary2<TToken>>>(obj);
// We don't need whether or not the map contains the recipient, as the
// sequence of maps has already been copied from the set containing all
// the mappings for the target recipients: it is guaranteed to be here.
IDictionary2<TToken> holder = handlersMap[key];
// Try to remove the registered handler for the input token,
// for the current message type (unknown from here).
if (holder.TryRemove(token) &&
holder.Count == 0)
{
// If the map is empty, remove the recipient entirely from its container
_ = handlersMap.TryRemove(key);
IMapping mapping = Unsafe.As<IMapping>(handlersMap);
// This recipient has no registrations left for this combination of token
// and message type, so this mapping can be removed from its associated set.
_ = set.Remove(mapping);
// If the resulting set is empty, then this means that there are no more handlers
// left for this recipient for any message or token type, so the recipient can also
// be removed from the map of all existing recipients with at least one handler.
if (set.Count == 0)
{
_ = this.recipientsMap.TryRemove(key);
}
// If no handlers are left at all for any recipient, across all message types and token
// types, remove the set of mappings entirely for the current recipient, and remove the
// strong reference to it as well. This is the same situation that would've been achieved
// by just calling UnregisterAll(recipient).
if (handlersMap.Count == 0)
{
_ = this.typesMap.TryRemove(mapping.TypeArguments);
}
}
}
}
finally
{
// Release the lock, if we did acquire it
if (lockTaken)
{
Monitor.Exit(this.recipientsMap);
}
// If we got to renting the array of maps, return it to the shared pool.
// Remove references to avoid leaks coming from the shared memory pool.
// We manually create a span and clear it as a small optimization, as
// arrays rented from the pool can be larger than the requested size.
if (maps is not null)
{
maps.AsSpan(0, i).Clear();
ArrayPool<object>.Shared.Return(maps);
}
}
}
/// <inheritdoc/>
public void Unregister<TMessage, TToken>(object recipient, TToken token)
where TMessage : class
where TToken : IEquatable<TToken>
{
ArgumentNullException.ThrowIfNull(recipient);
ArgumentNullException.For<TToken>.ThrowIfNull(token);
lock (this.recipientsMap)
{
if (typeof(TToken) == typeof(Unit))
{
// Get the registration list, if available
if (!TryGetMapping<TMessage>(out Mapping? mapping))
{
return;
}
Recipient key = new(recipient);
// Remove the handler (there can only be one for the unit type)
if (!mapping.TryRemove(key))
{
return;
}
// Remove the map entirely from this container, and remove the link to the map itself to
// the current mapping between existing registered recipients (or entire recipients too).
// This is the same as below, except for the unit type there can only be one handler, so
// removing it already implies the target recipient has no remaining handlers left.
_ = mapping.TryRemove(key);
// If there are no handlers left at all for this type combination, drop it
if (mapping.Count == 0)
{
_ = this.typesMap.TryRemove(mapping.TypeArguments);
}
HashSet<IMapping> set = this.recipientsMap[key];
// The current mapping no longer has any handlers left for this recipient.
// Remove it and then also remove the recipient if this was the last handler.
// Again, this is the same as below, except with the assumption of the unit type.
_ = set.Remove(mapping);
if (set.Count == 0)
{
_ = this.recipientsMap.TryRemove(key);
}
}
else
{
// Get the registration list, if available
if (!TryGetMapping<TMessage, TToken>(out Mapping<TToken>? mapping))
{
return;
}
Recipient key = new(recipient);
if (!mapping.TryGetValue(key, out Dictionary2<TToken, object?>? dictionary))
{
return;
}
// Remove the target handler
if (dictionary.TryRemove(token) &&
dictionary.Count == 0)
{
// If the map is empty, it means that the current recipient has no remaining
// registered handlers for the current <TMessage, TToken> combination, regardless,
// of the specific token value (ie. the channel used to receive messages of that type).
// We can remove the map entirely from this container, and remove the link to the map itself
// to the current mapping between existing registered recipients (or entire recipients too).
_ = mapping.TryRemove(key);
// If there are no handlers left at all for this type combination, drop it
if (mapping.Count == 0)
{
_ = this.typesMap.TryRemove(mapping.TypeArguments);
}
HashSet<IMapping> set = this.recipientsMap[key];
// The current mapping no longer has any handlers left for this recipient
_ = set.Remove(mapping);
// If the current recipients has no handlers left at all, remove it
if (set.Count == 0)
{
_ = this.recipientsMap.TryRemove(key);
}
}
}
}
}
/// <inheritdoc/>
public TMessage Send<TMessage, TToken>(TMessage message, TToken token)
where TMessage : class
where TToken : IEquatable<TToken>
{
ArgumentNullException.ThrowIfNull(message);
ArgumentNullException.For<TToken>.ThrowIfNull(token);
object?[] rentedArray;
Span<object?> pairs;
int i = 0;
lock (this.recipientsMap)
{
if (typeof(TToken) == typeof(Unit))
{
// Check whether there are any registered recipients
if (!TryGetMapping<TMessage>(out Mapping? mapping))
{
goto End;
}
// Check the number of remaining handlers, see below
int totalHandlersCount = mapping.Count;
if (totalHandlersCount == 0)
{
goto End;
}
pairs = rentedArray = ArrayPool<object?>.Shared.Rent(2 * totalHandlersCount);
// Same logic as below, except here we're only traversing one handler per recipient
Dictionary2<Recipient, object?>.Enumerator mappingEnumerator = mapping.GetEnumerator();
while (mappingEnumerator.MoveNext())
{
pairs[2 * i] = mappingEnumerator.GetValue();
pairs[(2 * i) + 1] = mappingEnumerator.GetKey().Target;
i++;
}
}
else
{
// Check whether there are any registered recipients
if (!TryGetMapping<TMessage, TToken>(out Mapping<TToken>? mapping))
{
goto End;
}
// We need to make a local copy of the currently registered handlers, since users might
// try to unregister (or register) new handlers from inside one of the currently existing
// handlers. We can use memory pooling to reuse arrays, to minimize the average memory
// usage. In practice, we usually just need to pay the small overhead of copying the items.
// The current mapping contains all the currently registered recipients and handlers for
// the <TMessage, TToken> combination in use. In the worst case scenario, all recipients
// will have a registered handler with a token matching the input one, meaning that we could
// have at worst a number of pending handlers to invoke equal to the total number of recipient
// in the mapping. This relies on the fact that tokens are unique, and that there is only
// one handler associated with a given token. We can use this upper bound as the requested
// size for each array rented from the pool, which guarantees that we'll have enough space.
int totalHandlersCount = mapping.Count;
if (totalHandlersCount == 0)
{
goto End;
}
// Rent the array and also assign it to a span, which will be used to access values.
// We're doing this to avoid the array covariance checks slowdown in the loops below.
pairs = rentedArray = ArrayPool<object?>.Shared.Rent(2 * totalHandlersCount);
// Copy the handlers to the local collection.
// The array is oversized at this point, since it also includes
// handlers for different tokens. We can reuse the same variable
// to count the number of matching handlers to invoke later on.
// This will be the array slice with valid handler in the rented buffer.
Dictionary2<Recipient, Dictionary2<TToken, object?>>.Enumerator mappingEnumerator = mapping.GetEnumerator();
// Explicit enumerator usage here as we're using a custom one
// that doesn't expose the single standard Current property.
while (mappingEnumerator.MoveNext())
{
// Pick the target handler, if the token is a match for the recipient
if (mappingEnumerator.GetValue().TryGetValue(token, out object? handler))
{
// This span access should always guaranteed to be valid due to the size of the
// array being set according to the current total number of registered handlers,
// which will always be greater or equal than the ones matching the previous test.
// We're still using a checked span accesses here though to make sure an out of
// bounds write can never happen even if an error was present in the logic above.
pairs[2 * i] = handler;
pairs[(2 * i) + 1] = mappingEnumerator.GetKey().Target;
i++;
}
}
}
}
try
{
// The core broadcasting logic is the same as the weak reference messenger one
WeakReferenceMessenger.SendAll(pairs, i, message);
}
finally
{
// As before, we also need to clear it first to avoid having potentially long
// lasting memory leaks due to leftover references being stored in the pool.
Array.Clear(rentedArray, 0, 2 * i);
ArrayPool<object?>.Shared.Return(rentedArray);
}
End:
return message;
}
/// <inheritdoc/>
void IMessenger.Cleanup()
{
// The current implementation doesn't require any kind of cleanup operation, as
// all the internal data structures are already kept in sync whenever a recipient
// is added or removed. This method is implemented through an explicit interface
// implementation so that developers using this type directly will not see it in
// the API surface (as it wouldn't be useful anyway, since it's a no-op here).
}
/// <inheritdoc/>
public void Reset()
{
lock (this.recipientsMap)
{
this.recipientsMap.Clear();
this.typesMap.Clear();
}
}
/// <summary>
/// Tries to get the <see cref="Mapping"/> instance of currently
/// registered recipients for the input <typeparamref name="TMessage"/> type.
/// </summary>
/// <typeparam name="TMessage">The type of message to send.</typeparam>
/// <param name="mapping">The resulting <see cref="Mapping"/> instance, if found.</param>
/// <returns>Whether or not the required <see cref="Mapping"/> instance was found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryGetMapping<TMessage>([NotNullWhen(true)] out Mapping? mapping)
where TMessage : class
{
Type2 key = new(typeof(TMessage), typeof(Unit));
if (this.typesMap.TryGetValue(key, out IMapping? target))
{
// This method and the ones below are the only ones handling values in the types map,
// and here we are sure that the object reference we have points to an instance of the
// right type. Using an unsafe cast skips two conditional branches and is faster.
mapping = Unsafe.As<Mapping>(target);
return true;
}
mapping = null;
return false;
}
/// <summary>
/// Tries to get the <see cref="Mapping{TToken}"/> instance of currently registered recipients
/// for the combination of types <typeparamref name="TMessage"/> and <typeparamref name="TToken"/>.
/// </summary>
/// <typeparam name="TMessage">The type of message to send.</typeparam>
/// <typeparam name="TToken">The type of token to identify what channel to use to send the message.</typeparam>
/// <param name="mapping">The resulting <see cref="Mapping{TToken}"/> instance, if found.</param>
/// <returns>Whether or not the required <see cref="Mapping{TToken}"/> instance was found.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool TryGetMapping<TMessage, TToken>([NotNullWhen(true)] out Mapping<TToken>? mapping)
where TMessage : class
where TToken : IEquatable<TToken>
{
Type2 key = new(typeof(TMessage), typeof(TToken));
if (this.typesMap.TryGetValue(key, out IMapping? target))
{
mapping = Unsafe.As<Mapping<TToken>>(target);
return true;
}
mapping = null;
return false;
}
/// <summary>
/// Gets the <see cref="Mapping"/> instance of currently
/// registered recipients for the input <typeparamref name="TMessage"/> type.
/// </summary>
/// <typeparam name="TMessage">The type of message to send.</typeparam>
/// <returns>A <see cref="Mapping"/> instance with the requested type arguments.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Mapping GetOrAddMapping<TMessage>()
where TMessage : class
{
Type2 key = new(typeof(TMessage), typeof(Unit));
ref IMapping? target = ref this.typesMap.GetOrAddValueRef(key);
target ??= Mapping.Create<TMessage>();
return Unsafe.As<Mapping>(target);
}
/// <summary>
/// Gets the <see cref="Mapping{TToken}"/> instance of currently registered recipients
/// for the combination of types <typeparamref name="TMessage"/> and <typeparamref name="TToken"/>.
/// </summary>
/// <typeparam name="TMessage">The type of message to send.</typeparam>
/// <typeparam name="TToken">The type of token to identify what channel to use to send the message.</typeparam>
/// <returns>A <see cref="Mapping{TToken}"/> instance with the requested type arguments.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private Mapping<TToken> GetOrAddMapping<TMessage, TToken>()
where TMessage : class
where TToken : IEquatable<TToken>
{
Type2 key = new(typeof(TMessage), typeof(TToken));
ref IMapping? target = ref this.typesMap.GetOrAddValueRef(key);
target ??= Mapping<TToken>.Create<TMessage>();
return Unsafe.As<Mapping<TToken>>(target);
}
/// <summary>
/// A mapping type representing a link to recipients and their view of handlers per communication channel.
/// </summary>
/// <remarks>
/// This type is a specialization of <see cref="Mapping{TToken}"/> for <see cref="Unit"/> tokens.
/// </remarks>
private sealed class Mapping : Dictionary2<Recipient, object?>, IMapping
{
/// <summary>
/// Initializes a new instance of the <see cref="Mapping"/> class.
/// </summary>
/// <param name="messageType">The message type being used.</param>
private Mapping(Type messageType)
{
TypeArguments = new Type2(messageType, typeof(Unit));
}
/// <summary>
/// Creates a new instance of the <see cref="Mapping"/> class.
/// </summary>
/// <typeparam name="TMessage">The type of message to receive.</typeparam>
/// <returns>A new <see cref="Mapping"/> instance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Mapping Create<TMessage>()
where TMessage : class
{
return new(typeof(TMessage));
}
/// <inheritdoc/>
public Type2 TypeArguments { get; }
}
/// <summary>
/// A mapping type representing a link to recipients and their view of handlers per communication channel.
/// </summary>
/// <typeparam name="TToken">The type of token to use to pick the messages to receive.</typeparam>
/// <remarks>
/// This type is defined for simplicity and as a workaround for the lack of support for using type aliases
/// over open generic types in C# (using type aliases can only be used for concrete, closed types).
/// </remarks>
private sealed class Mapping<TToken> : Dictionary2<Recipient, Dictionary2<TToken, object?>>, IMapping
where TToken : IEquatable<TToken>
{
/// <summary>
/// Initializes a new instance of the <see cref="Mapping{TToken}"/> class.
/// </summary>
/// <param name="messageType">The message type being used.</param>
private Mapping(Type messageType)
{
TypeArguments = new Type2(messageType, typeof(TToken));
}
/// <summary>
/// Creates a new instance of the <see cref="Mapping{TToken}"/> class.
/// </summary>
/// <typeparam name="TMessage">The type of message to receive.</typeparam>
/// <returns>A new <see cref="Mapping{TToken}"/> instance.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Mapping<TToken> Create<TMessage>()
where TMessage : class
{
return new(typeof(TMessage));
}
/// <inheritdoc/>
public Type2 TypeArguments { get; }
}
/// <summary>
/// An interface for the <see cref="Mapping"/> and <see cref="Mapping{TToken}"/> types which allows to retrieve
/// the type arguments from a given generic instance without having any prior knowledge about those arguments.
/// </summary>
private interface IMapping : IDictionary2<Recipient>
{
/// <summary>
/// Gets the <see cref="Type2"/> instance representing the current type arguments.
/// </summary>
Type2 TypeArguments { get; }
}
/// <summary>
/// A simple type representing a recipient.
/// </summary>
/// <remarks>
/// This type is used to enable fast indexing in each mapping dictionary,
/// since it acts as an external override for the <see cref="GetHashCode"/> and
/// <see cref="Equals(object?)"/> methods for arbitrary objects, removing both
/// the virtual call and preventing instances overriding those methods in this context.
/// Using this type guarantees that all the equality operations are always only done
/// based on reference equality for each registered recipient, regardless of its type.
/// </remarks>
private readonly struct Recipient : IEquatable<Recipient>
{
/// <summary>
/// The registered recipient.
/// </summary>
public readonly object Target;
/// <summary>
/// Initializes a new instance of the <see cref="Recipient"/> struct.
/// </summary>
/// <param name="target">The target recipient instance.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Recipient(object target)
{
Target = target;
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(Recipient other)
{
return ReferenceEquals(Target, other.Target);
}
/// <inheritdoc/>
public override bool Equals(object? obj)
{
return obj is Recipient other && Equals(other);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this.Target);
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> when trying to add a duplicate handler.
/// </summary>
private static void ThrowInvalidOperationExceptionForDuplicateRegistration()
{
throw new InvalidOperationException("The target recipient has already subscribed to the target message.");
}
}
| 47.526193 | 142 | 0.5988 | [
"MIT"
] | Avid29/dotnet | CommunityToolkit.Mvvm/Messaging/StrongReferenceMessenger.cs | 40,825 | C# |
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using WebMail.Server.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace WebMail.Server.Controllers
{
public class HomeController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly IHostingEnvironment _env;
public HomeController(UserManager<ApplicationUser> userManager, IHostingEnvironment env)
{
_userManager = userManager;
_env = env;
}
public async Task<IActionResult> Index()
{
//ViewBag.MainDotJs = await GetMainDotJs();
if (Request.Query.ContainsKey("emailConfirmCode") &&
Request.Query.ContainsKey("userId"))
{
var userId = Request.Query["userId"].ToString();
var code = Request.Query["emailConfirmCode"].ToString();
code = code.Replace(" ", "+");
var applicationUser = await _userManager.FindByIdAsync(userId);
if (applicationUser != null && !applicationUser.EmailConfirmed)
{
var valid = await _userManager.ConfirmEmailAsync(applicationUser, code);
if (valid.Succeeded)
{
ViewBag.emailConfirmed = true;
}
}
}
else if (User.Identity != null && !string.IsNullOrEmpty(User.Identity.Name))
{
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var roles = await _userManager.GetRolesAsync(user);
var userResult = new { User = new { DisplayName = user.UserName, Roles = roles.ToList() } };
ViewBag.user = userResult;
}
return View();
}
public IActionResult Error()
{
ViewData["RequestId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
return View();
}
// Becasue for production this is hashed chunk so has changes on each production build
private async Task<string> GetMainDotJs()
{
var basePath = _env.WebRootPath + "//dist//";
if (_env.IsDevelopment() && !System.IO.File.Exists(basePath + "main.js"))
{
// Just a .js request to make it wait to finish webpack dev middleware finish creating bundles:
// More info here: https://github.com/aspnet/JavaScriptServices/issues/578#issuecomment-272039541
using (var client = new HttpClient())
{
var requestUri = Request.Scheme + "://" + Request.Host + "/dist/main.js";
await client.GetAsync(requestUri);
}
}
var info = new System.IO.DirectoryInfo(basePath);
var file = info.GetFiles()
.Where(f => _env.IsDevelopment() ? f.Name == "main.js" : f.Name.StartsWith("main.") && !f.Name.EndsWith("bundle.map"));
return file.FirstOrDefault().Name;
}
}
}
| 38.918605 | 135 | 0.577233 | [
"MIT"
] | Damenus/webmail | Server/Controllers/HomeController.cs | 3,349 | C# |
namespace GithubActions.Tests.Fixtures
{
public class TestSettings
{
public bool TargetLocalHost { get; set; }
public string ApiKeyHeader { get; set; }
public string ApiKeyValue { get; set; }
public string BaseApiUrlFormatString { get; set; }
}
} | 29 | 58 | 0.648276 | [
"MIT"
] | swiftbitdotco/GithubActionsWithDotNetCore | test/GithubActions.Tests/Fixtures/TestSettings.cs | 290 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
#pragma warning disable 1591
namespace Silk.NET.OpenGL
{
public enum GetTexBumpParameterATI
{
BumpRotMatrixAti = 0x8775,
BumpRotMatrixSizeAti = 0x8776,
BumpNumTexUnitsAti = 0x8777,
BumpTexUnitsAti = 0x8778,
}
}
| 20.285714 | 57 | 0.685446 | [
"MIT"
] | AzyIsCool/Silk.NET | src/OpenGL/Silk.NET.OpenGL/Enums/GetTexBumpParameterATI.gen.cs | 426 | 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("BuiltToRoam.UI.UAP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BuiltToRoam.UI.UAP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.310345 | 84 | 0.740741 | [
"Apache-2.0"
] | builttoroam/realestateinspector | BuiltToRoam.UI/BuiltToRoam.UI.UAP/Properties/AssemblyInfo.cs | 1,056 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IDeviceEnrollmentLimitConfigurationRequestBuilder.
/// </summary>
public partial interface IDeviceEnrollmentLimitConfigurationRequestBuilder : IDeviceEnrollmentConfigurationRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IDeviceEnrollmentLimitConfigurationRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IDeviceEnrollmentLimitConfigurationRequest Request(IEnumerable<Option> options);
}
}
| 37.833333 | 153 | 0.606461 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IDeviceEnrollmentLimitConfigurationRequestBuilder.cs | 1,362 | C# |
using System.Windows;
namespace UnlimitedCsvCompare
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 15.75 | 42 | 0.624339 | [
"MIT"
] | JustinMoss/CsvUtilities | UnlimitedCsvCompare/App.xaml.cs | 191 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MyUSC.MyTeams {
public partial class AddMembers {
/// <summary>
/// pnlInvite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlInvite;
/// <summary>
/// Label1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label Label1;
/// <summary>
/// lblFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFirstName;
/// <summary>
/// txtFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFirstName;
/// <summary>
/// lblLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastName;
/// <summary>
/// txtLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLastName;
/// <summary>
/// lblCity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblCity;
/// <summary>
/// txtCity control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtCity;
/// <summary>
/// lblState control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblState;
/// <summary>
/// ddlState control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlState;
/// <summary>
/// LblPostalCode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label LblPostalCode;
/// <summary>
/// txtPostalCode control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPostalCode;
/// <summary>
/// lblEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblEmail;
/// <summary>
/// txtEmail control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtEmail;
/// <summary>
/// btnFindFriends control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ImageButton btnFindFriends;
/// <summary>
/// btnCancelFind control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ImageButton btnCancelFind;
/// <summary>
/// pnlResults control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel pnlResults;
/// <summary>
/// lblResultMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResultMessage;
/// <summary>
/// btnInviteNew control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton btnInviteNew;
/// <summary>
/// tblResults control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Table tblResults;
/// <summary>
/// Master property.
/// </summary>
/// <remarks>
/// Auto-generated property.
/// </remarks>
public new MyUSC.MyTeams.OrgMaster Master {
get {
return ((MyUSC.MyTeams.OrgMaster)(base.Master));
}
}
}
}
| 34.692308 | 84 | 0.536031 | [
"Unlicense"
] | tlayson/MySC | MyUSC/MyTeams/AddMembers.aspx.designer.cs | 7,218 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.ECS.Filters
{
public interface IComponentFilter {
/// <summary>
/// Returns true if the block should be filtered out.
/// </summary>
bool FilterBlock(BlockAccessor block);
/// <summary>
/// Updates filter with new data
/// </summary>
void UpdateFilter(BlockAccessor block);
}
}
| 21.111111 | 55 | 0.705263 | [
"MIT"
] | Nominom/.NET-Core-game-engine | ECSCore/Filters/IComponentFilter.cs | 382 | C# |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Utilities
{
/// <summary>
/// Builds a string. Unlike StringBuilder this class lets you reuse it's internal buffer.
/// </summary>
internal class StringBuffer
{
private char[] _buffer;
private int _position;
private static readonly char[] _emptyBuffer = new char[0];
public int Position
{
get { return _position; }
set { _position = value; }
}
public StringBuffer()
{
_buffer = _emptyBuffer;
}
public StringBuffer(int initalSize)
{
_buffer = new char[initalSize];
}
public void Append(char value)
{
// test if the buffer array is large enough to take the value
if (_position == _buffer.Length)
{
EnsureSize(1);
}
// set value and increment poisition
_buffer[_position++] = value;
}
public void Clear()
{
_buffer = _emptyBuffer;
_position = 0;
}
private void EnsureSize(int appendLength)
{
char[] newBuffer = new char[(_position + appendLength) * 2];
Array.Copy(_buffer, newBuffer, _position);
_buffer = newBuffer;
}
public override string ToString()
{
return ToString(0, _position);
}
public string ToString(int start, int length)
{
// TODO: validation
return new string(_buffer, start, length);
}
public char[] GetInternalBuffer()
{
return _buffer;
}
}
}
#endif | 27.60396 | 92 | 0.64957 | [
"Unlicense"
] | madparker/LumarcaUnity | LumarcaUnity2/Assets/Scripts/JsonDotNet/Source/Utilities/StringBuffer.cs | 2,788 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orchard;
using Orchard.Data;
using Orchard.Security;
using TestApi.Entities;
namespace TestApi.Repository
{
public class AuthRepository : IDisposable
{
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IRepository<Client> _clientRepository;
private readonly IRepository<RefreshToken> _refreshTokenRepository;
public AuthRepository(IWorkContextAccessor workContextAccessor,
IRepository<Client> clientRepository,
IRepository<RefreshToken> refreshTokenRepository) {
_workContextAccessor = workContextAccessor;
_clientRepository = clientRepository;
_refreshTokenRepository = refreshTokenRepository;
}
public IUser FindUser(string userName, string password)
{
var membershipService = _workContextAccessor.GetContext().Resolve<IMembershipService>();
var user = membershipService.ValidateUser(userName, password);
return user;
}
public Client FindClient(string clientId) {
var client = _clientRepository.Fetch(x => x.Id == clientId).FirstOrDefault();
return client;
}
public void AddRefreshToken(RefreshToken token)
{
var existingToken = _refreshTokenRepository.Get(r => r.Subject == token.Subject && r.ClientId == token.ClientId);
if (existingToken != null)
{
RemoveRefreshToken(existingToken.Id);
}
_refreshTokenRepository.Create(token);
}
public void RemoveRefreshToken(string refreshTokenId)
{
var refreshToken = _refreshTokenRepository.Fetch(x => x.Id == refreshTokenId).FirstOrDefault();
if (refreshToken != null)
_refreshTokenRepository.Delete(refreshToken);
}
public RefreshToken FindRefreshToken(string refreshTokenId)
{
var refreshToken = _refreshTokenRepository.Fetch(x => x.Id == refreshTokenId).FirstOrDefault();
return refreshToken;
}
public List<RefreshToken> GetAllRefreshTokens()
{
return _refreshTokenRepository.Fetch(x => true).ToList();
}
protected virtual void Dispose(bool disposing) {
if (disposing) { }
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
} | 32.481013 | 125 | 0.641855 | [
"BSD-3-Clause"
] | Fogolan/OrchardForWork | src/Orchard.Web/Modules/TestApi/Repository/AuthRepository.cs | 2,568 | C# |
namespace Shoc.Cli.Model
{
/// <summary>
/// The shoc profile definition
/// </summary>
public class ShocProfile
{
/// <summary>
/// The profile name
/// </summary>
public string Name { get; set; }
/// <summary>
/// The api root
/// </summary>
public string Api { get; set; }
/// <summary>
/// The authority root
/// </summary>
public string Authority { get; set; }
}
} | 21.391304 | 45 | 0.473577 | [
"Apache-2.0"
] | imastio/shoc | Shoc.Cli/Model/ShocProfile.cs | 494 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the pinpoint-email-2018-07-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.PinpointEmail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.PinpointEmail.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for GetDomainStatisticsReport operation
/// </summary>
public class GetDomainStatisticsReportResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
GetDomainStatisticsReportResponse response = new GetDomainStatisticsReportResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("DailyVolumes", targetDepth))
{
var unmarshaller = new ListUnmarshaller<DailyVolume, DailyVolumeUnmarshaller>(DailyVolumeUnmarshaller.Instance);
response.DailyVolumes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("OverallVolume", targetDepth))
{
var unmarshaller = OverallVolumeUnmarshaller.Instance;
response.OverallVolume = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException"))
{
return BadRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException"))
{
return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("TooManyRequestsException"))
{
return TooManyRequestsExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonPinpointEmailException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static GetDomainStatisticsReportResponseUnmarshaller _instance = new GetDomainStatisticsReportResponseUnmarshaller();
internal static GetDomainStatisticsReportResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetDomainStatisticsReportResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.104839 | 196 | 0.647094 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/PinpointEmail/Generated/Model/Internal/MarshallTransformations/GetDomainStatisticsReportResponseUnmarshaller.cs | 4,973 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using GraphQL.Builders;
using GraphQL.Types;
using Microsoft.EntityFrameworkCore;
namespace GraphQL.EntityFramework
{
partial class EfGraphQLService<TDbContext>
where TDbContext : DbContext
{
public void AddQueryConnectionField<TReturn>(
IComplexGraphType graph,
string name,
Func<ResolveEfFieldContext<TDbContext, object>, IQueryable<TReturn>>? resolve = null,
Type? itemGraphType = null,
IEnumerable<QueryArgument>? arguments = null,
int pageSize = 10,
string? description = null)
where TReturn : class
{
Guard.AgainstNull(nameof(graph), graph);
var connection = BuildQueryConnectionField(name, resolve, pageSize, itemGraphType, description);
var field = graph.AddField(connection.FieldType);
field.AddWhereArgument(arguments);
}
public void AddQueryConnectionField<TSource, TReturn>(
IComplexGraphType graph,
string name,
Func<ResolveEfFieldContext<TDbContext, TSource>, IQueryable<TReturn>>? resolve = null,
Type? itemGraphType = null,
IEnumerable<QueryArgument>? arguments = null,
int pageSize = 10,
string? description = null)
where TReturn : class
{
Guard.AgainstNull(nameof(graph), graph);
var connection = BuildQueryConnectionField(name, resolve, pageSize, itemGraphType, description);
var field = graph.AddField(connection.FieldType);
field.AddWhereArgument(arguments);
}
ConnectionBuilder<TSource> BuildQueryConnectionField<TSource, TReturn>(
string name,
Func<ResolveEfFieldContext<TDbContext, TSource>, IQueryable<TReturn>>? resolve,
int pageSize,
Type? itemGraphType,
string? description)
where TReturn : class
{
Guard.AgainstNullWhiteSpace(nameof(name), name);
Guard.AgainstNegative(nameof(pageSize), pageSize);
itemGraphType ??= GraphTypeFinder.FindGraphType<TReturn>();
var fieldType = GetFieldType<TSource>(name, itemGraphType);
var builder = ConnectionBuilder<TSource>.Create<FakeGraph>(name);
if (description != null)
{
builder.Description(description);
}
builder.PageSize(pageSize).Bidirectional();
SetField(builder, fieldType);
if (resolve != null)
{
builder.Resolve(
context =>
{
var efFieldContext = BuildContext(context);
var query = resolve(efFieldContext);
query = includeAppender.AddIncludes(query, context);
var names = GetKeyNames<TReturn>();
query = query.ApplyGraphQlArguments(context, names);
return query
.ApplyConnectionContext(
context.First,
context.After,
context.Last,
context.Before,
context,
context.CancellationToken,
efFieldContext.Filters);
});
}
return builder;
}
}
} | 36.744898 | 108 | 0.551791 | [
"MIT"
] | GroggyPirate/GraphQL.EntityFramework | src/GraphQL.EntityFramework/GraphApi/EfGraphQLService_QueryableConnection.cs | 3,603 | 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("pozitivan_i_negativan_broj")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("pozitivan_i_negativan_broj")]
[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("2094e644-25d7-4277-9205-b2fa568277b2")]
// 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.378378 | 84 | 0.752817 | [
"MIT"
] | Runta90/AlgebraCSharp2019-1 | ConsoleApp1/pozitivan_i_negativan_broj/Properties/AssemblyInfo.cs | 1,423 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Ads.GoogleAds.V7.Services.Snippets
{
using Google.Ads.GoogleAds.V7.Resources;
using Google.Ads.GoogleAds.V7.Services;
public sealed partial class GeneratedKeywordPlanCampaignKeywordServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetKeywordPlanCampaignKeyword</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetKeywordPlanCampaignKeyword()
{
// Create client
KeywordPlanCampaignKeywordServiceClient keywordPlanCampaignKeywordServiceClient = KeywordPlanCampaignKeywordServiceClient.Create();
// Initialize request argument(s)
string resourceName = "customers/[CUSTOMER_ID]/keywordPlanCampaignKeywords/[KEYWORD_PLAN_CAMPAIGN_KEYWORD_ID]";
// Make the request
KeywordPlanCampaignKeyword response = keywordPlanCampaignKeywordServiceClient.GetKeywordPlanCampaignKeyword(resourceName);
}
}
}
| 43.475 | 143 | 0.730305 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/ads/googleads/v7/googleads-csharp/Google.Ads.GoogleAds.V7.Services.StandaloneSnippets/KeywordPlanCampaignKeywordServiceClient.GetKeywordPlanCampaignKeywordSnippet.g.cs | 1,739 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Nez;
using Game.Entities;
using Game.Components;
using Microsoft.Xna.Framework;
using Nez.Textures;
using Microsoft.Xna.Framework.Graphics;
using Nez.Sprites;
namespace Game.Scenes
{
/// <summary>
/// Escena para la intro del juego
/// Descartada, no es necesario actualmente.
/// </summary>
class IntroGame : Scene
{
public override void initialize()
{
}
}
}
| 20.142857 | 49 | 0.654255 | [
"MIT"
] | JonathanNaranjo/CorredorDeLaberintos | Source/Game/Scenes/IntroGame.cs | 566 | C# |
using Api.Domain.Dtos.User;
using Api.Domain.Entities;
using Api.Domain.Interfaces;
using Api.Domain.Interfaces.Repositories;
using Api.Domain.Models;
using Api.Service.Notifications;
using Api.Service.Services;
using Api.Service.Test.Helpers;
using AutoMapper;
using Bogus;
using Bogus.Extensions.Brazil;
using ExpectedObjects;
using Microsoft.Extensions.Logging;
using Moq;
using System;
using Xunit;
namespace Api.Service.Test.IUserServiceTests
{
public class UserServiceTest
{
private readonly UserService _service;
// MOCKS
private readonly Mock<ILogger<UserService>> _logger = new();
private readonly Mock<INotifier> _notifier = new();
private readonly Mock<IMapper> _mapper = new();
private readonly Mock<IRepository<UserEntity>> _userEntityRepository = new();
private readonly Mock<IUserRepository> _userRepository = new();
// FAKER
private static readonly Guid FakerUserId = Guid.NewGuid();
private static readonly DateTime FakerCreatedAt = DateTime.UtcNow;
private static readonly Faker Faker = new("pt_BR");
private static readonly string FakerName = Faker.Name.FullName();
private static readonly string FakerEmail = Faker.Internet.Email();
private static readonly string FakerDocument = Faker.Person.Cpf();
public UserServiceTest()
{
_service = new UserService(_logger.Object, _notifier.Object, _mapper.Object, _userEntityRepository.Object, _userRepository.Object);
}
#region POST
[Theory]
[MemberData(nameof(PostSchemas))]
[Trait(nameof(UserServiceTest), "POST")]
public async void Post(PostModel testModel)
{
SetupMocks(testModel);
var result = new UserDtoCreateResult();
var exception = await Record.ExceptionAsync(async () =>
{
result = await _service.Post(testModel.Request);
});
TestLogHelpers.VerifyLogger(_logger, LogLevel.Information, null, Times.Exactly(testModel.LoggedInformationTimes));
TestLogHelpers.VerifyLogger(_logger, LogLevel.Error, null, Times.Exactly(testModel.LoggedErrorTimes));
if (exception != null)
{
Assert.Equal(testModel.ExceptionType, exception.GetType());
return;
}
testModel.ExpectedResult.ToExpectedObject().ShouldEqual(result);
}
public static TheoryData<PostModel> PostSchemas = new()
{
new PostModel
{
Description = "Failed - invalid request [NULL]",
Request = null,
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExceptionType = typeof(ArgumentNullException)
},
new PostModel
{
Description = "Failed - invalid request [INVALID NAME]",
Request = GetUserDtoCreate_Invalid_Name(string.Empty),
LoggedInformationTimes = 0,
LoggedErrorTimes = 1,
ExpectedResult = null,
},
new PostModel
{
Description = "Failed - email already registered [EMAIL]",
Request = GetUserDtoCreate(),
GetByEmailResponse = GetUserEntity_EmailAlreadyRegistered(),
LoggedInformationTimes = 0,
LoggedErrorTimes = 1,
ExpectedResult = null
},
new PostModel
{
Description = "Success - record saved successfully",
Request = GetUserDtoCreate(),
GetByEmailResponse = null,
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = GetUserDtoCreateResult(),
}
};
public class PostModel
{
public string Description { get; set; }
public UserDtoCreate Request { get; set; }
public UserEntity GetByEmailResponse { get; set; }
public UserDtoCreateResult ExpectedResult { get; set; }
public int LoggedInformationTimes { get; set; }
public int LoggedErrorTimes { get; set; }
public Type ExceptionType { get; set; }
}
private void SetupMocks(PostModel testModel)
{
var userModel = new UserModel
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument,
Status = true
};
var userEntity = new UserEntity(FakerName, FakerEmail, true)
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Document = FakerDocument,
Status = true
};
_userRepository
.Setup(c => c.GetByEmail(FakerEmail))
.ReturnsAsync(testModel.GetByEmailResponse);
_mapper
.Setup(c => c.Map<UserModel>(testModel.Request))
.Returns(userModel);
_mapper
.Setup(c => c.Map<UserEntity>(userModel))
.Returns(userEntity);
_userEntityRepository
.Setup(c => c.InsertAsync(userEntity))
.ReturnsAsync(userEntity);
_mapper
.Setup(c => c.Map<UserDtoCreateResult>(userEntity))
.Returns(testModel.ExpectedResult);
}
#endregion
#region PUT
[Theory]
[MemberData(nameof(PutSchemas))]
[Trait(nameof(UserServiceTest), "PUT")]
public async void Put(PutModel testModel)
{
SetupMocks(testModel);
var result = new UserDtoUpdateResult();
var exception = await Record.ExceptionAsync(async () =>
{
result = await _service.Put(testModel.Request);
});
TestLogHelpers.VerifyLogger(_logger, LogLevel.Information, null, Times.Exactly(testModel.LoggedInformationTimes));
TestLogHelpers.VerifyLogger(_logger, LogLevel.Error, null, Times.Exactly(testModel.LoggedErrorTimes));
if (exception != null)
{
Assert.Equal(testModel.ExceptionType, exception.GetType());
return;
}
testModel.ExpectedResult.ToExpectedObject().ShouldEqual(result);
}
public static TheoryData<PutModel> PutSchemas = new()
{
new PutModel
{
Name = "Failed - invalid name",
Request = GetUserDtoUpdate(string.Empty),
SelectAsyncResponse = null,
LoggedInformationTimes = 0,
LoggedErrorTimes = 1,
ExpectedResult = null
},
new PutModel
{
Name = "Failed - record not found",
Request = GetUserDtoUpdate(FakerName),
SelectAsyncResponse = null,
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = null
},
new PutModel
{
Name = "Success - record updated successfully",
Request = GetUserDtoUpdate(FakerName),
SelectAsyncResponse = GetUserEntity(),
LoggedInformationTimes = 1,
LoggedErrorTimes = 0,
ExpectedResult = GetUserDtoUpdateResult()
}
};
public class PutModel
{
public string Name { get; set; }
public UserDtoUpdate Request { get; set; }
public int LoggedInformationTimes { get; set; }
public int LoggedErrorTimes { get; set; }
public UserEntity SelectAsyncResponse { get; set; }
public UserDtoUpdateResult ExpectedResult { get; set; }
public Type ExceptionType { get; set; }
}
private void SetupMocks(PutModel testModel)
{
var userModel = new UserModel
{
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument
};
var userEntity = new UserEntity(FakerName, FakerEmail, true)
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Document = FakerDocument,
Status = true
};
_mapper
.Setup(c => c.Map<UserModel>(testModel.Request))
.Returns(userModel);
_mapper
.Setup(c => c.Map<UserEntity>(userModel))
.Returns(userEntity);
_userEntityRepository
.Setup(c => c.SelectAsync(userEntity.Id))
.ReturnsAsync(testModel.SelectAsyncResponse);
_userEntityRepository
.Setup(c => c.UpdateAsync(userEntity))
.ReturnsAsync(userEntity);
_mapper
.Setup(c => c.Map<UserDtoUpdateResult>(userEntity))
.Returns(testModel.ExpectedResult);
}
#endregion
#region DELETE
[Theory]
[MemberData(nameof(DeleteSchema))]
[Trait(nameof(UserServiceTest), "DELETE")]
public async void Delete(DeleteModel testModel)
{
SetupMocks(testModel);
var result = false;
var exception = await Record.ExceptionAsync(async () =>
{
result = await _service.Delete(testModel.Request);
});
TestLogHelpers.VerifyLogger(_logger, LogLevel.Information, null, Times.Exactly(testModel.LoggedInformationTimes));
TestLogHelpers.VerifyLogger(_logger, LogLevel.Error, null, Times.Exactly(testModel.LoggedErrorTimes));
if (exception != null)
{
Assert.Equal(testModel.ExceptionType, exception.GetType());
return;
}
testModel.ExpectedResult.ToExpectedObject().ShouldEqual(result);
}
public static TheoryData<DeleteModel> DeleteSchema = new()
{
new DeleteModel
{
Description = "Failed - invalid UserId",
Request = Guid.Empty,
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = false
},
new DeleteModel
{
Description = "Failed - user not found",
Request = FakerUserId,
ExistAsyncResult = false,
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = false
},
new DeleteModel
{
Description = "Success - record deleted successfully",
Request = FakerUserId,
ExistAsyncResult = true,
LoggedInformationTimes = 1,
LoggedErrorTimes = 0,
ExpectedResult = true
},
};
public class DeleteModel
{
public string Description { get; set; }
public Guid Request { get; set; }
public bool ExpectedResult { get; set; }
public bool ExistAsyncResult { get; set; }
public int LoggedInformationTimes { get; set; }
public int LoggedErrorTimes { get; set; }
public Type ExceptionType { get; set; }
}
private void SetupMocks(DeleteModel testModel)
{
_userEntityRepository
.Setup(c => c.ExistAsync(testModel.Request))
.ReturnsAsync(testModel.ExistAsyncResult);
_userEntityRepository
.Setup(c => c.DeleteAsync(testModel.Request))
.ReturnsAsync(true);
}
#endregion
#region PATCH
[Theory]
[MemberData(nameof(PatchSchema))]
[Trait(nameof(UserServiceTest), "PATCH")]
public async void Patch(PatchModel testModel)
{
SetupMocks(testModel);
var result = new UserDto();
var exception = await Record.ExceptionAsync(async () =>
{
result = await _service.ChangeStatus(testModel.Request);
});
TestLogHelpers.VerifyLogger(_logger, LogLevel.Information, null, Times.Exactly(testModel.LoggedInformationTimes));
TestLogHelpers.VerifyLogger(_logger, LogLevel.Error, null, Times.Exactly(testModel.LoggedErrorTimes));
if (exception != null)
{
Assert.Equal(testModel.ExceptionType, exception.GetType());
return;
}
if (result == null) return;
testModel.ExpectedResult
.ToExpectedObject(x => x.Ignore(i => i.CreatedAt))
.ShouldEqual(result);
}
public static TheoryData<PatchModel> PatchSchema = new()
{
new PatchModel
{
Description = "Failed - invalid UserId",
Request = Guid.Empty,
SelectAsyncResponse = null,
LoggedInformationTimes = 0,
LoggedErrorTimes = 1,
ExpectedResult = null
},
new PatchModel
{
Description = "Failed - invalid UserId",
Request = FakerUserId,
SelectAsyncResponse = null,
LoggedInformationTimes = 1,
LoggedErrorTimes = 0,
ExpectedResult = null
},
new PatchModel
{
Description = "Success - status updated successfully",
Request = FakerUserId,
SelectAsyncResponse = GetUserEntity(),
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = GetUserDto(false)
},
new PatchModel
{
Description = "Success - status updated successfully",
Request = FakerUserId,
SelectAsyncResponse = GetUserEntity(false),
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = GetUserDto()
}
};
public class PatchModel
{
public string Description { get; set; }
public Guid Request { get; set; }
public UserDto ExpectedResult { get; set; }
public UserEntity SelectAsyncResponse { get; set; }
public int LoggedInformationTimes { get; set; }
public int LoggedErrorTimes { get; set; }
public Type ExceptionType { get; set; }
}
private void SetupMocks(PatchModel testModel)
{
_userEntityRepository
.Setup(c => c.SelectAsync(testModel.Request))
.ReturnsAsync(testModel.SelectAsyncResponse);
UserModel userModel;
if (testModel.SelectAsyncResponse != null)
{
var status = !testModel.SelectAsyncResponse.Status;
userModel = new UserModel
{
Id = testModel.SelectAsyncResponse.Id,
CreatedAt = testModel.SelectAsyncResponse.CreatedAt,
Name = testModel.SelectAsyncResponse.Name,
Email = testModel.SelectAsyncResponse.Email,
Document = testModel.SelectAsyncResponse.Document,
Status = status
};
}
else
{
userModel = new UserModel
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument,
Status = true
};
}
var userEntity = new UserEntity(userModel.Name, userModel.Email, userModel.Status)
{
Id = userModel.Id,
CreatedAt = userModel.CreatedAt,
UpdatedAt = userModel.UpdatedAt,
Document = userModel.Document
};
_mapper
.Setup(c => c.Map<UserModel>(testModel.SelectAsyncResponse))
.Returns(userModel);
_mapper
.Setup(c => c.Map<UserEntity>(userModel))
.Returns(userEntity);
_userEntityRepository
.Setup(c => c.UpdateAsync(userEntity))
.ReturnsAsync(userEntity);
var userDto = new UserDto
{
Id = userEntity.Id,
CreatedAt = userEntity.CreatedAt,
Name = userEntity.Name,
Email = userEntity.Email,
Document = userEntity.Document,
Status = userEntity.Status
};
_mapper
.Setup(c => c.Map<UserDto>(userEntity))
.Returns(userDto);
}
#endregion
#region GET
[Theory]
[MemberData(nameof(GetSchema))]
[Trait(nameof(UserServiceTest), "GET")]
public async void Get(GetModel testModel)
{
SetupMocks(testModel);
var result = new UserDto();
var exception = await Record.ExceptionAsync(async () =>
{
result = await _service.Get(testModel.Request);
});
TestLogHelpers.VerifyLogger(_logger, LogLevel.Information, null, Times.Exactly(testModel.LoggedInformationTimes));
TestLogHelpers.VerifyLogger(_logger, LogLevel.Error, null, Times.Exactly(testModel.LoggedErrorTimes));
if (exception != null)
{
Assert.Equal(testModel.ExceptionType, exception.GetType());
}
testModel.ExpectedResult.ToExpectedObject().ShouldEqual(result);
}
public static TheoryData<GetModel> GetSchema = new()
{
new GetModel
{
Description = "Failed - invalid userId",
Request = Guid.Empty,
LoggedInformationTimes = 0,
LoggedErrorTimes = 1,
ExpectedResult = null
},
new GetModel
{
Description = "Failed - user not found",
Request = FakerUserId,
SelectAsyncResponse = null,
LoggedInformationTimes = 1,
LoggedErrorTimes = 0,
ExpectedResult = null
},
new GetModel
{
Description = "success - get user",
Request = FakerUserId,
SelectAsyncResponse = GetUserEntity(),
LoggedInformationTimes = 0,
LoggedErrorTimes = 0,
ExpectedResult = GetUserDto()
}
};
public class GetModel
{
public string Description { get; set; }
public Guid Request { get; set; }
public UserEntity SelectAsyncResponse { get; set; }
public UserDto ExpectedResult { get; set; }
public int LoggedInformationTimes { get; set; }
public int LoggedErrorTimes { get; set; }
public Type ExceptionType { get; set; }
}
private void SetupMocks(GetModel testModel)
{
_userEntityRepository
.Setup(c => c.SelectAsync(testModel.Request))
.ReturnsAsync(testModel.SelectAsyncResponse);
_mapper
.Setup(c => c.Map<UserDto>(testModel.SelectAsyncResponse))
.Returns(testModel.ExpectedResult);
}
#endregion
// PRIVATES METHODS =============
private static UserDto GetUserDto(bool status = true)
{
return new()
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument.Replace(".", "").Replace("-", ""),
Status = status
};
}
private static UserDtoCreate GetUserDtoCreate()
{
return new()
{
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument,
};
}
private static UserDtoCreate GetUserDtoCreate_Invalid_Name(string name)
{
return new()
{
Name = name,
Email = FakerEmail,
Document = FakerDocument
};
}
private static UserDtoCreateResult GetUserDtoCreateResult()
{
return new()
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument,
Status = true
};
}
private static UserDtoUpdate GetUserDtoUpdate(string name)
{
return new()
{
Id = FakerUserId,
Name = name,
Email = FakerEmail,
Document = FakerDocument,
Status = true
};
}
private static UserDtoUpdateResult GetUserDtoUpdateResult()
{
return new()
{
Id = FakerUserId,
Name = FakerName,
Email = FakerEmail,
Document = FakerDocument,
UpdatedAt = DateTime.UtcNow,
Status = true
};
}
private static UserEntity GetUserEntity(bool status = true)
{
return new(FakerName, FakerEmail, status)
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Document = FakerDocument.Replace(".", "").Replace("-", "")
};
}
private static UserEntity GetUserEntity_EmailAlreadyRegistered()
{
return new(FakerName, FakerEmail, true)
{
Id = FakerUserId,
CreatedAt = FakerCreatedAt,
Document = FakerDocument,
Status = true
};
}
}
} | 33.004342 | 143 | 0.520609 | [
"MIT"
] | fabioborges-ti/api-netcore5 | test/Api.Service.Test/IUserServiceTests/UserServiceTest.cs | 22,806 | C# |
// Copyright 2004-2010 Castle Project - http://www.castleproject.org/
//
// 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 Castle.DynamicProxy.Tests.GenClasses
{
using System;
public class MethodWithArgumentBeingArrayOfGenericTypeOfT
{
public virtual T Method<T>( Action<T>[] actions) where T : class
{
return default(T);
}
}
} | 32.851852 | 76 | 0.718151 | [
"Apache-2.0"
] | Convey-Compliance/Castle.Core-READONLY | src/Castle.Core.Tests/GenClasses/MethodWithArgumentBeingArrayOfGenericTypeOfT.cs | 887 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Media.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Base class for defining an input. Use sub classes of this class to
/// specify tracks selections and related metadata.
/// </summary>
public partial class InputDefinition
{
/// <summary>
/// Initializes a new instance of the InputDefinition class.
/// </summary>
public InputDefinition()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the InputDefinition class.
/// </summary>
/// <param name="includedTracks">The list of TrackDescriptors which
/// define the metadata and selection of tracks in the input.</param>
public InputDefinition(IList<TrackDescriptor> includedTracks = default(IList<TrackDescriptor>))
{
IncludedTracks = includedTracks;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the list of TrackDescriptors which define the metadata
/// and selection of tracks in the input.
/// </summary>
[JsonProperty(PropertyName = "includedTracks")]
public IList<TrackDescriptor> IncludedTracks { get; set; }
}
}
| 32.912281 | 103 | 0.640192 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/mediaservices/Microsoft.Azure.Management.Media/src/Generated/Models/InputDefinition.cs | 1,876 | C# |
namespace Avanade.Challenge.Project.CrossCutting
{
public class Class1
{
}
}
| 12.857143 | 49 | 0.677778 | [
"MIT"
] | josenildolins/Avanade-Desafio-API | src/Avanade.Challenge.Project.CrossCutting/Class1.cs | 92 | C# |
// ReSharper disable All
using System;
using System.Configuration;
using System.Diagnostics;
using System.Net.Http;
using System.Web.Http;
using System.Runtime.Caching;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Hosting;
using System.Web.Http.Routing;
using Xunit;
namespace MixERP.Net.Api.Core.Tests
{
public class PartyUserControlViewRouteTests
{
[Theory]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/count", "GET", typeof(PartyUserControlViewController), "Count")]
[InlineData("/api/core/party-user-control-view/count", "GET", typeof(PartyUserControlViewController), "Count")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/all", "GET", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/core/party-user-control-view/all", "GET", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/export", "GET", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/core/party-user-control-view/export", "GET", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view", "GET", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/core/party-user-control-view", "GET", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/page/1", "GET", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/core/party-user-control-view/page/1", "GET", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/count-filtered/{filterName}", "GET", typeof(PartyUserControlViewController), "CountFiltered")]
[InlineData("/api/core/party-user-control-view/count-filtered/{filterName}", "GET", typeof(PartyUserControlViewController), "CountFiltered")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/get-filtered/{pageNumber}/{filterName}", "GET", typeof(PartyUserControlViewController), "GetFiltered")]
[InlineData("/api/core/party-user-control-view/get-filtered/{pageNumber}/{filterName}", "GET", typeof(PartyUserControlViewController), "GetFiltered")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/display-fields", "GET", typeof(PartyUserControlViewController), "GetDisplayFields")]
[InlineData("/api/core/party-user-control-view/display-fields", "GET", typeof(PartyUserControlViewController), "GetDisplayFields")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/count", "HEAD", typeof(PartyUserControlViewController), "Count")]
[InlineData("/api/core/party-user-control-view/count", "HEAD", typeof(PartyUserControlViewController), "Count")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/all", "HEAD", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/core/party-user-control-view/all", "HEAD", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/export", "HEAD", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/core/party-user-control-view/export", "HEAD", typeof(PartyUserControlViewController), "Get")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view", "HEAD", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/core/party-user-control-view", "HEAD", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/page/1", "HEAD", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/core/party-user-control-view/page/1", "HEAD", typeof(PartyUserControlViewController), "GetPaginatedResult")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/count-filtered/{filterName}", "HEAD", typeof(PartyUserControlViewController), "CountFiltered")]
[InlineData("/api/core/party-user-control-view/count-filtered/{filterName}", "HEAD", typeof(PartyUserControlViewController), "CountFiltered")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(PartyUserControlViewController), "GetFiltered")]
[InlineData("/api/core/party-user-control-view/get-filtered/{pageNumber}/{filterName}", "HEAD", typeof(PartyUserControlViewController), "GetFiltered")]
[InlineData("/api/{apiVersionNumber}/core/party-user-control-view/display-fields", "HEAD", typeof(PartyUserControlViewController), "GetDisplayFields")]
[InlineData("/api/core/party-user-control-view/display-fields", "HEAD", typeof(PartyUserControlViewController), "GetDisplayFields")]
[Conditional("Debug")]
public void TestRoute(string url, string verb, Type type, string actionName)
{
//Arrange
url = url.Replace("{apiVersionNumber}", this.ApiVersionNumber);
url = Host + url;
//Act
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);
IHttpControllerSelector controller = this.GetControllerSelector();
IHttpActionSelector action = this.GetActionSelector();
IHttpRouteData route = this.Config.Routes.GetRouteData(request);
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
request.Properties[HttpPropertyKeys.HttpConfigurationKey] = this.Config;
HttpControllerDescriptor controllerDescriptor = controller.SelectController(request);
HttpControllerContext context = new HttpControllerContext(this.Config, route, request)
{
ControllerDescriptor = controllerDescriptor
};
var actionDescriptor = action.SelectAction(context);
//Assert
Assert.NotNull(controllerDescriptor);
Assert.NotNull(actionDescriptor);
Assert.Equal(type, controllerDescriptor.ControllerType);
Assert.Equal(actionName, actionDescriptor.ActionName);
}
#region Fixture
private readonly HttpConfiguration Config;
private readonly string Host;
private readonly string ApiVersionNumber;
public PartyUserControlViewRouteTests()
{
this.Host = ConfigurationManager.AppSettings["HostPrefix"];
this.ApiVersionNumber = ConfigurationManager.AppSettings["ApiVersionNumber"];
this.Config = GetConfig();
}
private HttpConfiguration GetConfig()
{
if (MemoryCache.Default["Config"] == null)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("VersionedApi", "api/" + this.ApiVersionNumber + "/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Routes.MapHttpRoute("DefaultApi", "api/{schema}/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.EnsureInitialized();
MemoryCache.Default["Config"] = config;
return config;
}
return MemoryCache.Default["Config"] as HttpConfiguration;
}
private IHttpControllerSelector GetControllerSelector()
{
if (MemoryCache.Default["ControllerSelector"] == null)
{
IHttpControllerSelector selector = this.Config.Services.GetHttpControllerSelector();
return selector;
}
return MemoryCache.Default["ControllerSelector"] as IHttpControllerSelector;
}
private IHttpActionSelector GetActionSelector()
{
if (MemoryCache.Default["ActionSelector"] == null)
{
IHttpActionSelector selector = this.Config.Services.GetActionSelector();
return selector;
}
return MemoryCache.Default["ActionSelector"] as IHttpActionSelector;
}
#endregion
}
} | 61.233577 | 178 | 0.693408 | [
"MPL-2.0"
] | asine/mixerp | src/Libraries/Web API/Core/Tests/PartyUserControlViewRouteTests.cs | 8,389 | C# |
namespace KeyVault.Acmebot.Options
{
public class GandiOptions
{
public string ApiKey { get; set; }
}
}
| 15.625 | 42 | 0.624 | [
"Apache-2.0"
] | CMeeg/keyvault-acmebot | KeyVault.Acmebot/Options/GandiOptions.cs | 127 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해
// 제어됩니다. 어셈블리와 관련된 정보를 수정하려면
// 이러한 특성 값을 변경하세요.
[assembly: AssemblyTitle("CefSharpWpfDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CefSharpWpfDemo")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하세요.
[assembly: ComVisible(false)]
//지역화 가능 애플리케이션 빌드를 시작하려면 다음을 설정하세요.
//.csproj 파일에서 <PropertyGroup> 내에 <UICulture>CultureYouAreCodingWith</UICulture>를
//설정하십시오. 예를 들어 소스 파일에서 영어(미국)를
//사용하는 경우 <UICulture>를 en-US로 설정합니다. 그런 다음 아래
//NeutralResourceLanguage 특성의 주석 처리를 제거합니다. 아래 줄의 "en-US"를 업데이트하여
//프로젝트 파일의 UICulture 설정과 일치시킵니다.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //테마별 리소스 사전의 위치
//(페이지 또는 응용 프로그램 리소스 사진에
// 리소스가 없는 경우에 사용됨)
ResourceDictionaryLocation.SourceAssembly //제네릭 리소스 사전의 위치
//(페이지 또는 응용 프로그램 리소스 사진에
// 리소스가 없는 경우에 사용됨)
)]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를
// 기본값으로 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 29.678571 | 91 | 0.700963 | [
"MIT"
] | devncore/stackoverflow-sample | src/answers/cefsharp-wpf-demo/CefSharpWpfDemo/CefSharpWpfDemo/Properties/AssemblyInfo.cs | 2,437 | C# |
// Copyright (c) Amer Koleci and contributors.
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
using SharpGen.Runtime;
namespace Vortice.WIC
{
public partial class IWICImagingFactory2
{
public IWICImagingFactory2()
{
ComUtilities.CreateComInstance(
WICImagingFactoryClsid,
ComContext.InprocServer,
typeof(IWICImagingFactory2).GUID,
this);
}
}
}
| 25.6 | 100 | 0.628906 | [
"MIT"
] | DanielElam/Vortice.Windows | src/Vortice.Direct2D1/WIC/IWICImagingFactory2.cs | 512 | 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("AngularJS_SignalR")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("AngularJS_SignalR")]
[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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9a53b654-3122-45fc-9cbd-1ddb53f8e26f")]
// 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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.333333 | 84 | 0.756522 | [
"Apache-2.0"
] | softwarejc/angularjs-signalr | AngularJS-SignalR/AngularJS-SignalR/Properties/AssemblyInfo.cs | 1,383 | C# |
namespace XmlExplorerVMLib.ViewModels.XML
{
using XmlExplorerVMLib.Models;
using XmlExplorerVMLib.Models.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using XmlExplorerLib.interfaces;
/// <summary>
/// Implements a treeview model that represents an Xml tree for binding to a WPF TreeView.
/// </summary>
internal class XPathNavigatorTreeViewModel : Base.BaseViewModel
{
#region fields
private DateTime LoadingStarted;
private bool _IsLoading = false;
private object _Document;
private readonly ObservableCollection<IXPathNavigator> _XPathRoot;
#endregion fields
#region constructors
/// <summary>
/// Class constructor
/// </summary>
public XPathNavigatorTreeViewModel()
{
Errors = new ObservableCollection<Error>();
_XPathRoot = new ObservableCollection<IXPathNavigator>();
}
#endregion constructors
#region properties
public XmlNamespaceManager XmlNamespaceManager { get; private set; }
public ObservableCollection<NamespaceDefinition> NamespaceDefinitions { get; private set; }
public int DefaultNamespaceCount { get; private set; }
public ObservableCollection<Error> Errors { get; private set; }
/// <summary>
/// Gets whether the document, if any, specifies schema information and can, therefore, be validated.
/// </summary>
public bool CanValidate { get; private set; }
/// <summary>
/// Gets the model of the Xml document tree nodes.
/// </summary>
public object Document
{
get
{
return _Document;
}
private set
{
if (_Document != value)
{
_Document = value;
this.IsLoading = false;
this.LoadTime = DateTime.Now - this.LoadingStarted;
NotifyPropertyChanged(() => Document);
}
}
}
public IEnumerable<IXPathNavigator> XPathRoot
{
get
{
return _XPathRoot;
}
}
public TimeSpan LoadTime { get; set; }
public bool IsLoading
{
get { return _IsLoading; }
set
{
if (_IsLoading != value)
{
_IsLoading = value;
base.NotifyPropertyChanged(() => IsLoading);
}
}
}
public string FileName { get; private set; }
#endregion properties
#region methods
public void FileOpen(
string filePathName,
EventHandler OnFinished,
EventHandler<EventArgs<Exception>> OnException)
{
this.FileName = filePathName;
BeginOpen(new FileInfo(filePathName), OnFinished, OnException );
}
public void BeginOpen(
FileInfo fileInfo,
EventHandler OnFinished,
EventHandler<EventArgs<Exception>> OnException)
{
ClearErrorCollection();
this.LoadingStarted = DateTime.Now;
this.IsLoading = true;
Application.Current.Dispatcher.Invoke((Action)delegate
{
_XPathRoot.Clear();
});
ThreadStart start = delegate ()
{
XPathNavigator navigator = null;
try
{
navigator = OpenXPathNavigator(fileInfo);
this.LoadNamespaceDefinitions(navigator);
this.Validate(navigator);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
this.AddError(ex.Message);
if (OnException != null)
OnException(this, new EventArgs<Exception>(ex));
}
finally
{
Application.Current.Dispatcher.Invoke(
new Action<XPathNavigator>(SetDocument),
DispatcherPriority.Normal, navigator);
this.ConvertDocument(Document, _XPathRoot);
if (OnFinished != null)
OnFinished(this, EventArgs.Empty);
}
};
new Thread(start).Start();
}
private void ConvertDocument(object document,
ObservableCollection<IXPathNavigator> treeRoot)
{
XPathNavigator navigator;
navigator = document as XPathNavigator;
if (navigator == null)
return;
if (navigator == null)
return;
var root = new XPathNavigatorViewModel(navigator);
Application.Current.Dispatcher.Invoke((Action)delegate
{
foreach (var item in root.Children)
treeRoot.Add(item);
});
return;
}
public void SetDocument(XPathNavigator navigator)
{
try
{
this.Document = navigator;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
throw;
}
}
private static XPathNavigator OpenXPathNavigator(FileInfo fileInfo)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
XPathDocument document = null;
using (XmlReader reader = XmlReader.Create(fileInfo.FullName, readerSettings))
{
document = new XPathDocument(reader);
}
return document.CreateNavigator();
}
/// <summary>
/// Saves a copy of the tree's XML file.
/// </summary>
public bool Save(bool formatting, string fileName)
{
try
{
var fileInfo = new FileInfo(fileName);
using (FileStream stream = new FileStream(fileInfo.FullName,
FileMode.Create, FileAccess.Write,
FileShare.None))
{
this.Save(stream, formatting);
}
FileName = fileName;
return true;
}
catch
{
}
return false;
}
public void Save(Stream stream, bool formatting)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.Encoding = Encoding.UTF8;
settings.OmitXmlDeclaration = false;
settings.Indent = formatting;
using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
{
XPathNavigator navigator = this.Document as XPathNavigator;
if (navigator != null)
{
navigator.WriteSubtree(writer);
}
else
{
XPathNodeIterator iterator = this.Document as XPathNodeIterator;
if (iterator != null)
{
foreach (XPathNavigator node in iterator)
{
switch (node.NodeType)
{
case XPathNodeType.Attribute:
writer.WriteString(node.Value);
writer.WriteWhitespace(Environment.NewLine);
break;
default:
node.WriteSubtree(writer);
if (node.NodeType == XPathNodeType.Text)
writer.WriteWhitespace(Environment.NewLine);
break;
}
}
}
}
writer.Flush();
}
}
private void LoadNamespaceDefinitions(XPathNavigator navigator)
{
if (navigator == null)
{
this.XmlNamespaceManager = null;
return;
}
this.XmlNamespaceManager = new XmlNamespaceManager(navigator.NameTable);
XPathNodeIterator namespaces = navigator.Evaluate(@"//namespace::*[not(. = ../../namespace::*)]") as XPathNodeIterator;
this.NamespaceDefinitions = new ObservableCollection<NamespaceDefinition>();
this.DefaultNamespaceCount = 0;
// add any namespaces within the scope of the navigator to the namespace manager
foreach (var namespaceElement in namespaces)
{
XPathNavigator namespaceNavigator = namespaceElement as XPathNavigator;
if (namespaceNavigator == null)
continue;
NamespaceDefinition definition = new NamespaceDefinition()
{
OldPrefix = namespaceNavigator.Name,
Namespace = namespaceNavigator.Value,
};
if (string.IsNullOrEmpty(definition.OldPrefix))
{
if (DefaultNamespaceCount > 0)
definition.OldPrefix = "default" + (this.DefaultNamespaceCount + 1).ToString();
else
definition.OldPrefix = "default";
this.DefaultNamespaceCount++;
}
definition.NewPrefix = definition.OldPrefix;
this.NamespaceDefinitions.Add(definition);
this.XmlNamespaceManager.AddNamespace(definition.NewPrefix, definition.Namespace);
}
}
/***
public XPathNavigatorView GetSelectedNavigatorView()
{
// get the selected node
XPathNavigatorView navigator = this.SelectedItem as XPathNavigatorView;
// if there is no selected node, default to the root node
if (navigator == null && this.Items.Count > 0)
return this.Items[0] as XPathNavigatorView;
return navigator;
}
public void CopyOuterXml()
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
if (navigatorView == null)
return;
string text = this.GetXPathNavigatorFormattedOuterXml(navigatorView.XPathNavigator);
Clipboard.SetText(text);
}
public void CopyXml()
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
if (navigatorView == null)
return;
string text = this.GetXPathNavigatorFormattedXml(navigatorView.XPathNavigator);
Clipboard.SetText(text);
}
***/
private string GetXPathNavigatorFormattedXml(XPathNavigator navigator)
{
string outer = this.GetXPathNavigatorFormattedOuterXml(navigator);
int index = outer.IndexOf(">") + 1;
string xml = outer;
if (index < xml.Length && index > 0)
xml = xml.Remove(index);
return xml;
}
private string GetXPathNavigatorFormattedOuterXml(XPathNavigator navigator)
{
using (MemoryStream stream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.ASCII;
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter writer = XmlTextWriter.Create(stream, settings))
{
navigator.WriteSubtree(writer);
writer.Flush();
return Encoding.ASCII.GetString(stream.ToArray());
}
}
}
/// <summary>
/// Returns a string representing the full path of an XPathNavigator.
/// </summary>
/// <param name="navigator">An XPathNavigator.</param>
/// <returns></returns>
public string GetXmlNodeFullPath(XPathNavigator navigator)
{
// create a StringBuilder for assembling the path
StringBuilder sb = new StringBuilder();
// clone the navigator (cursor), so the node doesn't lose it's place
navigator = navigator.Clone();
// traverse the navigator's ancestry all the way to the top
while (navigator != null)
{
// skip anything but elements
if (navigator.NodeType == XPathNodeType.Element)
{
// insert the node and a seperator
sb.Insert(0, navigator.Name);
sb.Insert(0, "/");
}
if (!navigator.MoveToParent())
break;
}
return sb.ToString();
}
/***
public void ExpandAll()
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
if (navigatorView == null)
return;
navigatorView.ExpandAll();
}
public void CollapseAll()
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
if (navigatorView == null)
return;
navigatorView.CollapseAll();
}
public void SelectFirstResult(XPathNodeIterator iterator)
{
if (iterator == null || iterator.Count < 1)
return;
if (!iterator.MoveNext())
return;
// select the first node in the set
XPathNavigator targetNavigator = iterator.Current;
if (targetNavigator == null)
return;
this.SelectXPathNavigator(targetNavigator);
}
public void SelectXPathNavigator(XPathNavigator targetNavigator)
{
if (targetNavigator == null)
throw new ArgumentNullException("targetNavigator");
// we've found a node, so build an ancestor stack
Stack<XPathNavigator> ancestors = this.GetAncestors(targetNavigator);
IEnumerable items = this.Items;
XPathNavigatorView targetView = null;
while (ancestors.Count > 0)
{
XPathNavigator navigator = ancestors.Pop();
foreach (object item in items)
{
XPathNavigatorView view = item as XPathNavigatorView;
if (view == null)
return;
if (view.XPathNavigator.IsSamePosition(navigator))
{
if (ancestors.Count > 0)
{
view.IsExpanded = true;
items = view.Children;
}
targetView = view;
break;
}
}
}
if (targetView != null)
{
XPathNavigatorView previousSelectedItem = this.SelectedItem as XPathNavigatorView;
if (targetView.IsSelected && targetView != previousSelectedItem)
targetView.IsSelected = false;
targetView.IsSelected = true;
if (previousSelectedItem != null && previousSelectedItem != targetView && previousSelectedItem.IsSelected)
{
previousSelectedItem.IsSelected = false;
}
}
return;
}
***/
/// <summary>
/// Builds and returns a Stack of XPathNavigator ancestors for a given XPathNavigator.
/// </summary>
/// <param name="navigator">The XPathNavigator from which to build a stack.</param>
/// <returns></returns>
private Stack<XPathNavigator> GetAncestors(XPathNavigator navigator)
{
if (navigator == null)
throw new ArgumentNullException("navigator");
Stack<XPathNavigator> ancestors = new Stack<XPathNavigator>();
// navigate up the xml tree, building the stack as we go
while (navigator != null)
{
// push the current ancestor onto the stack
ancestors.Push(navigator);
// clone the current navigator cursor, so we don't lose our place
navigator = navigator.Clone();
// if we've reached the top, we're done
if (!navigator.MoveToParent())
break;
// if we've reached the root, we're done
if (navigator.NodeType == XPathNodeType.Root)
break;
}
// return the result
return ancestors;
}
/***
public string CopyXPath()
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
string text = this.GetXmlNodeFullPath(navigatorView.XPathNavigator);
Clipboard.SetText(text);
return text;
}
public object EvaluateXPath(string xpath)
{
XPathNavigatorView navigatorView = this.GetSelectedNavigatorView();
if (navigatorView == null)
return null;
// evaluate the expression, return the result
return navigatorView.XPathNavigator.Evaluate(xpath, this.XmlNamespaceManager);
}
***/
/// <summary>
/// Performs validation against any schemas provided in the document, if any.
/// If validation is not possible, because no schemas are provided, an InvalidOperationException is thrown.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException" />
public List<Error> Validate(XPathNavigator navigator)
{
try
{
this.CanValidate = false;
ClearErrorCollection();
if (navigator == null)
return null;
string xsiPrefix = this.XmlNamespaceManager.LookupPrefix("http://www.w3.org/2001/XMLSchema-instance");
if (string.IsNullOrEmpty(xsiPrefix))
{
this.AddError("The document does not have a schema specified.", XmlSeverityType.Warning);
return this.Errors.ToList();
}
XmlSchemaSet schemas = new XmlSchemaSet();
/*
* I can't believe I have to do this manually, but, here we go...
*
* When loading a document with an XmlReader and performing validation, it will automatically
* detect schemas specified in the document with @xsi:schemaLocation and @xsi:noNamespaceSchemaLocation attributes.
* We get line number and column, but not a reference to the actual offending xml node or xpath navigator.
*
* When validating an xpath navigator, it ignores these attributes, doesn't give us line number or column,
* but does give us the offending xpath navigator.
*
* */
foreach (var schemaAttribute in navigator.Select(
string.Format("//@{0}:noNamespaceSchemaLocation", xsiPrefix),
this.XmlNamespaceManager))
{
XPathNavigator attributeNavigator = schemaAttribute as XPathNavigator;
if (attributeNavigator == null)
continue;
string value = attributeNavigator.Value;
value = this.ResolveSchemaFileName(value);
// add the schema
schemas.Add(null, value);
}
foreach (var schemaAttribute in navigator.Select(
string.Format("//@{0}:schemaLocation", xsiPrefix),
this.XmlNamespaceManager))
{
XPathNavigator attributeNavigator = schemaAttribute as XPathNavigator;
if (attributeNavigator == null)
continue;
string value = attributeNavigator.Value;
List<KeyValuePair<string, string>> namespaceDefs = this.ParseNamespaceDefinitions(value);
foreach (var pair in namespaceDefs)
schemas.Add(pair.Key, pair.Value);
}
// validate the document
navigator.CheckValidity(schemas, this.OnValidationEvent);
this.CanValidate = true;
}
catch (FileNotFoundException ex)
{
string message = string.Format(
"Cannot find the schema document at '{0}'", ex.FileName);
this.AddError(message);
}
catch (Exception ex)
{
this.AddError(ex.Message);
}
return this.Errors.ToList();
}
private List<KeyValuePair<string, string>> ParseNamespaceDefinitions(string value)
{
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();
// the value should be like: http://www.w3schools.com note.xsd
// namespace path
// split it on space
string[] values = value.Split(" ".ToCharArray());
for (int i = 0; i < values.Length; i += 2)
{
// first value is namespace (it's not supposed to have spaces in it)
string targetNamespace = values[i];
// second value should be the filename
string schemaFileName = null;
if (i < values.Length - 1)
{
schemaFileName = values[i + 1];
schemaFileName = this.ResolveSchemaFileName(schemaFileName);
}
KeyValuePair<string, string> pair = new KeyValuePair<string, string>(targetNamespace, schemaFileName);
pairs.Add(pair);
}
return pairs;
}
private string ResolveSchemaFileName(string schemaFileName)
{
if (!File.Exists(schemaFileName))
{
// try prepending the current file's path
if (this.FileName != null)
schemaFileName = Path.Combine(Path.GetDirectoryName(FileName), schemaFileName);
}
return schemaFileName;
}
private void OnValidationEvent(object sender, ValidationEventArgs e)
{
Error error = new Error();
error.Description = e.Message;
error.Category = e.Severity;
XmlSchemaValidationException exception = e.Exception as XmlSchemaValidationException;
if (exception != null)
{
error.SourceObject = exception.SourceObject;
}
this.AddError(error);
}
private void AddError(string description)
{
this.AddError(description, XmlSeverityType.Error);
}
private void AddError(string description, XmlSeverityType category)
{
Error error = new Error();
error.Description = description;
error.Category = category;
this.AddError(error);
}
private void AddError(Error error)
{
if (this.FileName == null)
error.File = "Untitled";
else
error.File = this.FileName;
error.DefaultOrder = this.Errors.Count;
AddErrorIntoCollection(error);
}
private void ClearErrorCollection()
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
this.Errors.Clear();
}));
}
private void AddErrorIntoCollection(Error error)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
this.Errors.Add(error);
}));
}
/***
protected override void OnMouseUp(MouseButtonEventArgs e)
{
try
{
base.OnMouseUp(e);
if (e.ChangedButton != MouseButton.Right)
return;
DependencyObject obj = this.InputHitTest(e.GetPosition(this)) as DependencyObject;
if (obj == null)
return;
// cycle up the tree until you hit a TreeViewItem
while (obj != null && !(obj is TreeViewItem))
{
obj = VisualTreeHelper.GetParent(obj);
}
TreeViewItem item = obj as TreeViewItem;
if (item == null)
return;
XPathNavigatorView view = item.DataContext as XPathNavigatorView;
if (view == null)
return;
view.IsSelected = true;
ContextMenu contextMenu = this.Resources["treeContextMenu"] as ContextMenu;
if (contextMenu == null)
return;
contextMenu.PlacementTarget = item;
contextMenu.IsOpen = true;
}
catch (Exception ex)
{
App.HandleException(ex);
}
}
***/
#endregion methods
}
}
| 33.036991 | 131 | 0.51088 | [
"MIT"
] | Dirkster99/XmlExplorer | source/Components/XmlExplorerVMLib/ViewModels/XML/XPathNavigatoreTreeViewModel.cs | 26,795 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
namespace Nest
{
public interface IDeleteRoleResponse : IResponse
{
[JsonProperty("found")]
bool Found { get; }
}
public class DeleteRoleResponse : ResponseBase, IDeleteRoleResponse
{
public bool Found { get; internal set; }
}
}
| 17.473684 | 68 | 0.740964 | [
"Apache-2.0"
] | BedeGaming/elasticsearch-net | src/Nest/XPack/Security/Role/DeleteRole/DeleteRoleResponse.cs | 334 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the appflow-2020-08-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Appflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Appflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// SourceConnectorProperties Marshaller
/// </summary>
public class SourceConnectorPropertiesMarshaller : IRequestMarshaller<SourceConnectorProperties, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(SourceConnectorProperties requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetAmplitude())
{
context.Writer.WritePropertyName("Amplitude");
context.Writer.WriteObjectStart();
var marshaller = AmplitudeSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Amplitude, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetDatadog())
{
context.Writer.WritePropertyName("Datadog");
context.Writer.WriteObjectStart();
var marshaller = DatadogSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Datadog, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetDynatrace())
{
context.Writer.WritePropertyName("Dynatrace");
context.Writer.WriteObjectStart();
var marshaller = DynatraceSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Dynatrace, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetGoogleAnalytics())
{
context.Writer.WritePropertyName("GoogleAnalytics");
context.Writer.WriteObjectStart();
var marshaller = GoogleAnalyticsSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.GoogleAnalytics, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetInforNexus())
{
context.Writer.WritePropertyName("InforNexus");
context.Writer.WriteObjectStart();
var marshaller = InforNexusSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.InforNexus, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetMarketo())
{
context.Writer.WritePropertyName("Marketo");
context.Writer.WriteObjectStart();
var marshaller = MarketoSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Marketo, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetS3())
{
context.Writer.WritePropertyName("S3");
context.Writer.WriteObjectStart();
var marshaller = S3SourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.S3, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetSalesforce())
{
context.Writer.WritePropertyName("Salesforce");
context.Writer.WriteObjectStart();
var marshaller = SalesforceSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Salesforce, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetSAPOData())
{
context.Writer.WritePropertyName("SAPOData");
context.Writer.WriteObjectStart();
var marshaller = SAPODataSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.SAPOData, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetServiceNow())
{
context.Writer.WritePropertyName("ServiceNow");
context.Writer.WriteObjectStart();
var marshaller = ServiceNowSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.ServiceNow, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetSingular())
{
context.Writer.WritePropertyName("Singular");
context.Writer.WriteObjectStart();
var marshaller = SingularSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Singular, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetSlack())
{
context.Writer.WritePropertyName("Slack");
context.Writer.WriteObjectStart();
var marshaller = SlackSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Slack, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetTrendmicro())
{
context.Writer.WritePropertyName("Trendmicro");
context.Writer.WriteObjectStart();
var marshaller = TrendmicroSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Trendmicro, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetVeeva())
{
context.Writer.WritePropertyName("Veeva");
context.Writer.WriteObjectStart();
var marshaller = VeevaSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Veeva, context);
context.Writer.WriteObjectEnd();
}
if(requestObject.IsSetZendesk())
{
context.Writer.WritePropertyName("Zendesk");
context.Writer.WriteObjectStart();
var marshaller = ZendeskSourcePropertiesMarshaller.Instance;
marshaller.Marshall(requestObject.Zendesk, context);
context.Writer.WriteObjectEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static SourceConnectorPropertiesMarshaller Instance = new SourceConnectorPropertiesMarshaller();
}
} | 34.832579 | 124 | 0.610418 | [
"Apache-2.0"
] | ianb888/aws-sdk-net | sdk/src/Services/Appflow/Generated/Model/Internal/MarshallTransformations/SourceConnectorPropertiesMarshaller.cs | 7,698 | C# |
// <copyright file=Circle3DGeo.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:57 PM</date>
using System;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace HciLab.Utilities.Mash3D
{
public static class Circle3DGeo
{
/// <summary>
/// Generates a model of a Circle given specified parameters
/// </summary>
/// <param name="center">Center position of the circle</param>
/// <param name="radius">Radius of circle</param>
/// <param name="normal">Vector normal to circle's plane</param>
/// <param name="resolution">Number of slices to iterate the circumference of the circle</param>
/// <returns>A GeometryModel3D representation of the circle</returns>
public static GeometryModel3D GetCircleModel(Point3D center, double radius, Vector3D normal, int resolution, Color pColor)
{
var mod = new GeometryModel3D();
var geo = new MeshGeometry3D();
// Generate the circle in the XZ-plane
// Add the center first
geo.Positions.Add(new Point3D(0, 0, 0));
// Iterate from angle 0 to 2*PI
double t = 2 * Math.PI / resolution;
for (int i = 0; i < resolution; i++)
{
geo.Positions.Add(new Point3D(radius * Math.Cos(t * i), 0, -radius * Math.Sin(t * i)));
}
// Add points to MeshGeoemtry3D
for (int i = 0; i < resolution; i++)
{
var a = 0;
var b = i + 1;
var c = (i < (resolution - 1)) ? i + 2 : 1;
geo.TriangleIndices.Add(a);
geo.TriangleIndices.Add(b);
geo.TriangleIndices.Add(c);
}
mod.Geometry = geo;
// Create transforms
var trn = new Transform3DGroup();
// Up Vector (normal for XZ-plane)
var up = new Vector3D(0, 1, 0);
// Set normal length to 1
normal.Normalize();
var axis = Vector3D.CrossProduct(up, normal); // Cross product is rotation axis
var angle = Vector3D.AngleBetween(up, normal); // Angle to rotate
trn.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(axis, angle)));
trn.Children.Add(new TranslateTransform3D(new Vector3D(center.X, center.Y, center.Z)));
mod.Transform = trn;
mod.Material = new DiffuseMaterial(new SolidColorBrush(pColor));
return mod;
}
public static GeometryModel3D GetCircleModel(double pX, double pY, double pRadius, Color pColor, double pZ)
{
return GetCircleModel(new Point3D(pX, pY, pZ), pRadius, new Vector3D(0, 0, 1), 200, pColor);
}
}
}
| 44.980392 | 150 | 0.642982 | [
"MIT"
] | HCUM/kobelu | HciLab.Utilities/Mash3D/Circle3DGeo.cs | 4,588 | C# |
using System;
namespace Avalonia.Controls
{
public class NativeMenuItemBase : AvaloniaObject
{
private NativeMenu? _parent;
internal NativeMenuItemBase()
{
}
public static readonly DirectProperty<NativeMenuItemBase, NativeMenu?> ParentProperty =
AvaloniaProperty.RegisterDirect<NativeMenuItemBase, NativeMenu?>("Parent", o => o.Parent, (o, v) => o.Parent = v);
public NativeMenu? Parent
{
get => _parent;
set => SetAndRaise(ParentProperty, ref _parent, value);
}
}
}
| 24.375 | 126 | 0.618803 | [
"MIT"
] | Kibnet/Avalonia | src/Avalonia.Controls/NativeMenuItemBase.cs | 587 | C# |
namespace ForumSquare.Client.Models
{
public class ApiError
{
public string Message { get; set; }
public string Details { get; set; }
public string StackTrace { get; set; }
}
}
| 19.545455 | 46 | 0.6 | [
"MIT"
] | ajgoldenwings/Asp-Net-Blazor-Forum-Square | ForumSquare/ForumSquare.Client/Models/ApiError.cs | 217 | C# |
using System;
using System.Threading.Tasks;
using SmartSql.Test.Entities;
using SmartSql.TypeHandlers;
using Xunit;
namespace SmartSql.Test.Unit.TypeHandlers
{
public class TypeHandlerFactoryTest
{
TypeHandlerFactory typeHandlerFactory = new TypeHandlerFactory();
Type enumType = typeof(NumericalEnum);
[Fact]
public void TestEnumType()
{
var typeHandler = typeHandlerFactory.GetTypeHandler(enumType);
Assert.NotNull(typeHandler);
}
[Fact]
public void TestConcurrentRegisterEnum()
{
var enumType = typeof(NumericalEnum);
var taskMax = 200;
var current = 0;
var tasks = new Task[taskMax];
while (current < taskMax)
{
var task = new Task(() =>
{
var typeHandler = typeHandlerFactory.GetTypeHandler(enumType);
});
tasks[current] = task;
task.Start();
current++;
}
try
{
Task.WaitAll(tasks);
}
catch (Exception e)
{
Console.WriteLine(e);
var typeHandler = typeHandlerFactory.GetTypeHandler(enumType);
throw;
}
}
}
} | 24.927273 | 82 | 0.512764 | [
"Apache-2.0"
] | MetSystem/SmartSql | src/SmartSql.Test.Unit/TypeHandlers/TypeHandlerFactoryTest.cs | 1,371 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FeelUnity : MonoBehaviour
{
public FeelDevice deviceKind;
public string deviceName;
public Feel device { get; private set; }
void Awake()
{
device = new Feel(deviceKind);
device.Connect(deviceName);
}
void FixedUpdate()
{
if (device == null) return;
device.ParseMessages();
}
void OnDestroy()
{
if (device == null) return;
device.EndSession();
device.Disconnect();
device.Destroy();
device = null;
}
}
| 19.34375 | 44 | 0.597738 | [
"MIT"
] | KevinBalz/FeelSDK | Assets/FeelSDK/Scripts/FeelUnity.cs | 621 | 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("Infrastructure")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Infrastructure")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2fbf6347-1fea-4111-9144-7a55d76ce216")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.745896 | [
"MIT"
] | hardsky/process-monitor | Infrastructure/Properties/AssemblyInfo.cs | 1,404 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using Microsoft.SqlTools.Hosting.v2;
namespace Microsoft.SqlTools.Hosting.Utility
{
public class ServiceProviderNotSetException : InvalidOperationException {
public ServiceProviderNotSetException()
: base(SR.ServiceProviderNotSet) {
}
}
} | 26.352941 | 101 | 0.732143 | [
"MIT"
] | Bhaskers-Blu-Org2/sqltoolsservice | src/Microsoft.SqlTools.Hosting.v2/Utility/ServiceProviderNotSetException.cs | 448 | C# |
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using Optsol.Components.Infra.Bus.Delegates;
using Optsol.Components.Infra.Bus.Events;
using Optsol.Components.Infra.RabbitMQ.Connections;
using Optsol.Components.Infra.RabbitMQ.Services;
using Optsol.Components.Shared.Settings;
using Optsol.Components.Test.Shared.Logger;
using System;
using Xunit;
namespace Optsol.Components.Test.Unit.Infra.Bus
{
public class EventBusRabbitMQSpec
{
//TODO: Criar teste para EventBusRabbitMQSpec
//[Trait("Bus", "RabbitMQ")]
//[Fact(DisplayName = "Deve Testar", Skip = "Teste")]
public void DeveTestar()
{
//Given
var settings = new RabbitMQSettings
{
HostName = "localhost",
Port = 5672,
UserName = "guest",
Password = "guest",
ExchangeName = "playgroung_event_bus"
};
var logger = new XunitLogger<EventBusRabbitMQ>();
var loggerFactoryMock = new Mock<ILoggerFactory>();
loggerFactoryMock.Setup(setup => setup.CreateLogger(It.IsAny<string>())).Returns(logger);
var rabbitMQConnectionMock = new Mock<RabbitMQConnection>(loggerFactoryMock.Object, settings);
var eventBusRabbitMQ = new EventBusRabbitMQ(settings, loggerFactoryMock.Object, rabbitMQConnectionMock.Object);
var teste = new Teste
{
Nome = Guid.NewGuid().ToString()
};
//When
eventBusRabbitMQ.Subscribe<Teste>(received: EventBusRabbitMQ_OnReceivedMessage);
eventBusRabbitMQ.Publish(teste);
//Then
logger.Logs.Should().NotBeEmpty();
}
private void EventBusRabbitMQ_OnReceivedMessage(ReceivedMessageEventArgs e)
{
e.Message.Should().NotBeNull();
}
}
public class Teste : IEvent
{
public string Nome { get; set; }
}
}
| 31.375 | 123 | 0.622012 | [
"MIT"
] | carlosmachel/components-backend-core | test/Optsol.Components.Test.Unit/Infra/Bus/EventBusRabbitMQSpec.cs | 2,010 | C# |
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using Foundatio.Repositories.Models;
namespace Exceptionless.Core.Extensions;
public static class EnumerableExtensions {
public static IReadOnlyCollection<T> UnionOriginalAndModified<T>(this IReadOnlyCollection<ModifiedDocument<T>> documents) where T : class, new() {
return documents.Select(d => d.Value).Union(documents.Select(d => d.Original).Where(d => d != null)).ToList();
}
public static bool Contains<T>(this IEnumerable<T> enumerable, Func<T, bool> function) {
var a = enumerable.FirstOrDefault(function);
var b = default(T);
return !Equals(a, b);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) {
return source.DistinctBy(keySelector, EqualityComparer<TKey>.Default);
}
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) {
if (source == null)
throw new ArgumentNullException(nameof(source));
if (keySelector == null)
throw new ArgumentNullException(nameof(keySelector));
if (comparer == null)
throw new ArgumentNullException(nameof(comparer));
return DistinctByImpl(source, keySelector, comparer);
}
private static IEnumerable<TSource> DistinctByImpl<TSource, TKey>(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) {
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
if (knownKeys.Add(keySelector(element)))
yield return element;
}
public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action) {
foreach (var item in collection ?? new List<T>())
action(item);
}
public static bool CollectionEquals<T>(this IEnumerable<T> source, IEnumerable<T> other) {
using var sourceEnumerator = source.GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (sourceEnumerator.MoveNext()) {
if (!otherEnumerator.MoveNext()) {
// counts differ
return false;
}
if (sourceEnumerator.Current != null && sourceEnumerator.Current.Equals(otherEnumerator.Current)) {
// values aren't equal
return false;
}
}
return !otherEnumerator.MoveNext();
}
public static int GetCollectionHashCode<T>(this IEnumerable<T> source) {
string assemblyQualifiedName = typeof(T).AssemblyQualifiedName;
int hashCode = assemblyQualifiedName?.GetHashCode() ?? 0;
foreach (var item in source) {
if (item == null)
continue;
unchecked {
hashCode = (hashCode * 397) ^ item.GetHashCode();
}
}
return hashCode;
}
/// <summary>
/// Helper method for paging objects in a given source
/// </summary>
/// <typeparam name="T">type of object in source collection</typeparam>
/// <param name="source">source collection to be paged</param>
/// <param name="pageSize">page size</param>
/// <returns>a collection of sub-collections by page size</returns>
public static IEnumerable<ReadOnlyCollection<T>> Page<T>(this IEnumerable<T> source, int pageSize) {
Contract.Requires(source != null);
Contract.Requires(pageSize > 0);
Contract.Ensures(Contract.Result<IEnumerable<IEnumerable<T>>>() != null);
using (var enumerator = source.GetEnumerator()) {
while (enumerator.MoveNext()) {
var currentPage = new List<T>(pageSize) { enumerator.Current };
while (currentPage.Count < pageSize && enumerator.MoveNext()) {
currentPage.Add(enumerator.Current);
}
yield return new ReadOnlyCollection<T>(currentPage);
}
}
}
}
| 39.390476 | 167 | 0.637573 | [
"Apache-2.0"
] | 491134648/Exceptionless | src/Exceptionless.Core/Extensions/EnumerableExtensions.cs | 4,138 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
using XRTK.Utilities.Gltf.Schema;
namespace XRTK.Utilities.Gltf.Serialization
{
internal static class GltfConversions
{
// glTF matrix: column vectors, column-major storage, +Y up, +Z forward, -X right, right-handed
// unity matrix: column vectors, column-major storage, +Y up, +Z forward, +X right, left-handed
// multiply by a negative X scale to convert handedness
private static readonly Vector3 CoordinateSpaceConversionScale = new Vector3(-1, 1, 1);
private static readonly Vector4 TangentSpaceConversionScale = new Vector4(-1, 1, 1, -1);
internal static Matrix4x4 GetTrsProperties(this GltfNode node, out Vector3 position, out Quaternion rotation, out Vector3 scale)
{
Matrix4x4 matrix = node.matrix.GetMatrix4X4Value();
if (!node.useTRS)
{
matrix.GetTrsProperties(out position, out rotation, out scale);
}
else
{
position = node.translation.GetVector3Value();
rotation = node.rotation.GetQuaternionValue();
scale = node.scale.GetVector3Value(false);
}
return matrix;
}
internal static Color GetColorValue(this float[] colorArray)
{
return new Color(colorArray[0], colorArray[1], colorArray[2], colorArray.Length < 4 ? 1f : colorArray[3]);
}
internal static float[] SetColorValue(this Color color)
{
return new[] { color.r, color.g, color.b, color.a };
}
internal static Vector2 GetVector2Value(this float[] vector2Array)
{
return new Vector2(vector2Array[0], vector2Array[1]);
}
internal static float[] SetVector2Value(this Vector2 vector)
{
return new[] { vector.x, vector.y };
}
internal static Vector3 GetVector3Value(this float[] vector3Array, bool convert = true)
{
var vector = new Vector3(vector3Array[0], vector3Array[1], vector3Array[2]);
return convert ? Vector3.Scale(vector, CoordinateSpaceConversionScale) : vector;
}
internal static float[] SetVector3Value(this Vector3 vector, bool convert = true)
{
if (convert)
{
vector = Vector3.Scale(vector, CoordinateSpaceConversionScale);
}
return new[] { vector.x, vector.y, vector.z };
}
internal static Quaternion GetQuaternionValue(this float[] quaternionArray, bool convert = true)
{
var axes = new Vector3(quaternionArray[0], quaternionArray[1], quaternionArray[2]);
if (convert)
{
axes = Vector3.Scale(axes, CoordinateSpaceConversionScale) * -1.0f;
}
return new Quaternion(axes.x, axes.y, axes.z, quaternionArray[3]);
}
internal static float[] SetQuaternionValue(this Quaternion quaternion, bool convert = true)
{
// get the original axis and apply conversion scale as well as potential rotation axis flip
var axes = new Vector3(quaternion.x, quaternion.y, quaternion.z);
if (convert)
{
axes = Vector3.Scale(axes, CoordinateSpaceConversionScale) * 1.0f;
}
return new[] { axes.x, axes.y, axes.z, quaternion.w };
}
internal static Matrix4x4 GetMatrix4X4Value(this double[] matrixArray)
{
var matrix = new Matrix4x4(
new Vector4((float)matrixArray[0], (float)matrixArray[1], (float)matrixArray[2], (float)matrixArray[3]),
new Vector4((float)matrixArray[4], (float)matrixArray[5], (float)matrixArray[6], (float)matrixArray[7]),
new Vector4((float)matrixArray[8], (float)matrixArray[9], (float)matrixArray[10], (float)matrixArray[11]),
new Vector4((float)matrixArray[12], (float)matrixArray[13], (float)matrixArray[14], (float)matrixArray[15]));
Matrix4x4 convert = Matrix4x4.Scale(CoordinateSpaceConversionScale);
return convert * matrix * convert;
}
internal static float[] SetMatrix4X4Value(this Matrix4x4 matrix)
{
var convert = Matrix4x4.Scale(CoordinateSpaceConversionScale);
matrix = convert * matrix * convert;
return new[]
{
matrix.m00, matrix.m10, matrix.m20, matrix.m30,
matrix.m01, matrix.m11, matrix.m21, matrix.m31,
matrix.m02, matrix.m12, matrix.m22, matrix.m32,
matrix.m03, matrix.m13, matrix.m23, matrix.m33
};
}
internal static void GetTrsProperties(this Matrix4x4 matrix, out Vector3 position, out Quaternion rotation, out Vector3 scale)
{
position = matrix.GetColumn(3);
Vector3 x = matrix.GetColumn(0);
Vector3 y = matrix.GetColumn(1);
Vector3 z = matrix.GetColumn(2);
Vector3 calculatedZ = Vector3.Cross(x, y);
bool mirrored = Vector3.Dot(calculatedZ, z) < 0.0f;
scale.x = x.magnitude * (mirrored ? -1.0f : 1.0f);
scale.y = y.magnitude;
scale.z = z.magnitude;
rotation = Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1));
}
internal static int[] GetIntArray(this GltfAccessor accessor, bool flipFaces = true)
{
if (accessor.type != "SCALAR")
{
return null;
}
var array = new int[accessor.count];
GetTypeDetails(accessor.componentType, out int componentSize, out float _);
var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize;
var byteOffset = accessor.BufferView.byteOffset;
var bufferData = accessor.BufferView.Buffer.BufferData;
if (accessor.byteOffset >= 0)
{
byteOffset += accessor.byteOffset;
}
for (int i = 0; i < accessor.count; i++)
{
if (accessor.componentType == GltfComponentType.Float)
{
array[i] = (int)Mathf.Floor(BitConverter.ToSingle(bufferData, byteOffset + i * stride));
}
else
{
array[i] = (int)GetDiscreteUnsignedElement(bufferData, byteOffset + i * stride, accessor.componentType);
}
}
if (flipFaces)
{
for (int i = 0; i < array.Length; i += 3)
{
var temp = array[i];
array[i] = array[i + 2];
array[i + 2] = temp;
}
}
return array;
}
internal static Vector2[] GetVector2Array(this GltfAccessor accessor, bool flip = true)
{
if (accessor.type != "VEC2" || accessor.componentType == GltfComponentType.UnsignedInt)
{
return null;
}
var array = new Vector2[accessor.count];
GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 2;
var byteOffset = accessor.BufferView.byteOffset;
var bufferData = accessor.BufferView.Buffer.BufferData;
if (accessor.byteOffset >= 0)
{
byteOffset += accessor.byteOffset;
}
if (accessor.normalized) { maxValue = 1; }
for (int i = 0; i < accessor.count; i++)
{
if (accessor.componentType == GltfComponentType.Float)
{
array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
}
else
{
array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
}
if (flip)
{
array[i].y = 1.0f - array[i].y;
}
}
return array;
}
internal static Vector3[] GetVector3Array(this GltfAccessor accessor, bool convert = true)
{
if (accessor.type != "VEC3" || accessor.componentType == GltfComponentType.UnsignedInt)
{
return null;
}
var array = new Vector3[accessor.count];
GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 3;
var byteOffset = accessor.BufferView.byteOffset;
var bufferData = accessor.BufferView.Buffer.BufferData;
if (accessor.byteOffset >= 0)
{
byteOffset += accessor.byteOffset;
}
if (accessor.normalized) { maxValue = 1; }
for (int i = 0; i < accessor.count; i++)
{
if (accessor.componentType == GltfComponentType.Float)
{
array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
array[i].z = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
}
else
{
array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
array[i].z = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
}
if (convert)
{
array[i].x *= CoordinateSpaceConversionScale.x;
array[i].y *= CoordinateSpaceConversionScale.y;
array[i].z *= CoordinateSpaceConversionScale.z;
}
}
return array;
}
internal static Vector4[] GetVector4Array(this GltfAccessor accessor, bool convert = true)
{
if (accessor.type != "VEC4" || accessor.componentType == GltfComponentType.UnsignedInt)
{
return null;
}
var array = new Vector4[accessor.count];
GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 4;
var byteOffset = accessor.BufferView.byteOffset;
var bufferData = accessor.BufferView.Buffer.BufferData;
if (accessor.byteOffset >= 0)
{
byteOffset += accessor.byteOffset;
}
if (accessor.normalized) { maxValue = 1; }
for (int i = 0; i < accessor.count; i++)
{
if (accessor.componentType == GltfComponentType.Float)
{
array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
array[i].z = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
array[i].w = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 3);
}
else
{
array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
array[i].z = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
array[i].w = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 3, accessor.componentType) / maxValue;
}
if (convert)
{
array[i].x *= TangentSpaceConversionScale.x;
array[i].y *= TangentSpaceConversionScale.y;
array[i].z *= TangentSpaceConversionScale.z;
array[i].w *= TangentSpaceConversionScale.w;
}
}
return array;
}
internal static Color[] GetColorArray(this GltfAccessor accessor)
{
if (accessor.type != "VEC3" && accessor.type != "VEC4" || accessor.componentType == GltfComponentType.UnsignedInt)
{
return null;
}
var array = new Color[accessor.count];
GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
bool hasAlpha = accessor.type == "VEC4";
var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * (hasAlpha ? 4 : 3);
var byteOffset = accessor.BufferView.byteOffset;
var bufferData = accessor.BufferView.Buffer.BufferData;
if (accessor.byteOffset >= 0)
{
byteOffset += accessor.byteOffset;
}
for (int i = 0; i < accessor.count; i++)
{
if (accessor.componentType == GltfComponentType.Float)
{
array[i].r = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
array[i].g = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
array[i].b = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
array[i].a = hasAlpha ? BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 3) : 1f;
}
else
{
array[i].r = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
array[i].g = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
array[i].b = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
array[i].a = hasAlpha ? GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 3, accessor.componentType) / maxValue : 1f;
}
}
return array;
}
private static void GetTypeDetails(GltfComponentType type, out int componentSize, out float maxValue)
{
componentSize = 1;
maxValue = byte.MaxValue;
switch (type)
{
case GltfComponentType.Byte:
componentSize = sizeof(sbyte);
maxValue = sbyte.MaxValue;
break;
case GltfComponentType.UnsignedByte:
componentSize = sizeof(byte);
maxValue = byte.MaxValue;
break;
case GltfComponentType.Short:
componentSize = sizeof(short);
maxValue = short.MaxValue;
break;
case GltfComponentType.UnsignedShort:
componentSize = sizeof(ushort);
maxValue = ushort.MaxValue;
break;
case GltfComponentType.UnsignedInt:
componentSize = sizeof(uint);
maxValue = uint.MaxValue;
break;
case GltfComponentType.Float:
componentSize = sizeof(float);
maxValue = float.MaxValue;
break;
default:
throw new Exception("Unsupported component type.");
}
}
private static int GetDiscreteElement(byte[] data, int offset, GltfComponentType type)
{
switch (type)
{
case GltfComponentType.Byte:
return Convert.ToSByte(data[offset]);
case GltfComponentType.UnsignedByte:
return data[offset];
case GltfComponentType.Short:
return BitConverter.ToInt16(data, offset);
case GltfComponentType.UnsignedShort:
return BitConverter.ToUInt16(data, offset);
case GltfComponentType.UnsignedInt:
return (int)BitConverter.ToUInt32(data, offset);
default:
throw new Exception($"Unsupported type passed in: {type}");
}
}
private static uint GetDiscreteUnsignedElement(byte[] data, int offset, GltfComponentType type)
{
switch (type)
{
case GltfComponentType.Byte:
return (uint)Convert.ToSByte(data[offset]);
case GltfComponentType.UnsignedByte:
return data[offset];
case GltfComponentType.Short:
return (uint)BitConverter.ToInt16(data, offset);
case GltfComponentType.UnsignedShort:
return BitConverter.ToUInt16(data, offset);
case GltfComponentType.UnsignedInt:
return BitConverter.ToUInt32(data, offset);
default:
throw new Exception($"Unsupported type passed in: {type}");
}
}
}
}
| 42.473923 | 160 | 0.554482 | [
"MIT"
] | XRTK/com.xrtk.gltf | XRTK.glTF/Packages/com.xrtk.gltf/Runtime/Serialization/GltfConversions.cs | 18,733 | C# |
namespace Calculator_CSharp.Models
{
public class Calculator
{
public decimal LeftOperand { get; set; }
public decimal RightOperand { get; set; }
public string Operator { get; set; }
public decimal Result { get; set; }
public Calculator()
{
Result = 0;
}
}
} | 19.055556 | 49 | 0.548105 | [
"MIT"
] | lyubohd/Software-Technologies | 16. ASP.NET - Exercise/Calculator/Calculator-CSharp/Models/Calculator.cs | 345 | C# |
/* FailureSign.xaml.cs
* part of Bovender framework
*
* Copyright 2014-2018 Daniel Kraus
*
* 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.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Bovender.Mvvm.Views
{
/// <summary>
/// Interaction logic for FailureSign.xaml
/// </summary>
public partial class FailureSign : UserControl
{
public FailureSign()
{
InitializeComponent();
}
}
}
| 29.355556 | 76 | 0.700227 | [
"Apache-2.0",
"BSD-3-Clause"
] | bovender/bovender | Bovender/Mvvm/Views/FailureSign.xaml.cs | 1,323 | C# |
using System.Collections.Generic;
namespace WarOfEmpires.Domain.Empires {
public static class ResearchDefinitionFactory {
private static readonly Dictionary<ResearchType, ResearchDefinition> _researches = new Dictionary<ResearchType, ResearchDefinition>();
private static ResearchDefinition GenerateEfficiency() {
return new ResearchDefinition(
ResearchType.Efficiency,
0.05M,
"Efficiency allows each of your workers to produce more resources"
);
}
private static ResearchDefinition GenerateCommerce() {
return new ResearchDefinition(
ResearchType.Commerce,
0.05M,
"Commerce increases the gold income of your workers"
);
}
private static ResearchDefinition GenerateTactics() {
return new ResearchDefinition(
ResearchType.Tactics,
0.05M,
"Tactics increases the number of casualties your army inflicts on the battlefield"
);
}
private static ResearchDefinition GenerateCombatMedicine() {
return new ResearchDefinition(
ResearchType.CombatMedicine,
-0.04M,
"Combat medicine lowers the number of casualties your army suffers in battle"
);
}
private static ResearchDefinition GenerateSafeStorage() {
return new ResearchDefinition(
ResearchType.SafeStorage,
0.06M,
"Safe storage makes your workers store a percentage of their production in your banks automatically"
);
}
private static ResearchDefinition GenerateRegency() {
return new ResearchDefinition(
ResearchType.Regency,
0.05M,
"Regents hire back a percentage of the mercenaries you lose when you are attacked"
);
}
static ResearchDefinitionFactory() {
foreach (var definition in new[] {
GenerateEfficiency(), GenerateCommerce(),
GenerateTactics(), GenerateCombatMedicine(),
GenerateSafeStorage(), GenerateRegency()
}) {
_researches.Add(definition.Type, definition);
}
}
public static ResearchDefinition Get(ResearchType type) {
return _researches[type];
}
}
}
| 35.857143 | 142 | 0.588446 | [
"MIT"
] | maikelbos0/WarOfEmpires | WarOfEmpires.Domain/Empires/ResearchDefinitionFactory.cs | 2,512 | C# |
/******************************************************
* Project Name : VAdvantage
* Class Name : MRequestProcessorLog
* Purpose : Request Processor Log
* Class Used : X_R_RequestProcessorLog,ViennaProcessorLog
* Chronological Development
* Raghunandan 21-Jan-2010
*****************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process;
using System.Windows.Forms;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using System.Threading;
using System.Data;
using VAdvantage.Logging;
using System.Data.SqlClient;
namespace VAdvantage.Model
{
public class MRequestProcessorLog : X_R_RequestProcessorLog, ViennaProcessorLog
{
/// <summary>
/// Standard Constructor
/// </summary>
/// <param name="ctx"></param>
/// <param name="R_RequestProcessorLog_ID"></param>
/// <param name="trxName"></param>
public MRequestProcessorLog(Ctx ctx, int R_RequestProcessorLog_ID, Trx trxName)
: base(ctx, R_RequestProcessorLog_ID, trxName)
{
if (R_RequestProcessorLog_ID == 0)
{
SetIsError(false);
}
}
/// <summary>
/// Load Constructor
/// </summary>
/// <param name="ctx"></param>
/// <param name="idr"></param>
/// <param name="trxName"></param>
public MRequestProcessorLog(Ctx ctx, IDataReader idr, Trx trxName)
: base(ctx, idr, trxName)
{
}
/// <summary>
/// Parent Constructor
/// </summary>
/// <param name="parent"></param>
/// <param name="summary"></param>
public MRequestProcessorLog(MRequestProcessor parent, String summary)
: this(parent.GetCtx(), 0, parent.Get_TrxName())
{
SetClientOrg(parent);
SetR_RequestProcessor_ID(parent.GetR_RequestProcessor_ID());
SetSummary(summary);
}
}
}
| 30.013699 | 87 | 0.586947 | [
"Apache-2.0"
] | AsimKhan2019/ERP-CMR-DMS | ViennaAdvantageWeb/ModelLibrary/Model/MRequestProcessorLog.cs | 2,193 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.ComponentModel.DataAnnotations;
using Squidex.Infrastructure.Commands;
namespace Squidex.Web
{
public sealed class EntityCreatedDto
{
[Required]
[Display(Description = "Id of the created entity.")]
public string? Id { get; set; }
[Display(Description = "The new version of the entity.")]
public long Version { get; set; }
public static EntityCreatedDto FromResult<T>(EntityCreatedResult<T> result)
{
return new EntityCreatedDto { Id = result.IdOrValue?.ToString(), Version = result.Version };
}
}
}
| 34.678571 | 104 | 0.504634 | [
"MIT"
] | BigHam/squidex | backend/src/Squidex.Web/EntityCreatedDto.cs | 974 | C# |
namespace Vernuntii.VersionPresentation
{
/// <summary>
/// Kind of semantic version presentation.
/// </summary>
public enum VersionPresentationKind
{
/// <summary>
/// Single value.
/// </summary>
Value,
/// <summary>
/// Object with properties.
/// </summary>
Complex
}
}
| 20.222222 | 46 | 0.516484 | [
"MIT"
] | Teneko-NET-Tools/Teneko.MessagesVersioning | src/Vernuntii.Calculator/VersionPresentation/VersionPresentationKind.cs | 366 | C# |
using System;
using System.Collections.Generic;
using NetworkTables.Tables;
using WPILib.Commands;
using WPILib.Interfaces;
namespace WPILib.SmartDashboard
{
/// <summary>
/// The <see cref="SendableChooser"/> class is a useful tool for presenting a
/// selection of options to the <see cref="SmartDashboard"/>.
/// </summary><remarks>
/// One use for this is to be able to select between multiple
/// autonomous modes. You can do this by putting every possible <see cref="Command"/>
/// you want to run as an autonomous into a <see cref="SendableChooser"/> and then put
/// it into the <see cref="SmartDashboard"/> to have a list of options appear on the
/// laptop. Once autonomous starts, simply ask the <see cref="SendableChooser"/> what
/// the selected value is.
/// </remarks>
public class SendableChooser : ISendable
{
private const string Default = "default";
private const string Selected = "selected";
private const string Options = "options";
private readonly List<string> m_choices = new List<string>();
private readonly List<object> m_values = new List<object>();
private string m_defaultChoice = null;
private object m_defaultValue = null;
/// <summary>
/// Instantiates a <see cref="SendableChooser"/>
/// </summary>
public SendableChooser()
{
}
/// <summary>
/// Adds the given object tot the list of options. On the
/// <see cref="SmartDashboard"/> on the desktop, the object will appear as the given name.
/// </summary>
/// <param name="name">The name of the option</param>
/// <param name="obj">The option</param>
public void AddObject(string name, object obj)
{
if (m_defaultChoice == null)
{
AddDefault(name, obj);
return;
}
for (int i = 0; i < m_choices.Count; i++)
{
if (m_choices[i].Equals(name))
{
m_choices[i] = name;
m_values[i] = obj;
return;
}
}
m_choices.Add(name);
m_values.Add(obj);
Table?.PutStringArray(Options, m_choices.ToArray());
}
/// <summary>
/// Add the given object to the list of options and marks it as the default.
/// Functionally, this is very close to
/// <see cref="SendableChooser.AddObject(string, object)">AddObject(...)</see> except that it will
/// use this as the default option if none other is explicitly selected.
/// </summary>
/// <param name="name">The name of the option</param>
/// <param name="obj">The option</param>
public void AddDefault(string name, object obj)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name), "Name cannot be null");
}
m_defaultChoice = name;
m_defaultValue = obj;
Table?.PutString(Default, m_defaultChoice);
AddObject(name, obj);
}
/// <summary>
/// Returns the selected option. If there is none selected, it will return
/// the default. If there is none selected, then it will return null.
/// </summary>
/// <returns>The option selected</returns>
public object GetSelected()
{
string selected = Table.GetString(Selected, null);
for (int i = 0; i < m_values.Count; ++i)
{
if (m_choices[i].Equals(selected))
{
return m_values[i];
}
}
return m_defaultValue;
}
/// <inheritdoc/>
public void InitTable(ITable subtable)
{
Table = subtable;
if (Table != null)
{
Table.PutStringArray(Options, m_choices.ToArray());
if (m_defaultChoice != null)
{
Table.PutString(Default, m_defaultChoice);
}
}
}
/// <inheritdoc/>
public ITable Table { get; private set; }
/// <inheritdoc/>
public string SmartDashboardType => "String Chooser";
}
}
| 33.656489 | 106 | 0.542527 | [
"MIT"
] | Team-1922/OzWPILib.NET | WPILib/SmartDashboard/SendableChooser.cs | 4,411 | C# |
namespace Roslin.Msg.std_msgs
{
[MsgInfo("std_msgs/Header", "2176decaecbce78abc3b96ef049fabed", @"# Standard metadata for higher-level stamped data types.
# This is generally used to communicate timestamped data
# in a particular coordinate frame.
#
# sequence ID: consecutively increasing ID
uint32 seq
#Two-integer timestamp that is expressed as:
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')
# time-handling sugar is provided by the client library
time stamp
#Frame this data is associated with
string frame_id
")]
public partial class Header : RosMsg
{
public System.UInt32 seq
{
get;
set;
}
public System.DateTime stamp
{
get;
set;
}
public System.String frame_id
{
get;
set;
}
public Header(): base()
{
}
public Header(System.IO.BinaryReader binaryReader): base(binaryReader)
{
}
public override void Serilize(System.IO.BinaryWriter binaryWriter)
{
binaryWriter.Write(seq);
binaryWriter.Write(stamp);
binaryWriter.Write(frame_id.Length); binaryWriter . Write ( System . Text . Encoding . UTF8 . GetBytes ( frame_id ) ) ;
}
public override void Deserilize(System.IO.BinaryReader binaryReader)
{
seq = binaryReader.ReadUInt32();
stamp = binaryReader.ReadDateTime();
frame_id = System.Text.Encoding.UTF8.GetString(binaryReader.ReadBytes(binaryReader.ReadInt32()));
}
}
} | 29.542373 | 132 | 0.623637 | [
"MIT"
] | MoeLang/Roslin | Msg/GenMsgs/std_msgs/Header.cs | 1,743 | C# |
//
// OptimizerContext.cs
//
// Author:
// Martin Baulig <mabaul@microsoft.com>
//
// Copyright (c) 2019 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Linker.Steps;
namespace Mono.Linker.Optimizer
{
using Configuration;
using BasicBlocks;
public class OptimizerContext
{
public LinkContext Context {
get;
}
public OptimizerOptions Options {
get;
}
public string MainModule {
get;
}
public AnnotationStore Annotations => Context.Annotations;
OptimizerContext (LinkContext context, OptimizerOptions options, string mainModule)
{
Context = context;
Options = options;
MainModule = mainModule;
}
public void LogMessage (MessageImportance importance, string message)
{
Context.Logger.LogMessage (importance, message);
}
public void LogWarning (string message)
{
Context.Logger.LogMessage (MessageImportance.High, message);
}
[Conditional ("DEBUG")]
public void LogDebug (string message)
{
Context.Logger.LogMessage (MessageImportance.Low, message);
}
static bool initialized;
public static void Initialize (LinkContext linkContext, string mainModule, OptimizerOptions options)
{
if (initialized)
return;
initialized = true;
var context = new OptimizerContext (linkContext, options, mainModule);
if (options.CheckSize)
options.ReportMode |= ReportMode.Size;
if (options.OptimizerReport.IsEnabled (ReportMode.Detailed) || options.OptimizerReport.IsEnabled (ReportMode.Size)) {
options.AnalyzeAll = options.ScanAllModules = true;
if (options.Preprocessor == OptimizerOptions.PreprocessorMode.None)
options.Preprocessor = OptimizerOptions.PreprocessorMode.Automatic;
}
linkContext.Pipeline.AddStepAfter (typeof (TypeMapStep), new InitializeOptimizerStep (context));
if (options.EnableBlazor)
linkContext.Pipeline.AddStepBefore(typeof(MarkStep), new BlazorPreserveStep(context));
linkContext.Pipeline.AddStepBefore (typeof (MarkStep), new PreprocessStep (context));
linkContext.Pipeline.ReplaceStep (typeof (MarkStep), new ConditionalMarkStep (context));
linkContext.Pipeline.AppendStep (new SizeReportStep (context));
if (options.CompareWith != null)
linkContext.Pipeline.AppendStep (new CompareWithReportStep (context));
linkContext.Pipeline.AppendStep (new GenerateReportStep (context));
linkContext.Pipeline.AppendStep (new FinalCheckStep (context));
context.ResolveAssemblies ();
}
const string LinkerSupportType = "System.Runtime.CompilerServices.MonoLinkerSupport";
const string IsTypeAvailableName = "System.Boolean " + LinkerSupportType + "::IsTypeAvailable()";
const string IsTypeNameAvailableName = "System.Boolean " + LinkerSupportType + "::IsTypeAvailable(System.String)";
TypeDefinition _corlib_support_type;
TypeDefinition _test_helper_support_type;
SupportMethodRegistration _is_weak_instance_of;
SupportMethodRegistration _as_weak_instance_of;
SupportMethodRegistration _is_feature_supported;
SupportMethodRegistration _is_type_available;
SupportMethodRegistration _is_type_name_available;
SupportMethodRegistration _require_feature;
Lazy<TypeDefinition> _platform_not_support_exception;
Lazy<MethodDefinition> _platform_not_supported_exception_ctor;
FieldInfo _tracer_stack_field;
void ResolveAssemblies ()
{
foreach (var reference in Options.AssemblyReferences) {
var assembly = Context.Resolve (reference);
LogMessage (MessageImportance.Normal, $"Resolved assembly reference: {reference} {assembly}");
}
}
void Initialize ()
{
LogMessage (MessageImportance.High, $"Initializing {Program.ProgramName}.");
var mainName = Path.GetFileNameWithoutExtension (MainModule);
foreach (var asm in Context.GetAssemblies ()) {
switch (asm.Name.Name) {
case "mscorlib":
_corlib_support_type = asm.MainModule.GetType (LinkerSupportType);
CorlibAssembly = asm;
break;
case "TestHelpers":
_test_helper_support_type = asm.MainModule.GetType (LinkerSupportType);
break;
default:
if (asm.Name.Name.Equals (mainName))
MainAssembly = asm;
break;
}
}
if (CorlibAssembly == null) {
Console.Error.WriteLine ($"Cannot find `mscorlib.dll` is assembly list.");
// throw new OptimizerException ($"Cannot find `mscorlib.dll` is assembly list.");
}
if (MainAssembly == null)
throw new OptimizerException ($"Cannot find main module `{MainModule}` is assembly list.");
_is_weak_instance_of = ResolveSupportMethod ("IsWeakInstanceOf");
_as_weak_instance_of = ResolveSupportMethod ("AsWeakInstanceOf");
_is_feature_supported = ResolveSupportMethod ("IsFeatureSupported");
_is_type_available = ResolveSupportMethod (IsTypeAvailableName, true);
_is_type_name_available = ResolveSupportMethod (IsTypeNameAvailableName, true);
_require_feature = ResolveSupportMethod ("RequireFeature");
_platform_not_support_exception = new Lazy<TypeDefinition> (
() => Context.GetType ("System.PlatformNotSupportedException") ?? throw new OptimizerException ($"Can't find `System.PlatformNotSupportedException`."));
_platform_not_supported_exception_ctor = new Lazy<MethodDefinition> (
() => _platform_not_support_exception.Value.Methods.FirstOrDefault (m => m.Name == ".ctor") ?? throw new OptimizerException ($"Can't find `System.PlatformNotSupportedException`."));
_tracer_stack_field = typeof (Tracer).GetField ("dependency_stack", BindingFlags.Instance | BindingFlags.NonPublic);
}
SupportMethodRegistration ResolveSupportMethod (string name, bool full = false)
{
var corlib = _corlib_support_type?.Methods.FirstOrDefault (m => full ? m.FullName == name : m.Name == name);
var helper = _test_helper_support_type?.Methods.FirstOrDefault (m => full ? m.FullName == name : m.Name == name);
return new SupportMethodRegistration (corlib, helper);
}
public AssemblyDefinition CorlibAssembly {
get;
private set;
}
public AssemblyDefinition MainAssembly {
get;
private set;
}
public TypeDefinition MonoLinkerSupportType {
get;
private set;
}
public bool IsWeakInstanceOfMethod (MethodDefinition method) => _is_weak_instance_of.Matches (method);
public bool IsTypeAvailableMethod (MethodDefinition method) => _is_type_available.Matches (method);
public bool IsTypeNameAvailableMethod (MethodDefinition method) => _is_type_name_available.Matches (method);
public bool AsWeakInstanceOfMethod (MethodDefinition method) => _as_weak_instance_of.Matches (method);
public bool IsFeatureSupportedMethod (MethodDefinition method) => _is_feature_supported.Matches (method);
public bool IsRequireFeatureMethod (MethodDefinition method) => _require_feature.Matches (method);
public bool IsEnabled (MethodDefinition method)
{
return Options.ScanAllModules || method.Module.Assembly == MainAssembly || Options.EnableDebugging (this, method.DeclaringType);
}
internal int GetDebugLevel (MethodDefinition method)
{
return Options.EnableDebugging (this, method) ? 5 : 0;
}
internal void Debug ()
{ }
readonly HashSet<TypeDefinition> conditional_types = new HashSet<TypeDefinition> ();
readonly Dictionary<MethodDefinition, ConstantValue> constant_methods = new Dictionary<MethodDefinition, ConstantValue> ();
readonly Dictionary<TypeDefinition, List<Type>> type_entries = new Dictionary<TypeDefinition, List<Type>> ();
readonly Dictionary<MethodDefinition, List<Method>> method_entries = new Dictionary<MethodDefinition, List<Method>> ();
public bool IsConditionalTypeMarked (TypeDefinition type)
{
return conditional_types.Contains (type);
}
public void MarkConditionalType (TypeDefinition type)
{
conditional_types.Add (type);
}
internal void AddTypeEntry (TypeDefinition type, Type entry)
{
if (!type_entries.TryGetValue (type, out var list)) {
list = new List<Type> ();
type_entries.Add (type, list);
}
list.Add (entry);
}
internal List<Type> GetTypeEntries (TypeDefinition type)
{
if (type_entries.TryGetValue (type, out var list))
return list;
return null;
}
internal void AddMethodEntry (MethodDefinition method, Method entry)
{
if (!method_entries.TryGetValue (method, out var list)) {
list = new List<Method> ();
method_entries.Add (method, list);
}
list.Add (entry);
}
internal List<Method> GetMethodEntries (MethodDefinition method)
{
if (method_entries.TryGetValue (method, out var list))
return list;
return null;
}
internal void AttemptingToRedefineConditional (TypeDefinition type)
{
var message = $"Attempting to mark type `{type}` after it's already been used in a conditional!";
LogMessage (MessageImportance.High, message);
if (Options.NoConditionalRedefinition)
throw new OptimizerException (message);
}
internal void MarkAsConstantMethod (MethodDefinition method, ConstantValue value)
{
constant_methods.Add (method, value);
Options.OptimizerReport?.MarkAsConstantMethod (method, value);
}
internal bool TryGetConstantMethod (MethodDefinition method, out ConstantValue value)
{
return constant_methods.TryGetValue (method, out value);
}
internal IList<MethodDefinition> GetConstantMethods ()
{
return constant_methods.Keys.ToList ();
}
internal bool TryFastResolve (MethodReference reference, out MethodDefinition resolved)
{
if (reference is MethodDefinition method) {
resolved = method;
return true;
}
resolved = null;
if (reference.MetadataToken.TokenType != TokenType.MemberRef && reference.MetadataToken.TokenType != TokenType.MethodSpec)
return false;
if (reference.DeclaringType.IsNested || reference.DeclaringType.HasGenericParameters)
return false;
var type = reference.DeclaringType.Resolve ();
if (type == null)
return false;
if (type == _corlib_support_type || type == _test_helper_support_type) {
resolved = reference.Resolve ();
return true;
}
return false;
}
internal Instruction CreateNewPlatformNotSupportedException (MethodDefinition method)
{
var reference = method.DeclaringType.Module.ImportReference (_platform_not_supported_exception_ctor.Value);
return Instruction.Create (OpCodes.Newobj, reference);
}
static bool IsAssemblyBound (TypeDefinition td)
{
do {
if (td.IsNestedPrivate || td.IsNestedAssembly || td.IsNestedFamilyAndAssembly)
return true;
td = td.DeclaringType;
} while (td != null);
return false;
}
static string TokenString (object o)
{
if (o == null)
return "N:null";
if (o is TypeReference t) {
bool addAssembly = true;
var td = t as TypeDefinition ?? t.Resolve ();
if (td != null) {
addAssembly = td.IsNotPublic || IsAssemblyBound (td);
t = td;
}
var addition = addAssembly ? $":{t.Module}" : "";
return $"{(o as IMetadataTokenProvider).MetadataToken.TokenType}:{o}{addition}";
}
if (o is IMetadataTokenProvider)
return (o as IMetadataTokenProvider).MetadataToken.TokenType + ":" + o;
return "Other:" + o;
}
internal List<string> DumpTracerStack ()
{
var list = new List<string> ();
var stack = (Stack<object>)_tracer_stack_field.GetValue (Context.Tracer);
if (stack == null)
return list;
LogMessage (MessageImportance.Normal, "Dependency Stack:");
foreach (var dependency in stack) {
var formatted = TokenString (dependency);
list.Add (formatted);
LogMessage (MessageImportance.Normal, " " + formatted);
}
return list;
}
internal bool SizeCheckFailed {
get; set;
}
class SupportMethodRegistration
{
public MethodDefinition Corlib {
get;
}
public MethodDefinition Helper {
get;
}
public SupportMethodRegistration (MethodDefinition corlib, MethodDefinition helper)
{
Corlib = corlib;
Helper = helper;
}
public bool Matches (MethodDefinition method) => method != null && (method == Corlib || method == Helper);
}
class InitializeOptimizerStep : OptimizerBaseStep
{
public InitializeOptimizerStep (OptimizerContext context)
: base (context)
{
}
protected override void Process ()
{
Context.Initialize ();
}
}
}
}
| 31.971564 | 185 | 0.737622 | [
"MIT"
] | xamarin/linker-optimizer | Mono.Linker.Optimizer/Mono.Linker.Optimizer/OptimizerContext.cs | 13,494 | C# |
using System;
namespace Ludiq.PeekCore
{
public struct ScriptReference
{
/// <summary>
/// The ID of the script in the source file.
/// </summary>
public int fileID;
/// <summary>
/// The GUID of the source file (script or DLL).
/// </summary>
public string guid;
private ScriptReference(string guid, int fileID)
{
this.guid = guid;
this.fileID = fileID;
}
public static ScriptReference Existing(Type type)
{
return new ScriptReference(ScriptUtility.GetScriptGuid(type), ScriptUtility.GetFileID(type));
}
public static ScriptReference Manual(string guid, int fileID)
{
return new ScriptReference(guid, fileID);
}
public static ScriptReference Cs(string csGuid)
{
return new ScriptReference(csGuid, ScriptUtility.CsFileID);
}
public static ScriptReference Dll(string dllGuid, Type type)
{
return new ScriptReference(dllGuid, ScriptUtility.GetDllFileID(type));
}
public static ScriptReference Dll(string dllGuid, string @namespace, string typeName)
{
return new ScriptReference(dllGuid, ScriptUtility.GetDllFileID(@namespace, typeName));
}
public override string ToString()
{
return $"{{fileID: {fileID}, guid: {guid}, type: 3}}";
}
}
}
| 22.777778 | 96 | 0.705691 | [
"MIT"
] | 3-Delta/Unity-UGUI-UI | Assets/3rd/Ludiq/Ludiq.PeekCore/Editor/Utilities/ScriptReference.cs | 1,232 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.OpcUa.Twin.Models {
using System.Collections.Generic;
/// <summary>
/// Request node attribute read or update
/// </summary>
public class ReadRequestModel {
/// <summary>
/// Attributes to update or read
/// </summary>
public List<AttributeReadRequestModel> Attributes { get; set; }
/// <summary>
/// Optional header
/// </summary>
public RequestHeaderModel Header { get; set; }
}
}
| 31.88 | 99 | 0.526976 | [
"MIT"
] | TheWaywardHayward/Industrial-IoT | components/opc-ua/src/Microsoft.Azure.IIoT.OpcUa/src/Twin/Models/ReadRequestModel.cs | 797 | C# |
using System;
using SimpleFixture.Conventions;
using Xunit;
namespace SimpleFixture.Tests.FixtureTests.Primitives
{
public class TypeFixtureTests
{
[Fact]
public void Fixture_Locate_Type()
{
var fixture = new Fixture();
var type = fixture.Locate<Type>();
Assert.NotNull(type);
Assert.Equal(TypeConvention.LocateType, type);
}
[Fact]
public void Fixture_Generate_Type()
{
var fixture = new Fixture();
var type = fixture.Generate<Type>();
Assert.NotNull(type);
}
}
}
| 20.387097 | 58 | 0.564873 | [
"MIT"
] | razorrit/Ritesh-UnitTest | tests/SimpleFixture.Tests/FixtureTests/Primitives/TypeFixtureTests.cs | 634 | C# |
namespace KEI.Infrastructure
{
public interface IDialogFactory
{
public IDataContainer ShowDialog(string dialogName, IDataContainer parameters = null);
public void RegisterDialog<TDialog>(string name)
where TDialog : IDialog, new();
}
}
| 25.363636 | 94 | 0.688172 | [
"MIT"
] | athulrajts/Resusables | Infrastructure/KEI.Infrastructure.Core/ViewService/FileDialogs/IDialogFactory.cs | 281 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using BaseLib.Xwt.Interop;
using Xwt;
using Xwt.Backends;
namespace BaseLib.Xwt
{
using Xwt = global::Xwt;
public abstract class Platform
{
static Dictionary<string, Type> _typeslooked = new Dictionary<string, Type>();
public static Type GetType(string typeName)
{
if (_typeslooked.TryGetValue(typeName, out Type type))
{
return type;
}
type = Type.GetType(typeName);
if (type != null) return (_typeslooked[typeName] = type);
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return (_typeslooked[typeName]=type);
}
return null;
}
public static void Initialize(ToolkitType type)
{
try
{
if (Platform.OSPlatform == PlatformID.Unix/* || Platform.OSPlatform == PlatformID.MacOSX*/)
{
switch (type)
{
case ToolkitType.Gtk3:
LoadDlls("3.0");
break;
case ToolkitType.Gtk:
LoadDlls("2.0");
break;
}
}
Application.Initialize(type);
//_instance = Create();
}
catch (Exception e)
{
throw;
}
}
public static PlatformID OSPlatform
{
get
{
if (System.Environment.OSVersion.Platform != PlatformID.MacOSX &&
System.Environment.OSVersion.Platform != PlatformID.Unix)
{
return PlatformID.Win32Windows;
}
else
{
if (Directory.Exists("/Applications")
& Directory.Exists("/System")
& Directory.Exists("/Users")
& Directory.Exists("/Volumes"))
{
return PlatformID.MacOSX;
}
else
{
return PlatformID.Unix;
}
}
}
}
private static Platform _instance = null;
public static Platform Instance
{
get
{
if (_instance == null)
{
_instance = Create();
}
return _instance;
}
}
public IEnumerable<Tuple<IntPtr, object>> Search(WindowFrame window, Point pt)
{
var disp = GetDisplay(window);
return AllForms(disp, window.GetBackend()).Where(_t => GetWindowRect(disp, _t.Item2).Contains(pt));
}
public IEnumerable<Tuple<IntPtr, object>> AllForms(WindowFrame windowfordisplay)
{
var disp = GetDisplay(windowfordisplay);
return AllForms(disp, windowfordisplay.GetBackend());
}
public abstract IEnumerable<Tuple<IntPtr, object>> AllForms(IntPtr display, Xwt.Backends.IWindowFrameBackend window);
public virtual IntPtr GetDisplay(WindowFrame window) => IntPtr.Zero;
public abstract Rectangle GetWindowRect(IntPtr display, object form);
private static void LoadDlls(string dllversion)
{
LoadDll("gdk-sharp", dllversion);
LoadDll("glib-sharp", dllversion);
LoadDll("pango-sharp", dllversion);
LoadDll("gdk-sharp", dllversion);
LoadDll("gtk-sharp", dllversion);
LoadDll("atk-sharp", dllversion);
}
private static void LoadDll(string name, string dllversion)
{
if (Platform.OSPlatform == PlatformID.Unix)
{
Assembly.LoadFile($"/usr/lib/cli/{name}-{dllversion}/{name}.dll");
}
else
{
Assembly.Load(new AssemblyName($"{name}, Version={dllversion}"));
}
}
private static Platform Create()
{
switch (OSPlatform)
{
case PlatformID.Win32Windows: return new Implementation.PlatformWin32();
case PlatformID.MacOSX:
if (Toolkit.CurrentEngine.Type == ToolkitType.XamMac)
{
return new Implementation.PlatformXamMac();
}
else if (Toolkit.CurrentEngine.Type == ToolkitType.Gtk)
{
return new Implementation.PlatformGtkMac();
}
break;
case PlatformID.Unix:
{
if (Toolkit.CurrentEngine.Type == ToolkitType.Gtk3)
{
return new Implementation.X11_GTK3();
}
else
{
return new Implementation.X11_GTK2();
}
}
}
throw new NotImplementedException();
}
}
namespace Implementation
{
internal class PlatformXamMac : Platform
{
// const string qlib = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
const string qlib = @"/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/CoreGraphics";
[DllImport(qlib)]
static extern IntPtr CGWindowListCopyWindowInfo(int option, uint relativeToWindow);
[DllImport(qlib)]
static extern IntPtr CFArrayGetValueAtIndex(IntPtr array, int index);
[DllImport(qlib)]
static extern int CFArrayGetCount(IntPtr array);
[DllImport(qlib)]
static extern IntPtr CFDictionaryGetValue(IntPtr dict, IntPtr key);
[DllImport(qlib)]
static extern int CFDictionaryGetCount(IntPtr dict);
[DllImport(qlib)]
static extern bool CFDictionaryContainsKey(IntPtr dict, IntPtr key);
[DllImport(qlib)]
static extern int CFDictionaryGetKeysAndValues(IntPtr dict, IntPtr[] keys, IntPtr[] values);
[DllImport(qlib)]
static extern bool CGRectMakeWithDictionaryRepresentation(IntPtr dict, out CGRect rect);
[StructLayout(LayoutKind.Sequential)]
struct CGRect
{
public double x, y, w, h;
}
public override IEnumerable<Tuple<IntPtr, object>> AllForms(IntPtr display, IWindowFrameBackend window)
{
var wi = CGWindowListCopyWindowInfo(0x1, 0);
var count = CFArrayGetCount(wi);
var app = XamMac.appkit_nsapplication.GetPropertyValueStatic("SharedApplication");
var winarray = (Array)app.GetType().GetPropertyValue(app, "Windows");
var curapp = XamMac.appkit_nsrunningapp.GetPropertyValueStatic("CurrentApplication");
var appid = (int)XamMac.appkit_nsrunningapp.GetPropertyValue(curapp, "ProcessIdentifier");
var kCGWindowIsOnscreen = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowIsOnscreen");
var name_window = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowName");
var id_window = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowNumber");
var id_owner = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowOwnerPID");
var kCGWindowBounds = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowBounds");
for (int nit = 0; nit < count; nit++)
{
var cfdict = CFArrayGetValueAtIndex(wi, nit);
var visible = OpenTK.Platform.MacOS.Cocoa.SendBool(CFDictionaryGetValue(cfdict, kCGWindowIsOnscreen), OpenTK.Platform.MacOS.Selector.Get("boolValue"));
if (visible)
{
var windowid = OpenTK.Platform.MacOS.Cocoa.SendInt(CFDictionaryGetValue(cfdict, id_window), OpenTK.Platform.MacOS.Selector.Get("intValue"));
var i2 = OpenTK.Platform.MacOS.Cocoa.SendInt(CFDictionaryGetValue(cfdict, id_owner), OpenTK.Platform.MacOS.Selector.Get("intValue"));
if (i2 == appid)
{
foreach (var nswin in winarray) // AppKit.NSApplication.SharedApplication.Windows
{
object nint = nswin.GetType().GetPropertyValue(nswin, "WindowNumber");
if ((nint as System.IConvertible).ToInt32(null) == windowid)
{
yield return new Tuple<IntPtr, object>(new IntPtr(windowid), nswin);
}
}
}
else
{
if (CGRectMakeWithDictionaryRepresentation(CFDictionaryGetValue(cfdict, kCGWindowBounds), out CGRect rr))
{
var name = OpenTK.Platform.MacOS.Cocoa.FromNSString(CFDictionaryGetValue(cfdict, name_window));
object r2 = Activator.CreateInstance(XamMac.cg_cgrect, new object[] { rr.x, rr.y, rr.w, rr.h });
var r3 = (Xwt.Rectangle)XamMac.xwtmacbackend.InvokeStatic("ToDesktopRect", r2);
if (name != "Dock") // todo check with screenbounds
{
yield return new Tuple<IntPtr, object>(new IntPtr(windowid), r3);
}
}
}
}
}
OpenTK.Platform.MacOS.Cocoa.SendVoid(wi, OpenTK.Platform.MacOS.Selector.Release);
}
public override Rectangle GetWindowRect(IntPtr display, object form)
{
if (form is IWindowFrameBackend)
{
return (form as IWindowFrameBackend).Bounds;
}
if (form is Rectangle)
{
return (Rectangle)form;
}
throw new ApplicationException();
}
}
internal class PlatformGtkMac : Platform
{
// const string qlib = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
const string qlib = @"/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/CoreGraphics";
[DllImport(qlib)]
static extern IntPtr CGWindowListCopyWindowInfo(int option, uint relativeToWindow);
[DllImport(qlib)]
static extern IntPtr CFArrayGetValueAtIndex(IntPtr array, int index);
[DllImport(qlib)]
static extern int CFArrayGetCount(IntPtr array);
[DllImport(qlib)]
static extern IntPtr CFDictionaryGetValue(IntPtr dict, IntPtr key);
[DllImport(qlib)]
static extern int CFDictionaryGetCount(IntPtr dict);
[DllImport(qlib)]
static extern bool CFDictionaryContainsKey(IntPtr dict, IntPtr key);
[DllImport(qlib)]
static extern int CFDictionaryGetKeysAndValues(IntPtr dict, IntPtr[] keys, IntPtr[] values);
[DllImport(qlib)]
static extern bool CGRectMakeWithDictionaryRepresentation(IntPtr dict, out CGRect rect);
public PlatformGtkMac()
{
Platform.GetType("Xwt.Gtk.Mac.MacPlatformBackend").Assembly.GetType("Xwt.Mac.NSApplicationInitializer").InvokeStatic("Initialize");
}
[StructLayout(LayoutKind.Sequential)]
struct CGRect
{
public double x, y, w, h;
}
public Dictionary<int, object> CreateGdkLookup()
{
var d = new Dictionary<int, object>();
foreach (var _gtkwin in ((Array)Gtk.gtk_window.InvokeStatic("ListToplevels")).Cast<object>())
{
var gdkwin = _gtkwin.GetType().GetPropertyValue(_gtkwin, "GdkWindow");
if (gdkwin != null)
{
var nswin = GtkMac.gdk_quartz_window_get_nswindow((IntPtr)gdkwin.GetType().GetPropertyValue(gdkwin, "Handle"));
var _windowid = OpenTK.Platform.MacOS.Cocoa.SendIntPtr(nswin, OpenTK.Platform.MacOS.Selector.Get("windowNumber"));
// var windowid = OpenTK.Platform.MacOS.Cocoa.SendInt(_windowid, OpenTK.Platform.MacOS.Selector.Get("intValue"));
// var nsint= nswin.GetType().GetPropertyValue(nswin, "WindowNumber");
d[_windowid.ToInt32()] = _gtkwin;
}
}
return d;
}
public override IEnumerable<Tuple<IntPtr, object>> AllForms(IntPtr _display, IWindowFrameBackend window)
{
var wi = CGWindowListCopyWindowInfo(0x1, 0);
var count = CFArrayGetCount(wi);
var winarray = CreateGdkLookup();
var curapp = XamMac.appkit_nsrunningapp.GetPropertyValueStatic("CurrentApplication");
var appid = (int)XamMac.appkit_nsrunningapp.GetPropertyValue(curapp, "ProcessIdentifier");
var kCGWindowIsOnscreen = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowIsOnscreen");
var name_window = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowName");
var id_window = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowNumber");
var id_owner = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowOwnerPID");
var kCGWindowBounds = OpenTK.Platform.MacOS.Cocoa.ToNSString("kCGWindowBounds");
for (int nit = 0; nit < count; nit++)
{
var cfdict = CFArrayGetValueAtIndex(wi, nit);
var visible = OpenTK.Platform.MacOS.Cocoa.SendBool(CFDictionaryGetValue(cfdict, kCGWindowIsOnscreen), OpenTK.Platform.MacOS.Selector.Get("boolValue"));
if (visible)
{
var windowid = OpenTK.Platform.MacOS.Cocoa.SendInt(CFDictionaryGetValue(cfdict, id_window), OpenTK.Platform.MacOS.Selector.Get("intValue"));
var i2 = OpenTK.Platform.MacOS.Cocoa.SendInt(CFDictionaryGetValue(cfdict, id_owner), OpenTK.Platform.MacOS.Selector.Get("intValue"));
if (i2 == appid)
{
if (winarray.TryGetValue(windowid, out object gtkwin))
{
yield return new Tuple<IntPtr, object>(new IntPtr(windowid), gtkwin);
}
}
else
{
if (CGRectMakeWithDictionaryRepresentation(CFDictionaryGetValue(cfdict, kCGWindowBounds), out CGRect rr))
{
var name = OpenTK.Platform.MacOS.Cocoa.FromNSString(CFDictionaryGetValue(cfdict, name_window));
if (name != "Dock") // todo check with screenbounds
{
yield return new Tuple<IntPtr, object>(new IntPtr(windowid), new Rectangle(rr.x,rr.y,rr.w,rr.h));
}
}
}
}
}
OpenTK.Platform.MacOS.Cocoa.SendVoid(wi, OpenTK.Platform.MacOS.Selector.Release);
}
public override Rectangle GetWindowRect(IntPtr display, object form)
{
if (form is IWindowFrameBackend)
{
return (form as IWindowFrameBackend).Bounds;
}
if (form is Rectangle)
{
return (Rectangle)form;
}
if (form.GetType().Name == "Window")
{
var gdkwin = form.GetType().GetPropertyValue(form, "GdkWindow");
var xy = new object[] { 0, 0 };
var wh = new object[] { 0, 0 };
gdkwin.GetType().Invoke(gdkwin, "GetOrigin", xy);
gdkwin.GetType().Invoke(gdkwin, "GetSize", wh);
return new Rectangle((int)xy[0], (int)xy[1], (int)wh[0], (int)wh[1]);
}
throw new ApplicationException();
}
}
internal class PlatformWin32 : Platform
{
public override Rectangle GetWindowRect(IntPtr display, object form)
{
IntPtr hwnd;
if (form is IntPtr)
{
hwnd = (IntPtr)form;
}
else if (Xwt.Toolkit.CurrentEngine.Type == ToolkitType.Wpf)
{
var wih = Activator.CreateInstance(Win32.swi_wininterophelper, new object[] { form });
hwnd = (IntPtr)wih.GetType().GetPropertyValue(wih, "Handle");
}
else if (Xwt.Toolkit.CurrentEngine.Type == ToolkitType.Gtk)
{
var gtkwin = form;
var gdkwin = gtkwin.GetType().GetPropertyValue(gtkwin, "GdkWindow");
var xy = new object[] { 0, 0 };
var wh = new object[] { 0, 0 };
gdkwin.GetType().Invoke(gdkwin, "GetOrigin", xy);
gdkwin.GetType().Invoke(gdkwin, "GetSize", wh);
return new Rectangle((int)xy[0], (int)xy[1], (int)wh[0], (int)wh[1]);
}
else
{
throw new NotImplementedException();
}
Win32.GetWindowRect(hwnd, out Win32.RECT r);
return new Rectangle(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
}
public override IEnumerable<Tuple<IntPtr, object>> AllForms(IntPtr display, Xwt.Backends.IWindowFrameBackend window)
{
var found = new List<IntPtr>();
Win32.EnumWindowsProc func = (hwnd, lparam) =>
{
if ((Win32.GetWindowLongPtr(hwnd, -16) & 0x10000000L) != 0) // WS_STYLE&WS_VISIBLE
{
found.Add(hwnd);
}
return true;
};
Win32.EnumWindows(func, IntPtr.Zero);
if (Xwt.Toolkit.CurrentEngine.Type == ToolkitType.Wpf)
{
return found.Select(_h =>
{
var obj = Win32.swi_hwndsource.InvokeStatic("FromHwnd", _h);
obj = obj?.GetType().GetPropertyValue(obj, "RootVisual");
return new Tuple<IntPtr, object>(_h, obj ?? _h);
});
}
else if (Xwt.Toolkit.CurrentEngine.Type == ToolkitType.Gtk)
{
var d = CreateGtkLookup();
return found.Select(_h =>
{
d.TryGetValue(_h, out object obj);
// var obj = Win32.swi_hwndsource.InvokeStatic("FromHwnd", _h);
// obj = obj?.GetType().GetPropertyValue(obj, "RootVisual");
return new Tuple<IntPtr, object>(_h, obj ?? _h);
});
}
else
{
return found.Select(_h => new Tuple<IntPtr, object>(_h, _h));
}
}
public Dictionary<IntPtr, object> CreateGtkLookup()
{
var d = new Dictionary<IntPtr, object>();
foreach (var _gtkwin in ((Array)Gtk.gtk_window.InvokeStatic("ListToplevels")).Cast<object>())
{
var gdkwin = _gtkwin.GetType().GetPropertyValue(_gtkwin, "GdkWindow");
if (gdkwin != null)
{
d[gdk_win32_drawable_get_handle((IntPtr)gdkwin.GetType().GetPropertyValue(gdkwin, "Handle"))] = _gtkwin;
}
}
return d;
}
const string linux_libgdk_win_name = "libgdk-win32-2.0-0.dll";
[DllImport(linux_libgdk_win_name, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr gdk_win32_drawable_get_handle(IntPtr raw);
}
internal class X11_GTK2 : X11
{
const string libGtk = "libgdk-win32-2.0-0.dll";
[DllImport(libGtk)]
internal extern static IntPtr gdk_x11_drawable_get_xid(IntPtr window);
[DllImport(libGtk)]
public static extern IntPtr gdk_x11_display_get_xdisplay(IntPtr gdskdisplay);
protected override IntPtr getxdisplay(IntPtr display)
{
return gdk_x11_display_get_xdisplay(display);
}
protected override IntPtr getxid(IntPtr gdkwin)
{
return gdk_x11_drawable_get_xid(gdkwin);
}
}
internal class X11_GTK3 : X11
{
const string libGtk = "libgdk-3-0.dll";
[DllImport(libGtk)]
internal extern static IntPtr gdk_x11_window_get_xid(IntPtr window);
[DllImport(libGtk)]
public static extern IntPtr gdk_x11_display_get_xdisplay(IntPtr gdskdisplay);
protected override IntPtr getxdisplay(IntPtr display)
{
return gdk_x11_display_get_xdisplay(display);
}
protected override IntPtr getxid(IntPtr gdkwin)
{
return gdk_x11_window_get_xid(gdkwin);
}
public override Rectangle GetWindowRect(IntPtr xdisp, object gtkwin)
{
if (!(gtkwin is IntPtr))
{
var gdkwin = gtkwin.GetType().GetPropertyValue(gtkwin, "GdkWindow");
var t = gdkwin.GetType();
var xy = new object[] { 0, 0 };
t.Invoke(gdkwin, "GetOrigin", xy);
return new Rectangle((int)xy[0], (int)xy[1], (int)t.GetPropertyValue(gdkwin, "Width"), (int)t.GetPropertyValue(gdkwin, "Height"));
}
return base.GetWindowRect(xdisp, gtkwin);
}
}
internal abstract class X11 : Platform
{
const string libX11 = "libX11";
[DllImport(libX11)]
public extern static int XQueryTree(IntPtr display, IntPtr window, out IntPtr root_return, out IntPtr parent_return, out IntPtr children_return, out int nchildren_return);
[DllImport(libX11)]
public extern static int XFree(IntPtr data);
[DllImport(libX11)]
public extern static void XGetWindowAttributes(IntPtr display, IntPtr hwnd, ref XWindowAttributes wndAttr);
[StructLayout(LayoutKind.Sequential)]
internal struct XWindowAttributes
{
public int x, y; /* location of window */
public int width, height; /* width and height of window */
public int border_width; /* border width of window */
public int depth; /* depth of window */
public IntPtr visual; /* the associated visual structure */
public IntPtr root; /* root of screen containing window */
public int _class; /* InputOutput, InputOnly*/
public int bit_gravity; /* one of the bit gravity values */
public int win_gravity; /* one of the window gravity values */
public int backing_store; /* NotUseful, WhenMapped, Always */
public ulong backing_planes; /* planes to be preserved if possible */
public ulong backing_pixel; /* value to be used when restoring planes */
public int/*Bool*/ save_under; /* boolean, should bits under be saved? */
public IntPtr colormap; /* color map to be associated with window */
public int/*Bool*/ map_installed; /* boolean, is color map currently installed*/
public int map_state; /* IsUnmapped, IsUnviewable, IsViewable */
public long all_event_masks; /* set of events all people have interest in*/
public long your_event_mask; /* my event mask */
public long do_not_propagate_mask; /* set of events that should not propagate */
public int/*Bool*/ override_redirect; /* boolean value for override-redirect */
public IntPtr screen; /* back pointer to correct screen */
}
protected abstract IntPtr getxdisplay(IntPtr display);
protected abstract IntPtr getxid(IntPtr gdkwin);
public override IntPtr GetDisplay(WindowFrame window)
{
var gtkkwin = window.GetBackend().Window;
var gdkdisp = gtkkwin.GetType().GetPropertyValue(gtkkwin, "Display");
var display = (IntPtr)gdkdisp.GetType().GetPropertyValue(gdkdisp, "Handle");
var xdisp = getxdisplay(display);
return xdisp;
}
public override IEnumerable<Tuple<IntPtr, object>> AllForms(IntPtr xdisp, Xwt.Backends.IWindowFrameBackend window)
{
var gtkkwin = window.Window;
var gdkscr = gtkkwin.GetType().GetPropertyValue(gtkkwin, "Screen");
var rw = gdkscr.GetType().GetPropertyValue(gdkscr, "RootWindow");
var rwh = (IntPtr)rw.GetType().GetPropertyValue(rw, "Handle");
var rootWindow = getxid(rwh);
try
{
var d = CreateGdkLookup();
return _AllWindows(xdisp, rootWindow, d);
}
finally
{
}
}
public Dictionary<IntPtr, object> CreateGdkLookup()
{
var d = new Dictionary<IntPtr, object>();
foreach (var _gtkwin in ((Array)Gtk.gtk_window.InvokeStatic("ListToplevels")).Cast<object>())
{
var gdkwin = _gtkwin.GetType().GetPropertyValue(_gtkwin, "GdkWindow");
if (gdkwin != null)
{
d[getxid((IntPtr)gdkwin.GetType().GetPropertyValue(gdkwin, "Handle"))] = _gtkwin;
}
}
return d;
}
private IEnumerable<Tuple<IntPtr, object>> _AllWindows(IntPtr display, IntPtr rootWindow, Dictionary<IntPtr, object> gtkwins, int level = 0)
{
var status = XQueryTree(display, rootWindow, out IntPtr root_return, out IntPtr parent_return, out IntPtr children_return, out int nchildren_return);
if (nchildren_return > 0)
{
try
{
IntPtr[] children = new IntPtr[nchildren_return];
Marshal.Copy(children_return, children, 0, nchildren_return);
for (int nit = children.Length - 1; nit >= 0; nit--)
{
if (gtkwins.TryGetValue(children[nit], out object gtkwin))
{
yield return new Tuple<IntPtr, object>(children[nit], gtkwin);
}
else
{
var attr = new XWindowAttributes();
XGetWindowAttributes(display, children[nit], ref attr);
if (attr.map_state == 2)
{
if (level < 2)
{
bool fnd = false;
foreach (var form in _AllWindows(display, children[nit], gtkwins, level + 1))
{
if (form.Item2 != null)
{
fnd = true;
yield return form;
break;
}
}
if (!fnd && level == 0)
{
yield return new Tuple<IntPtr, object>(children[nit], children[nit]);
}
}
}
}
}
}
finally
{
XFree(children_return);
}
}
}
public override Rectangle GetWindowRect(IntPtr xdisp, object gtkwin)
{
if (gtkwin is IntPtr)
{
var attr = new XWindowAttributes();
XGetWindowAttributes(xdisp, (IntPtr)gtkwin, ref attr);
return new Rectangle(attr.x, attr.y, attr.width, attr.height);
}
else
{
var gdkwin = gtkwin.GetType().GetPropertyValue(gtkwin, "GdkWindow");
var xy = new object[] { 0, 0 };
var wh = new object[] { 0, 0 };
gdkwin.GetType().Invoke(gdkwin, "GetOrigin", xy);
gdkwin.GetType().Invoke(gdkwin, "GetSize", wh);
return new Rectangle((int)xy[0], (int)xy[1], (int)wh[0], (int)wh[1]);
}
}
}
}
} | 45.145349 | 183 | 0.497682 | [
"MIT"
] | Bert1974/BB74.Controls.Xwt | BB74.Controls/DockPanel/BaseLib/FrameWork.cs | 31,062 | C# |
using Discord;
using Discord.Webhook;
using System;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Data;
namespace omaha_watch_bot
{
class Program
{
private string stableVersion, betaVersion, devVersion, canaryVersion;
private DiscordWebhookClient mainClient;
public static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
public async Task MainAsync()
{
mainClient = new DiscordWebhookClient("link here");
Console.WriteLine("Omaha Watch Bot is now active.");
await FetchOmaha();
await Task.Delay(Timeout.Infinite);
}
private async Task FetchOmaha()
{
WebClient client = new WebClient();
stableVersion = betaVersion = devVersion = canaryVersion = "0";
// This task will loop indefinitely.
while (true)
{
StreamReader reader = new StreamReader(client.OpenRead("https://omahaproxy.appspot.com/all.json?os=win"));
string content = reader.ReadToEnd();
content = "{" + content[15..^1];
//Console.WriteLine(content);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(content);
DataTable dataTable = dataSet.Tables["versions"];
EmbedBuilder embed = new EmbedBuilder();
foreach (DataRow row in dataTable.Rows)
{
//Console.WriteLine(row["channel"] + " - " + row["version"]);
if (row["channel"].Equals("canary"))
{
if (canaryVersion.Equals("0")) canaryVersion = row["version"].ToString();
else
{
if (!canaryVersion.Equals(row["version"].ToString()))
{
embed.Title = "Canary update available!";
embed.AddField("New version: ", row["version"].ToString(), false).WithColor(Color.DarkPurple);
await mainClient.SendMessageAsync(embeds: new[] { embed.Build() });
canaryVersion = row["version"].ToString();
}
}
}
else if (row["channel"].Equals("dev"))
{
if (devVersion.Equals("0")) devVersion = row["version"].ToString();
else
{
if (!devVersion.Equals(row["version"].ToString()))
{
embed.Title = "Dev update available!";
embed.AddField("New version: ", row["version"].ToString(), false).WithColor(Color.Red);
await mainClient.SendMessageAsync(embeds: new[] { embed.Build() });
devVersion = row["version"].ToString();
}
}
}
else if (row["channel"].Equals("beta"))
{
if (betaVersion.Equals("0")) betaVersion = row["version"].ToString();
else
{
if (!betaVersion.Equals(row["version"].ToString()))
{
embed.Title = "Beta update available!";
embed.AddField("New version: ", row["version"].ToString(), false).WithColor(Color.Gold);
await mainClient.SendMessageAsync(embeds: new[] { embed.Build() });
betaVersion = row["version"].ToString();
}
}
}
else if (row["channel"].Equals("stable"))
{
if (stableVersion.Equals("0")) stableVersion = row["version"].ToString();
else
{
if (!stableVersion.Equals(row["version"].ToString()))
{
embed.Title = "Stable update available!";
embed.AddField("New version: ", row["version"].ToString(), false).WithColor(Color.Green);
await mainClient.SendMessageAsync(embeds: new[] { embed.Build() });
stableVersion = row["version"].ToString();
}
}
}
}
await Task.Delay(1800000);
}
}
}
}
| 43.122807 | 126 | 0.442636 | [
"MIT"
] | tangalbert919/omaha-watch-bot | C#/Program.cs | 4,918 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using EFCore.BulkExtensions.SqlAdapters;
namespace EFCore.BulkExtensions
{
public class TableInfo
{
public string Schema { get; set; }
public string SchemaFormated => Schema != null ? $"[{Schema}]." : "";
public string TableName { get; set; }
public string FullTableName => $"{SchemaFormated}[{TableName}]";
public List<string> PrimaryKeys { get; set; }
public bool HasSinglePrimaryKey { get; set; }
public bool UpdateByPropertiesAreNullable { get; set; }
protected string TempDBPrefix => BulkConfig.UseTempDB ? "#" : "";
public string TempTableSufix { get; set; }
public string TempTableName => $"{TableName}{TempTableSufix}";
public string FullTempTableName => $"{SchemaFormated}[{TempDBPrefix}{TempTableName}]";
public string FullTempOutputTableName => $"{SchemaFormated}[{TempDBPrefix}{TempTableName}Output]";
public bool CreatedOutputTable => BulkConfig.SetOutputIdentity || BulkConfig.CalculateStats;
public bool InsertToTempTable { get; set; }
public string IdentityColumnName { get; set; }
public bool HasIdentity => IdentityColumnName != null;
public bool HasOwnedTypes { get; set; }
public bool HasAbstractList { get; set; }
public bool ColumnNameContainsSquareBracket { get; set; }
public bool LoadOnlyPKColumn { get; set; }
public int NumberOfEntities { get; set; }
public BulkConfig BulkConfig { get; set; }
public Dictionary<string, string> OutputPropertyColumnNamesDict { get; set; } = new Dictionary<string, string>();
public Dictionary<string, string> PropertyColumnNamesDict { get; set; } = new Dictionary<string, string>();
public Dictionary<string, FastProperty> FastPropertyDict { get; set; } = new Dictionary<string, FastProperty>();
public Dictionary<string, INavigation> OwnedTypesDict { get; set; } = new Dictionary<string, INavigation>();
public HashSet<string> ShadowProperties { get; set; } = new HashSet<string>();
public Dictionary<string, ValueConverter> ConvertibleProperties { get; set; } = new Dictionary<string, ValueConverter>();
public string TimeStampOutColumnType => "varbinary(8)";
public string TimeStampColumnName { get; set; }
public static TableInfo CreateInstance<T>(DbContext context, IList<T> entities, OperationType operationType, BulkConfig bulkConfig)
{
return CreateInstance<T>(context, typeof(T), entities, operationType, bulkConfig);
}
public static TableInfo CreateInstance(DbContext context, Type type, IList<object> entities, OperationType operationType, BulkConfig bulkConfig)
{
return CreateInstance<object>(context, type, entities, operationType, bulkConfig);
}
private static TableInfo CreateInstance<T>(DbContext context, Type type, IList<T> entities, OperationType operationType, BulkConfig bulkConfig)
{
var tableInfo = new TableInfo
{
NumberOfEntities = entities.Count,
BulkConfig = bulkConfig ?? new BulkConfig() { }
};
tableInfo.BulkConfig.OperationType = operationType;
bool isExplicitTransaction = context.Database.GetDbConnection().State == ConnectionState.Open;
if (tableInfo.BulkConfig.UseTempDB == true && !isExplicitTransaction && (operationType != OperationType.Insert || tableInfo.BulkConfig.SetOutputIdentity))
{
throw new InvalidOperationException("UseTempDB when set then BulkOperation has to be inside Transaction. More info in README of the library in GitHub.");
// Otherwise throws exception: 'Cannot access destination table' (gets Dropped too early because transaction ends before operation is finished)
}
var isDeleteOperation = operationType == OperationType.Delete;
tableInfo.LoadData<T>(context, type, entities, isDeleteOperation);
return tableInfo;
}
#region Main
public void LoadData<T>(DbContext context, IList<T> entities, bool loadOnlyPKColumn)
{
LoadData<T>(context, typeof(T), entities, loadOnlyPKColumn);
}
public void LoadData(DbContext context, Type type, IList<object> entities, bool loadOnlyPKColumn)
{
LoadData<object>(context, type, entities, loadOnlyPKColumn);
}
private void LoadData<T>(DbContext context, Type type, IList<T> entities, bool loadOnlyPKColumn)
{
LoadOnlyPKColumn = loadOnlyPKColumn;
var entityType = context.Model.FindEntityType(type);
if (entityType == null)
{
type = entities[0].GetType();
entityType = context.Model.FindEntityType(type);
HasAbstractList = true;
}
if (entityType == null)
throw new InvalidOperationException($"DbContext does not contain EntitySet for Type: { type.Name }");
//var relationalData = entityType.Relational(); relationalData.Schema relationalData.TableName // DEPRECATED in Core3.0
bool isSqlServer = context.Database.ProviderName.EndsWith(DbServer.SqlServer.ToString());
string defaultSchema = isSqlServer ? "dbo" : null;
Schema = entityType.GetSchema() ?? defaultSchema;
TableName = entityType.GetTableName();
TempTableSufix = "Temp";
if (!BulkConfig.UseTempDB || BulkConfig.UniqueTableNameTempDb)
{
TempTableSufix += Guid.NewGuid().ToString().Substring(0, 8); // 8 chars of Guid as tableNameSufix to avoid same name collision with other tables
}
bool AreSpecifiedUpdateByProperties = BulkConfig.UpdateByProperties?.Count() > 0;
var primaryKeys = entityType.FindPrimaryKey()?.Properties?.Select(a => a.Name)?.ToList();
HasSinglePrimaryKey = primaryKeys?.Count == 1;
PrimaryKeys = AreSpecifiedUpdateByProperties ? BulkConfig.UpdateByProperties : primaryKeys;
var allProperties = entityType.GetProperties().AsEnumerable();
// load all derived type properties
if (entityType.IsAbstract())
{
var extendedAllProperties = allProperties.ToList();
foreach (var derived in entityType.GetDirectlyDerivedTypes())
{
extendedAllProperties.AddRange(derived.GetProperties());
}
allProperties = extendedAllProperties.Distinct();
}
var ownedTypes = entityType.GetNavigations().Where(a => a.GetTargetType().IsOwned());
HasOwnedTypes = ownedTypes.Any();
OwnedTypesDict = ownedTypes.ToDictionary(a => a.Name, a => a);
IdentityColumnName = allProperties.SingleOrDefault(a => a.IsPrimaryKey() && (a.ClrType.Name.StartsWith("Byte") || a.ClrType.Name.StartsWith("SByte") || a.ClrType.Name.StartsWith("Int") || a.ClrType.Name.StartsWith("UInt")) && !a.ClrType.Name.EndsWith("[]") && a.ValueGenerated == ValueGenerated.OnAdd)?.Name; // ValueGenerated equals OnAdd even for nonIdentity column like Guid so we only type int as second condition
// timestamp/row version properties are only set by the Db, the property has a [Timestamp] Attribute or is configured in FluentAPI with .IsRowVersion()
// They can be identified by the columne type "timestamp" or .IsConcurrencyToken in combination with .ValueGenerated == ValueGenerated.OnAddOrUpdate
string timestampDbTypeName = nameof(TimestampAttribute).Replace("Attribute", "").ToLower(); // = "timestamp";
var timeStampProperties = allProperties.Where(a => (a.IsConcurrencyToken && a.ValueGenerated == ValueGenerated.OnAddOrUpdate) || a.GetColumnType() == timestampDbTypeName);
TimeStampColumnName = timeStampProperties.FirstOrDefault()?.GetColumnName(); // can be only One
var allPropertiesExceptTimeStamp = allProperties.Except(timeStampProperties);
var properties = allPropertiesExceptTimeStamp.Where(a => a.GetComputedColumnSql() == null);
// TimeStamp prop. is last column in OutputTable since it is added later with varbinary(8) type in which Output can be inserted
OutputPropertyColumnNamesDict = allPropertiesExceptTimeStamp.Concat(timeStampProperties).ToDictionary(a => a.Name, b => b.GetColumnName().Replace("]", "]]")); // square brackets have to be escaped
ColumnNameContainsSquareBracket = allPropertiesExceptTimeStamp.Concat(timeStampProperties).Any(a => a.GetColumnName().Contains("]"));
bool AreSpecifiedPropertiesToInclude = BulkConfig.PropertiesToInclude?.Count() > 0;
bool AreSpecifiedPropertiesToExclude = BulkConfig.PropertiesToExclude?.Count() > 0;
if (AreSpecifiedPropertiesToInclude)
{
if (AreSpecifiedUpdateByProperties) // Adds UpdateByProperties to PropertyToInclude if they are not already explicitly listed
{
foreach (var updateByProperty in BulkConfig.UpdateByProperties)
{
if (!BulkConfig.PropertiesToInclude.Contains(updateByProperty))
{
BulkConfig.PropertiesToInclude.Add(updateByProperty);
}
}
}
else // Adds PrimaryKeys to PropertyToInclude if they are not already explicitly listed
{
foreach (var primaryKey in PrimaryKeys)
{
if (!BulkConfig.PropertiesToInclude.Contains(primaryKey))
{
BulkConfig.PropertiesToInclude.Add(primaryKey);
}
}
}
}
foreach (var property in allProperties)
{
if (property.PropertyInfo != null) // skip Shadow Property
{
FastPropertyDict.Add(property.Name, new FastProperty(property.PropertyInfo));
}
}
UpdateByPropertiesAreNullable = properties.Any(a => PrimaryKeys != null && PrimaryKeys.Contains(a.Name) && a.IsNullable);
if (AreSpecifiedPropertiesToInclude || AreSpecifiedPropertiesToExclude)
{
if (AreSpecifiedPropertiesToInclude && AreSpecifiedPropertiesToExclude)
throw new InvalidOperationException("Only one group of properties, either PropertiesToInclude or PropertiesToExclude can be specified, specifying both not allowed.");
if (AreSpecifiedPropertiesToInclude)
properties = properties.Where(a => BulkConfig.PropertiesToInclude.Contains(a.Name));
if (AreSpecifiedPropertiesToExclude)
properties = properties.Where(a => !BulkConfig.PropertiesToExclude.Contains(a.Name));
}
if (loadOnlyPKColumn)
{
PropertyColumnNamesDict = properties.Where(a => PrimaryKeys.Contains(a.Name)).ToDictionary(a => a.Name, b => b.GetColumnName().Replace("]", "]]"));
}
else
{
PropertyColumnNamesDict = properties.ToDictionary(a => a.Name, b => b.GetColumnName().Replace("]", "]]"));
ShadowProperties = new HashSet<string>(properties.Where(p => p.IsShadowProperty() && !p.IsForeignKey()).Select(p => p.GetColumnName()));
foreach (var property in properties.Where(p => p.GetValueConverter() != null))
{
string columnName = property.GetColumnName();
ValueConverter converter = property.GetValueConverter();
ConvertibleProperties.Add(columnName, converter);
}
foreach (var navigation in entityType.GetNavigations().Where(x => !x.IsCollection() && !x.GetTargetType().IsOwned()))
{
FastPropertyDict.Add(navigation.Name, new FastProperty(navigation.PropertyInfo));
}
if (HasOwnedTypes) // Support owned entity property update. TODO: Optimize
{
foreach (var navgationProperty in ownedTypes)
{
var property = navgationProperty.PropertyInfo;
FastPropertyDict.Add(property.Name, new FastProperty(property));
Type navOwnedType = type.Assembly.GetType(property.PropertyType.FullName);
var ownedEntityType = context.Model.FindEntityType(property.PropertyType);
if (ownedEntityType == null) // when entity has more then one ownedType (e.g. Address HomeAddress, Address WorkAddress) or one ownedType is in multiple Entities like Audit is usually.
{
ownedEntityType = context.Model.GetEntityTypes().SingleOrDefault(a => a.DefiningNavigationName == property.Name && a.DefiningEntityType.Name == entityType.Name);
}
var ownedEntityProperties = ownedEntityType.GetProperties().ToList();
var ownedEntityPropertyNameColumnNameDict = new Dictionary<string, string>();
foreach (var ownedEntityProperty in ownedEntityProperties)
{
if (!ownedEntityProperty.IsPrimaryKey())
{
string columnName = ownedEntityProperty.GetColumnName();
ownedEntityPropertyNameColumnNameDict.Add(ownedEntityProperty.Name, columnName);
var ownedEntityPropertyFullName = property.Name + "_" + ownedEntityProperty.Name;
if (!FastPropertyDict.ContainsKey(ownedEntityPropertyFullName))
{
FastPropertyDict.Add(ownedEntityPropertyFullName, new FastProperty(ownedEntityProperty.PropertyInfo));
}
}
var converter = ownedEntityProperty.GetValueConverter();
if (converter != null)
{
ConvertibleProperties.Add($"{navgationProperty.Name}_{ownedEntityProperty.Name}", converter);
}
}
var ownedProperties = property.PropertyType.GetProperties();
foreach (var ownedProperty in ownedProperties)
{
if (ownedEntityPropertyNameColumnNameDict.ContainsKey(ownedProperty.Name))
{
string columnName = ownedEntityPropertyNameColumnNameDict[ownedProperty.Name];
var ownedPropertyType = Nullable.GetUnderlyingType(ownedProperty.PropertyType) ?? ownedProperty.PropertyType;
bool doAddProperty = true;
if (AreSpecifiedPropertiesToInclude && !BulkConfig.PropertiesToInclude.Contains(columnName))
{
doAddProperty = false;
}
if (AreSpecifiedPropertiesToExclude && BulkConfig.PropertiesToExclude.Contains(columnName))
{
doAddProperty = false;
}
if (doAddProperty)
{
PropertyColumnNamesDict.Add(property.Name + "." + ownedProperty.Name, columnName);
OutputPropertyColumnNamesDict.Add(property.Name + "." + ownedProperty.Name, columnName);
}
}
}
}
}
}
}
/// <summary>
/// Supports <see cref="System.Data.SqlClient.SqlBulkCopy"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlBulkCopy"></param>
/// <param name="entities"></param>
/// <param name="setColumnMapping"></param>
/// <param name="progress"></param>
public void SetSqlBulkCopyConfig<T>(System.Data.SqlClient.SqlBulkCopy sqlBulkCopy, IList<T> entities, bool setColumnMapping, Action<decimal> progress)
{
sqlBulkCopy.DestinationTableName = InsertToTempTable ? FullTempTableName : FullTableName;
sqlBulkCopy.BatchSize = BulkConfig.BatchSize;
sqlBulkCopy.NotifyAfter = BulkConfig.NotifyAfter ?? BulkConfig.BatchSize;
sqlBulkCopy.SqlRowsCopied += (sender, e) =>
{
progress?.Invoke(ProgressHelper.GetProgress(entities.Count, e.RowsCopied)); // round to 4 decimal places
};
sqlBulkCopy.BulkCopyTimeout = BulkConfig.BulkCopyTimeout ?? sqlBulkCopy.BulkCopyTimeout;
sqlBulkCopy.EnableStreaming = BulkConfig.EnableStreaming;
if (setColumnMapping)
{
foreach (var element in PropertyColumnNamesDict)
{
sqlBulkCopy.ColumnMappings.Add(element.Key, element.Value);
}
}
}
/// <summary>
/// Supports <see cref="Microsoft.Data.SqlClient.SqlBulkCopy"/>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sqlBulkCopy"></param>
/// <param name="entities"></param>
/// <param name="setColumnMapping"></param>
/// <param name="progress"></param>
public void SetSqlBulkCopyConfig<T>(Microsoft.Data.SqlClient.SqlBulkCopy sqlBulkCopy, IList<T> entities, bool setColumnMapping, Action<decimal> progress)
{
sqlBulkCopy.DestinationTableName = InsertToTempTable ? FullTempTableName : FullTableName;
sqlBulkCopy.BatchSize = BulkConfig.BatchSize;
sqlBulkCopy.NotifyAfter = BulkConfig.NotifyAfter ?? BulkConfig.BatchSize;
sqlBulkCopy.SqlRowsCopied += (sender, e) =>
{
progress?.Invoke(ProgressHelper.GetProgress(entities.Count, e.RowsCopied)); // round to 4 decimal places
};
sqlBulkCopy.BulkCopyTimeout = BulkConfig.BulkCopyTimeout ?? sqlBulkCopy.BulkCopyTimeout;
sqlBulkCopy.EnableStreaming = BulkConfig.EnableStreaming;
if (setColumnMapping)
{
foreach (var element in PropertyColumnNamesDict)
{
sqlBulkCopy.ColumnMappings.Add(element.Key, element.Value);
}
}
}
#endregion
#region SqlCommands
public void CheckHasIdentity(DbContext context) // No longer used
{
context.Database.OpenConnection();
try
{
var sqlConnection = context.Database.GetDbConnection();
var currentTransaction = context.Database.CurrentTransaction;
using (var command = sqlConnection.CreateCommand())
{
if (currentTransaction != null)
command.Transaction = currentTransaction.GetDbTransaction();
command.CommandText = SqlQueryBuilder.SelectIdentityColumnName(TableName, Schema);
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
IdentityColumnName = reader.GetString(0);
}
}
}
}
}
finally
{
context.Database.CloseConnection();
}
}
public async Task CheckHasIdentityAsync(DbContext context, CancellationToken cancellationToken) // No longer used
{
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
var sqlConnection = context.Database.GetDbConnection();
var currentTransaction = context.Database.CurrentTransaction;
try
{
using (var command = sqlConnection.CreateCommand())
{
if (currentTransaction != null)
command.Transaction = currentTransaction.GetDbTransaction();
command.CommandText = SqlQueryBuilder.SelectIdentityColumnName(TableName, Schema);
using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
if (reader.HasRows)
{
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
IdentityColumnName = reader.GetString(0);
}
}
}
}
}
finally
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
}
public bool CheckTableExist(DbContext context, TableInfo tableInfo)
{
bool tableExist = false;
var sqlConnection = context.Database.GetDbConnection();
var currentTransaction = context.Database.CurrentTransaction;
try
{
if (currentTransaction == null)
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
}
using (var command = sqlConnection.CreateCommand())
{
if (currentTransaction != null)
command.Transaction = currentTransaction.GetDbTransaction();
command.CommandText = SqlQueryBuilder.CheckTableExist(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
tableExist = (int)reader[0] == 1;
}
}
}
}
}
finally
{
if (currentTransaction == null)
sqlConnection.Close();
}
return tableExist;
}
public async Task<bool> CheckTableExistAsync(DbContext context, TableInfo tableInfo, CancellationToken cancellationToken)
{
bool tableExist = false;
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
try
{
var sqlConnection = context.Database.GetDbConnection();
var currentTransaction = context.Database.CurrentTransaction;
using (var command = sqlConnection.CreateCommand())
{
if (currentTransaction != null)
command.Transaction = currentTransaction.GetDbTransaction();
command.CommandText = SqlQueryBuilder.CheckTableExist(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
using (var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
if (reader.HasRows)
{
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
tableExist = (int)reader[0] == 1;
}
}
}
}
}
finally
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
return tableExist;
}
protected int GetNumberUpdated(DbContext context)
{
var resultParameter = SqlClientHelper.CreateParameter(context.Database.GetDbConnection());
resultParameter.ParameterName = "@result";
resultParameter.DbType = DbType.Int32;
resultParameter.Direction = ParameterDirection.Output;
string sqlQueryCount = SqlQueryBuilder.SelectCountIsUpdateFromOutputTable(this);
context.Database.ExecuteSqlRaw($"SET @result = ({sqlQueryCount});", resultParameter);
return (int)resultParameter.Value;
}
protected async Task<int> GetNumberUpdatedAsync(DbContext context, CancellationToken cancellationToken)
{
var resultParameters = new List<IDbDataParameter>();
var p = SqlClientHelper.CreateParameter(context.Database.GetDbConnection());
p.ParameterName = "@result";
p.DbType = DbType.Int32;
p.Direction = ParameterDirection.Output;
resultParameters.Add(p);
string sqlQueryCount = SqlQueryBuilder.SelectCountIsUpdateFromOutputTable(this);
await context.Database.ExecuteSqlRawAsync($"SET @result = ({sqlQueryCount});", resultParameters, cancellationToken).ConfigureAwait(false); // TODO cancellationToken if Not
return (int)resultParameters.FirstOrDefault().Value;
}
#endregion
public static string GetUniquePropertyValues(object entity, List<string> propertiesNames, Dictionary<string, FastProperty> fastPropertyDict)
{
StringBuilder result = new StringBuilder(1024);
foreach (var propertyName in propertiesNames)
{
result.Append(fastPropertyDict[propertyName].Get(entity).ToString());
}
return result.ToString();
}
#region ReadProcedures
public Dictionary<string, string> ConfigureBulkReadTableInfo(DbContext context)
{
InsertToTempTable = true;
var previousPropertyColumnNamesDict = PropertyColumnNamesDict;
BulkConfig.PropertiesToInclude = PrimaryKeys;
PropertyColumnNamesDict = PropertyColumnNamesDict.Where(a => PrimaryKeys.Contains(a.Key)).ToDictionary(i => i.Key, i => i.Value);
return previousPropertyColumnNamesDict;
}
public void UpdateReadEntities<T>(IList<T> entities, IList<T> existingEntities)
{
UpdateReadEntities<T>(typeof(T), entities, existingEntities);
}
public void UpdateReadEntities(Type type, IList<object> entities, IList<object> existingEntities)
{
UpdateReadEntities<object>(type, entities, existingEntities);
}
internal void UpdateReadEntities<T>(Type type, IList<T> entities, IList<T> existingEntities)
{
List<string> propertyNames = PropertyColumnNamesDict.Keys.ToList();
if (HasOwnedTypes)
{
foreach (string ownedTypeName in OwnedTypesDict.Keys)
{
var ownedTypeProperties = OwnedTypesDict[ownedTypeName].ClrType.GetProperties();
foreach (var ownedTypeProperty in ownedTypeProperties)
{
propertyNames.Remove(ownedTypeName + "." + ownedTypeProperty.Name);
}
propertyNames.Add(ownedTypeName);
}
}
List<string> selectByPropertyNames = PropertyColumnNamesDict.Keys.Where(a => PrimaryKeys.Contains(a)).ToList();
Dictionary<string, T> existingEntitiesDict = new Dictionary<string, T>();
foreach (var existingEntity in existingEntities)
{
string uniqueProperyValues = GetUniquePropertyValues(existingEntity, selectByPropertyNames, FastPropertyDict);
existingEntitiesDict.Add(uniqueProperyValues, existingEntity);
}
for (int i = 0; i < NumberOfEntities; i++)
{
T existingEntity;
T entity = entities[i];
string uniqueProperyValues = GetUniquePropertyValues(entity, selectByPropertyNames, FastPropertyDict);
if (existingEntitiesDict.TryGetValue(uniqueProperyValues, out existingEntity))
{
foreach (var propertyName in propertyNames)
{
var propertyValue = FastPropertyDict[propertyName].Get(existingEntity);
FastPropertyDict[propertyName].Set(entity, propertyValue);
}
}
}
}
#endregion
protected void UpdateEntitiesIdentity<T>(Type type, IList<T> entities, IList<T> entitiesWithOutputIdentity)
{
if (BulkConfig.PreserveInsertOrder) // Updates PK in entityList
{
string identityPropertyName = OutputPropertyColumnNamesDict.SingleOrDefault(a => a.Value == IdentityColumnName).Key;
for (int i = 0; i < NumberOfEntities; i++)
{
var propertyValue = FastPropertyDict[identityPropertyName].Get(entitiesWithOutputIdentity[i]);
FastPropertyDict[identityPropertyName].Set(entities[i], propertyValue);
if (TimeStampColumnName != null) // timestamp/rowversion is also generated by the SqlServer so if exist should ba updated as well
{
string timeStampPropertyName = OutputPropertyColumnNamesDict.SingleOrDefault(a => a.Value == TimeStampColumnName).Key;
var timeStampPropertyValue = FastPropertyDict[timeStampPropertyName].Get(entitiesWithOutputIdentity[i]);
FastPropertyDict[timeStampPropertyName].Set(entities[i], timeStampPropertyValue);
}
}
}
else // Clears entityList and then refills it with loaded entites from Db
{
entities.Clear();
((List<T>)entities).AddRange(entitiesWithOutputIdentity);
}
}
// Compiled queries created manually to avoid EF Memory leak bug when using EF with dynamic SQL:
// https://github.com/borisdj/EFCore.BulkExtensions/issues/73
// Once the following Issue gets fixed(expected in EF 3.0) this can be replaced with code segment: DirectQuery
// https://github.com/aspnet/EntityFrameworkCore/issues/12905
#region CompiledQuery
public void LoadOutputData<T>(DbContext context, IList<T> entities) where T : class
{
LoadOutputData<T>(context, typeof(T), entities);
}
public void LoadOutputData(DbContext context, Type type, IList<object> entities)
{
LoadOutputData<object>(context, type, entities);
}
internal void LoadOutputData<T>(DbContext context, Type type, IList<T> entities) where T : class
{
bool hasIdentity = OutputPropertyColumnNamesDict.Any(a => a.Value == IdentityColumnName);
if (BulkConfig.SetOutputIdentity && hasIdentity)
{
string sqlQuery = SqlQueryBuilder.SelectFromOutputTable(this);
var entitiesWithOutputIdentity = (typeof(T) == type) ? QueryOutputTable<T>(context, sqlQuery).ToList() :
QueryOutputTable(context, type, sqlQuery).Cast<T>().ToList();
UpdateEntitiesIdentity(type, entities, entitiesWithOutputIdentity);
}
if (BulkConfig.CalculateStats)
{
string sqlQueryCount = SqlQueryBuilder.SelectCountIsUpdateFromOutputTable(this);
int numberUpdated = GetNumberUpdated(context);
BulkConfig.StatsInfo = new StatsInfo
{
StatsNumberUpdated = numberUpdated,
StatsNumberInserted = entities.Count - numberUpdated
};
}
}
public async Task LoadOutputDataAsync<T>(DbContext context, IList<T> entities, CancellationToken cancellationToken) where T : class
{
await LoadOutputDataAsync<T>(context, typeof(T), entities, cancellationToken).ConfigureAwait(false);
}
public async Task LoadOutputDataAsync(DbContext context, Type type, IList<object> entities, CancellationToken cancellationToken)
{
await LoadOutputDataAsync<object>(context, type, entities, cancellationToken).ConfigureAwait(false);
}
internal async Task LoadOutputDataAsync<T>(DbContext context, Type type, IList<T> entities, CancellationToken cancellationToken) where T : class
{
bool hasIdentity = OutputPropertyColumnNamesDict.Any(a => a.Value == IdentityColumnName);
if (BulkConfig.SetOutputIdentity && hasIdentity)
{
string sqlQuery = SqlQueryBuilder.SelectFromOutputTable(this);
//var entitiesWithOutputIdentity = await QueryOutputTableAsync<T>(context, sqlQuery).ToListAsync(cancellationToken).ConfigureAwait(false); // TempFIX
var entitiesWithOutputIdentity = (typeof(T) == type) ? QueryOutputTable<T>(context, sqlQuery).ToList() :
QueryOutputTable(context, type, sqlQuery).Cast<T>().ToList();
UpdateEntitiesIdentity(type, entities, entitiesWithOutputIdentity);
}
if (BulkConfig.CalculateStats)
{
int numberUpdated = await GetNumberUpdatedAsync(context, cancellationToken).ConfigureAwait(false);
BulkConfig.StatsInfo = new StatsInfo
{
StatsNumberUpdated = numberUpdated,
StatsNumberInserted = entities.Count - numberUpdated
};
}
}
protected IEnumerable<T> QueryOutputTable<T>(DbContext context, string sqlQuery) where T : class
{
var compiled = EF.CompileQuery(GetQueryExpression<T>(sqlQuery));
var result = compiled(context);
return result;
}
protected IEnumerable QueryOutputTable(DbContext context, Type type, string sqlQuery)
{
var compiled = EF.CompileQuery(GetQueryExpression(type, sqlQuery));
var result = compiled(context);
return result;
}
/*protected IAsyncEnumerable<T> QueryOutputTableAsync<T>(DbContext context, string sqlQuery) where T : class
{
var compiled = EF.CompileAsyncQuery(GetQueryExpression<T>(sqlQuery));
var result = compiled(context);
return result;
}*/
public Expression<Func<DbContext, IQueryable<T>>> GetQueryExpression<T>(string sqlQuery, bool ordered = true) where T : class
{
Expression<Func<DbContext, IQueryable<T>>> expression = null;
if (BulkConfig.TrackingEntities) // If Else can not be replaced with Ternary operator for Expression
{
expression = (ctx) => ctx.Set<T>().FromSqlRaw(sqlQuery);
}
else
{
expression = (ctx) => ctx.Set<T>().FromSqlRaw(sqlQuery).AsNoTracking();
}
return ordered ? Expression.Lambda<Func<DbContext, IQueryable<T>>>(OrderBy(typeof(T), expression.Body, PrimaryKeys[0]), expression.Parameters) : expression;
// ALTERNATIVELY OrderBy with DynamicLinq ('using System.Linq.Dynamic.Core;' NuGet required) that eliminates need for custom OrderBy<T> method with Expression.
//var queryOrdered = query.OrderBy(PrimaryKeys[0]);
}
public Expression<Func<DbContext, IEnumerable>> GetQueryExpression(Type entityType, string sqlQuery, bool ordered = true)
{
var parameter = Expression.Parameter(typeof(DbContext), "ctx");
var method = typeof(DbContext).GetMethod("Set").MakeGenericMethod(entityType);
var expression = Expression.Call(parameter, method);
method = typeof(RelationalQueryableExtensions).GetMethod("FromSqlRaw").MakeGenericMethod(entityType);
expression = Expression.Call(method, expression, Expression.Constant(sqlQuery), Expression.Constant(Array.Empty<object>()));
if (BulkConfig.TrackingEntities) // If Else can not be replaced with Ternary operator for Expression
{
}
else
{
method = typeof(EntityFrameworkQueryableExtensions).GetMethod("AsNoTracking").MakeGenericMethod(entityType);
expression = Expression.Call(method, expression);
}
expression = ordered ? OrderBy(entityType, expression, PrimaryKeys[0]) : expression;
return Expression.Lambda<Func<DbContext, IEnumerable>>(expression, parameter);
// ALTERNATIVELY OrderBy with DynamicLinq ('using System.Linq.Dynamic.Core;' NuGet required) that eliminates need for custom OrderBy<T> method with Expression.
//var queryOrdered = query.OrderBy(PrimaryKeys[0]);
}
private static MethodCallExpression OrderBy(Type entityType, Expression source, string ordering)
{
PropertyInfo property = entityType.GetProperty(ordering);
ParameterExpression parameter = Expression.Parameter(entityType);
MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property);
LambdaExpression orderByExp = Expression.Lambda(propertyAccess, parameter);
return Expression.Call(typeof(Queryable), "OrderBy", new Type[] { entityType, property.PropertyType }, source, Expression.Quote(orderByExp));
}
#endregion
// Currently not used until issue from previous segment is fixed in EFCore
#region DirectQuery
/*public void UpdateOutputIdentity<T>(DbContext context, IList<T> entities) where T : class
{
if (HasSinglePrimaryKey)
{
var entitiesWithOutputIdentity = QueryOutputTable<T>(context).ToList();
UpdateEntitiesIdentity(entities, entitiesWithOutputIdentity);
}
}
public async Task UpdateOutputIdentityAsync<T>(DbContext context, IList<T> entities) where T : class
{
if (HasSinglePrimaryKey)
{
var entitiesWithOutputIdentity = await QueryOutputTable<T>(context).ToListAsync().ConfigureAwait(false);
UpdateEntitiesIdentity(entities, entitiesWithOutputIdentity);
}
}
protected IQueryable<T> QueryOutputTable<T>(DbContext context) where T : class
{
string q = SqlQueryBuilder.SelectFromOutputTable(this);
var query = context.Set<T>().FromSql(q);
if (!BulkConfig.TrackingEntities)
{
query = query.AsNoTracking();
}
var queryOrdered = OrderBy(query, PrimaryKeys[0]);
// ALTERNATIVELY OrderBy with DynamicLinq ('using System.Linq.Dynamic.Core;' NuGet required) that eliminates need for custom OrderBy<T> method with Expression.
//var queryOrdered = query.OrderBy(PrimaryKeys[0]);
return queryOrdered;
}
private static IQueryable<T> OrderBy<T>(IQueryable<T> source, string ordering)
{
Type entityType = typeof(T);
PropertyInfo property = entityType.GetProperty(ordering);
ParameterExpression parameter = Expression.Parameter(entityType);
MemberExpression propertyAccess = Expression.MakeMemberAccess(parameter, property);
LambdaExpression orderByExp = Expression.Lambda(propertyAccess, parameter);
MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { entityType, property.PropertyType }, source.Expression, Expression.Quote(orderByExp));
var orderedQuery = source.Provider.CreateQuery<T>(resultExp);
return orderedQuery;
}*/
#endregion
}
}
| 51.404732 | 429 | 0.60032 | [
"MIT"
] | adimosh/EFCore.BulkExtensions | EFCore.BulkExtensions/TableInfo.cs | 41,278 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ACTransit.Contracts.Data.Schedules.PublicSite
{
/// <summary>
/// Active days of scheduled line(s).
/// </summary>
[DataContract]
public class DayCode
{
/// <summary>
/// Key (internal code) and associated Value (for Display purposes). If Value is empty, display Description instead.
/// </summary>
[DataMember]
public KeyValuePair<string, string> KeyValue { get; set; }
/// <summary>
/// Longer description
/// </summary>
[DataMember]
public string Description { get; set; }
}
} | 29.416667 | 130 | 0.577904 | [
"MIT"
] | actransitorg/ACTransit.CusRel | ACTransit.Contracts/Data/ACTransit.Contracts.Data.Schedules/PublicSite/DayCode.cs | 708 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace EventsStore.EventsModels.Cluster
{
using System;
using Newtonsoft.Json;
using Microsoft.ServiceFabric.Instrumentation.Tracing.Definitions.TypedTraceRecords.Testability;
[JsonObject("ChaosStarted")]
public sealed class ChaosStartedEvent : ClusterEvent
{
public ChaosStartedEvent(ChaosStartedTraceRecord traceRecord) : base(traceRecord.EventInstanceId, traceRecord.TimeStamp, traceRecord.Category)
{
this.MaxConcurrentFaults = traceRecord.MaxConcurrentFaults;
this.TimeToRunInSeconds = traceRecord.TimeToRunInSeconds;
this.MaxClusterStabilizationTimeoutInSeconds = traceRecord.MaxClusterStabilizationTimeoutInSeconds;
this.WaitTimeBetweenIterationsInSeconds = traceRecord.WaitTimeBetweenIterationsInSeconds;
this.WaitTimeBetweenFautlsInSeconds = traceRecord.WaitTimeBetweenFautlsInSeconds;
this.MoveReplicaFaultEnabled = traceRecord.MoveReplicaFaultEnabled;
this.IncludedNodeTypeList = traceRecord.IncludedNodeTypeList;
this.IncludedApplicationList = traceRecord.IncludedApplicationList;
this.ClusterHealthPolicy = traceRecord.ClusterHealthPolicy;
this.ChaosContext = traceRecord.ChaosContext;
}
[JsonProperty(PropertyName = "MaxConcurrentFaults")]
public long MaxConcurrentFaults { get; set; }
[JsonProperty(PropertyName = "TimeToRunInSeconds")]
public double TimeToRunInSeconds { get; set; }
[JsonProperty(PropertyName = "MaxClusterStabilizationTimeoutInSeconds")]
public double MaxClusterStabilizationTimeoutInSeconds { get; set; }
[JsonProperty(PropertyName = "WaitTimeBetweenIterationsInSeconds")]
public double WaitTimeBetweenIterationsInSeconds { get; set; }
[JsonProperty(PropertyName = "WaitTimeBetweenFautlsInSeconds")]
public double WaitTimeBetweenFautlsInSeconds { get; set; }
[JsonProperty(PropertyName = "MoveReplicaFaultEnabled")]
public bool MoveReplicaFaultEnabled { get; set; }
[JsonProperty(PropertyName = "IncludedNodeTypeList")]
public string IncludedNodeTypeList { get; set; }
[JsonProperty(PropertyName = "IncludedApplicationList")]
public string IncludedApplicationList { get; set; }
[JsonProperty(PropertyName = "ClusterHealthPolicy")]
public string ClusterHealthPolicy { get; set; }
[JsonProperty(PropertyName = "ChaosContext")]
public string ChaosContext { get; set; }
}
}
| 47.35 | 150 | 0.699754 | [
"MIT"
] | AndreyTretyak/service-fabric | src/prod/src/managed/EventsStore/EventsStore.EventsModels/Cluster/ChaosStartedEvent.cs | 2,841 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AnyStore.BLL
{
class transactionDetailBLL
{
public int id { get; set; }
public int transastion_id { get; set; }
public int product_id { get; set; }
public decimal rate { get; set; }
public decimal qty { get; set; }
public decimal discount { get; set; }
public decimal total { get; set; }
public int dea_cust_id { get; set; }
public DateTime added_date { get; set; }
public int added_by { get; set; }
}
}
| 27.130435 | 48 | 0.61859 | [
"MIT"
] | mhusny/Simple-Invoicing-System | AnyStore/BLL/transactionDetailBLL.cs | 626 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using Amazon.Runtime;
namespace Amazon.SimpleEmail.Model
{
/// <summary>
/// Returns information about the VerifyEmailIdentity response and response metadata.
/// </summary>
public class VerifyEmailIdentityResponse : VerifyEmailIdentityResult
{
/// <summary>
/// Gets and sets the VerifyEmailIdentityResult property.
/// An empty element. Receiving this element indicates that the request completed successfully.
/// </summary>
[Obsolete(@"This property has been deprecated. All properties of the VerifyEmailIdentityResult class are now available on the VerifyEmailIdentityResponse class. You should use the properties on VerifyEmailIdentityResponse instead of accessing them through VerifyEmailIdentityResult.")]
public VerifyEmailIdentityResult VerifyEmailIdentityResult
{
get
{
return this;
}
}
}
}
| 37.204545 | 293 | 0.709835 | [
"Apache-2.0"
] | virajs/aws-sdk-net | AWSSDK_DotNet35/Amazon.SimpleEmail/Model/VerifyEmailIdentityResponse.cs | 1,637 | C# |
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace AdMaiora.Listy
{
[Register ("RegistrationDoneViewController")]
partial class RegistrationDoneViewController
{
[Outlet]
UIKit.UIButton GoToLoginButton { get; set; }
[Outlet]
UIKit.UIImageView HeadImage { get; set; }
[Outlet]
UIKit.UILabel WelcomeLabel { get; set; }
void ReleaseDesignerOutlets ()
{
if (HeadImage != null) {
HeadImage.Dispose ();
HeadImage = null;
}
if (GoToLoginButton != null) {
GoToLoginButton.Dispose ();
GoToLoginButton = null;
}
if (WelcomeLabel != null) {
WelcomeLabel.Dispose ();
WelcomeLabel = null;
}
}
}
}
| 20.906977 | 84 | 0.686318 | [
"MIT"
] | admaiorastudio/listy | Listy/Listy.iOS/UI/SubControllers/RegistrationDoneViewController.designer.cs | 899 | C# |
#pragma warning disable 1591
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
[assembly: Android.Runtime.ResourceDesignerAttribute("g0rdan.MvvmCross.Plugin.SimpleEmail.Droid.Resource", IsApplication=false)]
namespace g0rdan.MvvmCross.Plugin.SimpleEmail.Droid
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class String
{
// aapt resource value: 0x7f020000
public static int library_name = 2130837504;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
| 22.844828 | 128 | 0.603019 | [
"MIT"
] | g0rdan/g0rdan.MvvmCross.Plugins | source/Droid/g0rdan.MvvmCross.Plugin.SimpleEmail.Droid/Resources/Resource.designer.cs | 1,325 | C# |
// The MIT License (MIT)
// Copyright (c) 1994-2017 Sage Software, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#region Namespace
using Sage.CA.SBS.ERP.Sage300.Common.Models;
using ValuedParter.TU.Resources.Forms;
#endregion
namespace ValuedParter.TU.Models.Enums
{
/// <summary>
/// Enum for Complete
/// </summary>
public enum Complete
{
/// <summary>
/// Gets or sets No
/// </summary>
[EnumValue("No", typeof(ReceiptHeaderResx))]
No = 0,
/// <summary>
/// Gets or sets Yes
/// </summary>
[EnumValue("Yes", typeof(ReceiptHeaderResx))]
Yes = 1
}
} | 36 | 88 | 0.691551 | [
"MIT"
] | DavidFWang/Sage300-SDK | samples/Receipt/ValuedParter.TU.Models/Enums/Complete.cs | 1,728 | C# |
using System;
namespace Zest.OrderManagement.Common.Utilities
{
/// <summary>
/// Attribute class for storing description related to C# Enum items.
/// </summary>
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDescriptionAttribute : Attribute
{
/// <summary>
/// Gets the description binded to this attribute.
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="EnumDescriptionAttribute"/> class.
/// </summary>
/// <param name="description">The description.</param>
public EnumDescriptionAttribute(string description)
{
Description = description;
}
}
}
| 30.5 | 91 | 0.622951 | [
"MIT"
] | hpsanampudi/Zest.OrderManagement | src/Zest.OrderManagement.Common/Utilities/EnumDescription.cs | 795 | C# |
/*************************************************************************
* Copyright © 2015-2019 Mogoson. All rights reserved.
*------------------------------------------------------------------------
* File : Texture2DExtention.cs
* Description : Extention for UnityEngine.Texture2D.
*------------------------------------------------------------------------
* Author : Mogoson
* Version : 1.0
* Date : 10/24/2015
* Description : Initial development version.
*************************************************************************/
using MGS.Common.Converter;
using MGS.Logger;
using UnityEngine;
namespace MGS.UCommon.Extension
{
/// <summary>
/// Extention for UnityEngine.Texture2D.
/// </summary>
public static class Texture2DExtention
{
#region Public Static Method
/// <summary>
/// Update the pixels of Texture2D.
/// </summary>
/// <param name="texture2D">Base Texture2D.</param>
/// <param name="colorArray">Color array for pixels.</param>
/// <param name="mipLevel">The mip level of the texture to write to.</param>
/// <param name="updateMipmaps">When set to true, mipmap levels are recalculated.</param>
/// <param name="makeNointerReadable">When set to true, system memory copy of a texture is released.</param>
public static void UpdatePixels(this Texture2D texture2D, Color[] colorArray, int mipLevel = 0, bool updateMipmaps = false, bool makeNointerReadable = false)
{
if (colorArray == null || colorArray.Length != texture2D.width * texture2D.height)
{
LogUtility.LogError("Update pixels of Texture2D error: The color array is null or invalid.");
return;
}
texture2D.SetPixels(colorArray, mipLevel);
texture2D.Apply(updateMipmaps, makeNointerReadable);
}
/// <summary>
/// Update the pixels of Texture2D.
/// </summary>
/// <param name="texture2D">Base Texture2D.</param>
/// <param name="colorArray">Color array for pixels.</param>
/// <param name="mipLevel">The mip level of the texture to write to.</param>
/// <param name="updateMipmaps">When set to true, mipmap levels are recalculated.</param>
/// <param name="makeNointerReadable">When set to true, system memory copy of a texture is released.</param>
public static void UpdatePixels(this Texture2D texture2D, Color[,] colorArray, int mipLevel = 0, bool updateMipmaps = false, bool makeNointerReadable = false)
{
if (colorArray == null || colorArray.Length != texture2D.width * texture2D.height)
{
LogUtility.LogError("Update pixels of Texture2D error: The color array is null or invalid.");
return;
}
var colors = ArrayConverter.ToOneDimention(colorArray);
UpdatePixels(texture2D, colors, mipLevel, updateMipmaps, makeNointerReadable);
}
/// <summary>
/// Update the pixels of Texture2D.
/// </summary>
/// <param name="texture2D">Base Texture2D.</param>
/// <param name="colorArray">Color array for pixels.</param>
/// <param name="mipLevel">The mip level of the texture to write to.</param>
/// <param name="updateMipmaps">When set to true, mipmap levels are recalculated.</param>
/// <param name="makeNointerReadable">When set to true, system memory copy of a texture is released.</param>
public static void UpdatePixels(this Texture2D texture2D, Color32[] colorArray, int mipLevel = 0, bool updateMipmaps = false, bool makeNointerReadable = false)
{
if (colorArray == null || colorArray.Length != texture2D.width * texture2D.height)
{
LogUtility.LogError("Update pixels of Texture2D error: The color array is null or invalid.");
return;
}
texture2D.SetPixels32(colorArray, mipLevel);
texture2D.Apply(updateMipmaps, makeNointerReadable);
}
/// <summary>
/// Update the pixels of Texture2D.
/// </summary>
/// <param name="texture2D">Base Texture2D.</param>
/// <param name="colorArray">Color array for pixels.</param>
/// <param name="mipLevel">The mip level of the texture to write to.</param>
/// <param name="updateMipmaps">When set to true, mipmap levels are recalculated.</param>
/// <param name="makeNointerReadable">When set to true, system memory copy of a texture is released.</param>
public static void UpdatePixels(this Texture2D texture2D, Color32[,] colorArray, int mipLevel = 0, bool updateMipmaps = false, bool makeNointerReadable = false)
{
if (colorArray == null || colorArray.Length != texture2D.width * texture2D.height)
{
LogUtility.LogError("Update pixels of Texture2D error: The color array is null or invalid.");
return;
}
var colors = ArrayConverter.ToOneDimention(colorArray);
UpdatePixels(texture2D, colors, mipLevel, updateMipmaps, makeNointerReadable);
}
#endregion
}
} | 50.009434 | 168 | 0.590643 | [
"Apache-2.0"
] | mogoson/CodeProject | UCommon/Extension/Texture2DExtention.cs | 5,304 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
/* Code built upon https://github.com/IsaiahKelly/quake3-movement-for-unity/blob/master/Quake3Movement/Scripts/Q3PlayerController.cs */
[Serializable]
public struct MovementData
{
public CharacterController m_Character;
public Camera m_Camera;
public bool Jump;
public float m_Friction;
public float m_Gravity;
public float m_JumpForce;
[Tooltip("How precise air control is")]
public float m_AirControl;
[Tooltip("Automatically jump when holding jump button")]
public bool m_AutoBunnyHop;
public Vector3 m_MoveDirectionNorm;
public Vector3 m_PlayerVelocity;
public float Speed { get { return m_Character.velocity.magnitude; } }
}
[System.Serializable]
public struct MovementSettings
{
public float MaxSpeed;
public float Deceleration;
public float Acceleration;
}
[RequireComponent(typeof(CharacterController))]
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
public MovementData m_Data;
public MovementSettings m_GroundSettings;
public MovementSettings m_AirSettings;
public MovementSettings m_StrafeSettings;
// Used to queue the next jump just before hitting the ground.
private bool m_JumpQueued = false;
// Used to display real time friction values.
private float m_PlayerFriction = 0;
private Vector3 m_MoveInput;
private Transform m_Tran;
private Transform m_CamTran;
private void Start()
{
m_Tran = transform;
m_Data.m_Character = GetComponent<CharacterController>();
if (!m_Data.m_Camera)
m_Data.m_Camera = Camera.main;
m_CamTran = m_Data.m_Camera.transform;
Cursor.lockState = CursorLockMode.Locked;
}
public void Move(InputAction.CallbackContext p_Context)
{
m_MoveInput = new Vector3(p_Context.ReadValue<Vector2>().x, 0, p_Context.ReadValue<Vector2>().y);
}
public void Jump(InputAction.CallbackContext p_context)
{
m_Data.Jump = p_context.performed;
}
private void Update()
{
QueueJump();
// Set movement state.
if (m_Data.m_Character.isGrounded)
{
GroundMove();
}
else
{
AirMove();
}
// Move the character.
m_Data.m_Character.Move(m_Data.m_PlayerVelocity * Time.deltaTime);
}
// Queues the next jump.
private void QueueJump()
{
if (m_Data.m_AutoBunnyHop)
{
m_JumpQueued = m_Data.Jump;
return;
}
if (m_Data.Jump && !m_JumpQueued)
{
m_JumpQueued = true;
}
if (!m_Data.Jump)
{
m_JumpQueued = false;
}
}
// Handle air movement.
private void AirMove()
{
float accel;
var wishdir = new Vector3(m_MoveInput.x, 0, m_MoveInput.z);
wishdir = m_Tran.TransformDirection(wishdir);
float wishspeed = wishdir.magnitude;
wishspeed *= m_AirSettings.MaxSpeed;
wishdir.Normalize();
m_Data.m_MoveDirectionNorm = wishdir;
// CPM Air control.
float wishspeed2 = wishspeed;
if (Vector3.Dot(m_Data.m_PlayerVelocity, wishdir) < 0)
{
accel = m_AirSettings.Deceleration;
}
else
{
accel = m_AirSettings.Acceleration;
}
// If the player is ONLY strafing left or right
if (m_MoveInput.z == 0 && m_MoveInput.x != 0)
{
if (wishspeed > m_StrafeSettings.MaxSpeed)
{
wishspeed = m_StrafeSettings.MaxSpeed;
}
accel = m_StrafeSettings.Acceleration;
}
Accelerate(wishdir, wishspeed, accel);
if (m_Data.m_AirControl > 0)
{
AirControl(wishdir, wishspeed2);
}
// Apply gravity
m_Data.m_PlayerVelocity.y -= m_Data.m_Gravity * Time.deltaTime;
}
// Air control occurs when the player is in the air, it allows players to move side
// to side much faster rather than being 'sluggish' when it comes to cornering.
private void AirControl(Vector3 targetDir, float targetSpeed)
{
// Only control air movement when moving forward or backward.
if (Mathf.Abs(m_MoveInput.z) < 0.001 || Mathf.Abs(targetSpeed) < 0.001)
{
return;
}
float zSpeed = m_Data.m_PlayerVelocity.y;
m_Data.m_PlayerVelocity.y = 0;
/* Next two lines are equivalent to idTech's VectorNormalize() */
float speed = m_Data.m_PlayerVelocity.magnitude;
m_Data.m_PlayerVelocity.Normalize();
float dot = Vector3.Dot(m_Data.m_PlayerVelocity, targetDir);
float k = 32;
k *= m_Data.m_AirControl * dot * dot * Time.deltaTime;
// Change direction while slowing down.
if (dot > 0)
{
m_Data.m_PlayerVelocity.x *= speed + targetDir.x * k;
m_Data.m_PlayerVelocity.y *= speed + targetDir.y * k;
m_Data.m_PlayerVelocity.z *= speed + targetDir.z * k;
m_Data.m_PlayerVelocity.Normalize();
m_Data.m_MoveDirectionNorm = m_Data.m_PlayerVelocity;
}
m_Data.m_PlayerVelocity.x *= speed;
m_Data.m_PlayerVelocity.y = zSpeed; // Note this line
m_Data.m_PlayerVelocity.z *= speed;
}
// Handle ground movement.
private void GroundMove()
{
// Do not apply friction if the player is queueing up the next jump
if (!m_JumpQueued)
{
ApplyFriction(1.0f);
}
else
{
ApplyFriction(0);
}
var wishdir = new Vector3(m_MoveInput.x, 0, m_MoveInput.z);
wishdir = m_Tran.TransformDirection(wishdir);
wishdir.Normalize();
m_Data.m_MoveDirectionNorm = wishdir;
var wishspeed = wishdir.magnitude;
wishspeed *= m_GroundSettings.MaxSpeed;
Accelerate(wishdir, wishspeed, m_GroundSettings.Acceleration);
// Reset the gravity velocity
m_Data.m_PlayerVelocity.y = -m_Data.m_Gravity * Time.deltaTime;
if (m_JumpQueued)
{
m_Data.m_PlayerVelocity.y = m_Data.m_JumpForce;
m_JumpQueued = false;
}
}
private void ApplyFriction(float t)
{
// Equivalent to VectorCopy();
Vector3 vec = m_Data.m_PlayerVelocity;
vec.y = 0;
float speed = vec.magnitude;
float drop = 0;
// Only apply friction when grounded.
if (m_Data.m_Character.isGrounded)
{
float control = speed < m_GroundSettings.Deceleration ? m_GroundSettings.Deceleration : speed;
drop = control * m_Data.m_Friction * Time.deltaTime * t;
}
float newSpeed = speed - drop;
m_PlayerFriction = newSpeed;
if (newSpeed < 0)
{
newSpeed = 0;
}
if (speed > 0)
{
newSpeed /= speed;
}
m_Data.m_PlayerVelocity.x *= newSpeed;
// m_Data.playerVelocity.y *= newSpeed;
m_Data.m_PlayerVelocity.z *= newSpeed;
}
// Calculates acceleration based on desired speed and direction.
private void Accelerate(Vector3 targetDir, float targetSpeed, float accel)
{
float currentspeed = Vector3.Dot(m_Data.m_PlayerVelocity, targetDir);
float addspeed = targetSpeed - currentspeed;
if (addspeed <= 0)
{
return;
}
float accelspeed = accel * Time.deltaTime * targetSpeed;
if (accelspeed > addspeed)
{
accelspeed = addspeed;
}
m_Data.m_PlayerVelocity.x += accelspeed * targetDir.x;
m_Data.m_PlayerVelocity.z += accelspeed * targetDir.z;
}
}
| 25.251773 | 135 | 0.681225 | [
"MIT"
] | o92design/FzGameJam2021 | Lager25/Assets/Scripts/Player/Movement/src/PlayerMovement.cs | 7,123 | C# |
using System.Collections.Generic;
namespace UploadApp.Pages.Boards.Uploads
{
public partial class Report
{
}
}
| 11.666667 | 40 | 0.635714 | [
"MIT"
] | KyusangCho/UploadApp | UploadApp/Pages/Boards/Uploads/Report.razor.cs | 142 | C# |
using System;
using System.Threading.Tasks;
namespace NftUnity.Test.Extensions
{
public static class TaskExtensions
{
public static T CompletesIn<T>(this Task<T> task, TimeSpan interval)
{
var completedInTime = task.Wait(interval);
if (task.Exception != null)
{
throw task.Exception;
}
if (!completedInTime)
{
throw new TimeoutException();
}
return task.Result;
}
}
} | 22.333333 | 76 | 0.522388 | [
"Apache-2.0"
] | usetech-llc/nft_unity | src/NftUnity.Test/Extensions/TaskExtensions.cs | 538 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.