content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rekognition-2016-06-27.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.Rekognition.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Rekognition.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for FaceSearchSettings Object /// </summary> public class FaceSearchSettingsUnmarshaller : IUnmarshaller<FaceSearchSettings, XmlUnmarshallerContext>, IUnmarshaller<FaceSearchSettings, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> FaceSearchSettings IUnmarshaller<FaceSearchSettings, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public FaceSearchSettings Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; FaceSearchSettings unmarshalledObject = new FaceSearchSettings(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("CollectionId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.CollectionId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("FaceMatchThreshold", targetDepth)) { var unmarshaller = FloatUnmarshaller.Instance; unmarshalledObject.FaceMatchThreshold = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static FaceSearchSettingsUnmarshaller _instance = new FaceSearchSettingsUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static FaceSearchSettingsUnmarshaller Instance { get { return _instance; } } } }
35.234694
167
0.637996
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/Rekognition/Generated/Model/Internal/MarshallTransformations/FaceSearchSettingsUnmarshaller.cs
3,453
C#
using RemindManager.Models.Frequencies; using System.Collections.Generic; using Xamarin.Forms; namespace RemindManager.Models.Interfaces { /// <summary> /// Интерфейс напоминания /// </summary> public interface IReminder { /// <summary> /// Идентификатор /// </summary> uint Id { get; set; } /// <summary> /// Наименование /// </summary> string Name { get; set; } /// <summary> /// Описание /// </summary> string Description { get; set; } /// <summary> /// Частота события вида <see cref="FrequencySelectionModel"/> /// </summary> FrequencySelectionModel Frequency { get; set; } /// <summary> /// Данные частоты напоминания /// </summary> IFrequencyData FrequencyData { get; set; } /// <summary> /// Список чисел, которые указывают, /// за сколько минут нужно напомнить /// </summary> List<byte> RemindBefore { get; set; } /// <summary> /// Шаблон контрола выбора времени /// </summary> public ControlTemplate TimePickerTemplate { get; } } }
24.632653
70
0.540182
[ "MIT" ]
AidarGiza/RemindManager
RemindManager/RemindManager/Models/Interfaces/IReminder.cs
1,386
C#
using System; using System.Reflection; using Xunit; using Xunit.Abstractions; namespace Dynamic.Tests { public class LoadUnsafeAssembly { private ITestOutputHelper _output; public LoadUnsafeAssembly(ITestOutputHelper output) { _output = output; } [Fact] public void InvokeAssemblyMethod() { string filePath = @"C:\Users\nickc\Dropbox\dynamic\dynamic\bin\Release\Dynamic.dll"; Assembly unsafeAssembly = Assembly.LoadFile(filePath); Type unsafeType = unsafeAssembly.GetType("Dynamic.LoadMeLater"); object unsafeTypeInstance = Activator.CreateInstance(unsafeType); var result = unsafeType.InvokeMember("InvokeMeLater", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, unsafeTypeInstance, null).ToString(); _output.WriteLine(result); } [Fact] public void InvokeAssemblyMethodDynamic() { string filePath = @"C:\Users\nickc\Dropbox\dynamic\dynamic\bin\Release\Dynamic.dll"; Assembly unsafeAssembly = Assembly.LoadFile(filePath); Type unsafeType = unsafeAssembly.GetType("Dynamic.LoadMeLater"); dynamic unsafeTypeInstance = Activator.CreateInstance(unsafeType); var result = unsafeTypeInstance.InvokeMeLater(); _output.WriteLine(result); } } }
35.116279
96
0.628477
[ "MIT" ]
heynickc/DynamicType
Dynamic.Tests/LoadUnsafeAssembly.cs
1,512
C#
// // System.ComponentModel.ListSortDirection.cs // // Author: // Rodrigo Moya (rodrigo@ximian.com) // // (C) Rodrigo Moya, 2002 // // // 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. // namespace System.ComponentModel { /// <summary> /// Specifies the direction of a sort operation. /// </summary> public enum ListSortDirection { Ascending = 0, Descending = 1 } }
34.292683
73
0.74111
[ "Apache-2.0" ]
121468615/mono
mcs/class/System/System.ComponentModel/ListSortDirection.cs
1,406
C#
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.Shapes; namespace Towers { public partial class WindowChooseNumber : Window { public int result { get; private set; } const int numberPixels = 40; int maxNumber; public WindowChooseNumber(int maxNumber) { InitializeComponent(); this.maxNumber = maxNumber; int width = (int)Math.Ceiling(Math.Sqrt(maxNumber)); int height = (int)Math.Ceiling((double)maxNumber / width); for (int i = 0; i <= height; i ++) { gridMain.RowDefinitions.Add(new RowDefinition()); } for (int i = 0; i < width; i++) { gridMain.ColumnDefinitions.Add(new ColumnDefinition()); } int temp = 0; while (temp < maxNumber) { Button buttonNumber = new Button(); buttonNumber.Click += ReturnValue; buttonNumber.Content = (temp+1).ToString(); Grid.SetColumn(buttonNumber, temp% width); Grid.SetRow(buttonNumber, temp/ width); gridMain.Children.Add(buttonNumber); temp++; } Button buttonEmpty = new Button(); buttonEmpty.Click += ReturnValue; Grid.SetColumnSpan(buttonEmpty, width); Grid.SetColumn(buttonEmpty, 0); Grid.SetRow(buttonEmpty, height + 1); gridMain.Children.Add(buttonEmpty); result = 0; this.Height = numberPixels*(height+1); this.Width = numberPixels * width; this.PreviewKeyDown += new KeyEventHandler(NumberIsPressed); Point point = Mouse.GetPosition(Application.Current.MainWindow); this.Top = point.Y+ Application.Current.MainWindow.Top+ SystemParameters.WindowCaptionHeight; this.Left = point.X + Application.Current.MainWindow.Left; } private void NumberIsPressed(object sender, KeyEventArgs e) { if (e.Key == Key.D1 || e.Key == Key.NumPad1) { result = 1; } else if (e.Key == Key.D2 || e.Key == Key.NumPad2) { result = 2; } else if (e.Key == Key.D3 || e.Key == Key.NumPad3) { result = 3; } else if (e.Key == Key.D4 || e.Key == Key.NumPad4) { result = 4; } else if (e.Key == Key.D5 || e.Key == Key.NumPad5) { result = 5; } else if (e.Key == Key.D6 || e.Key == Key.NumPad6) { result = 6; } else if (e.Key == Key.D7 || e.Key == Key.NumPad7) { result = 7; } else if (e.Key == Key.D8 || e.Key == Key.NumPad8) { result = 8; } else if (e.Key == Key.D9 || e.Key == Key.NumPad9) { result = 9; } else if (e.Key == Key.Escape) { result = 0; Close(); } if (result > maxNumber) { result = maxNumber; } Close(); } private void ReturnValue(object sender, RoutedEventArgs e) { if (((Button)sender).Content != null) result = int.Parse(((Button)sender).Content.ToString()); else result = 0; Close(); } } }
30.945313
105
0.480939
[ "MIT" ]
Kaszub09/Pyramids-Solver-and-Generator
Pyramids/WindowChooseNumber.xaml.cs
3,963
C#
using UnityEngine; public class Entity : MonoBehaviour { [SerializeField] protected LayerMask obstacleLayerMask; protected Animator animator; protected Vector3 directionVector; void Awake() { animator = GetComponent<Animator>(); } void OnEnable() { animator.GetBehaviour<DeathAnimator>().target = gameObject; } public virtual Vector3 GetDirectionVector() { return directionVector; } protected virtual void Dying() { enabled = false; GetComponent<Collider2D>().enabled = false; } protected virtual void Dead() { Destroy(gameObject); } }
19.193548
63
0.705882
[ "MIT" ]
mpmitchell/Honours-Project
Assets/Game/Scripts/Entities/Entity.cs
597
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; namespace CellopointAddin.Web.Models.Account { public class LoginViewModel { [Required] public string UsernameOrEmailAddress { get; set; } [Required] [DisableAuditing] public string Password { get; set; } public bool RememberMe { get; set; } } }
20.833333
58
0.650667
[ "MIT" ]
chuncui0207/cellopoint-add-in
service/src/CellopointAddin.Web.Mvc/Models/Account/LoginViewModel.cs
377
C#
using Newtonsoft.Json; using SQLiteDatabase; using System; using System.Collections.Generic; using System.Linq; public class SQLiteTable<T> where T : new() { readonly SQLiteDB _db; readonly string _tableIdentifier; readonly SQLiteConfiguration _config; readonly System.Reflection.PropertyInfo[] _itemProperties; readonly System.Reflection.PropertyInfo _primaryKeyProperty; public SQLiteTable(SQLiteDB db, string tableIdentifier, SQLiteConfiguration config) { _db = db; _tableIdentifier = tableIdentifier; _config = config; _itemProperties = typeof(T).GetProperties(); foreach (var property in _itemProperties) { if (property.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length != 0) { _primaryKeyProperty = property; break; } } } public IEnumerable<T> GetItems() { return AggregateDbReaderItems(_db.GetAllData(_tableIdentifier)); } //public T GetItem(string primaryKeyValue) //{ //} public IEnumerable<T> Query(string query) { return AggregateDbReaderItems(_db.Select(query)); } //public IEnumerable<T> Query(Expression<Func<T, bool>> queryPredicate) //{ //} public bool Insert(T item) { bool successful = false; try { List<SQLiteDB.DB_DataPair> dataPairList = new List<SQLiteDB.DB_DataPair>(); SQLiteDB.DB_DataPair data = new SQLiteDB.DB_DataPair(); LogHelper.Log(LoggingLevel.TRACE, _config, "Creating new " + typeof(T).Name); foreach (var property in _itemProperties) { if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0) { // If the property is marked as required and is null, throw an exception if (property.GetCustomAttributes(typeof(RequiredAttribute), false).Length != 0 && //!property.PropertyType.IsValueType && property.GetValue(item) == null) { throw new RequiredFieldException(property.Name); } string fieldName = property.Name; var fieldNameAttribute = property.GetCustomAttributes(typeof(FieldNameAttribute), false).FirstOrDefault() as FieldNameAttribute; if (fieldNameAttribute != null) { // cleanse by replacing all spaces with underscores // TODO rip out all symbols and other invalid characters fieldName = fieldNameAttribute.FieldName.Replace(" ", "_"); } data.fieldName = fieldName; data.value = ConvertValueToString(item, property); dataPairList.Add(data); LogHelper.Log(LoggingLevel.TRACE, _config, "Added {" + data.fieldName + ", " + data.value + "} to object."); } } int changeCount = _db.Insert(_tableIdentifier, dataPairList); LogHelper.Log(LoggingLevel.LOG, _config, changeCount + " change(s) on insert to " + _tableIdentifier); if (changeCount > 0) { successful = true; } } catch (Exception ex) { LogHelper.Log(LoggingLevel.ERROR, _config, ex.ToString()); } return successful; } public bool Update(T item) { bool successful = false; List<SQLiteDB.DB_DataPair> dataPairList = new List<SQLiteDB.DB_DataPair>(); SQLiteDB.DB_DataPair data = new SQLiteDB.DB_DataPair(); SQLiteDB.DB_ConditionPair condition = new SQLiteDB.DB_ConditionPair(); foreach (var property in _itemProperties) { // if the property isn't being ignored if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0) { // if isn't primary key if (property.GetCustomAttributes(typeof(PrimaryKeyAttribute), false).Length == 0) { data.fieldName = property.Name; data.value = ConvertValueToString(item, property); dataPairList.Add(data); } // else is, it can't be updated but instead used for finding record to update else { condition.fieldName = property.Name; condition.value = ConvertValueToString(item, property); condition.condition = SQLiteDB.DB_Condition.EQUAL_TO; } } } if (_db.Update(_tableIdentifier, dataPairList, condition) > 0) { successful = true; } return successful; } public bool Delete(string primaryKeyValue) { bool successful = false; SQLiteDB.DB_ConditionPair condition = new SQLiteDB.DB_ConditionPair(); condition.fieldName = _primaryKeyProperty.Name; condition.value = primaryKeyValue; condition.condition = SQLiteDB.DB_Condition.EQUAL_TO; if (_db.DeleteRow(_tableIdentifier, condition) > 0) { successful = true; } return successful; } public void Truncate() { _db.ClearTable(_tableIdentifier); } private static string ConvertValueToString(T item, System.Reflection.PropertyInfo property) { string strValue; if (property.PropertyType.Equals(typeof(double)) || property.PropertyType.Equals(typeof(float)) || property.PropertyType.Equals(typeof(int)) || property.PropertyType.Equals(typeof(long)) || property.PropertyType.Equals(typeof(short)) || property.PropertyType.Equals(typeof(string))) { strValue = property.GetValue(item).ToString(); } else { strValue = JsonConvert.SerializeObject(property.GetValue(item)); } return strValue; } private List<T> AggregateDbReaderItems(DBReader reader) { List<T> items = new List<T>(); while (reader != null && reader.Read()) { T item = new T(); foreach (var property in _itemProperties) { // if the property isn't being ignored if (property.GetCustomAttributes(typeof(ColumnIgnoreAttribute), false).Length == 0) { string propertyName = property.Name; var fieldNameAttribute = property.GetCustomAttributes(typeof(FieldNameAttribute), false).FirstOrDefault() as FieldNameAttribute; if (fieldNameAttribute != null) { // cleanse by replacing all spaces with underscores // TODO rip out all symbols and other invalid characters propertyName = fieldNameAttribute.FieldName.Replace(" ", "_"); } LogHelper.Log(LoggingLevel.TRACE, _config, "Finding key " + propertyName); if (property.PropertyType.Equals(typeof(double))) { property.SetValue(item, reader.GetDoubleValue(propertyName)); } else if (property.PropertyType.Equals(typeof(float))) { property.SetValue(item, reader.GetFloatValue(propertyName)); } else if (property.PropertyType.Equals(typeof(int))) { property.SetValue(item, reader.GetIntValue(propertyName)); } else if (property.PropertyType.Equals(typeof(long))) { property.SetValue(item, reader.GetLongValue(propertyName)); } else if (property.PropertyType.Equals(typeof(short))) { property.SetValue(item, reader.GetShortValue(propertyName)); } else if (property.PropertyType.Equals(typeof(string))) { property.SetValue(item, reader.GetStringValue(propertyName)); } else { // was serialized object deserializedValue = JsonConvert.DeserializeObject(reader.GetStringValue(propertyName), property.PropertyType); property.SetValue(item, deserializedValue); } } } items.Add(item); } return items; } }
35.12549
148
0.550631
[ "MIT" ]
chriszumberge/SQLiteORM.Net
SQLiteORM.Net/Assets/SQLiteORM.Net/Source/SQLiteTable.cs
8,959
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Vpc.V20170312.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class ModifyCustomerGatewayAttributeRequest : AbstractModel { /// <summary> /// 对端网关ID,例如:cgw-2wqq41m9,可通过DescribeCustomerGateways接口查询对端网关。 /// </summary> [JsonProperty("CustomerGatewayId")] public string CustomerGatewayId{ get; set; } /// <summary> /// 对端网关名称,可任意命名,但不得超过60个字符。 /// </summary> [JsonProperty("CustomerGatewayName")] public string CustomerGatewayName{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> internal override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "CustomerGatewayId", this.CustomerGatewayId); this.SetParamSimple(map, prefix + "CustomerGatewayName", this.CustomerGatewayName); } } }
32.862745
95
0.668854
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Vpc/V20170312/Models/ModifyCustomerGatewayAttributeRequest.cs
1,762
C#
namespace Akade.IndexedSet.Tests.Samples.Appointments; internal static class DateOnlyExtensions { public static DateTime WithDayTime(this DateOnly dateOnly, int hours, int minutes) { return new DateTime(dateOnly.Year, dateOnly.Month, dateOnly.Day, hours, minutes, 0); } }
29.4
92
0.748299
[ "MIT" ]
akade/Akade.IndexedSet
Akade.IndexedSet.Tests/Samples/Appointments/DateOnlyExtensions.cs
296
C#
// Copyright (c) 2017 Jan Pluskal, Matus Dobrotka // //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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Netfox.SnooperWebmails.Tests")] [assembly: Guid("7ab53449-ddc5-48a2-9723-0eef472ceabc")]
40.9
74
0.772616
[ "Apache-2.0" ]
mvondracek/NetfoxDetective
Framework/Snoopers/SnooperWebmails.Tests/Properties/AssemblyInfo.cs
820
C#
using System; namespace Septem.Notifications.Core.Exceptions; internal class ServiceNotImplementedException<T> : Exception { public ServiceNotImplementedException() : base($"{typeof(T).FullName} not implemented") { } }
21.272727
91
0.747863
[ "MIT" ]
rasimismatulin/Septem.Utils
src/Septem.Notifications.Core/Exceptions/ServiceNotImplementedException.cs
236
C#
using System; namespace DepartmentStoreOne.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
19.636364
70
0.680556
[ "Apache-2.0" ]
takemurakimio/department-store
DepartmentStoreOne/Models/ErrorViewModel.cs
216
C#
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; namespace PvrtcTest { public sealed class DirectBitmap : IDisposable { public DirectBitmap(int width, int height) { Width = width; Height = height; Bits = new byte[width * height * 4]; m_bitsHandle = GCHandle.Alloc(Bits, GCHandleType.Pinned); Bitmap = new Bitmap(Width, Height, Stride, PixelFormat.Format32bppArgb, m_bitsHandle.AddrOfPinnedObject()); } ~DirectBitmap() { Dispose(false); } public void SetPixel(int x, int y, Color color) { int index = x + (y * Width); unchecked { uint value = (uint)color.ToArgb(); Bits[index + 0] = (byte)(value >> 0); Bits[index + 1] = (byte)(value >> 8); Bits[index + 2] = (byte)(value >> 16); Bits[index + 3] = (byte)(value >> 24); } } public Color GetPixel(int x, int y) { int index = x + (y * Width); uint col = BitConverter.ToUInt32(Bits, index); return Color.FromArgb(unchecked((int)col)); } public void Dispose() { GC.SuppressFinalize(this); Dispose(true); } private void Dispose(bool disposing) { if (!m_disposed) { Bitmap.Dispose(); m_bitsHandle.Free(); m_disposed = true; } } public int Height { get; } public int Width { get; } public int Stride => Width * 4; public Bitmap Bitmap { get; } public byte[] Bits { get; } public IntPtr BitsPtr => m_bitsHandle.AddrOfPinnedObject(); private readonly GCHandle m_bitsHandle; private bool m_disposed; } }
21.774648
110
0.64489
[ "MIT" ]
AssetRipper/TextureDecoder
PvrtcTest/DirectBitmap.cs
1,546
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace PacketViewer.Heuristic { class C_REQUEST_USER_PAPERDOLL_INFO : AbstractPacketHeuristic { public static ushort PossibleOpcode; public static string Name = ""; public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) return; if (message.Payload.Count < 6) return; Reader.Skip(2); try { Name = Reader.ReadTeraString(); } catch { return; } PossibleOpcode = message.OpCode; } public static void Confirm() { OpcodeFinder.Instance.SetOpcode(PossibleOpcode, OpcodeEnum.C_REQUEST_USER_PAPERDOLL_INFO); } } }
26.25
102
0.612698
[ "MIT" ]
Fenixk/ShinraMeter
PacketViewer.Core/Heuristic/C_REQUEST_USER_PAPERDOLL_INFO.cs
947
C#
using System.Collections.Generic; using SheepIt.Api.Model.Components; using SheepIt.Api.Model.Packages; namespace SheepIt.Api.Model.DeploymentProcesses { public class DeploymentProcess { // identity public int Id { get; set; } // relations public int ComponentId { get; set; } public virtual Component Component { get; set; } public virtual List<Package> Packages { get; set; } // data public byte[] File { get; set; } } }
22.708333
59
0.581651
[ "MIT" ]
sheepit/sheepit
source/SheepIt.Api/Model/DeploymentProcesses/DeploymentProcess.cs
545
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Screens; using osu.Game.Graphics.Containers; namespace osu.Game.Screens { public class OsuScreenStack : ScreenStack { [Cached] private BackgroundScreenStack backgroundScreenStack; private readonly ParallaxContainer parallaxContainer; protected float ParallaxAmount => parallaxContainer.ParallaxAmount; public OsuScreenStack() { InternalChild = parallaxContainer = new ParallaxContainer { RelativeSizeAxes = Axes.Both, Child = backgroundScreenStack = new BackgroundScreenStack { RelativeSizeAxes = Axes.Both }, }; ScreenPushed += screenPushed; ScreenExited += ScreenChanged; } public void PushSynchronously(OsuScreen screen) { LoadComponent(screen); Push(screen); } private void screenPushed(IScreen prev, IScreen next) { if (LoadState < LoadState.Ready) { // dependencies must be present to stay in a sane state. // this is generally only ever hit by test scenes. Schedule(() => screenPushed(prev, next)); return; } // create dependencies synchronously to ensure leases are in a sane state. ((OsuScreen)next).CreateLeasedDependencies((prev as OsuScreen)?.Dependencies ?? Dependencies); ScreenChanged(prev, next); } protected virtual void ScreenChanged(IScreen prev, IScreen next) { setParallax(next); } private void setParallax(IScreen next) => parallaxContainer.ParallaxAmount = ParallaxContainer.DEFAULT_PARALLAX_AMOUNT * (((IOsuScreen)next)?.BackgroundParallaxAmount ?? 1.0f); } }
32.363636
147
0.608146
[ "MIT" ]
peppy/osu-new
osu.Game/Screens/OsuScreenStack.cs
2,071
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace SimpleCqrs { public class AssemblyTypeCatalog : ITypeCatalog { private readonly IEnumerable<Type> loadedTypes; public AssemblyTypeCatalog(IEnumerable<Assembly> assemblies) { loadedTypes = LoadTypes(assemblies); } public Type[] LoadedTypes { get { return loadedTypes.ToArray(); } } public Type[] GetDerivedTypes(Type type) { return ( from derivedType in loadedTypes where type != derivedType where type.IsAssignableFrom(derivedType) select derivedType).ToArray(); } public Type[] GetDerivedTypes<T>() { return GetDerivedTypes(typeof(T)); } public Type[] GetGenericInterfaceImplementations(Type type) { return (from derivedType in loadedTypes from interfaceType in derivedType.GetInterfaces() where interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == type select derivedType).Distinct().ToArray(); } public Type[] GetInterfaceImplementations(Type type) { return (from derivedType in loadedTypes where !derivedType.IsInterface from interfaceType in derivedType.GetInterfaces() where interfaceType == type select derivedType).Distinct().ToArray(); } public Type[] GetInterfaceImplementations<T>() { return GetInterfaceImplementations(typeof(T)); } private static IEnumerable<Type> LoadTypes(IEnumerable<Assembly> assemblies) { var loadedTypes = new List<Type>(); foreach(var assembly in assemblies) { try { var types = assembly.GetTypes(); loadedTypes.AddRange(types); } catch(ReflectionTypeLoadException exception) { exception.LoaderExceptions .Select(e => e.Message) .Distinct().ToList() .ForEach(message => Debug.WriteLine(message)); } } return loadedTypes; } } }
32.345679
106
0.521374
[ "Unlicense", "MIT" ]
AdnanAsotic/SimpleCQRS
src/SimpleCqrs/AssemblyTypeCatalog.cs
2,622
C#
using System; using PostSharp.Aspects; namespace PostSharpWeaving { [Serializable] public class ConsoleWriterAspect : OnMethodBoundaryAspect { public override void OnEntry(MethodExecutionArgs args) { base.OnEntry(args); Console.WriteLine(args.Method.Name); } } }
20.352941
63
0.618497
[ "Apache-2.0" ]
weeniearms/codeweaving
src/PostSharpWeaving/PostSharpWeaving/ConsoleWriterAspect.cs
348
C#
namespace DataAccess.UnitTests.Expressions { using System; using System.Linq.Expressions; using System.Reflection; using Crest.DataAccess; using Crest.DataAccess.Expressions; using FluentAssertions; using NSubstitute; using Xunit; public class MappingCacheTests { private static readonly PropertyInfo ServiceObjectProperty = typeof(ServiceObject).GetProperty(nameof(ServiceObject.Property)); private readonly Lazy<MappingCache> cache; private readonly IMappingInfoFactory factory; private MappingCacheTests() { this.factory = Substitute.For<IMappingInfoFactory>(); this.cache = new Lazy<MappingCache>( () => new MappingCache(new[] { this.factory })); } private MappingCache Cache => this.cache.Value; public sealed class TryCreateMemberAccess : MappingCacheTests { [Fact] public void ShouldReturnAnExpressionForAccessingTheMappedProperty() { this.SetMappingInfo(CreateMapping()); LambdaExpression result = this.Cache.CreateMemberAccess( typeof(DataAccessObject), ServiceObjectProperty, x => x); result.Body.Should().BeAssignableTo<MemberExpression>() .Which.Member.Name.Should().Be(nameof(DataAccessObject.DbField)); } [Fact] public void ShouldThrowForUnknownProperties() { this.SetMappingInfo(Expression.Empty()); Action action = () => this.Cache.CreateMemberAccess( typeof(DataAccessObject), ServiceObjectProperty, x => x); action.Should().Throw<InvalidOperationException>() .WithMessage("*parameter*"); } [Fact] public void ShouldThrowForUnknownSourceTypes() { Action action = () => this.Cache.CreateMemberAccess( typeof(UnknownClass), ServiceObjectProperty, x => x); action.Should().Throw<InvalidOperationException>() .WithMessage("*type*"); } [Fact] public void ShouldTransformTheExpression() { this.SetMappingInfo(CreateMapping()); LambdaExpression result = this.Cache.CreateMemberAccess( typeof(DataAccessObject), ServiceObjectProperty, _ => Expression.Constant("123")); result.Body.Should().BeAssignableTo<ConstantExpression>(); } private static Expression CreateMapping() { // Create an expression for: d.DbField = s.Property Expression<Func<DataAccessObject, string>> data = d => d.DbField; Expression<Func<ServiceObject, string>> service = s => s.Property; return Expression.Assign(data.Body, service.Body); } private void SetMappingInfo(Expression expression) { var mappingInfo = new MappingInfo( typeof(DataAccessObject), typeof(ServiceObject), expression); this.factory.GetMappingInformation().Returns(new[] { mappingInfo }); } } private sealed class DataAccessObject { public string DbField { get; set; } } private sealed class ServiceObject { public string Property { get; set; } } private sealed class UnknownClass { } } }
32.5
87
0.546806
[ "MIT" ]
samcragg/Crest
test/DataAccess.UnitTests/Expressions/MappingCacheTests.cs
3,835
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 sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// This is the response object from the DescribeFlowDefinition operation. /// </summary> public partial class DescribeFlowDefinitionResponse : AmazonWebServiceResponse { private DateTime? _creationTime; private string _failureReason; private string _flowDefinitionArn; private string _flowDefinitionName; private FlowDefinitionStatus _flowDefinitionStatus; private HumanLoopActivationConfig _humanLoopActivationConfig; private HumanLoopConfig _humanLoopConfig; private HumanLoopRequestSource _humanLoopRequestSource; private FlowDefinitionOutputConfig _outputConfig; private string _roleArn; /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The timestamp when the flow definition was created. /// </para> /// </summary> [AWSProperty(Required=true)] public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property FailureReason. /// <para> /// The reason your flow definition failed. /// </para> /// </summary> [AWSProperty(Max=1024)] public string FailureReason { get { return this._failureReason; } set { this._failureReason = value; } } // Check to see if FailureReason property is set internal bool IsSetFailureReason() { return this._failureReason != null; } /// <summary> /// Gets and sets the property FlowDefinitionArn. /// <para> /// The Amazon Resource Name (ARN) of the flow defintion. /// </para> /// </summary> [AWSProperty(Required=true, Max=1024)] public string FlowDefinitionArn { get { return this._flowDefinitionArn; } set { this._flowDefinitionArn = value; } } // Check to see if FlowDefinitionArn property is set internal bool IsSetFlowDefinitionArn() { return this._flowDefinitionArn != null; } /// <summary> /// Gets and sets the property FlowDefinitionName. /// <para> /// The Amazon Resource Name (ARN) of the flow definition. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=63)] public string FlowDefinitionName { get { return this._flowDefinitionName; } set { this._flowDefinitionName = value; } } // Check to see if FlowDefinitionName property is set internal bool IsSetFlowDefinitionName() { return this._flowDefinitionName != null; } /// <summary> /// Gets and sets the property FlowDefinitionStatus. /// <para> /// The status of the flow definition. Valid values are listed below. /// </para> /// </summary> [AWSProperty(Required=true)] public FlowDefinitionStatus FlowDefinitionStatus { get { return this._flowDefinitionStatus; } set { this._flowDefinitionStatus = value; } } // Check to see if FlowDefinitionStatus property is set internal bool IsSetFlowDefinitionStatus() { return this._flowDefinitionStatus != null; } /// <summary> /// Gets and sets the property HumanLoopActivationConfig. /// <para> /// An object containing information about what triggers a human review workflow. /// </para> /// </summary> public HumanLoopActivationConfig HumanLoopActivationConfig { get { return this._humanLoopActivationConfig; } set { this._humanLoopActivationConfig = value; } } // Check to see if HumanLoopActivationConfig property is set internal bool IsSetHumanLoopActivationConfig() { return this._humanLoopActivationConfig != null; } /// <summary> /// Gets and sets the property HumanLoopConfig. /// <para> /// An object containing information about who works on the task, the workforce task price, /// and other task details. /// </para> /// </summary> [AWSProperty(Required=true)] public HumanLoopConfig HumanLoopConfig { get { return this._humanLoopConfig; } set { this._humanLoopConfig = value; } } // Check to see if HumanLoopConfig property is set internal bool IsSetHumanLoopConfig() { return this._humanLoopConfig != null; } /// <summary> /// Gets and sets the property HumanLoopRequestSource. /// <para> /// Container for configuring the source of human task requests. Used to specify if Amazon /// Rekognition or Amazon Textract is used as an integration source. /// </para> /// </summary> public HumanLoopRequestSource HumanLoopRequestSource { get { return this._humanLoopRequestSource; } set { this._humanLoopRequestSource = value; } } // Check to see if HumanLoopRequestSource property is set internal bool IsSetHumanLoopRequestSource() { return this._humanLoopRequestSource != null; } /// <summary> /// Gets and sets the property OutputConfig. /// <para> /// An object containing information about the output file. /// </para> /// </summary> [AWSProperty(Required=true)] public FlowDefinitionOutputConfig OutputConfig { get { return this._outputConfig; } set { this._outputConfig = value; } } // Check to see if OutputConfig property is set internal bool IsSetOutputConfig() { return this._outputConfig != null; } /// <summary> /// Gets and sets the property RoleArn. /// <para> /// The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) execution /// role for the flow definition. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string RoleArn { get { return this._roleArn; } set { this._roleArn = value; } } // Check to see if RoleArn property is set internal bool IsSetRoleArn() { return this._roleArn != null; } } }
32.828452
107
0.597629
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/DescribeFlowDefinitionResponse.cs
7,846
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Rulesets.Catch.Objects.Drawables; namespace osu.Game.Rulesets.Catch.Skinning.Default { internal class FruitPiece : CatchHitObjectPiece { /// <summary> /// Because we're adding a border around the fruit, we need to scale down some. /// </summary> public const float RADIUS_ADJUST = 1.1f; public readonly Bindable<FruitVisualRepresentation> VisualRepresentation = new Bindable<FruitVisualRepresentation>(); protected override BorderPiece BorderPiece { get; } protected override HyperBorderPiece HyperBorderPiece { get; } public FruitPiece() { RelativeSizeAxes = Axes.Both; InternalChildren = new Drawable[] { new FruitPulpFormation { AccentColour = { BindTarget = AccentColour }, VisualRepresentation = { BindTarget = VisualRepresentation } }, BorderPiece = new BorderPiece(), HyperBorderPiece = new HyperBorderPiece() }; } protected override void LoadComplete() { base.LoadComplete(); var fruitState = (IHasFruitState)ObjectState; VisualRepresentation.BindTo(fruitState.VisualRepresentation); } } }
33.978723
126
0.604884
[ "MIT" ]
Aleeeesz/osu
osu.Game.Rulesets.Catch/Skinning/Default/FruitPiece.cs
1,551
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Example3 : MonoBehaviour { [SerializeField] private Transform m_p1; [SerializeField] private Transform m_p2; [SerializeField] private Transform m_nearPoint; [SerializeField] private Transform m_dragPoint; [SerializeField] private LineRenderer m_line; [SerializeField] private Text m_textValue; [SerializeField] private Toggle m_toggleIsLimit; void Update () { m_line.SetPosition(0, m_p1.position); m_line.SetPosition(1, m_p2.position); var lerp = 0.0f; var nearPos = SystemCalc.GetLineNearPoint(m_p1.position, m_p2.position, m_nearPoint.position, m_toggleIsLimit.isOn, out lerp); nearPos.z = -1; m_dragPoint.position = nearPos; m_textValue.text = lerp.ToString("F2"); } }
22.833333
128
0.770073
[ "MIT" ]
LightGive/SystemCalc
SystemCalc/Assets/LightGive/Utilities/SystemCalc/Examples/Scripts/Example3.cs
824
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace decode2017_MW08.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
37.361111
99
0.620818
[ "Unlicense" ]
shunsuke-kawai/decode2017_MW08
decode2017_MW08/decode2017_MW08/decode2017_MW08.UWP/App.xaml.cs
4,037
C#
using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using WebApiPractice.Api.Enumerations; using WebApiPractice.Api.ValidationFlow; using WebApiPractice.Api.ResponseStructure; using WebApiPractice.Api.ValidationFlow.Interfaces; namespace WebApiPractice.Api.Resources.Customers.Validations { public interface IGetCustomersValidationContract : IValidationContract { public string NextCursor { get; set; } public string Status { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } public class GetCustomersValidationContractHandler : IValidationContractHandler { public Task<List<ErrorMessage>> Handle(IValidationContract request, CancellationToken cancellationToken = default) { if (request is not IGetCustomersValidationContract contract) { var errorMessage = $"Validation Handler {nameof(GetCustomersValidationContractHandler)}" + $" could not find contract: {nameof(IGetCustomersValidationContract)}"; throw new Exception(errorMessage); } var messages = new List<ErrorMessage>(); if (!string.IsNullOrEmpty(contract.Status)) { try { var enumStatus = Enumeration.FromValue<CustomerStatus>(contract.Status); } catch (Exception) { messages.Add(new ErrorMessage( nameof(contract.Status), $"{nameof(contract.Status)} is not recognized. Allowed values are {CustomerStatus.Prospective.Value}, {CustomerStatus.Current.Value}, {CustomerStatus.NonActive.Value}") ); } } #region Length validations SharedValidationMethods.ValidateStringLength(contract.FirstName, 30, nameof(contract.FirstName), ref messages); SharedValidationMethods.ValidateStringLength(contract.LastName, 70, nameof(contract.LastName), ref messages); #endregion return Task.FromResult(messages); } public bool AbortOnFailure() => true; public Type GetValidationContractType() => typeof(IGetCustomersValidationContract); } }
40.457627
192
0.639296
[ "MIT" ]
is-aka-konor/WebApiPractice
WebApiPractice.Api/Resources/Customers/Validations/GetCustomersValidationContractHandler.cs
2,389
C#
// // Copyright (c) 2004-2019 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; namespace NLog.UnitTests.Filters { using System; using Xunit; public class WhenRepeatedTests : NLogTestBase { [Fact] public void WhenRepeatedIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); } [Fact] public void WhenRepeatedIgnoreDualTargetTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets> <target name='debug' type='Debug' layout='${message}' /> <target name='debug2' type='Debug' layout='${message}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug,debug2'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); AssertDebugCounter("debug2", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); AssertDebugCounter("debug2", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); AssertDebugCounter("debug2", 2); } [Fact] public void WhenRepeatedLogAfterTimeoutTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' includeFirst='True' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 0); logger.Debug("zzz"); AssertDebugCounter("debug", 0); logger.Debug("zzz"); AssertDebugCounter("debug", 0); } [Fact] public void WhenRepeatedTimeoutIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' timeoutSeconds='10' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); timeSource.AddToLocalTime(TimeSpan.FromSeconds(5)); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); timeSource.AddToLocalTime(TimeSpan.FromSeconds(10)); logger.Debug("zzz"); AssertDebugCounter("debug", 4); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } [Fact] public void WhenRepeatedTimeoutLogAfterTimeoutTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' includeFirst='True' timeoutSeconds='10' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 0); logger.Debug("zzz"); AssertDebugCounter("debug", 0); logger.Debug("zzz"); AssertDebugCounter("debug", 0); timeSource.AddToLocalTime(TimeSpan.FromSeconds(5)); logger.Debug("zzz"); AssertDebugCounter("debug", 0); logger.Debug("b"); AssertDebugCounter("debug", 0); timeSource.AddToLocalTime(TimeSpan.FromSeconds(10)); logger.Debug("zzz"); AssertDebugCounter("debug", 1); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } [Fact] public void WhenRepeatedDefaultFilterCountIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' defaultFilterCacheSize='5' timeoutSeconds='10' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); logger.Debug("c"); AssertDebugCounter("debug", 4); logger.Debug("d"); AssertDebugCounter("debug", 5); timeSource.AddToLocalTime(TimeSpan.FromSeconds(5)); logger.Debug("e"); AssertDebugCounter("debug", 6); logger.Debug("f"); AssertDebugCounter("debug", 7); logger.Debug("zzz"); AssertDebugCounter("debug", 7); timeSource.AddToLocalTime(TimeSpan.FromSeconds(10)); for (int i = 0; i < 10; ++i) { char charCount = (char)('g' + i); logger.Debug(charCount.ToString()); AssertDebugCounter("debug", 8 + i); } logger.Debug("zzz"); AssertDebugCounter("debug", 18); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } [Fact] public void WhenRepeatedMaxCacheSizeIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' maxFilterCacheSize='5' defaultFilterCacheSize='5' timeoutSeconds='10' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); logger.Debug("c"); AssertDebugCounter("debug", 4); logger.Debug("d"); AssertDebugCounter("debug", 5); timeSource.AddToLocalTime(TimeSpan.FromSeconds(5)); logger.Debug("e"); AssertDebugCounter("debug", 6); logger.Debug("f"); AssertDebugCounter("debug", 7); logger.Debug("zzz"); AssertDebugCounter("debug", 7); timeSource.AddToLocalTime(TimeSpan.FromSeconds(10)); for (int i = 0; i < 10; ++i) { char charCount = (char)('g' + i); logger.Debug(charCount.ToString()); AssertDebugCounter("debug", 8 + i); } logger.Debug("zzz"); AssertDebugCounter("debug", 18); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } [Fact] public void WhenRepeatedLevelIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Error("zzz"); AssertDebugCounter("debug", 3); logger.Error("zzz"); AssertDebugCounter("debug", 3); logger.Debug("zzz"); AssertDebugCounter("debug", 3); logger.Fatal("zzz"); AssertDebugCounter("debug", 4); } [Fact] public void WhenRepeatedMaxLengthIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' maxLength='16' optimizeBufferDefaultLength='16' /> </filters> </logger> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzzzzzzzzzzzzzzz"); AssertDebugCounter("debug", 2); logger.Debug("zzzzzzzzzzzzzzzz"); AssertDebugCounter("debug", 2); logger.Debug("zzzzzzzzzzzzzzzzzzzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); } [Fact] public void WhenRepeatedFilterCountPropertyNameIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}${event-properties:item=hits}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' timeoutSeconds='5' filterCountPropertyName='hits' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); AssertDebugLastMessage("debug", "zzz"); logger.Debug("zzz"); AssertDebugCounter("debug", 2); timeSource.AddToLocalTime(TimeSpan.FromSeconds(3)); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); timeSource.AddToLocalTime(TimeSpan.FromSeconds(3)); logger.Debug("zzz"); AssertDebugCounter("debug", 4); AssertDebugLastMessage("debug", "zzz2"); logger.Debug("zzz"); AssertDebugCounter("debug", 4); timeSource.AddToLocalTime(TimeSpan.FromSeconds(12)); logger.Debug("zzz"); AssertDebugCounter("debug", 5); AssertDebugLastMessage("debug", "zzz"); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } [Fact] public void WhenRepeatedFilterCountAppendFormatIgnoreTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message}${event-properties:item=hits}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug'> <filters defaultAction='log'> <whenRepeated layout='${message}' action='Ignore' timeoutSeconds='5' filterCountMessageAppendFormat=' (Hits: {0})' /> </filters> </logger> </rules> </nlog>"); var defaultTimeSource = Time.TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(DateTimeKind.Local); Time.TimeSource.Current = timeSource; ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugCounter("debug", 1); logger.Debug("zzz"); AssertDebugCounter("debug", 2); AssertDebugLastMessage("debug", "zzz"); logger.Debug("zzz"); AssertDebugCounter("debug", 2); timeSource.AddToLocalTime(TimeSpan.FromSeconds(3)); logger.Debug("zzz"); AssertDebugCounter("debug", 2); logger.Debug("b"); AssertDebugCounter("debug", 3); timeSource.AddToLocalTime(TimeSpan.FromSeconds(3)); logger.Debug("zzz"); AssertDebugCounter("debug", 4); AssertDebugLastMessage("debug", "zzz (Hits: 2)"); logger.Debug("zzz"); AssertDebugCounter("debug", 4); timeSource.AddToLocalTime(TimeSpan.FromSeconds(12)); logger.Debug("zzz"); AssertDebugCounter("debug", 5); AssertDebugLastMessage("debug", "zzz"); } finally { Time.TimeSource.Current = defaultTimeSource; // restore default time source } } } }
38.017208
146
0.514057
[ "BSD-3-Clause" ]
AchimStuy/NLog
tests/NLog.UnitTests/Filters/WhenRepeatedTests.cs
19,883
C#
using System; using System.Runtime.InteropServices; using System.Text; namespace DevelopersCommunity.PerformanceCounters { internal static class NativeMethods { internal const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; internal const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; internal const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; internal const uint FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; internal const uint FORMAT_MESSAGE_FROM_HMODULE = 0x00000800; internal const uint FORMAT_MESSAGE_FROM_STRING = 0x00000400; internal const uint ERROR_SUCCESS = 0; internal const uint PDH_NO_DATA = 0x800007D5; internal const uint PDH_MORE_DATA = 0x800007D2; internal const uint PDH_CALC_NEGATIVE_DENOMINATOR = 0x800007D6; internal const uint PDH_CALC_NEGATIVE_VALUE = 0x800007D8; internal const uint PDH_CALC_NEGATIVE_TIMEBASE = 0x800007D7; internal const uint PDH_INVALID_DATA = 0xC0000BC6; internal const uint PDH_NO_MORE_DATA = 0xC0000BCC; internal const uint PDH_ENTRY_NOT_IN_LOG_FILE = 0xC0000BCD; internal const uint PDH_CSTATUS_NO_OBJECT = 0xC0000BB8; internal const uint PDH_RETRY = 0x800007D4; internal const uint PDH_DIALOG_CANCELLED = 0x800007D9; internal const uint PDH_MAX_COUNTER_PATH = 2048; internal const uint PERF_DETAIL_NOVICE = 100; internal const uint PERF_DETAIL_ADVANCED = 200; internal const uint PERF_DETAIL_EXPERT = 300; internal const uint PERF_DETAIL_WIZARD = 400; internal const uint PDH_FMT_DOUBLE = 0x00000200; [StructLayout(LayoutKind.Explicit)] internal struct PDH_FMT_COUNTERVALUE { [FieldOffset(0)] public uint CStatus; [FieldOffset(8)] public int longValue; [FieldOffset(8)] public double doubleValue; [FieldOffset(8)] public Int64 largeValue; [FieldOffset(8)] public IntPtr AnsiStringValue; [FieldOffset(8)] public IntPtr WideStringValue; } [StructLayout(LayoutKind.Sequential)] internal struct PDH_TIME_INFO { public long StartTime; public long EndTime; public uint SampleCount; } [StructLayout(LayoutKind.Sequential)] internal struct SYSTEMTIME { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } public delegate uint CounterPathCallBack(IntPtr arg); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct PDH_BROWSE_DLG_CONFIG { public PDH_BROWSE_DLG_CONFIG_Flags Flags; public IntPtr hWndOwner; public string szDataSource; public IntPtr szReturnPathBuffer; public uint cchReturnPathLength; public CounterPathCallBack pCallBack; public IntPtr dwCallBackArg; public uint CallBackStatus;//PDH_STATUS public uint dwDefaultDetailLevel; public string szDialogBoxCaption; } [Flags] internal enum PDH_BROWSE_DLG_CONFIG_Flags : uint { bIncludeInstanceIndex = 1, bSingleCounterPerAdd = 2, bSingleCounterPerDialog = 4, bLocalCountersOnly = 8, bWildCardInstances = 16, bHideDetailBox = 32, bInitializePath = 64, bDisableMachineSelection = 128, bIncludeCostlyObjects = 256, bShowObjectBrowser = 512 } //[StructLayout(LayoutKind.Sequential)] //internal struct FILETIME //{ // public ulong LowDateTime; // public uint dwHighDateTime; //} [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool FileTimeToSystemTime(ref long lpFileTime, out SYSTEMTIME lpSystemTime); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SystemTimeToFileTime(ref SYSTEMTIME lpSystemTime, out long lpFileTime); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr LoadLibrary(string lpModuleName); [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, ref IntPtr lpBuffer, uint nSize, IntPtr Arguments); [DllImport("Pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhEnumMachines(string szDataSource, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] char[] mszMachineNameList, ref uint pcchBufferLength ); [DllImport("pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhOpenQuery(string szDataSource, IntPtr dwUserData, out PdhQueryHandle phQuery); [DllImport("pdh.dll")] internal static extern uint PdhCloseQuery(IntPtr hQuery); [DllImport("pdh.dll")] internal static extern uint PdhSetQueryTimeRange(PdhQueryHandle hQuery, ref PDH_TIME_INFO pInfo); [DllImport("pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhAddCounter(PdhQueryHandle hQuery, string szFullCounterPath, IntPtr dwUserData, out IntPtr phCounter); [DllImport("pdh.dll")] internal static extern uint PdhCollectQueryData(PdhQueryHandle hQuery); [DllImport("pdh.dll")] internal static extern uint PdhCollectQueryDataWithTime(PdhQueryHandle hQuery, out long pllTimeStamp); [DllImport("pdh.dll")] internal static extern uint PdhGetFormattedCounterValue(IntPtr hCounter, uint dwFormat, IntPtr lpdwType, out PDH_FMT_COUNTERVALUE pValue); [DllImport("pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhExpandWildCardPath(string szDataSource, string szWildCardPath, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] char[] mszExpandedPathList, ref uint pcchPathListLength, uint dwFlags); [DllImport("pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhGetDataSourceTimeRange(string szDataSource, out uint pdwNumEntries, out PDH_TIME_INFO pInfo, ref uint pdwBufferSize); [DllImport("pdh.dll", CharSet = CharSet.Unicode)] internal static extern uint PdhBrowseCounters(ref PDH_BROWSE_DLG_CONFIG config); } }
39.441341
140
0.668839
[ "MIT" ]
DevelopersCommunity/PerformanceCounters
src/PerformanceCounters/NativeMethods.cs
7,062
C#
// <auto-generated /> using System; using CompanyManager.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CompanyManager.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.5") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("CompanyManager.Data.Models.City", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CountryId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("CountryId"); b.ToTable("Cities"); }); modelBuilder.Entity("CompanyManager.Data.Models.Company", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationDate") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Companies"); }); modelBuilder.Entity("CompanyManager.Data.Models.Country", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("Name") .IsUnique(); b.ToTable("Countries"); }); modelBuilder.Entity("CompanyManager.Data.Models.Document", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<byte[]>("Content") .HasColumnType("varbinary(max)"); b.Property<string>("FileExtension") .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<int>("OfficeId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("OfficeId"); b.ToTable("Documents"); }); modelBuilder.Entity("CompanyManager.Data.Models.Employee", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("ExperienceLevel") .HasColumnType("int"); b.Property<string>("FirstName") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Image") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<decimal>("Salary") .HasColumnType("decimal(18,2)"); b.Property<DateTime>("StartingDate") .HasColumnType("datetime2"); b.Property<byte>("VacationDays") .HasColumnType("tinyint"); b.HasKey("Id"); b.ToTable("Employees"); }); modelBuilder.Entity("CompanyManager.Data.Models.Office", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CityId") .HasColumnType("int"); b.Property<int>("CompanyId") .HasColumnType("int"); b.Property<bool>("IsHeadQuarters") .HasColumnType("bit"); b.HasKey("Id"); b.HasIndex("CityId"); b.HasIndex("CompanyId"); b.ToTable("Offices"); }); modelBuilder.Entity("CompanyManager.Data.Models.OfficeEmployee", b => { b.Property<int>("OfficeId") .HasColumnType("int"); b.Property<int>("EmployeeId") .HasColumnType("int"); b.HasKey("OfficeId", "EmployeeId"); b.HasIndex("EmployeeId"); b.ToTable("OfficeEmployees"); }); modelBuilder.Entity("CompanyManager.Data.Models.City", b => { b.HasOne("CompanyManager.Data.Models.Country", "Country") .WithMany("Cities") .HasForeignKey("CountryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("CompanyManager.Data.Models.Document", b => { b.HasOne("CompanyManager.Data.Models.Office", "Office") .WithMany("Documents") .HasForeignKey("OfficeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("CompanyManager.Data.Models.Office", b => { b.HasOne("CompanyManager.Data.Models.City", "City") .WithMany() .HasForeignKey("CityId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CompanyManager.Data.Models.Company", "Company") .WithMany("Offices") .HasForeignKey("CompanyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.OwnsOne("CompanyManager.Data.Models.Address", "Address", b1 => { b1.Property<int>("OfficeId") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b1.Property<string>("Street") .IsRequired() .HasColumnType("nvarchar(max)"); b1.Property<int>("StreetNumber") .HasColumnType("int"); b1.HasKey("OfficeId"); b1.ToTable("Offices"); b1.WithOwner() .HasForeignKey("OfficeId"); }); }); modelBuilder.Entity("CompanyManager.Data.Models.OfficeEmployee", b => { b.HasOne("CompanyManager.Data.Models.Employee", "Employee") .WithMany("OfficeEmployees") .HasForeignKey("EmployeeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CompanyManager.Data.Models.Office", "Office") .WithMany("OfficeEmployees") .HasForeignKey("OfficeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.364706
133
0.459488
[ "MIT" ]
LSvilenov/CompanyManager.Web
CompanyManager.Data/Migrations/ApplicationDbContextModelSnapshot.cs
9,530
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.InteropServices; using TestLibrary; unsafe partial class GenericsNative { [DllImport(nameof(GenericsNative), EntryPoint = "GetIComInterface")] [return: MarshalAs(UnmanagedType.Interface)] public static extern IComInterface<char> GetIComInterfaceC(); [DllImport(nameof(GenericsNative), EntryPoint = "GetIComInterfaceOut")] public static extern void GetIComInterfaceCOut( [MarshalAs(UnmanagedType.Interface)] out IComInterface<char> value ); [DllImport(nameof(GenericsNative), EntryPoint = "GetIComInterfacePtr")] [return: MarshalAs(UnmanagedType.Interface)] public static extern ref readonly IComInterface<char> GetIComInterfaceCRef(); [DllImport(nameof(GenericsNative), EntryPoint = "GetIComInterfaces")] public static extern void GetIComInterfaceCs( [MarshalAs( UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface, SizeParamIndex = 1 )] IComInterface<char>[] pValues, int count ); [DllImport(nameof(GenericsNative), EntryPoint = "GetIComInterfaces")] public static extern void GetIComInterfaceCs( [MarshalAs(UnmanagedType.Interface)] ref IComInterface<char> pValues, int count ); } unsafe partial class GenericsTest { private static void TestIComInterfaceC() { Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetIComInterfaceC()); Assert.Throws<MarshalDirectiveException>( () => GenericsNative.GetIComInterfaceCOut(out GenericsNative.IComInterface<char> value2) ); Assert.Throws<MarshalDirectiveException>(() => GenericsNative.GetIComInterfaceCRef()); GenericsNative.IComInterface<char>[] values = new GenericsNative.IComInterface<char>[3]; Assert.Throws<MarshalDirectiveException>( () => GenericsNative.GetIComInterfaceCs(values, values.Length) ); Assert.Throws<MarshalDirectiveException>( () => GenericsNative.GetIComInterfaceCs(ref values[0], values.Length) ); } }
35.203125
100
0.70617
[ "MIT" ]
belav/runtime
src/tests/Interop/PInvoke/Generics/GenericsTest.IComInterfaceC.cs
2,253
C#
using OrchardVNext.Localization; using System; namespace OrchardVNext { public class OrchardFatalException : Exception { private readonly LocalizedString _localizedMessage; public OrchardFatalException(LocalizedString message) : base(message.Text) { _localizedMessage = message; } public OrchardFatalException(LocalizedString message, Exception innerException) : base(message.Text, innerException) { _localizedMessage = message; } public LocalizedString LocalizedMessage { get { return _localizedMessage; } } } }
29.619048
87
0.68328
[ "BSD-3-Clause" ]
ahweb/OrchardNoCMS
src/OrchardVNext/OrchardFatalException.cs
624
C#
using UnityEngine; using System; using Undefined.Checkpoints; public class CheckPointManager : MonoBehaviour { #region Variables [Header("Last Save Information")] [SerializeField] private Save save; // Action public Action onSave; public Action onLoad; #endregion public void Save() { save = new Save(GameManager.Player.transform.position); onSave?.Invoke(); } public void Load() { //GameManager.Entity.ClearAllEntities(); GameManager.manager.RespawnPlayer(save.PlayerPosition); save.Load(); onLoad?.Invoke(); } }
20.7
63
0.644122
[ "Apache-2.0" ]
prize34/undefined
Assets/Scripts/Managers/CheckPointManager/CheckPointManager.cs
621
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RadioEnumProperty.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RadioEnumProperty.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.763889
183
0.604801
[ "MIT" ]
junhsieh/csharpexample
wpf/RadioEnumProperty/RadioEnumProperty/Properties/Resources.Designer.cs
2,793
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace MUXControlsTestApp { public sealed partial class ParallaxViewStackPanelPage : TestPage { public ParallaxViewStackPanelPage() { this.InitializeComponent(); } } }
26.714286
91
0.695187
[ "MIT" ]
07101994/microsoft-ui-xaml
dev/ParallaxView/TestUI/ParallaxViewStackPanelPage.xaml.cs
376
C#
using System; using System.IO; using System.Linq; using McMaster.Extensions.CommandLineUtils; using static Bullseye.Targets; using static SimpleExec.Command; namespace build { class Program { private const bool RequireTests = true; private const string ArtifactsDir = "artifacts"; private const string Build = "build"; private const string Test = "test"; private const string Pack = "pack"; static void Main(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false); var sign = app.Option<(bool hasValue, int theValue)>("--sign", "Sign binaries and nuget package", CommandOptionType.SingleOrNoValue); CleanArtifacts(); app.OnExecute(() => { Target(Build, () => { var solution = Directory.GetFiles(".", "*.sln", SearchOption.TopDirectoryOnly).First(); Run("dotnet", $"build {solution} -c Release"); if (sign.HasValue()) { Sign("IdentityModel.AspNetCore.OAuth2Introspection.dll", "./src/bin/release"); } }); Target(Test, DependsOn(Build), () => { try { var tests = Directory.GetFiles("./test", "*.csproj", SearchOption.AllDirectories); foreach (var test in tests) { Run("dotnet", $"test {test} -c Release --no-build"); } } catch (System.IO.DirectoryNotFoundException ex) { if (RequireTests) { throw new Exception($"No tests found: {ex.Message}"); }; } }); Target(Pack, DependsOn(Build), () => { var project = Directory.GetFiles("./src", "*.csproj", SearchOption.TopDirectoryOnly).First(); Run("dotnet", $"pack {project} -c Release -o ./{ArtifactsDir} --no-build"); if (sign.HasValue()) { Sign("*.nupkg", $"./{ArtifactsDir}"); } }); Target("default", DependsOn(Test, Pack)); RunTargetsAndExit(app.RemainingArguments); }); app.Execute(args); } private static void Sign(string extension, string directory) { var signClientConfig = Environment.GetEnvironmentVariable("SignClientConfig"); var signClientSecret = Environment.GetEnvironmentVariable("SignClientSecret"); if (string.IsNullOrWhiteSpace(signClientConfig)) { throw new Exception("SignClientConfig environment variable is missing. Aborting."); } if (string.IsNullOrWhiteSpace(signClientSecret)) { throw new Exception("SignClientSecret environment variable is missing. Aborting."); } var files = Directory.GetFiles(directory, extension, SearchOption.AllDirectories); foreach (var file in files) { Console.WriteLine(" Signing " + file); Run("./tools/signclient", $"sign -c {signClientConfig} -i {file} -r sc-ids@dotnetfoundation.org -s \"{signClientSecret}\" -n 'IdentityServer4'", noEcho: true); } } private static void CleanArtifacts() { Directory.CreateDirectory($"./{ArtifactsDir}"); foreach (var file in Directory.GetFiles($"./{ArtifactsDir}")) { File.Delete(file); } } } }
34.877193
175
0.491449
[ "Apache-2.0" ]
ErazerBrecht/IdentityModel.AspNetCore.OAuth2Introspection
build/Program.cs
3,978
C#
// Copyright (c) Microsoft. All rights reserved. namespace Microsoft.Azure.Devices.Routing.Core.Endpoints { using System.Threading.Tasks; using Microsoft.Azure.Devices.Routing.Core.Checkpointers; using Microsoft.Azure.Devices.Edge.Util; public class StoringAsyncEndpointExecutorFactory : IEndpointExecutorFactory { readonly EndpointExecutorConfig config; readonly AsyncEndpointExecutorOptions options; readonly IMessageStore messageStore; public StoringAsyncEndpointExecutorFactory(EndpointExecutorConfig config, AsyncEndpointExecutorOptions options, IMessageStore messageStore) { this.config = Preconditions.CheckNotNull(config, nameof(config)); this.options = Preconditions.CheckNotNull(options, nameof(options)); this.messageStore = Preconditions.CheckNotNull(messageStore, nameof(messageStore)); } public Task<IEndpointExecutor> CreateAsync(Endpoint endpoint) => this.CreateAsync(endpoint, NullCheckpointer.Instance, this.config); public Task<IEndpointExecutor> CreateAsync(Endpoint endpoint, ICheckpointer checkpointer) => this.CreateAsync(endpoint, checkpointer, this.config); public async Task<IEndpointExecutor> CreateAsync(Endpoint endpoint, ICheckpointer checkpointer, EndpointExecutorConfig endpointExecutorConfig) { Preconditions.CheckNotNull(endpoint, nameof(endpoint)); Preconditions.CheckNotNull(checkpointer, nameof(checkpointer)); Preconditions.CheckNotNull(endpointExecutorConfig, nameof(endpointExecutorConfig)); await this.messageStore.AddEndpoint(endpoint.Id); IEndpointExecutor endpointExecutor = new StoringAsyncEndpointExecutor(endpoint, checkpointer, endpointExecutorConfig, this.options, this.messageStore); return endpointExecutor; } } }
51.108108
163
0.752512
[ "MIT" ]
avranju/iotedge
edge-hub/src/Microsoft.Azure.Devices.Routing.Core/endpoints/StoringAsyncEndpointExecutorFactory.cs
1,891
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Openpay.EpiCommerce.AddOns.PaymentGateway.Models.CreationNewOrderRequest { public class CartItem { public string ItemName { get; set; } public string ItemGroup { get; set; } public string ItemCode { get; set; } public string ItemGroupCode { get; set; } public int ItemRetailUnitPrice { get; set; } public int ItemQty { get; set; } public int ItemRetailCharge { get; set; } } }
28.65
82
0.675393
[ "Apache-2.0" ]
openpay-innovations/episerver-plugin
Episerver-Plugin/Openpay.EpiCommerce.AddOns.PaymentGateway/Models/CreationNewOrderRequest/CartItem.cs
575
C#
// Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab using System.Diagnostics; namespace Landis.SpatialModeling { /// <summary> /// An individual site on a landscape. /// </summary> public struct Site { private ILandscape landscape; private Location location; private uint dataIndex; //--------------------------------------------------------------------- /// <summary> /// The data index assigned to inactive sites. /// </summary> public const uint InactiveSiteDataIndex = 0; //--------------------------------------------------------------------- /// <summary> /// Initializes a new instance for a site on a landscape. /// </summary> /// <param name="landscape"> /// The landscape where the site is located. /// </param> /// <param name="location"> /// The location of the site. /// </param> /// <param name="dataIndex"> /// The index of the site's data for site variables. /// </param> internal Site(ILandscape landscape, Location location, uint dataIndex) { Debug.Assert( landscape.IsValid(location) ); this.landscape = landscape; this.location = location; this.dataIndex = dataIndex; } //--------------------------------------------------------------------- /// <summary> /// The landscape on which the site is located. /// </summary> public ILandscape Landscape { get { return landscape; } } //--------------------------------------------------------------------- /// <summary> /// The location of the site. /// </summary> public Location Location { get { return location; } } //--------------------------------------------------------------------- /// <summary> /// The index of the site's data for site variables. /// </summary> public uint DataIndex { get { return dataIndex; } } //--------------------------------------------------------------------- /// <summary> /// Is the site active? /// </summary> public bool IsActive { get { return dataIndex != InactiveSiteDataIndex; } } //--------------------------------------------------------------------- /// <summary> /// Converts a site to a bool. /// </summary> /// <returns> /// true if the site's location can be converted to true (both row and /// column are positive) and the landscape is not null. /// </returns> public static implicit operator bool(Site site) { return site.location && (site.landscape != null); } //--------------------------------------------------------------------- /// <summary> /// Are two sites the same site? /// </summary> public static bool operator ==(Site site1, Site site2) { return (site1.location == site2.location) && (site1.landscape == site2.landscape); } //--------------------------------------------------------------------- /// <summary> /// Are two sites different? /// </summary> /// <remarks> /// The sites are different if they are on the same landscape, but /// their locations are different, or if they are on different /// landscapes. /// </remarks> public static bool operator !=(Site site1, Site site2) { return !(site1 == site2); } //--------------------------------------------------------------------- /// <summary> /// Gets a neighboring site. /// </summary> /// <param name="neighborLocation"> /// The location of the neighboring site relative to the site. /// </param> /// <returns> /// a site that converts to false if the neighbor's location is not /// a valid location for the site's landscape. /// </returns> public Site GetNeighbor(RelativeLocation neighborLocation) { Location? neighborAbsoluteLocation = location + neighborLocation; if (neighborAbsoluteLocation.HasValue) return landscape.GetSite(neighborAbsoluteLocation.Value); return new Site(); } //--------------------------------------------------------------------- /// <summary> /// Determines whether the specified object equals the current object. /// </summary> /// <param name="obj">The object to compare with the current object. /// </param> /// <returns><b>true</b> if the specified object is equal to the /// current object; otherwise, <b>false</b>.</returns> public override bool Equals(object obj) { //Check for null and compare run-time types. if (obj == null || GetType() != obj.GetType()) return false; Site site = (Site)obj; return this == site; } //--------------------------------------------------------------------- /// <summary> /// Computes a hash for a site. /// </summary> /// <remarks> /// A site's hash code is the hash code of its location. /// </remarks> public override int GetHashCode() { return Location.GetHashCode(); } //--------------------------------------------------------------------- /// <summary> /// Returns a string representation of a site. /// </summary> /// <returns> /// The string representation of the site's location: "(row, column)". /// </returns> public override string ToString() { return Location.ToString(); } } }
32.428571
80
0.405438
[ "Apache-2.0" ]
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/api/Site.cs
6,583
C#
namespace Movies.API.Models.Base { public abstract class Entity : EntityBase<int> { } }
14.428571
50
0.653465
[ "Apache-2.0" ]
6895mahfuzgit/MicroservicesMoviesWithIdentityApp
Movies.API/Models/Base/Entity.cs
103
C#
/****************************** Module Header ******************************\ * Module Name: DownloaderHelper.cs * Project: CSMultiThreadedWebDownloader * Copyright (c) Microsoft Corporation. * * This class supplies the methods to * 1. Initialize a HttpWebRequest object. * 2. Check the url and initialize some properties of a downloader. * 3. Check whether the destination file exists. If not, create a file with * the same size as the file to be downloaded. * * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Net; using System.Text.RegularExpressions; using System.IO; namespace CSMultiThreadedWebDownloader { public static class DownloaderHelper { public static HttpWebRequest InitializeHttpWebRequest(IDownloader downloader) { var webRequest = (HttpWebRequest)WebRequest.Create(downloader.Url); if (downloader.Credentials != null) { webRequest.Credentials = downloader.Credentials; } else { webRequest.Credentials = CredentialCache.DefaultCredentials; } if (downloader.Proxy != null) { webRequest.Proxy = downloader.Proxy; } else { webRequest.Proxy = WebRequest.DefaultWebProxy; } return webRequest; } /// <summary> /// Check the URL to download, including whether it supports Range, /// </summary> /// <param name="downloader"></param> /// <returns></returns> public static string CheckUrl(IDownloader downloader) { string fileName = string.Empty; // Check the file information on the remote server. var webRequest = InitializeHttpWebRequest(downloader); using (var response = webRequest.GetResponse()) { foreach (var header in response.Headers.AllKeys) { if (header.Equals("Accept-Ranges", StringComparison.OrdinalIgnoreCase)) { downloader.IsRangeSupported = true; } if (header.Equals("Content-Disposition", StringComparison.OrdinalIgnoreCase)) { string contentDisposition = response.Headers[header]; string pattern = ".[^;]*;\\s+filename=\"(?<file>.*)\""; Regex r = new Regex(pattern); Match m = r.Match(contentDisposition); if (m.Success) { fileName = m.Groups["file"].Value; } } } downloader.TotalSize = response.ContentLength; if (downloader.TotalSize <= 0) { throw new ApplicationException( "The file to download does not exist!"); } if (!downloader.IsRangeSupported) { downloader.StartPoint = 0; downloader.EndPoint = int.MaxValue; } } if (downloader.IsRangeSupported && (downloader.StartPoint != 0 || downloader.EndPoint != long.MaxValue)) { webRequest = InitializeHttpWebRequest(downloader); if (downloader.EndPoint != int.MaxValue) { webRequest.AddRange(downloader.StartPoint, downloader.EndPoint); } else { webRequest.AddRange(downloader.StartPoint); } using (var response = webRequest.GetResponse()) { downloader.TotalSize = response.ContentLength; } } return fileName; } /// <summary> /// Check whether the destination file exists. If not, create a file with the same /// size as the file to be downloaded. /// </summary> public static void CheckFileOrCreateFile(IDownloader downloader, object fileLocker) { // Lock other threads or processes to prevent from creating the file. lock (fileLocker) { FileInfo fileToDownload = new FileInfo(downloader.DownloadPath); if (fileToDownload.Exists) { // The destination file should have the same size as the file to be downloaded. if (fileToDownload.Length != downloader.TotalSize) { throw new ApplicationException( "The download path already has a file which does not match" + " the file to download. "); } } // Create a file. else { if (downloader.TotalSize == 0) { throw new ApplicationException("The file to download does not exist!"); } using (FileStream fileStream = File.Create(downloader.DownloadPath)) { long createdSize = 0; byte[] buffer = new byte[4096]; while (createdSize < downloader.TotalSize) { int bufferSize = (downloader.TotalSize - createdSize) < 4096 ? (int)(downloader.TotalSize - createdSize) : 4096; fileStream.Write(buffer, 0, bufferSize); createdSize += bufferSize; } } } } } } }
36.180791
99
0.496252
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
OneCodeTeam/Multithreaded web downloader (CSMultiThreadedWebDownloader)/[C#]-Multithreaded web downloader (CSMultiThreadedWebDownloader)/C#/CSMultiThreadedWebDownloader/DownloaderHelper.cs
6,406
C#
using UnityEngine; using System.Collections; using Photon.Pun; /* * Credit To : Scott Sewell, developer at KinematicSoup * http://www.kinematicsoup.com/news/2016/8/9/rrypp5tkubynjwxhxjzd42s3o034o8 * / /* * Interpolates an object to the transform at the latest FixedUpdate from the transform at the previous FixedUpdate. * It is critical this script's execution order is set before all other scripts that modify a transform from FixedUpdate. */ [RequireComponent(typeof(InterpolatedTransformUpdater))] public class InterpolatedTransform : MonoBehaviourPunCallbacks { [HideInInspector] public Vector3[] m_lastPositions; // Stores the transform of the object from the last two FixedUpdates [HideInInspector] public int m_newTransformIndex; // Keeps track of which index is storing the newest value. /* * Initializes the list of previous orientations */ public virtual void OnEnable() { ForgetPreviousTransforms(); } /* * Resets the previous transform list to store only the objects's current transform. Useful to prevent * interpolation when an object is teleported, for example. */ public virtual void ForgetPreviousTransforms() { m_lastPositions = new Vector3[2]; m_lastPositions[0] = transform.position; m_lastPositions[1] = transform.position; m_newTransformIndex = 0; } public virtual void ResetPositionTo(Vector3 resetTo) { StartCoroutine(forcePosition()); IEnumerator forcePosition() { //Reset position to 'resetTo' transform.position = resetTo; //Remove old interpolation ForgetPreviousTransforms(); yield return new WaitForEndOfFrame(); } } /* * Sets the object transform to what it was last FixedUpdate instead of where is was last interpolated to, * ensuring it is in the correct position for gameplay scripts. */ public virtual void FixedUpdate() { Vector3 mostRecentTransform = m_lastPositions[m_newTransformIndex]; transform.position = mostRecentTransform; } /* * Runs after ofther scripts to save the objects's final transform. */ public virtual void LateFixedUpdate() { m_newTransformIndex = OldTransformIndex(); // Set new index to the older stored transform. m_lastPositions[m_newTransformIndex] = transform.position; } /* * Interpolates the object transform to the latest FixedUpdate's transform */ public virtual void Update() { Vector3 newestTransform = m_lastPositions[m_newTransformIndex]; Vector3 olderTransform = m_lastPositions[OldTransformIndex()]; transform.position = Vector3.Lerp(olderTransform, newestTransform, InterpolationController.InterpolationFactor); } /* * The index of the older stored transform */ public virtual int OldTransformIndex() { return (m_newTransformIndex == 0 ? 1 : 0); } }
32.404255
121
0.686474
[ "Unlicense" ]
U3cSeroH1/PUN2TUTORIAL
Assets/thirdparty/_FPS Player/FixedInterpolation/InterpolatedTransform.cs
3,048
C#
// ReSharper disable once CheckNamespace namespace System { internal static class StringExtensions { public static bool IsNullOrWhiteSpace(this string value) { #if !(NET20 || NET35) return string.IsNullOrWhiteSpace(value); #else if (value == null) { return true; } for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } return true; #endif } } }
21.571429
64
0.456954
[ "MIT" ]
StefH/Stef.Validation
src/Stef.Validation/Compatibility/StringExtensions.cs
606
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("RPNTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RPNTest")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f51ba1b9-9cc6-4943-bf9b-005038731dca")] // 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.351351
84
0.74602
[ "MIT" ]
polytronicgr/Fusion3D
RPNTest/Properties/AssemblyInfo.cs
1,385
C#
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.TestTools.UnitTesting; using CM.Payments.Client.Model; using System.Reflection; using CM.Payments.Client.Enums; //<auto-generated> // IMPORTANT NOTE: // This code is generated by MessageUnitTestGenerator in this project. // Date and time: 06-04-2018 14:52:28 // // Changes to this file may cause incorrect behavior and will be lost on the next code generation. //</auto-generated> namespace CM.Payments.Client.Test { [TestClass, ExcludeFromCodeCoverage] public partial class SofortDetailsResponseTests : BaseJsonConvertTests { public TestContext TestContext { get; set; } [TestMethod] public void SofortDetailsResponse() { var obj = new SofortDetailsResponse { AuthenticationUrl = "Lorum_552", BankAccountNumber = "Lorum_3", BankBic = "Lorum_848", CallbackUrl = "Lorum_597", CancelledUrl = "Lorum_252", ConsumerName = "Lorum_343", Description = "Lorum_494", ExpiredUrl = "Lorum_0", FailedUrl = "Lorum_640", PurchaseId = "Lorum_598", SuccessUrl = "Lorum_961", TransactionId = "Lorum_863" }; var deserialized = ConversionTest(obj); Assert.IsNotNull(deserialized); Assert.AreEqual(obj.AuthenticationUrl, deserialized.AuthenticationUrl); Assert.AreEqual(obj.BankAccountNumber, deserialized.BankAccountNumber); Assert.AreEqual(obj.BankBic, deserialized.BankBic); Assert.AreEqual(obj.CallbackUrl, deserialized.CallbackUrl); Assert.AreEqual(obj.CancelledUrl, deserialized.CancelledUrl); Assert.AreEqual(obj.ConsumerName, deserialized.ConsumerName); Assert.AreEqual(obj.Description, deserialized.Description); Assert.AreEqual(obj.ExpiredUrl, deserialized.ExpiredUrl); Assert.AreEqual(obj.FailedUrl, deserialized.FailedUrl); Assert.AreEqual(obj.PurchaseId, deserialized.PurchaseId); Assert.AreEqual(obj.SuccessUrl, deserialized.SuccessUrl); Assert.AreEqual(obj.TransactionId, deserialized.TransactionId); } } }
34.79661
98
0.762786
[ "MIT" ]
Finturi/payments-sdk-net
Source/CM.Payments.Client.Test.40/Generated/SofortDetailsResponse_Tests.cs
2,055
C#
public class Program { private static void Main() { var engine = new Engine(); engine.Start(); } }
15.875
34
0.535433
[ "MIT" ]
tanyta78/CSharpOOP
Exam Preparation/Avatar2/Avatar2/Program.cs
129
C#
using System.Windows; using System.Windows.Controls; namespace LightBuzz.Vitruvius.WPF { public static class ControlExtensions { static readonly Point ZERO = new Point(0, 0); public static Rect Position(this Control element) { try { return new Rect { Location = element.PointToScreen(ZERO), Width = element.ActualWidth, Height = element.ActualHeight }; } catch { return Rect.Empty; } } public static bool IntersectsWith(this Control first, Control second) { return first.Position().IntersectsWith(second.Position()); } public static void Show(this UIElement control) { if (control.Visibility != Visibility.Visible) { control.Visibility = Visibility.Visible; } } public static void Hide(this UIElement control) { if (control.Visibility != Visibility.Collapsed) { control.Visibility = Visibility.Collapsed; } } } }
25.44898
77
0.504411
[ "Apache-2.0" ]
LightBuzz/Vitruvius
Kinect v1/LightBuzz.Vitruvius.WPF/Extensions/ControlExtensions.cs
1,249
C#
namespace BedStats { internal class BedStatsArguments { /// <summary> /// Display Verbose logging during processing. /// </summary> public bool verbose; /// <summary> /// NormalizeInput .BED files prior to processing. /// </summary> public bool normalizeInputs; /// <summary> /// Output file for use with VennTool. /// </summary> public string outputVennTool; /// <summary> /// Create an Excel file with BED stats. /// </summary> public string xlFilename; /// <summary> /// List of 2 or 3 input .BED files to process. /// </summary> public string[] inputFiles; /// <summary> /// Displays the help. /// </summary> public bool Help = false; /// <summary> /// Constructor /// </summary> public BedStatsArguments() { this.Help = false; this.verbose = false; this.normalizeInputs = false; this.outputVennTool = null; this.xlFilename = null; this.inputFiles = null; } } }
24.895833
58
0.502929
[ "Apache-2.0" ]
dotnetbio/bio
Tools/BedStats/BedStatsArguments.cs
1,195
C#
// Copyright 2016 Esri. // // 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 Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace ArcGISRuntime.WPF.Samples.FeatureLayerQuery { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Feature layer query", category: "Data", description: "Find features in a feature table which match an SQL query.", instructions: "Input the name of a U.S. state into the text field. When you click the button, a query is performed and the matching features are highlighted or an error is returned.", tags: new[] { "query", "search" })] public partial class FeatureLayerQuery { // Create reference to service of US States. private string _statesUrl = "https://services.arcgis.com/jIL9msH9OI208GCb/arcgis/rest/services/USA_Daytime_Population_2016/FeatureServer/0"; // Create globally available feature table for easy referencing. private ServiceFeatureTable _featureTable; // Create globally available feature layer for easy referencing. private FeatureLayer _featureLayer; public FeatureLayerQuery() { InitializeComponent(); // Create the UI, setup the control references and execute initialization. Initialize(); } private void Initialize() { // Create new Map with basemap. Map myMap = new Map(Basemap.CreateTopographic()); // Create and set initial map location. MapPoint initialLocation = new MapPoint(-11000000, 5000000, SpatialReferences.WebMercator); myMap.InitialViewpoint = new Viewpoint(initialLocation, 100000000); // Create feature table using a URL. _featureTable = new ServiceFeatureTable(new Uri(_statesUrl)); // Create feature layer using this feature table. Make it slightly transparent. _featureLayer = new FeatureLayer(_featureTable) { Opacity = 0.6, // Work around service setting. MaxScale = 10 }; // Create a new renderer for the States Feature Layer. SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1); SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Transparent, lineSymbol); // Set States feature layer renderer. _featureLayer.Renderer = new SimpleRenderer(fillSymbol); // Add feature layer to the map. myMap.OperationalLayers.Add(_featureLayer); // Adjust the selection color. MyMapView.SelectionProperties.Color = Color.Cyan; // Assign the map to the MapView. MyMapView.Map = myMap; } private async void OnQueryClicked(object sender, RoutedEventArgs e) { // Remove any previous feature selections that may have been made. _featureLayer.ClearSelection(); // Begin query process. await QueryStateFeature(QueryEntry.Text); } private async Task QueryStateFeature(string stateName) { try { // Create a query parameters that will be used to Query the feature table. QueryParameters queryParams = new QueryParameters(); // Trim whitespace on the state name to prevent broken queries. string formattedStateName = stateName.Trim().ToUpper(); // Construct and assign the where clause that will be used to query the feature table. queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + formattedStateName + "%'"; // Query the feature table. FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams); // Cast the QueryResult to a List so the results can be interrogated. List<Feature> features = queryResult.ToList(); if (features.Any()) { // Create an envelope. EnvelopeBuilder envBuilder = new EnvelopeBuilder(SpatialReferences.WebMercator); // Loop over each feature from the query result. foreach (Feature feature in features) { // Add the extent of each matching feature to the envelope. envBuilder.UnionOf(feature.Geometry.Extent); // Select each feature. _featureLayer.SelectFeature(feature); } // Zoom to the extent of the selected feature(s). await MyMapView.SetViewpointGeometryAsync(envBuilder.ToGeometry(), 50); } else { MessageBox.Show("Retry your query with a valid state name, like 'California'.", "State not found!"); } } catch (Exception ex) { MessageBox.Show("An error occurred.\n" + ex, "Sample error"); } } } }
41.894366
191
0.623634
[ "Apache-2.0" ]
Druffl3/arcgis-runtime-samples-dotnet
src/WPF/ArcGISRuntime.WPF.Viewer/Samples/Data/FeatureLayerQuery/FeatureLayerQuery.xaml.cs
5,949
C#
using CommonCore.LockPause; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CommonCore.SideScrollerGame { /// <summary> /// Controller for a player follow camera /// </summary> public class CameraFollowScript : MonoBehaviour { private const float TargetDistanceThreshold = 0.5f; /// <summary> /// If set, will follow the player(s) /// </summary> public bool FollowPlayer = true; public float MaxYDist = 0; public float YOffset = 1; public List<Transform> PlayerTransforms; [SerializeField] private Camera AttachedCamera; private float MoveSpeed; private Vector3? MoveTarget; private void Start() { if (AttachedCamera == null) AttachedCamera = GetComponent<Camera>(); } private void LateUpdate() { if (LockPauseModule.IsPaused()) return; if (FollowPlayer) { //multiple player handling for hmslug Vector2 centroid; if (PlayerTransforms.Count == 1) { centroid = PlayerTransforms[0].position; } else { centroid = Vector2.zero; int validPlayers = 0; foreach (var t in PlayerTransforms) { if (t == null) //skip invalid transforms continue; centroid += (Vector2)t.position; validPlayers++; } centroid /= validPlayers; } //max y dist handling float yPos = transform.position.y - YOffset; float yPosToCentroid = centroid.y - yPos; float distYPosToCentroid = Mathf.Abs(yPosToCentroid); if (distYPosToCentroid > MaxYDist) { yPos += Mathf.Sign(yPosToCentroid) * (distYPosToCentroid - MaxYDist); } transform.position = new Vector3(centroid.x, yPos + YOffset, transform.position.z); } else if(MoveTarget.HasValue) { //move to target Vector3 vecToTarget = MoveTarget.Value - transform.position; float distToTarget = vecToTarget.magnitude; if(distToTarget > TargetDistanceThreshold) { //move! float moveDistance = Mathf.Min(distToTarget, MoveSpeed * Time.fixedDeltaTime); transform.Translate(moveDistance * vecToTarget.normalized); } } } public Rect GetCameraBounds() { float distZ = Mathf.Abs(transform.position.z); //we always use z=0 as our plane Vector3 bottomLeft = AttachedCamera.ScreenToWorldPoint(new Vector3(0, 0, distZ)); Vector3 topRight = AttachedCamera.ScreenToWorldPoint(new Vector3(AttachedCamera.pixelWidth, AttachedCamera.pixelHeight, distZ)); float minX = bottomLeft.x; float maxX = topRight.x; float width = Mathf.Abs(maxX - minX); float minY = bottomLeft.y; float maxY = topRight.y; float height = Mathf.Abs(maxY - minY); //Debug.Log($"Camera bounds: minX={minX:F2} maxX={maxX:F2} width={width:F2}"); return new Rect(minX, minY, width, height); } public void MoveTo(Vector3 target, float speed) { MoveSpeed = speed; MoveTarget = target; } public void CancelMove() { MoveSpeed = 0; MoveTarget = null; } } }
31.152
140
0.518233
[ "MIT" ]
XCVG/heavymetalslug
Assets/CommonCoreGame/SideScrollerGame/CameraFollowScript.cs
3,896
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> //------------------------------------------------------------------------------ public partial class CMSFormControls_System_ObjectBindingControl { /// <summary> /// chkBindObject control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMS.Base.Web.UI.CMSCheckBox chkBindObject; }
31.173913
81
0.51325
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSFormControls/System/ObjectBindingControl.ascx.designer.cs
719
C#
using System; using System.Collections.Generic; using System.Threading; namespace Earth.Core { /// <summary> /// A message queue for passing messages between threads. Messages can be simple objects that are processed by /// the <see cref="MessageReceived"/> event, or they can be delegates which are invoked in /// the thread that is processing the queue. The queue can be processed in a dedicated thread by calling /// <see cref="StartInAnotherThread"/>, or in an existing thread by calling <see cref="StartInCurrentThread"/>. /// Finally, the current contents of the queue can be executed just once by calling <see cref="ProcessQueue"/>. /// </summary> public class MessageQueue : IDisposable { /// <summary> /// Raised when a message is received by the message queue. This event is raised in the thread that /// is handling messages for the queue. /// </summary> public event EventHandler<MessageQueueEventArgs> MessageReceived; /// <summary> /// Starts processing the queue in the current thread. This method does not return until /// <see cref="Terminate"/> is called. /// </summary> public void StartInCurrentThread() { lock (_queue) { if (_state != State.Stopped) throw new InvalidOperationException("The MessageQueue is already running."); _state = State.Running; } Run(); } /// <summary> /// Starts processing the queue in a separate thread. This method returns immediately. /// The thread created by this method will continue running until <see cref="Terminate"/> /// is called. /// </summary> public void StartInAnotherThread() { lock (_queue) { if (_state != State.Stopped) throw new InvalidOperationException("The MessageQueue is already running."); _state = State.Running; } Thread thread = new Thread(Run); thread.IsBackground = true; thread.Start(); } /// <summary> /// Processes messages currently in the queue using the calling thread. This method returns as soon as all /// messages currently in the queue have been processed. /// </summary> public void ProcessQueue() { List<MessageInfo> current = null; lock (_queue) { if (_state != State.Stopped) throw new InvalidOperationException("The MessageQueue is already running."); if (_queue.Count > 0) { _state = State.Running; current = new List<MessageInfo>(_queue); _queue.Clear(); } } if (current != null) { try { ProcessCurrentQueue(current); } finally { lock (_queue) { _state = State.Stopped; } } } } /// <summary> /// Stops queue processing started by <see cref="StartInCurrentThread"/>, <see cref="StartInAnotherThread"/>, /// or <see cref="ProcessQueue"/>. This method returns immediately without waiting for the message queue /// to stop. To wait for the message queue to stop, call <see cref="TerminateAndWait"/> instead. If the message /// queue is not running when this method is called, a "stop" message will be queued such that the message /// queue will be stopped when it starts processing messages again. /// </summary> public void Terminate() { Post(StopQueue, null); } /// <summary> /// Stops queue processing started by <see cref="StartInCurrentThread"/>, <see cref="StartInAnotherThread"/>, /// or <see cref="ProcessQueue"/>. This method does not return until the message queue has stopped. /// To signal the message queue to terminate without waiting, call <see cref="Terminate"/> instead. If the message /// queue is not running when this method is called, a "stop" message will be queued such that the message /// queue will be stopped when it starts processing messages again, and the calling thread will be blocked /// until that happens. /// </summary> public void TerminateAndWait() { Send(StopQueue, null); } /// <summary> /// Posts a delegate to the queue. This method returns immediately without waiting for the delegate to be invoked. /// </summary> /// <param name="callback">The callback to invoke when the message is processed.</param> /// <param name="userData">Optional data to pass to the <paramref name="callback"/> when it is invoked.</param> public void Post(Action<object> callback, object userData) { lock (_queue) { _queue.Add(new MessageInfo(callback, userData, null)); Monitor.Pulse(_queue); } } /// <summary> /// Posts a message to the queue. This method returns immediately without waiting for the message to be processed. /// </summary> /// <param name="message">The message to post to the queue.</param> public void Post(object message) { lock (_queue) { _queue.Add(new MessageInfo(null, message, null)); Monitor.Pulse(_queue); } } /// <summary> /// Sends a delegate to the queue. This method waits for the delegate to be invoked in the queue thread /// before returning. Calling this message from the queue thread itself will result in a deadlock. /// </summary> /// <param name="callback">The callback to invoke when the message is processed.</param> /// <param name="userData">Optional data to pass to the <paramref name="callback"/> when it is invoked.</param> public void Send(Action<object> callback, object userData) { MessageInfo messageInfo = new MessageInfo(callback, userData, new object()); lock (messageInfo.Done) { lock (_queue) { _queue.Add(messageInfo); Monitor.Pulse(_queue); } Monitor.Wait(messageInfo.Done); } } /// <summary> /// Sends a message to the queue. This method waits for the delegate to be invoked in the queue thread /// before returning. Calling this message from the queue thread itself will result in a deadlock. /// </summary> /// <param name="message">The message to post to the queue.</param> public void Send(object message) { MessageInfo messageInfo = new MessageInfo(null, message, new object()); lock (messageInfo.Done) { lock (_queue) { _queue.Add(messageInfo); Monitor.Pulse(_queue); } Monitor.Wait(messageInfo.Done); } } /// <summary> /// Blocks the calling thread until a message is waiting in the queue. /// This message should only be called on queues for which messages are processed /// explicitly with a call to <see cref="ProcessQueue"/>. /// </summary> public void WaitForMessage() { lock (_queue) { while (_queue.Count == 0) { Monitor.Wait(_queue); } } } /// <summary> /// Calls <see cref="Terminate"/>. /// </summary> public void Dispose() { Terminate(); } private void Run() { try { List<MessageInfo> current = new List<MessageInfo>(); do { lock (_queue) { if (_queue.Count > 0) { current.AddRange(_queue); _queue.Clear(); } else { Monitor.Wait(_queue); current.AddRange(_queue); _queue.Clear(); } } ProcessCurrentQueue(current); current.Clear(); } while (_state == State.Running); } finally { lock (_queue) { _state = State.Stopped; } } } private void ProcessCurrentQueue(List<MessageInfo> currentQueue) { for (int i = 0; i < currentQueue.Count; ++i) { if (_state == State.Stopping) { // Push the remainder of 'current' back into '_queue'. lock (_queue) { currentQueue.RemoveRange(0, i); _queue.InsertRange(0, currentQueue); } break; } ProcessMessage(currentQueue[i]); } } private void ProcessMessage(MessageInfo message) { if (message.Callback != null) { message.Callback(message.Message); } else { EventHandler<MessageQueueEventArgs> e = MessageReceived; if (e != null) { e(this, new MessageQueueEventArgs(message.Message)); } } if (message.Done != null) { lock (message.Done) { Monitor.Pulse(message.Done); } } } private void StopQueue(object userData) { _state = State.Stopping; } private struct MessageInfo { public MessageInfo(Action<object> callback, object message, object done) { Callback = callback; Message = message; Done = done; } public Action<object> Callback; public object Message; public object Done; } private enum State { Stopped, Running, Stopping, } private List<MessageInfo> _queue = new List<MessageInfo>(); private State _state; } }
35.262658
123
0.502109
[ "MIT" ]
Shakenbake158/Earth
Assets/Scripts/Core/MessageQueue.cs
11,145
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview { using Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.PowerShell; /// <summary>A list of firewall rules.</summary> [System.ComponentModel.TypeConverter(typeof(FirewallRuleListResultAutoGeneratedTypeConverter))] public partial class FirewallRuleListResultAutoGenerated { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.FirewallRuleListResultAutoGenerated" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGenerated" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGenerated DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new FirewallRuleListResultAutoGenerated(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.FirewallRuleListResultAutoGenerated" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGenerated" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGenerated DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new FirewallRuleListResultAutoGenerated(content); } /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.FirewallRuleListResultAutoGenerated" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal FirewallRuleListResultAutoGenerated(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IFirewallRule[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IFirewallRule>(__y, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.FirewallRuleTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).NextLink, global::System.Convert.ToString); AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.FirewallRuleListResultAutoGenerated" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal FirewallRuleListResultAutoGenerated(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).Value = (Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IFirewallRule[]) content.GetValueForProperty("Value",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).Value, __y => TypeConverterExtensions.SelectToArray<Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.IFirewallRule>(__y, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20171201.FirewallRuleTypeConverter.ConvertFrom)); ((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).NextLink = (string) content.GetValueForProperty("NextLink",((Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGeneratedInternal)this).NextLink, global::System.Convert.ToString); AfterDeserializePSObject(content); } /// <summary> /// Creates a new instance of <see cref="FirewallRuleListResultAutoGenerated" />, deserializing the content from a json string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Models.Api20200214Preview.IFirewallRuleListResultAutoGenerated FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.PostgreSql.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// A list of firewall rules. [System.ComponentModel.TypeConverter(typeof(FirewallRuleListResultAutoGeneratedTypeConverter))] public partial interface IFirewallRuleListResultAutoGenerated { } }
72.688889
632
0.720269
[ "MIT" ]
3quanfeng/azure-powershell
src/PostgreSql/generated/api/Models/Api20200214Preview/FirewallRuleListResultAutoGenerated.PowerShell.cs
9,679
C#
namespace InfernoInfinity.Core.Commands { using System; public class End : Command { public End(string[] data) : base(data) { } public override void Execute() { Environment.Exit(0); } } }
15.705882
46
0.509363
[ "MIT" ]
valkin88/CSharp-Fundamentals
CSharp OOP Advanced/Reflection and Attributes - Exercises/InfernoInfinity/InfernoInfinity/Core/Commands/End.cs
269
C#
//---------------------- // <auto-generated> // Generated using the NSwag toolchain v13.14.5.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org) // </auto-generated> //---------------------- #nullable enable using Shared.Models; #pragma warning disable 108 // Disable "CS0108 '{derivedDto}.ToJson()' hides inherited member '{dtoBase}.ToJson()'. Use the new keyword if hiding was intended." #pragma warning disable 114 // Disable "CS0114 '{derivedDto}.RaisePropertyChanged(String)' hides inherited member 'dtoBase.RaisePropertyChanged(String)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." #pragma warning disable 472 // Disable "CS0472 The result of the expression is always 'false' since a value of type 'Int32' is never equal to 'null' of type 'Int32?' #pragma warning disable 1573 // Disable "CS1573 Parameter '...' has no matching param tag in the XML comment for ... #pragma warning disable 1591 // Disable "CS1591 Missing XML comment for publicly visible type or member ..." #pragma warning disable 8073 // Disable "CS8073 The result of the expression is always 'false' since a value of type 'T' is never equal to 'null' of type 'T?'" #pragma warning disable 3016 // Disable "CS3016 Arrays as attribute arguments is not CLS-compliant" namespace DataHub.OperationalDataStore.System.ServiceDetails { using System = global::System; [System.CodeDom.Compiler.GeneratedCode("NSwag", "13.14.5.0 (NJsonSchema v10.5.2.0 (Newtonsoft.Json v13.0.0.0))")] public partial interface IServiceDetailService { /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Retrieves the list of elapsed times for reports</summary> /// <param name="batchDate">The bank date on which the particular report was generated.</param> /// <param name="recordId">Unique identifier of an entity</param> /// <returns>getAllReportTimesResponse</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetAllReportTimesResponse> GetAllReportTimesAsync(System.DateTimeOffset? batchDate = null, string? recordId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> /// <summary>Retrieves the list of elapsed times for reports generated during close of business processing</summary> /// <param name="batchDate">The bank date on which the particular report was generated.</param> /// <param name="recordId">Unique identifier of an entity</param> /// <returns>getAllReportTimesCOBResponse</returns> /// <exception cref="ApiException">A server side error occurred.</exception> System.Threading.Tasks.Task<GetAllReportTimesCOBResponse> GetAllReportTimesCOBAsync(System.DateTimeOffset batchDate, string? recordId = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } /// <summary>getAllReportTimesResponse</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetAllReportTimesResponse { [System.Text.Json.Serialization.JsonPropertyName("data")] public GetAllReportTimesResponseBody? Data { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetAllReportTimesResponseBody { /// <summary>Application to Update the Process Time for every individual report generated during Batch.</summary> [System.Text.Json.Serialization.JsonPropertyName("reportTimes")] public System.Collections.Generic.ICollection<ReportTimes>? ReportTimes { get; set; }= default!; } /// <summary>getAllReportTimesCOBResponse</summary> [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetAllReportTimesCOBResponse { [System.Text.Json.Serialization.JsonPropertyName("data")] public GetAllReportTimesCOBResponseBody? Data { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class GetAllReportTimesCOBResponseBody { /// <summary>Application to Update the Process Time for every individual report generated during Batch.</summary> [System.Text.Json.Serialization.JsonPropertyName("reportTimes")] public System.Collections.Generic.ICollection<ReportTimes2>? ReportTimes { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ReportTimes { /// <summary>Unique identifier of an entity</summary> [System.Text.Json.Serialization.JsonPropertyName("recordId")] public string? RecordId { get; set; }= default!; /// <summary>The bank date on which the particular report was generated.</summary> [System.Text.Json.Serialization.JsonPropertyName("batchDate")] public BatchDate? BatchDate { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class ReportTimes2 { /// <summary>Unique identifier of an entity</summary> [System.Text.Json.Serialization.JsonPropertyName("recordId")] public string? RecordId { get; set; }= default!; /// <summary>The bank date on which the particular report was generated.</summary> [System.Text.Json.Serialization.JsonPropertyName("batchDate")] public BatchDate2? BatchDate { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class BatchDate { /// <summary>The bank date on which the particular report was generated.</summary> [System.Text.Json.Serialization.JsonPropertyName("batchDate")] public string? BatchDate1 { get; set; }= default!; /// <summary>The beginning of the time interval in the current Day</summary> [System.Text.Json.Serialization.JsonPropertyName("startTime")] public string? StartTime { get; set; }= default!; /// <summary>The end of the time interval in corresponding Day</summary> [System.Text.Json.Serialization.JsonPropertyName("endTime")] public string? EndTime { get; set; }= default!; /// <summary>Contains the session number in which the agent is running</summary> [System.Text.Json.Serialization.JsonPropertyName("sessionNo")] public string? SessionNo { get; set; }= default!; /// <summary>Contains the elapsed time of the report in seconds</summary> [System.Text.Json.Serialization.JsonPropertyName("elapsedTime")] public string? ElapsedTime { get; set; }= default!; } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "10.5.2.0 (Newtonsoft.Json v13.0.0.0)")] public partial class BatchDate2 { /// <summary>The bank date on which the particular report was generated.</summary> [System.Text.Json.Serialization.JsonPropertyName("batchDate")] public string? BatchDate { get; set; }= default!; /// <summary>The beginning of the time interval in the current Day</summary> [System.Text.Json.Serialization.JsonPropertyName("startTime")] public string? StartTime { get; set; }= default!; /// <summary>The end of the time interval in corresponding Day</summary> [System.Text.Json.Serialization.JsonPropertyName("endTime")] public string? EndTime { get; set; }= default!; /// <summary>Contains the session number in which the agent is running</summary> [System.Text.Json.Serialization.JsonPropertyName("sessionNo")] public string? SessionNo { get; set; }= default!; /// <summary>Contains the elapsed time of the report in seconds</summary> [System.Text.Json.Serialization.JsonPropertyName("elapsedTime")] public string? ElapsedTime { get; set; }= default!; } } #pragma warning restore 1591 #pragma warning restore 1573 #pragma warning restore 472 #pragma warning restore 114 #pragma warning restore 108 #pragma warning restore 3016
51.807018
268
0.69308
[ "MIT" ]
ElevateData/OpenTemenos
src/DataHub.OperationalDataStore.System/ServiceDetailService.cs
8,859
C#
using NHapi.Base.Parser; using NHapi.Base; using NHapi.Base.Log; using System; using System.Collections.Generic; using NHapi.Model.V27.Segment; using NHapi.Model.V27.Datatype; using NHapi.Base.Model; namespace NHapi.Model.V27.Group { ///<summary> ///Represents the CSU_C09_STUDY_SCHEDULE Group. A Group is an ordered collection of message /// segments that can repeat together or be optionally in/excluded together. /// This Group contains the following elements: ///<ol> ///<li>0: CSS (Clinical Study Data Schedule Segment) optional </li> ///<li>1: CSU_C09_STUDY_OBSERVATION (a Group object) repeating</li> ///<li>2: CSU_C09_STUDY_PHARM (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class CSU_C09_STUDY_SCHEDULE : AbstractGroup { ///<summary> /// Creates a new CSU_C09_STUDY_SCHEDULE Group. ///</summary> public CSU_C09_STUDY_SCHEDULE(IGroup parent, IModelClassFactory factory) : base(parent, factory){ try { this.add(typeof(CSS), false, false); this.add(typeof(CSU_C09_STUDY_OBSERVATION), true, true); this.add(typeof(CSU_C09_STUDY_PHARM), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating CSU_C09_STUDY_SCHEDULE - this is probably a bug in the source code generator.", e); } } ///<summary> /// Returns CSS (Clinical Study Data Schedule Segment) - creates it if necessary ///</summary> public CSS CSS { get{ CSS ret = null; try { ret = (CSS)this.GetStructure("CSS"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of CSU_C09_STUDY_OBSERVATION (a Group object) - creates it if necessary ///</summary> public CSU_C09_STUDY_OBSERVATION GetSTUDY_OBSERVATION() { CSU_C09_STUDY_OBSERVATION ret = null; try { ret = (CSU_C09_STUDY_OBSERVATION)this.GetStructure("STUDY_OBSERVATION"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of CSU_C09_STUDY_OBSERVATION /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public CSU_C09_STUDY_OBSERVATION GetSTUDY_OBSERVATION(int rep) { return (CSU_C09_STUDY_OBSERVATION)this.GetStructure("STUDY_OBSERVATION", rep); } /** * Returns the number of existing repetitions of CSU_C09_STUDY_OBSERVATION */ public int STUDY_OBSERVATIONRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("STUDY_OBSERVATION").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the CSU_C09_STUDY_OBSERVATION results */ public IEnumerable<CSU_C09_STUDY_OBSERVATION> STUDY_OBSERVATIONs { get { for (int rep = 0; rep < STUDY_OBSERVATIONRepetitionsUsed; rep++) { yield return (CSU_C09_STUDY_OBSERVATION)this.GetStructure("STUDY_OBSERVATION", rep); } } } ///<summary> ///Adds a new CSU_C09_STUDY_OBSERVATION ///</summary> public CSU_C09_STUDY_OBSERVATION AddSTUDY_OBSERVATION() { return this.AddStructure("STUDY_OBSERVATION") as CSU_C09_STUDY_OBSERVATION; } ///<summary> ///Removes the given CSU_C09_STUDY_OBSERVATION ///</summary> public void RemoveSTUDY_OBSERVATION(CSU_C09_STUDY_OBSERVATION toRemove) { this.RemoveStructure("STUDY_OBSERVATION", toRemove); } ///<summary> ///Removes the CSU_C09_STUDY_OBSERVATION at the given index ///</summary> public void RemoveSTUDY_OBSERVATIONAt(int index) { this.RemoveRepetition("STUDY_OBSERVATION", index); } ///<summary> /// Returns first repetition of CSU_C09_STUDY_PHARM (a Group object) - creates it if necessary ///</summary> public CSU_C09_STUDY_PHARM GetSTUDY_PHARM() { CSU_C09_STUDY_PHARM ret = null; try { ret = (CSU_C09_STUDY_PHARM)this.GetStructure("STUDY_PHARM"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of CSU_C09_STUDY_PHARM /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public CSU_C09_STUDY_PHARM GetSTUDY_PHARM(int rep) { return (CSU_C09_STUDY_PHARM)this.GetStructure("STUDY_PHARM", rep); } /** * Returns the number of existing repetitions of CSU_C09_STUDY_PHARM */ public int STUDY_PHARMRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("STUDY_PHARM").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the CSU_C09_STUDY_PHARM results */ public IEnumerable<CSU_C09_STUDY_PHARM> STUDY_PHARMs { get { for (int rep = 0; rep < STUDY_PHARMRepetitionsUsed; rep++) { yield return (CSU_C09_STUDY_PHARM)this.GetStructure("STUDY_PHARM", rep); } } } ///<summary> ///Adds a new CSU_C09_STUDY_PHARM ///</summary> public CSU_C09_STUDY_PHARM AddSTUDY_PHARM() { return this.AddStructure("STUDY_PHARM") as CSU_C09_STUDY_PHARM; } ///<summary> ///Removes the given CSU_C09_STUDY_PHARM ///</summary> public void RemoveSTUDY_PHARM(CSU_C09_STUDY_PHARM toRemove) { this.RemoveStructure("STUDY_PHARM", toRemove); } ///<summary> ///Removes the CSU_C09_STUDY_PHARM at the given index ///</summary> public void RemoveSTUDY_PHARMAt(int index) { this.RemoveRepetition("STUDY_PHARM", index); } } }
30.869159
160
0.707841
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V27/Group/CSU_C09_STUDY_SCHEDULE.cs
6,606
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Ocelot.DependencyInjection; using Ocelot.Middleware; namespace Web.Novel.Bff { 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.AddOcelot(); services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Web.Fiction.Bff", 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", "Web.Fiction.Bff v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseOcelot().Wait(); } } }
29.508772
107
0.603448
[ "MIT" ]
zcqiand/Barasingha-WebApi
src/ApiGateways/Web.Bff/Web.Novel.Bff/Startup.cs
1,682
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using StructureMap.AutoMocking; namespace Chutzpah.Facts { public class Testable<TClassUnderTest> where TClassUnderTest : class { protected MoqAutoMocker<TClassUnderTest> autoMocker = new MoqAutoMocker<TClassUnderTest>(); public Testable() { } public Testable(Action<Testable<TClassUnderTest>> setup) { setup(this); } public Mock<TDependencyToMock> Mock<TDependencyToMock>() where TDependencyToMock : class { var a = autoMocker.Get<TDependencyToMock>(); return Moq.Mock.Get(a); } public void Inject<T>(T type) { autoMocker.Inject(type); } public void InjectArray<T>(T[] types) { autoMocker.InjectArray(types); } public void MockSelf() { autoMocker.PartialMockTheClassUnderTest(); } public TClassUnderTest ClassUnderTest { get { return autoMocker.ClassUnderTest; } } } }
22.529412
99
0.59356
[ "MIT" ]
CUSE341/CUSE.github.io
chutzpah/Facts/Testable.cs
1,151
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Ragnarok.ObjectModel; using Ragnarok.Utility; namespace Ragnarok.Extra.Effect.Animation { /// <summary> /// アニメーション停止時の挙動を指定します。 /// </summary> public enum FillBehavior { /// <summary> /// アニメーション終了時の値を保持し続けます。 /// </summary> HoldEnd, /// <summary> /// アニメーションを停止し、値を元に戻します。 /// </summary> Stop, } /// <summary> /// プロパティアニメーションに関わる基本クラスです。 /// </summary> public abstract class PropertyAnimation : NotifyObject, IAnimationTimeline { private bool initialized; private IPropertyObject pobj; private object startValue; private double currentTick; private bool isReversing; /// <summary> /// コンストラクタ /// </summary> public PropertyAnimation(Type propertyType) { if ((object)propertyType == null) { throw new ArgumentNullException(nameof(propertyType)); } TargetPropertyType = propertyType; } /// <summary> /// アニメーションの完了時に呼ばれます。 /// </summary> public event EventHandler Completed; /// <summary> /// アニメーション対象となるプロパティ型を取得します。 /// </summary> public Type TargetPropertyType { get; private set; } /// <summary> /// アニメーションの実行時間を取得または設定します。 /// </summary> public TimeSpan Duration { get { return GetValue<TimeSpan>(nameof(Duration)); } set { SetValue(nameof(Duration), value); } } /// <summary> /// アニメーションの実行時間[ミリ秒]を取得します。 /// </summary> [DependOn("Duration")] public double DurationMilliseconds { get { return Duration.TotalMilliseconds; } } /// <summary> /// アニメーションの開始時刻を取得または設定します。 /// </summary> public TimeSpan BeginTime { get { return GetValue<TimeSpan>(nameof(BeginTime)); } set { SetValue(nameof(BeginTime), value); } } /// <summary> /// アニメーションの開始時間[ミリ秒]を取得します。 /// </summary> [DependOn("BeginTime")] public double BeginTimeMilliseconds { get { return BeginTime.TotalMilliseconds; } } /// <summary> /// 時間内でアニメーションを無限に繰り返すかどうかを取得または設定します。 /// </summary> public bool IsRepeatForever { get { return GetValue<bool>(nameof(IsRepeatForever)); } set { SetValue(nameof(IsRepeatForever), value); } } /// <summary> /// 停止時の挙動を取得または設定します。 /// </summary> public FillBehavior FillBehavior { get { return GetValue<FillBehavior>(nameof(FillBehavior)); } set { SetValue(nameof(FillBehavior), value); } } /// <summary> /// 繰り返し時に往復するかどうかを取得または設定します。 /// </summary> public bool AutoReverse { get { return GetValue<bool>(nameof(AutoReverse)); } set { SetValue(nameof(AutoReverse), value); } } /// <summary> /// アニメーションが完了したかどうかを取得または設定します。 /// </summary> public bool IsCompleted { get { return GetValue<bool>(nameof(IsCompleted)); } private set { SetValue(nameof(IsCompleted), value); } } /// <summary> /// アニメーションが停止したかどうかを取得または設定します。 /// </summary> public bool IsStopped { get { return GetValue<bool>(nameof(IsStopped)); } private set { SetValue(nameof(IsStopped), value); } } /// <summary> /// アニメーション対象となるオブジェクトを取得または設定します。 /// </summary> public object Target { get { return GetValue<object>(nameof(Target)); } set { SetValue(nameof(Target), value); } } /// <summary> /// アニメーション対象となるプロパティ名を取得または設定します。 /// </summary> public string TargetProperty { get { return GetValue<string>(nameof(TargetProperty)); } set { SetValue(nameof(TargetProperty), value); } } /// <summary> /// アニメーションを開始します。 /// </summary> public void Begin(object target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (this.initialized) { throw new InvalidOperationException( "PropertyAnimationはすでに開始されています。"); } if (IsCompleted) { throw new InvalidOperationException( "PropertyAnimationはすでに完了されています。"); } // Targetが既に設定されている場合は引数のtargetを無視します。 if (Target == null) { Target = target; } else { target = Target; } this.pobj = GetPropertyObject(target); this.startValue = this.pobj.GetValue(target); OnBegin(target); this.currentTick = BeginTimeMilliseconds; this.initialized = true; } /// <summary> /// プロパティ値の取得・設定用オブジェクトを取得します。 /// </summary> private IPropertyObject GetPropertyObject(object target) { var pobj = MethodUtil.GetPropertyObject( target.GetType(), TargetProperty); if (pobj == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "{0}.{1}: プロパティ名が正しくありません。", target.GetType(), TargetProperty)); } if (!pobj.PropertyType.Equals(TargetPropertyType)) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "{0}.{1}: プロパティの型が正しくありません。", target.GetType(), TargetProperty)); } if (!pobj.CanRead) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "{0}.{1}: このプロパティは読み込みできません。", target.GetType(), TargetProperty)); } if (!pobj.CanWrite) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, "{0}.{1}: このプロパティには書き込みできません。", target.GetType(), TargetProperty)); } return pobj; } /// <summary> /// アニメーションの開始処理を行います。 /// </summary> protected virtual void OnBegin(object target) { } /// <summary> /// アニメーションを停止します。 /// </summary> public void Stop() { if (!this.initialized) { return; } IsStopped = true; // 必要であれば値を元に戻します。 if (FillBehavior == FillBehavior.Stop) { this.pobj.SetValue(Target, this.startValue); } OnStop(); } /// <summary> /// アニメーションの停止処理を行います。 /// </summary> protected virtual void OnStop() { } /// <summary> /// アニメーションが完了したときに呼ばれます。 /// </summary> private void Complete() { // アニメーション完了時はフラグを立て、イベントを呼びます。 IsCompleted = true; Completed.SafeRaiseEvent(this, EventArgs.Empty); Stop(); } /// <summary> /// アニメーション完了時の処理を行います。 /// </summary> protected virtual void OnCompleted() { } /// <summary> /// アニメーションの更新処理を行います。 /// </summary> public void DoEnterFrame(TimeSpan elapsedTime, object state) { if (!this.initialized) { return; } var durationMillis = DurationMilliseconds; var frameTick = 0.0; // アニメーション時間を更新します。 this.currentTick += elapsedTime.TotalMilliseconds; // IsRepeatForeverの場合は永遠に繰り返します。 // AutoReverseの場合は、アニメーションが最後まで行った後 // 進行度を元に戻しながらアニメーションを続けます。 if (IsRepeatForever && Duration == TimeSpan.Zero) { // 永遠に繰り返す場合、Durationが0ならば // frameTimeを常に0にします。 frameTick = 0.0; } else if (IsRepeatForever) { // 永遠に繰り返す場合は、進行度を巻き戻しながら繰り返します。 while (this.currentTick >= durationMillis) { this.currentTick -= durationMillis; this.isReversing = !this.isReversing; } // 繰り返しの進む方向を鑑みながらframeTimeを決定します。 if (AutoReverse && this.isReversing) { // 逆方向に進行度を進める場合 frameTick = durationMillis - this.currentTick; } else { // 正方向に進行度を進める場合(通常時) frameTick = this.currentTick; } } else { // 永遠に繰り返さない場合は、時間が来たら終了します。 if (this.currentTick >= durationMillis) { Complete(); return; } frameTick = this.currentTick; } // 新たなアニメーション補間値を設定します。 var frameTime = TimeSpan.FromMilliseconds(frameTick); var newValue = UpdateProperty(frameTime); this.pobj.SetValue(Target, newValue); } /// <summary> /// アニメーションの更新を行います。 /// </summary> protected abstract object UpdateProperty(TimeSpan frameTime); } }
27.381333
78
0.481691
[ "MIT" ]
ebifrier/Ragnarok
Ragnarok.Extra/Effect/Animation/PropertyAnimation.cs
12,220
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.KeyVault.Outputs { [OutputType] public sealed class CertifiateCertificatePolicySecretProperties { /// <summary> /// The Content-Type of the Certificate, such as `application/x-pkcs12` for a PFX or `application/x-pem-file` for a PEM. Changing this forces a new resource to be created. /// </summary> public readonly string ContentType; [OutputConstructor] private CertifiateCertificatePolicySecretProperties(string contentType) { ContentType = contentType; } } }
31.928571
179
0.696868
[ "ECL-2.0", "Apache-2.0" ]
AdminTurnedDevOps/pulumi-azure
sdk/dotnet/KeyVault/Outputs/CertifiateCertificatePolicySecretProperties.cs
894
C#
namespace TeamCitySharp.ActionTypes { public class ActionHelper { /// <summary> /// Create a url with fields /// </summary> /// <param name="url"></param> /// <param name="fields"></param> /// <returns></returns> public static string CreateFieldUrl(string url, string fields) { // if fields is not empty, then update the url with the fields keyword, otherwise do nothing if (!string.IsNullOrEmpty(fields)) { if (url.Contains("?")) url += "&fields=" + fields; else url += "?fields=" + fields; } return url; } public static string CleanUrl(string url) { return url .Replace("/httpAuth", "") .Replace("/guestAuth", "") .Replace("/app/rest", ""); } } }
25.0625
98
0.546135
[ "MIT" ]
TattsGroup/TeamCitySharp
src/TeamCitySharp/ActionTypes/ActionHelper.cs
804
C#
using System; using System.Collections.Generic; namespace Anagram { public class testWord { public string testOutput; public string test(string testWord1) { string testWord = testWord1.ToLower(); string sortedWord = ""; List<string>anagramList = new List<string>{}; char[] array = testWord.ToCharArray(); Array.Sort(array); sortedWord = string.Join("", array); anagramList.Add(sortedWord); foreach(string wordItem in anagramList) { // if (testWord == anagramList[wordItem] testOutput += wordItem + " "; } return testOutput; } } class AnagramApp { static void Main() { testWord word = new testWord(); string anagram = ""; string testLine = ""; string testLine1 = ""; do { Console.WriteLine("Please Enter Anagram"); anagram = Console.ReadLine(); testLine = word.test(anagram); Console.WriteLine(testLine); } while (anagram != "stop"); // Main(); } } }
17.654545
47
0.633368
[ "MIT" ]
sonekase/anagram-csharp
Anagram/Anagram.cs
971
C#
using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; namespace depot.Mvc.Example { public class MvcApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
27.555556
70
0.689516
[ "MIT" ]
Dzmuh/webstack-by-daniel
depot/src/Depot.Mvc.Example/Global.asax.cs
498
C#
using UnityEngine; using UnityEngine.Tilemaps; namespace UnityEditor { /// <summary> /// The Editor for a HexagonalRuleTile. /// </summary> [CustomEditor(typeof(HexagonalRuleTile), true)] [CanEditMultipleObjects] public class HexagonalRuleTileEditor : RuleTileEditor { /// <summary> /// The HexagonalRuleTile being edited. /// </summary> public HexagonalRuleTile hexTile => target as HexagonalRuleTile; /// <summary> /// Gets the index for a Rule with the HexagonalRuleTile to display an arrow. /// </summary> /// <param name="position">The adjacent position of the arrow.</param> /// <returns>Returns the index for a Rule with the HexagonalRuleTile to display an arrow.</returns> public override int GetArrowIndex(Vector3Int position) { if (position.y % 2 != 0) { position *= 2; position.x += 1; } if (position.x == 0) { if (position.y > 0) return hexTile.m_FlatTop ? 3 : 1; else return hexTile.m_FlatTop ? 5 : 7; } else if (position.y == 0) { if (position.x > 0) return hexTile.m_FlatTop ? 1 : 5; else return hexTile.m_FlatTop ? 7 : 3; } else { if (position.x < 0 && position.y > 0) return hexTile.m_FlatTop ? 6 : 0; else if (position.x > 0 && position.y > 0) return hexTile.m_FlatTop ? 0 : 2; else if (position.x < 0 && position.y < 0) return hexTile.m_FlatTop ? 8 : 6; else if (position.x > 0 && position.y < 0) return hexTile.m_FlatTop ? 2 : 8; } return -1; } /// <summary> /// Get the GUI bounds for a Rule. /// </summary> /// <param name="bounds">Cell bounds of the Rule.</param> /// <param name="rule">Rule to get GUI bounds for.</param> /// <returns>The GUI bounds for a rule.</returns> public override BoundsInt GetRuleGUIBounds(BoundsInt bounds, RuleTile.TilingRule rule) { foreach (var n in rule.GetNeighbors()) { if (n.Key.x == bounds.xMax - 1 && n.Key.y % 2 != 0) { bounds.xMax++; break; } } return base.GetRuleGUIBounds(bounds, rule); } /// <summary> /// Gets the GUI matrix size for a Rule of a HexagonalRuleTile /// </summary> /// <param name="bounds">Cell bounds of the Rule.</param> /// <returns>Returns the GUI matrix size for a Rule of a HexagonalRuleTile.</returns> public override Vector2 GetMatrixSize(BoundsInt bounds) { Vector2 size = base.GetMatrixSize(bounds); return hexTile.m_FlatTop ? new Vector2(size.y, size.x) : size; } /// <summary> /// Draws a Rule Matrix for the given Rule for a HexagonalRuleTile. /// </summary> /// <param name="tile">Tile to draw rule for.</param> /// <param name="rect">GUI Rect to draw rule at.</param> /// <param name="bounds">Cell bounds of the Rule.</param> /// <param name="tilingRule">Rule to draw Rule Matrix for.</param> public override void RuleMatrixOnGUI(RuleTile tile, Rect rect, BoundsInt bounds, RuleTile.TilingRule tilingRule) { bool flatTop = hexTile.m_FlatTop; Handles.color = EditorGUIUtility.isProSkin ? new Color(1f, 1f, 1f, 0.2f) : new Color(0f, 0f, 0f, 0.2f); float w = rect.width / (flatTop ? bounds.size.y : bounds.size.x); float h = rect.height / (flatTop ? bounds.size.x : bounds.size.y); // Grid if (flatTop) { for (int y = 0; y <= bounds.size.y; y++) { float left = rect.xMin + y * w; float offset = 0; if (y == 0 && bounds.yMax % 2 == 0) offset = h / 2; else if (y == bounds.size.y && bounds.yMin % 2 != 0) offset = h / 2; Handles.DrawLine(new Vector3(left, rect.yMin + offset), new Vector3(left, rect.yMax - offset)); if (y < bounds.size.y) { bool noOffset = (y + bounds.yMax) % 2 != 0; for (int x = 0; x < (noOffset ? (bounds.size.x + 1) : bounds.size.x); x++) { float top = rect.yMin + x * h + (noOffset ? 0 : h / 2); Handles.DrawLine(new Vector3(left, top), new Vector3(left + w, top)); } } } } else { for (int y = 0; y <= bounds.size.y; y++) { float top = rect.yMin + y * h; float offset = 0; if (y == 0 && bounds.yMax % 2 == 0) offset = w / 2; else if (y == bounds.size.y && bounds.yMin % 2 != 0) offset = w / 2; Handles.DrawLine(new Vector3(rect.xMin + offset, top), new Vector3(rect.xMax - offset, top)); if (y < bounds.size.y) { bool noOffset = (y + bounds.yMax) % 2 != 0; for (int x = 0; x < (noOffset ? (bounds.size.x + 1) : bounds.size.x); x++) { float left = rect.xMin + x * w + (noOffset ? 0 : w / 2); Handles.DrawLine(new Vector3(left, top), new Vector3(left, top + h)); } } } } var neighbors = tilingRule.GetNeighbors(); // Icons Handles.color = Color.white; for (int y = bounds.yMin; y < bounds.yMax; y++) { int xMax = y % 2 == 0 ? bounds.xMax : (bounds.xMax - 1); for (int x = bounds.xMin; x < xMax; x++) { Vector3Int pos = new Vector3Int(x, y, 0); Vector2 offset = new Vector2(x - bounds.xMin, -y + bounds.yMax - 1); Rect r = flatTop ? new Rect(rect.xMin + offset.y * w, rect.yMax - offset.x * h - h, w - 1, h - 1) : new Rect(rect.xMin + offset.x * w, rect.yMin + offset.y * h, w - 1, h - 1); if (y % 2 != 0) { if (flatTop) r.y -= h / 2; else r.x += w / 2; } RuleMatrixIconOnGUI(tilingRule, neighbors, pos, r); } } } /// <summary> /// Creates a Preview for the HexagonalRuleTile. /// </summary> protected override void CreatePreview() { base.CreatePreview(); m_PreviewGrid.cellLayout = GridLayout.CellLayout.Hexagon; m_PreviewGrid.cellSize = new Vector3(0.8659766f, 1.0f, 1.0f); m_PreviewGrid.cellSwizzle = hexTile.m_FlatTop ? GridLayout.CellSwizzle.YXZ : GridLayout.CellSwizzle.XYZ; foreach (var tilemap in m_PreviewTilemaps) { tilemap.tileAnchor = Vector3.zero; tilemap.ClearAllTiles(); } for (int x = -1; x <= 0; ++x) for (int y = -1; y <= 1; ++y) m_PreviewTilemaps[0].SetTile(new Vector3Int(x, y, 0), tile); m_PreviewTilemaps[1].SetTile(new Vector3Int(1, -1, 0), tile); m_PreviewTilemaps[1].SetTile(new Vector3Int(2, 0, 0), tile); m_PreviewTilemaps[1].SetTile(new Vector3Int(2, 1, 0), tile); for (int x = -1; x <= 1; x++) m_PreviewTilemaps[2].SetTile(new Vector3Int(x, -2, 0), tile); m_PreviewTilemaps[3].SetTile(new Vector3Int(1, 1, 0), tile); foreach (var tilemapRenderer in m_PreviewTilemapRenderers) tilemapRenderer.sortOrder = TilemapRenderer.SortOrder.TopRight; m_PreviewTilemapRenderers[0].sortingOrder = 0; m_PreviewTilemapRenderers[1].sortingOrder = -1; m_PreviewTilemapRenderers[2].sortingOrder = 1; m_PreviewTilemapRenderers[3].sortingOrder = 0; } } }
39.272321
120
0.468
[ "MIT" ]
AGGP-NHTI/Abeille
Assets/Systems/2d-extras-master/Editor/Tiles/HexagonalRuleTile/HexagonalRuleTileEditor.cs
8,797
C#
using Xunit; using Verify = CSharpVerifier<Xunit.Analyzers.SerializableClassMustHaveParameterlessConstructor>; public class SerializableClassMustHaveParameterlessConstructorFixerTests { [Fact] public async void WithPublicParameteredConstructor_AddsNewConstructor() { var before = @" public class [|MyTestCase|]: Xunit.Abstractions.IXunitSerializable { public MyTestCase(int x) { } void Xunit.Abstractions.IXunitSerializable.Deserialize(Xunit.Abstractions.IXunitSerializationInfo _) { } void Xunit.Abstractions.IXunitSerializable.Serialize(Xunit.Abstractions.IXunitSerializationInfo _) { } }"; var after = @" public class MyTestCase: Xunit.Abstractions.IXunitSerializable { [System.Obsolete(""Called by the de-serializer; should only be called by deriving classes for de-serialization purposes"")] public MyTestCase() { } public MyTestCase(int x) { } void Xunit.Abstractions.IXunitSerializable.Deserialize(Xunit.Abstractions.IXunitSerializationInfo _) { } void Xunit.Abstractions.IXunitSerializable.Serialize(Xunit.Abstractions.IXunitSerializationInfo _) { } }"; await Verify.VerifyCodeFixAsyncV2(before, after); } [Fact] public async void WithNonPublicParameterlessConstructor_ChangesVisibility_WithoutUsing() { var before = @" public class [|MyTestCase|]: Xunit.Abstractions.IXunitSerializable { protected MyTestCase() { throw new System.DivideByZeroException(); } void Xunit.Abstractions.IXunitSerializable.Deserialize(Xunit.Abstractions.IXunitSerializationInfo _) { } void Xunit.Abstractions.IXunitSerializable.Serialize(Xunit.Abstractions.IXunitSerializationInfo _) { } }"; var after = @" public class MyTestCase: Xunit.Abstractions.IXunitSerializable { [System.Obsolete(""Called by the de-serializer; should only be called by deriving classes for de-serialization purposes"")] public MyTestCase() { throw new System.DivideByZeroException(); } void Xunit.Abstractions.IXunitSerializable.Deserialize(Xunit.Abstractions.IXunitSerializationInfo _) { } void Xunit.Abstractions.IXunitSerializable.Serialize(Xunit.Abstractions.IXunitSerializationInfo _) { } }"; await Verify.VerifyCodeFixAsyncV2(before, after); } [Fact] public async void WithNonPublicParameterlessConstructor_ChangesVisibility_WithUsing() { var before = @" using System; using Xunit.Abstractions; public class [|MyTestCase|]: IXunitSerializable { protected MyTestCase() { throw new DivideByZeroException(); } void IXunitSerializable.Deserialize(IXunitSerializationInfo _) { } void IXunitSerializable.Serialize(IXunitSerializationInfo _) { } }"; var after = @" using System; using Xunit.Abstractions; public class MyTestCase: IXunitSerializable { [Obsolete(""Called by the de-serializer; should only be called by deriving classes for de-serialization purposes"")] public MyTestCase() { throw new DivideByZeroException(); } void IXunitSerializable.Deserialize(IXunitSerializationInfo _) { } void IXunitSerializable.Serialize(IXunitSerializationInfo _) { } }"; await Verify.VerifyCodeFixAsyncV2(before, after); } [Fact] public async void PreservesExistingObsoleteAttribute() { var before = @" using Xunit.Abstractions; using obo = System.ObsoleteAttribute; public class [|MyTestCase|]: IXunitSerializable { [obo(""This is my custom obsolete message"")] protected MyTestCase() { throw new System.DivideByZeroException(); } void IXunitSerializable.Deserialize(IXunitSerializationInfo _) { } void IXunitSerializable.Serialize(IXunitSerializationInfo _) { } }"; var after = @" using Xunit.Abstractions; using obo = System.ObsoleteAttribute; public class MyTestCase: IXunitSerializable { [obo(""This is my custom obsolete message"")] public MyTestCase() { throw new System.DivideByZeroException(); } void IXunitSerializable.Deserialize(IXunitSerializationInfo _) { } void IXunitSerializable.Serialize(IXunitSerializationInfo _) { } }"; await Verify.VerifyCodeFixAsyncV2(before, after); } }
36.13913
128
0.752887
[ "Apache-2.0" ]
louis-z/xunit.analyzers
src/xunit.analyzers.tests/Fixes/SerializableClassMustHaveParameterlessConstructorFixerTests.cs
4,044
C#
using System.Collections.Generic; using System.Globalization; using System.Linq; using Umbraco.Core.Models; using Umbraco.Web; using Umbraco.Web.Models; using RareDiseases.Common; using RareDiseases.Models.DocumentTypes.Nodes; using RareDiseases.Models.DocumentTypes.Pages; using RareDiseases.Models.Extensions; using RareDiseases.Models.Helpers; namespace RareDiseases.Models.DocumentTypes.Compositions { public class PageModel : RenderModel, IUmbracoCachedModel { public PageModel() : this(new UmbracoHelper(UmbracoContext.Current).TypedContent(UmbracoContext.Current.PageId)) { } public PageModel(IPublishedContent content) : base(content) { } public PageModel(IPublishedContent content, CultureInfo culture) : base(content, culture) { } #region [Content] public string Title => this.GetPropertyWithDefaultValue(Name); #endregion #region [SEO] public string SeoTitle => this.GetPropertyWithDefaultValue(Title); public string SeoDescription => this.GetPropertyValue<string>(); public string SeoKeywords => this.GetPropertyValue<string>(); public string SeoAuthor => this.GetPropertyValue<string>(); #endregion #region [Page Settings] public bool HideFromSiteNavigation => UmbracoNaviHide; public bool HideFromSiteSearch => this.GetPropertyValue<bool>(); public bool HideFromGoogleSearch => this.GetPropertyValue<bool>(); public bool HideFromSitemap => this.GetPropertyValue<bool>(); public string ExternalRedirect => this.GetPropertyValue<string>(); #endregion #region [Additional] public IEnumerable<PageModel> NavigationItems => this.GetCachedValue(() => Content.GetNavigationItems()); public IEnumerable<PageModel> SideBarNavigationItems => this.GetCachedValue(() => Content.GetSideBarNavigationItems(Constants.HomePageLevel + 1)); public IEnumerable<PageModel> SitemapItems => this.GetCachedValue(() => Content.GetSitemapItems()); public IEnumerable<PageModel> SitemapXMLItems => this.GetCachedValue(() => Content.GetSitemapXMLItems()); public HomeModel Home => this.GetCachedValue(() => GetHomeModel()); public SettingsModel Settings => this.GetCachedValue(() => GetSettingsModel()); public bool IsActivePage => this.GetCachedValue(() => GetIsActivePage()); public bool HasNavigationItems => this.GetCachedValue(() => NavigationItems.Any()); public string FullUrl => this.GetCachedValue(() => Content.UrlAbsolute()); public string Url => Content.Url; #endregion IDictionary<string, object> IUmbracoCachedModel.CachedProperties { get; } = new Dictionary<string, object>(); protected readonly UmbracoHelper UmbracoHelper = new UmbracoHelper(UmbracoContext.Current); protected string Name => Content.Name; private bool UmbracoNaviHide => this.GetPropertyValue<bool>(); private HomeModel GetHomeModel() { return Content.AncestorOrSelf(Constants.HomePageLevel).AsType<HomeModel>(); } private SettingsModel GetSettingsModel() { return UmbracoHelper.TypedContentSingleAtXPath("//Settings").AsType<SettingsModel>(); } private bool GetIsActivePage() { string currentPath = UmbracoContext.Current.PublishedContentRequest.PublishedContent.Path; return Utility.ContainsId(currentPath, Content.Id); } } }
34.084211
148
0.769302
[ "Apache-2.0" ]
tamarakatic/RareDiseases
RareDiseases.Models/DocumentTypes/Compositions/PageModel.cs
3,240
C#
using System; namespace Sample.Exceptionless.WebApi { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
19.25
69
0.616883
[ "MIT" ]
raychiutw/exceptionless_sample
src/Sample.Exceptionless.WebApi/WeatherForecast.cs
308
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Succubus.Backend.ZeroMQ.Messages.Diagnostics { class Ping : IDiagnostics { public DateTime Timestamp { get; set; } } }
19.071429
54
0.726592
[ "MIT" ]
COCPORN/succubus
src/Succubus/Succubus.Backend.ZeroMQ/Messages/Diagnostics/Ping.cs
269
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SevenTiny.Bantina.Logging; using SevenTiny.Cloud.ScriptEngine; using SevenTiny.Cloud.ScriptEngine.CSharp; namespace SevenTiny.Cloud.FaaS.GRpc { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddGrpc(); services.AddSingleton<IDynamicScriptEngine, CSharpDynamicScriptEngine>(); services.AddSingleton<ILogger, LogManager>(); } // 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.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGrpcService<DynamicScriptExecutorService>(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); }); }); } } }
36.468085
215
0.65986
[ "Apache-2.0" ]
sevenTiny/Chameleon.FaaS
src/dotnet/old/SevenTiny.Cloud.FaaS.GRpc/Startup.cs
1,716
C#
using SMLHelper.V2.Json; using SMLHelper.V2.Options.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ScannerRoomUpgrades.Configuration { public class Config: ConfigFile { } }
17.4375
43
0.774194
[ "MIT" ]
desperationfighter/Subnautica-Mods
ScannerRoomUpgrades/Configuration/Config.cs
281
C#
// SplitOrderedList.cs // // Copyright (c) 2010 Jérémie "Garuma" Laval // // 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.Threading; using System.Collections; using System.Collections.Generic; namespace erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen { internal class SplitOrderedList<TKey, T> { class Node { public bool Marked; public ulong Key; public TKey SubKey; public T Data; public Node Next; public Node Init (ulong key, TKey subKey, T data) { this.Key = key; this.SubKey = subKey; this.Data = data; this.Marked = false; this.Next = null; return this; } // Used to create dummy node public Node Init (ulong key) { this.Key = key; this.Data = default (T); this.Next = null; this.Marked = false; this.SubKey = default (TKey); return this; } // Used to create marked node public Node Init (Node wrapped) { this.Marked = true; this.Next = wrapped; this.Key = 0; this.Data = default (T); this.SubKey = default (TKey); return this; } } const int MaxLoad = 5; const uint BucketSize = 512; Node head; Node tail; Node[] buckets = new Node [BucketSize]; int count; int size = 2; SimpleRwLock slim = new SimpleRwLock (); readonly IEqualityComparer<TKey> comparer; public SplitOrderedList (IEqualityComparer<TKey> comparer) { this.comparer = comparer; head = new Node ().Init (0); tail = new Node ().Init (ulong.MaxValue); head.Next = tail; SetBucket (0, head); } public int Count { get { return count; } } public T InsertOrUpdate (uint key, TKey subKey, Func<T> addGetter, Func<T, T> updateGetter) { Node current; bool result = InsertInternal (key, subKey, default (T), addGetter, out current); if (result) return current.Data; // FIXME: this should have a CAS-like behavior return current.Data = updateGetter (current.Data); } public T InsertOrUpdate (uint key, TKey subKey, T addValue, T updateValue) { Node current; if (InsertInternal (key, subKey, addValue, null, out current)) return current.Data; // FIXME: this should have a CAS-like behavior return current.Data = updateValue; } public bool Insert (uint key, TKey subKey, T data) { Node current; return InsertInternal (key, subKey, data, null, out current); } public T InsertOrGet (uint key, TKey subKey, T data, Func<T> dataCreator) { Node current; InsertInternal (key, subKey, data, dataCreator, out current); return current.Data; } bool InsertInternal (uint key, TKey subKey, T data, Func<T> dataCreator, out Node current) { Node node = new Node ().Init (ComputeRegularKey (key), subKey, data); uint b = key % (uint)size; Node bucket; if ((bucket = GetBucket (b)) == null) bucket = InitializeBucket (b); if (!ListInsert (node, bucket, out current, dataCreator)) return false; int csize = size; if (Interlocked.Increment (ref count) / csize > MaxLoad && (csize & 0x40000000) == 0) Interlocked.CompareExchange (ref size, 2 * csize, csize); current = node; return true; } public bool Find (uint key, TKey subKey, out T data) { Node node; uint b = key % (uint)size; data = default (T); Node bucket; if ((bucket = GetBucket (b)) == null) bucket = InitializeBucket (b); if (!ListFind (ComputeRegularKey (key), subKey, bucket, out node)) return false; data = node.Data; return !node.Marked; } public bool CompareExchange (uint key, TKey subKey, T data, Func<T, bool> check) { Node node; uint b = key % (uint)size; Node bucket; if ((bucket = GetBucket (b)) == null) bucket = InitializeBucket (b); if (!ListFind (ComputeRegularKey (key), subKey, bucket, out node)) return false; if (!check (node.Data)) return false; node.Data = data; return true; } public bool Delete (uint key, TKey subKey, out T data) { uint b = key % (uint)size; Node bucket; if ((bucket = GetBucket (b)) == null) bucket = InitializeBucket (b); if (!ListDelete (bucket, ComputeRegularKey (key), subKey, out data)) return false; Interlocked.Decrement (ref count); return true; } public IEnumerator<T> GetEnumerator () { Node node = head.Next; while (node != tail) { while (node.Marked || (node.Key & 1) == 0) { node = node.Next; if (node == tail) yield break; } yield return node.Data; node = node.Next; } } Node InitializeBucket (uint b) { Node current; uint parent = GetParent (b); Node bucket; if ((bucket = GetBucket (parent)) == null) bucket = InitializeBucket (parent); Node dummy = new Node ().Init (ComputeDummyKey (b)); if (!ListInsert (dummy, bucket, out current, null)) return current; return SetBucket (b, dummy); } // Turn v's MSB off static uint GetParent (uint v) { uint t, tt; // Find MSB position in v var pos = (tt = v >> 16) > 0 ? (t = tt >> 8) > 0 ? 24 + logTable[t] : 16 + logTable[tt] : (t = v >> 8) > 0 ? 8 + logTable[t] : logTable[v]; return (uint)(v & ~(1 << pos)); } // Reverse integer bits and make sure LSB is set static ulong ComputeRegularKey (uint key) { return ComputeDummyKey (key) | 1; } // Reverse integer bits static ulong ComputeDummyKey (uint key) { return ((ulong)(((uint)reverseTable[key & 0xff] << 24) | ((uint)reverseTable[(key >> 8) & 0xff] << 16) | ((uint)reverseTable[(key >> 16) & 0xff] << 8) | ((uint)reverseTable[(key >> 24) & 0xff]))) << 1; } // Bucket storage is abstracted in a simple two-layer tree to avoid too much memory resize Node GetBucket (uint index) { if (index >= buckets.Length) return null; return buckets[index]; } Node SetBucket (uint index, Node node) { try { slim.EnterReadLock (); CheckSegment (index, true); Interlocked.CompareExchange (ref buckets[index], node, null); return buckets[index]; } finally { slim.ExitReadLock (); } } // When we run out of space for bucket storage, we use a lock-based array resize void CheckSegment (uint segment, bool readLockTaken) { if (segment < buckets.Length) return; if (readLockTaken) slim.ExitReadLock (); try { slim.EnterWriteLock (); while (segment >= buckets.Length) Array.Resize (ref buckets, buckets.Length * 2); } finally { slim.ExitWriteLock (); } if (readLockTaken) slim.EnterReadLock (); } Node ListSearch (ulong key, TKey subKey, ref Node left, Node h) { Node leftNodeNext = null, rightNode = null; do { Node t = h; Node tNext = t.Next; do { if (!tNext.Marked) { left = t; leftNodeNext = tNext; } t = tNext.Marked ? tNext.Next : tNext; if (t == tail) break; tNext = t.Next; } while (tNext.Marked || t.Key < key || (tNext.Key == key && !comparer.Equals (subKey, t.SubKey))); rightNode = t; if (leftNodeNext == rightNode) { if (rightNode != tail && rightNode.Next.Marked) continue; else return rightNode; } if (Interlocked.CompareExchange (ref left.Next, rightNode, leftNodeNext) == leftNodeNext) { if (rightNode != tail && rightNode.Next.Marked) continue; else return rightNode; } } while (true); } bool ListDelete (Node startPoint, ulong key, TKey subKey, out T data) { Node rightNode = null, rightNodeNext = null, leftNode = null; data = default (T); Node markedNode = null; do { rightNode = ListSearch (key, subKey, ref leftNode, startPoint); if (rightNode == tail || rightNode.Key != key || !comparer.Equals (subKey, rightNode.SubKey)) return false; data = rightNode.Data; rightNodeNext = rightNode.Next; if (!rightNodeNext.Marked) { if (markedNode == null) markedNode = new Node (); markedNode.Init (rightNodeNext); if (Interlocked.CompareExchange (ref rightNode.Next, markedNode, rightNodeNext) == rightNodeNext) break; } } while (true); if (Interlocked.CompareExchange (ref leftNode.Next, rightNodeNext, rightNode) != rightNode) ListSearch (rightNode.Key, subKey, ref leftNode, startPoint); return true; } bool ListInsert (Node newNode, Node startPoint, out Node current, Func<T> dataCreator) { ulong key = newNode.Key; Node rightNode = null, leftNode = null; do { rightNode = current = ListSearch (key, newNode.SubKey, ref leftNode, startPoint); if (rightNode != tail && rightNode.Key == key && comparer.Equals (newNode.SubKey, rightNode.SubKey)) return false; newNode.Next = rightNode; if (dataCreator != null) newNode.Data = dataCreator (); if (Interlocked.CompareExchange (ref leftNode.Next, newNode, rightNode) == rightNode) return true; } while (true); } bool ListFind (ulong key, TKey subKey, Node startPoint, out Node data) { Node rightNode = null, leftNode = null; data = null; rightNode = ListSearch (key, subKey, ref leftNode, startPoint); data = rightNode; return rightNode != tail && rightNode.Key == key && comparer.Equals (subKey, rightNode.SubKey); } static readonly byte[] reverseTable = { 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, 11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, 7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255 }; static readonly byte[] logTable = { 0xFF, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }; struct SimpleRwLock { const int RwWait = 1; const int RwWrite = 2; const int RwRead = 4; int rwlock; public void EnterReadLock () { SpinWait sw = new SpinWait (); do { while ((rwlock & (RwWrite | RwWait)) > 0) sw.SpinOnce (); if ((Interlocked.Add (ref rwlock, RwRead) & (RwWait | RwWait)) == 0) return; Interlocked.Add (ref rwlock, -RwRead); } while (true); } public void ExitReadLock () { Interlocked.Add (ref rwlock, -RwRead); } public void EnterWriteLock () { SpinWait sw = new SpinWait (); do { int state = rwlock; if (state < RwWrite) { if (Interlocked.CompareExchange (ref rwlock, RwWrite, state) == state) return; state = rwlock; } // We register our interest in taking the Write lock (if upgradeable it's already done) while ((state & RwWait) == 0 && Interlocked.CompareExchange (ref rwlock, state | RwWait, state) != state) state = rwlock; // Before falling to sleep while (rwlock > RwWait) sw.SpinOnce (); } while (true); } public void ExitWriteLock () { Interlocked.Add (ref rwlock, -RwWrite); } } } internal struct SpinWait { // The number of step until SpinOnce yield on multicore machine const int step = 10; const int maxTime = 200; static readonly bool isSingleCpu = (Environment.ProcessorCount == 1); int ntime; public void SpinOnce () { ntime += 1; ManualResetEvent mre = new ManualResetEvent (false); if (isSingleCpu) { // On a single-CPU system, spinning does no good mre.WaitOne (0); } else { if (ntime % step == 0) mre.WaitOne (0); else // Multi-CPU system might be hyper-threaded, let other thread run mre.WaitOne (Math.Min (ntime, maxTime) << 1); } } } }
28.328713
1,171
0.610373
[ "MIT" ]
espenrl/TnsNames
erl.Oracle.TnsNames/Antlr4.Runtime/Sharpen/Compat/SplitOrderedList.cs
14,308
C#
using System.Runtime.Serialization; namespace jcFUS.PCL.Transports.Auth { [DataContract] public class AuthRequestItem { [DataMember] public string Username { get; set; } [DataMember] public string Password { get; set; } } }
22.5
44
0.637037
[ "MIT" ]
jcapellman/jcFUS
jcFUS.PCL/Transports/Auth/AuthRequestItem.cs
272
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Avalonia; using Avalonia.Controls; namespace GridExtra.Avalonia { public partial class ResponsiveGrid { static ResponsiveGrid() { AffectsMeasure<ResponsiveGrid>(MaxDivisionProperty, BreakPointsProperty, XSProperty, SMProperty, MDProperty, LGProperty, XSProperty, SMProperty, XS_OffsetProperty, XS_PullProperty, XS_PushProperty, LG_OffsetProperty, LG_PullProperty, LG_PushProperty, MD_OffsetProperty, MD_PushProperty, MD_PullProperty ); } // 各種ブレークポイントの設定用プロパティ public int MaxDivision { get { return (int)GetValue(MaxDivisionProperty); } set { SetValue(MaxDivisionProperty, value); } } public static readonly StyledProperty<int> MaxDivisionProperty = AvaloniaProperty.Register<ResponsiveGrid, int>(nameof(MaxDivision), 12); public SizeThresholds Thresholds { get { return GetValue(BreakPointsProperty); } set { SetValue(BreakPointsProperty, value); } } public static readonly StyledProperty<SizeThresholds> BreakPointsProperty = AvaloniaProperty.Register<ResponsiveGrid, SizeThresholds>(nameof(Thresholds), null); public static int GetXS(AvaloniaObject obj) { return obj.GetValue(XSProperty); } public static void SetXS(AvaloniaObject obj, int value) { obj.SetValue(XSProperty, value); } // Using a AvaloniaProperty as the backing store for XS. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> XSProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("XS", 0); public static int GetSM(AvaloniaObject obj) { return obj.GetValue(SMProperty); } public static void SetSM(AvaloniaObject obj, int value) { obj.SetValue(SMProperty, value); } // Using a AvaloniaProperty as the backing store for SM. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> SMProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("SM", 0); public static int GetMD(AvaloniaObject obj) { return obj.GetValue(MDProperty); } public static void SetMD(AvaloniaObject obj, int value) { obj.SetValue(MDProperty, value); } // Using a AvaloniaProperty as the backing store for MD. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> MDProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("MD", 0); public static int GetLG(AvaloniaObject obj) { return obj.GetValue(LGProperty); } public static void SetLG(AvaloniaObject obj, int value) { obj.SetValue(LGProperty, value); } // Using a AvaloniaProperty as the backing store for LG. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> LGProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("LG", 0); public static int GetXS_Offset(AvaloniaObject obj) { return obj.GetValue(XS_OffsetProperty); } public static void SetXS_Offset(AvaloniaObject obj, int value) { obj.SetValue(XS_OffsetProperty, value); } public static readonly AvaloniaProperty<int> XS_OffsetProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("XS_Offset", 0); public static int GetSM_Offset(AvaloniaObject obj) { return obj.GetValue(SM_OffsetProperty); } public static void SetSM_Offset(AvaloniaObject obj, int value) { obj.SetValue(SM_OffsetProperty, value); } public static readonly AvaloniaProperty<int> SM_OffsetProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("SM_Offset", 0); public static int GetMD_Offset(AvaloniaObject obj) { return obj.GetValue(MD_OffsetProperty); } public static void SetMD_Offset(AvaloniaObject obj, int value) { obj.SetValue(MD_OffsetProperty, value); } public static readonly AvaloniaProperty<int> MD_OffsetProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("SM_Offset", 0); public static int GetLG_Offset(AvaloniaObject obj) { return obj.GetValue(LG_OffsetProperty); } public static void SetLG_Offset(AvaloniaObject obj, int value) { obj.SetValue(LG_OffsetProperty, value); } // Using a AvaloniaProperty as the backing store for LG_Offset. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> LG_OffsetProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("LG_Offset", 0); public static int GetXS_Push(AvaloniaObject obj) { return obj.GetValue(XS_PushProperty); } public static void SetXS_Push(AvaloniaObject obj, int value) { obj.SetValue(XS_PushProperty, value); } // Using a AvaloniaProperty as the backing store for XS_Push. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> XS_PushProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("XS_Push", 0); public static int GetSM_Push(AvaloniaObject obj) { return obj.GetValue(SM_PushProperty); } public static void SetSM_Push(AvaloniaObject obj, int value) { obj.SetValue(SM_PushProperty, value); } // Using a AvaloniaProperty as the backing store for SM_Push. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> SM_PushProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("SM_Push", 0); public static int GetMD_Push(AvaloniaObject obj) { return obj.GetValue(MD_PushProperty); } public static void SetMD_Push(AvaloniaObject obj, int value) { obj.SetValue(MD_PushProperty, value); } // Using a AvaloniaProperty as the backing store for MD_Push. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> MD_PushProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("MD_Push", 0); public static int GetLG_Push(AvaloniaObject obj) { return obj.GetValue(LG_PushProperty); } public static void SetLG_Push(AvaloniaObject obj, int value) { obj.SetValue(LG_PushProperty, value); } // Using a AvaloniaProperty as the backing store for LG_Push. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> LG_PushProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("LG_Push", 0); public static int GetXS_Pull(AvaloniaObject obj) { return obj.GetValue(XS_PullProperty); } public static void SetXS_Pull(AvaloniaObject obj, int value) { obj.SetValue(XS_PullProperty, value); } // Using a AvaloniaProperty as the backing store for XS_Pull. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> XS_PullProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("XS_Pull", 0); public static int GetSM_Pull(AvaloniaObject obj) { return obj.GetValue(SM_PullProperty); } public static void SetSM_Pull(AvaloniaObject obj, int value) { obj.SetValue(SM_PullProperty, value); } // Using a AvaloniaProperty as the backing store for SM_Pull. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> SM_PullProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("SM_Pull", 0); public static int GetMD_Pull(AvaloniaObject obj) { return obj.GetValue(MD_PullProperty); } public static void SetMD_Pull(AvaloniaObject obj, int value) { obj.SetValue(MD_PullProperty, value); } // Using a AvaloniaProperty as the backing store for MD_Pull. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> MD_PullProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("MD_Pull", 0); public static int GetLG_Pull(AvaloniaObject obj) { return obj.GetValue(LG_PullProperty); } public static void SetLG_Pull(AvaloniaObject obj, int value) { obj.SetValue(LG_PullProperty, value); } // Using a AvaloniaProperty as the backing store for LG_Pull. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> LG_PullProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("LG_Pull", 0); public static int GetActualColumn(AvaloniaObject obj) { return obj.GetValue(ActualColumnProperty); } protected static void SetActualColumn(AvaloniaObject obj, int value) { obj.SetValue(ActualColumnProperty, value); } // Using a AvaloniaProperty as the backing store for ActualColumn. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> ActualColumnProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("ActualColumn", 0); public static int GetActualRow(AvaloniaObject obj) { return obj.GetValue(ActualRowProperty); } protected static void SetActualRow(AvaloniaObject obj, int value) { obj.SetValue(ActualRowProperty, value); } // Using a AvaloniaProperty as the backing store for ActualRow. This enables animation, styling, binding, etc... public static readonly AvaloniaProperty<int> ActualRowProperty = AvaloniaProperty.RegisterAttached<ResponsiveGrid, Control, int>("ActualRow", 0); } }
35.049231
124
0.623738
[ "MIT" ]
jmacato/GridExtra
GridExtra.Avalonia/ResponsiveGrid.Properties.cs
11,431
C#
#region Copyright & License /* Copyright (c) 2022, Integrated Solutions, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Integrated Solutions, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.Collections.Generic; using System.Text; namespace ISI.Extensions.Jenkins { public class View { public string Name { get; set; } public string Description { get; set; } public string Url { get; set; } public Job[] Jobs { get; set; } public string GetDetailsUrlJson => this.Url + "api/json"; } }
60.967742
754
0.78836
[ "BSD-3-Clause" ]
ISI-Extensions/ISI.Extensions
src/ISI.Extensions.Jenkins/View.cs
1,892
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SWCustomProperties.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SWCustomProperties.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.791667
184
0.605084
[ "MIT" ]
Compac-Michael/SWCustomProperties
SWCustomProperties/SWCustomProperties/Properties/Resources.Designer.cs
2,795
C#
// Copyright (c) True Goodwill. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace FFT.TimeStamps.Benchmarks { using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; using BenchmarkDotNet.Attributes; using FILETIME = System.Runtime.InteropServices.ComTypes.FILETIME; /// <summary> /// This benchmark code was used to help determine the best way to get a value for TimeStamp.Now. /// </summary> public class NowMethods { private const string KERNEL32 = "kernel32.dll"; // Benchmark results - make sure you update this if you modify the code below. /* | Method | Mean | Error | StdDev | |-------------------- |---------:|---------:|---------:| | GetNowViaDateTime | 79.18 ns | 0.908 ns | 0.804 ns | | GetNowViaSystemCall | 16.32 ns | 0.161 ns | 0.143 ns | */ [Benchmark] public long GetNowViaDateTime() => DateTime.UtcNow.Ticks; [Benchmark] public long GetNowViaSystemCall() => GetSystemTimeAsFileTime(); private static long GetSystemTimeAsFileTime() { GetSystemTimeAsFileTime(out var fileTime); long time = 0; time |= (uint)fileTime.dwHighDateTime; time <<= sizeof(uint) * 8; time |= (uint)fileTime.dwLowDateTime; return time + 0x701ce1722770000L; } [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] private static extern void GetSystemTimeAsFileTime([Out] out FILETIME time); } }
33.041667
101
0.65889
[ "MIT" ]
FastFinTech/FFT.TimeStamps
src/FFT.TimeStamps.Benchmarks/NowMethods.cs
1,588
C#
using System.IO; using System.Reflection; using System.Runtime.CompilerServices; namespace FFXIV.Framework.Common { public class DirectoryHelper { [MethodImpl(MethodImplOptions.NoInlining)] public static string FindSubDirectory( string subDirectoryName) { var parentDirs = new string[] { Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }; foreach (var parentDir in parentDirs) { var dir = Path.Combine(parentDir, subDirectoryName); if (Directory.Exists(dir)) { return dir; } } return string.Empty; } public static void DirectoryCopy(string sourcePath, string destinationPath) { var sourceDirectory = new DirectoryInfo(sourcePath); var destinationDirectory = new DirectoryInfo(destinationPath); if (destinationDirectory.Exists == false) { destinationDirectory.Create(); destinationDirectory.Attributes = sourceDirectory.Attributes; } foreach (FileInfo fileInfo in sourceDirectory.GetFiles()) { fileInfo.CopyTo(destinationDirectory.FullName + @"\" + fileInfo.Name, true); } foreach (DirectoryInfo directoryInfo in sourceDirectory.GetDirectories()) { DirectoryCopy(directoryInfo.FullName, destinationDirectory.FullName + @"\" + directoryInfo.Name); } } } }
32.185185
114
0.570771
[ "BSD-3-Clause" ]
Xinkle/ACT.Hojoring
source/FFXIV.Framework/FFXIV.Framework/Common/DirectoryHelper.cs
1,738
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Controls; using System.Windows; using SnakeGame.ViewModel; namespace SnakeGame { public class Snake { private Path headEllipse; private Path tailEllipse; public SolidColorBrush BodyColor { get; set; } public SolidColorBrush HeadColor { get; set; } public Direction MovingDirection { get; set; } public int Length { get; set; } internal List<Tile> Body { get; } internal Tile Head { get; set; } public Snake(SolidColorBrush bodyColor, SolidColorBrush headColor, int length) { Length = length; BodyColor = bodyColor; HeadColor = headColor; MovingDirection = Direction.Right; Body = new List<Tile>(); headEllipse = null; tailEllipse = null; } public void InitializeSnake(Board board, int startX, int startY) { Head = board[startX, startY]; //Head.Fill(HeadColor); for (int i = 1; i <= Length; i++) { var square = board[startX - i, startY]; if (i < Length) square.Fill(BodyColor); Body.Add(square); } DrawHeadTail(); } public void DrawHeadTail() { if (headEllipse != null) Tile.myCanvas.Children.Remove(headEllipse); if (tailEllipse != null) Tile.myCanvas.Children.Remove(tailEllipse); int arcLength = 7 * Tile.Size; switch (MovingDirection) { case Direction.Left: headEllipse = DrawEllipse(arcLength, Tile.Size, Head.X + Tile.Size, Head.Y, 0, Tile.Size, HeadColor, 1); break; case Direction.Right: headEllipse = DrawEllipse(arcLength, Tile.Size, Head.X, Head.Y, 0, Tile.Size, HeadColor, 0); break; case Direction.Up: headEllipse = DrawEllipse(Tile.Size, arcLength, Head.X, Head.Y + Tile.Size, Tile.Size, 0, HeadColor, 0); break; case Direction.Down: headEllipse = DrawEllipse(Tile.Size, arcLength, Head.X, Head.Y, Tile.Size, 0, HeadColor, 1); break; } if (Body[Length - 2].RowIndex == Body.Last().RowIndex + 1) //Tail on the left tailEllipse = DrawEllipse(arcLength, Tile.Size, Body.Last().X + Tile.Size, Body.Last().Y, 0, Tile.Size, BodyColor, 1); else if (Body[Length - 2].RowIndex == Body.Last().RowIndex - 1) //Tail on the right tailEllipse = DrawEllipse(arcLength, Tile.Size, Body.Last().X, Body.Last().Y, 0, Tile.Size, BodyColor, 0); else if (Body[Length - 2].ColumnIndex == Body.Last().ColumnIndex + 1) //Tail pointed upwards tailEllipse = DrawEllipse(Tile.Size, arcLength, Body.Last().X, Body.Last().Y + Tile.Size, Tile.Size, 0, BodyColor, 0); else if (Body[Length - 2].ColumnIndex == Body.Last().ColumnIndex - 1) //Tail pointed down tailEllipse = DrawEllipse(Tile.Size, arcLength, Body.Last().X, Body.Last().Y, Tile.Size, 0, BodyColor, 1); } private Path DrawEllipse(int width, int height, int posX, int posY, int deltaX, int deltaY, SolidColorBrush color, int turn) { Path myPath = new Path(); myPath.Stroke = color; myPath.Fill = color; StreamGeometry geometry = new StreamGeometry(); using (StreamGeometryContext ctx = geometry.Open()) { ctx.BeginFigure(new Point(posX, posY), true, true); ctx.LineTo(new Point(posX + deltaX, posY + deltaY), false, false); ctx.ArcTo(new Point(posX, posY), new Size(width, height + 3), 0, false, (SweepDirection)turn, false, false); } geometry.Freeze(); myPath.Data = geometry; Tile.myCanvas.Children.Add(myPath); return myPath; } } }
39.813084
134
0.564085
[ "MIT" ]
Milka03/Snake-Game
SnakeGame/GameComponents/Snake.cs
4,262
C#
/* * Copyright(c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ extern alias TizenSystemInformation; using TizenSystemInformation.Tizen.System; using global::System; using System.ComponentModel; using System.Collections.Generic; using global::System.Runtime.InteropServices; using Tizen.NUI.BaseComponents; namespace Tizen.NUI { /// <summary> /// The window class is used internally for drawing.<br /> /// The window has an orientation and indicator properties.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public partial class Window : BaseHandle { private static readonly Window instance = Application.Instance?.GetWindow(); private global::System.Runtime.InteropServices.HandleRef stageCPtr; private Layer _rootLayer; private string _windowTitle; private List<Layer> _childLayers = new List<Layer>(); private LayoutController localController; private bool IsSupportedMultiWindow() { bool isSupported = false; Information.TryGetValue("http://tizen.org/feature/opengles.surfaceless_context", out isSupported); return isSupported; } internal Window(global::System.IntPtr cPtr, bool cMemoryOwn) : base(Interop.Window.Window_SWIGUpcast(cPtr), cMemoryOwn) { if (Interop.Stage.Stage_IsInstalled()) { stageCPtr = new global::System.Runtime.InteropServices.HandleRef(this, Interop.Stage.Stage_GetCurrent()); localController = new LayoutController(this); NUILog.Debug("layoutController id:" + localController.GetId()); } } /// <summary> /// Creates a new Window.<br /> /// This creates an extra window in addition to the default main window<br /> /// </summary> /// <param name="windowPosition">The position and size of the Window.</param> /// <param name="isTranslucent">Whether Window is translucent.</param> /// <returns>A new Window.</returns> /// <since_tizen> 6 </since_tizen> /// <feature> http://tizen.org/feature/opengles.surfaceless_context </feature> /// <exception cref="NotSupportedException">The required feature is not supported.</exception> public Window(Rectangle windowPosition = null, bool isTranslucent = false) : this(Interop.Window.Window_New__SWIG_0(Rectangle.getCPtr(windowPosition), "", isTranslucent), true) { if (IsSupportedMultiWindow() == false) { NUILog.Error("This device does not support surfaceless_context. So Window cannot be created. "); } if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Creates a new Window with a specific name.<br /> /// This creates an extra window in addition to the default main window<br /> /// </summary> /// <param name="name">The name for extra window. </param> /// <param name="windowPosition">The position and size of the Window.</param> /// <param name="isTranslucent">Whether Window is translucent.</param> /// <returns>A new Window.</returns> /// <since_tizen> 6 </since_tizen> /// <feature> http://tizen.org/feature/opengles.surfaceless_context </feature> /// <exception cref="NotSupportedException">The required feature is not supported.</exception> public Window(string name, Rectangle windowPosition = null, bool isTranslucent = false) : this(Interop.Window.Window_New__SWIG_0(Rectangle.getCPtr(windowPosition), name, isTranslucent), true) { if (IsSupportedMultiWindow() == false) { NUILog.Error("This device does not support surfaceless_context. So Window cannot be created. "); } this._windowTitle = name; if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Enumeration for orientation of the window is the way in which a rectangular page is oriented for normal viewing. /// </summary> /// <since_tizen> 3 </since_tizen> public enum WindowOrientation { /// <summary> /// Portrait orientation. The height of the display area is greater than the width. /// </summary> /// <since_tizen> 3 </since_tizen> Portrait = 0, /// <summary> /// Landscape orientation. A wide view area is needed. /// </summary> /// <since_tizen> 3 </since_tizen> Landscape = 90, /// <summary> /// Portrait inverse orientation. /// </summary> /// <since_tizen> 3 </since_tizen> PortraitInverse = 180, /// <summary> /// Landscape inverse orientation. /// </summary> /// <since_tizen> 3 </since_tizen> LandscapeInverse = 270, /// <summary> /// No orientation. It is for the preferred orientation /// Especially, NoOrientationPreference only has the effect for the preferred orientation. /// It is used to unset the preferred orientation with SetPreferredOrientation. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] NoOrientationPreference = -1 } /// <summary> /// Enumeration for the key grab mode for platform-level APIs. /// </summary> /// <since_tizen> 3 </since_tizen> public enum KeyGrabMode { /// <summary> /// Grabs a key only when on the top of the grabbing-window stack mode. /// </summary> Topmost = 0, /// <summary> /// Grabs a key together with the other client window(s) mode. /// </summary> Shared, /// <summary> /// Grabs a key exclusively regardless of the grabbing-window's position on the window stack with the possibility of overriding the grab by the other client window mode. /// </summary> OverrideExclusive, /// <summary> /// Grabs a key exclusively regardless of the grabbing-window's position on the window stack mode. /// </summary> Exclusive }; /// <summary> /// Enumeration for transition effect's state. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public enum EffectStates { /// <summary> /// None state. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] None = 0, /// <summary> /// Transition effect is started. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] Start, /// <summary> /// Transition effect is ended. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] End, } /// <summary> /// Enumeration for transition effect's type. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public enum EffectTypes { /// <summary> /// None type. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] None = 0, /// <summary> /// Window show effect. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] Show, /// <summary> /// Window hide effect. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] Hide, } /// <summary> /// The stage instance property (read-only).<br /> /// Gets the current window.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public static Window Instance { get { return instance; } } /// <summary> /// Gets or sets a window type. /// </summary> /// <since_tizen> 3 </since_tizen> public WindowType Type { get { WindowType ret = (WindowType)Interop.Window.GetType(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } set { Interop.Window.SetType(swigCPtr, (int)value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } /// <summary> /// Gets/Sets a window title. /// </summary> /// <since_tizen> 4 </since_tizen> public string Title { get { return _windowTitle; } set { _windowTitle = value; SetClass(_windowTitle, ""); } } /// <summary> /// The rendering behavior of a Window. /// </summary> /// <since_tizen> 5 </since_tizen> public RenderingBehaviorType RenderingBehavior { get { return GetRenderingBehavior(); } set { SetRenderingBehavior(value); } } /// <summary> /// The window size property (read-only). /// </summary> /// <since_tizen> 3 </since_tizen> public Size2D Size { get { Size2D ret = GetSize(); return ret; } } /// <summary> /// The background color property. /// </summary> /// <since_tizen> 3 </since_tizen> public Color BackgroundColor { set { SetBackgroundColor(value); } get { Color ret = GetBackgroundColor(); return ret; } } /// <summary> /// The DPI property (read-only).<br /> /// Retrieves the DPI of the display device to which the Window is connected.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public Vector2 Dpi { get { return GetDpi(); } } /// <summary> /// The layer count property (read-only).<br /> /// Queries the number of on-Window layers.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public uint LayerCount { get { return GetLayerCount(); } } /// <summary> /// Gets or sets a size of the window. /// </summary> /// <since_tizen> 4 </since_tizen> public Size2D WindowSize { get { return GetWindowSize(); } set { SetWindowSize(value); } } /// <summary> /// Gets or sets a position of the window. /// </summary> /// <since_tizen> 4 </since_tizen> public Position2D WindowPosition { get { return GetPosition(); } set { SetPosition(value); } } /// <summary> /// Sets position and size of the window. This API guarantees that /// both moving and resizing of window will appear on the screen at once. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public Rectangle WindowPositionSize { get { Position2D position = GetPosition(); Size2D size = GetSize(); Rectangle ret = new Rectangle(position.X, position.Y, size.Width, size.Height); return ret; } set { SetPositionSize(value); } } internal static Vector4 DEFAULT_BACKGROUND_COLOR { get { global::System.IntPtr cPtr = Interop.Stage.Stage_DEFAULT_BACKGROUND_COLOR_get(); Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } internal static Vector4 DEBUG_BACKGROUND_COLOR { get { global::System.IntPtr cPtr = Interop.Stage.Stage_DEBUG_BACKGROUND_COLOR_get(); Vector4 ret = (cPtr == global::System.IntPtr.Zero) ? null : new Vector4(cPtr, false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } internal List<Layer> LayersChildren { get { return _childLayers; } } /// <summary> /// Get the LayoutController for this Window. /// </summary> internal LayoutController LayoutController { get { return localController; } } /// <summary> /// Feed a key-event into the window. /// </summary> /// <param name="keyEvent">The key event to feed.</param> /// <since_tizen> 4 </since_tizen> [Obsolete("Please do not use! This will be deprecated! Please use FeedKey(Key keyEvent) instead!")] public static void FeedKeyEvent(Key keyEvent) { Interop.Window.Window_FeedKeyEvent(Key.getCPtr(keyEvent)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets whether the window accepts a focus or not. /// </summary> /// <param name="accept">If a focus is accepted or not. The default is true.</param> /// <since_tizen> 3 </since_tizen> public void SetAcceptFocus(bool accept) { Interop.Window.SetAcceptFocus(swigCPtr, accept); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Returns whether the window accepts a focus or not. /// </summary> /// <returns>True if the window accepts a focus, false otherwise.</returns> /// <since_tizen> 3 </since_tizen> public bool IsFocusAcceptable() { bool ret = Interop.Window.IsFocusAcceptable(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Shows the window if it is hidden. /// </summary> /// <since_tizen> 3 </since_tizen> public void Show() { Interop.Window.Show(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Hides the window if it is showing. /// </summary> /// <since_tizen> 3 </since_tizen> public void Hide() { Interop.Window.Hide(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Retrieves whether the window is visible or not. /// </summary> /// <returns>True if the window is visible.</returns> /// <since_tizen> 3 </since_tizen> public bool IsVisible() { bool temp = Interop.Window.IsVisible(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return temp; } /// <summary> /// Gets the count of supported auxiliary hints of the window. /// </summary> /// <returns>The number of supported auxiliary hints.</returns> /// <since_tizen> 3 </since_tizen> public uint GetSupportedAuxiliaryHintCount() { uint ret = Interop.Window.GetSupportedAuxiliaryHintCount(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the supported auxiliary hint string of the window. /// </summary> /// <param name="index">The index of the supported auxiliary hint lists.</param> /// <returns>The auxiliary hint string of the index.</returns> /// <since_tizen> 3 </since_tizen> public string GetSupportedAuxiliaryHint(uint index) { string ret = Interop.Window.GetSupportedAuxiliaryHint(swigCPtr, index); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Creates an auxiliary hint of the window. /// </summary> /// <param name="hint">The auxiliary hint string.</param> /// <param name="value">The value string.</param> /// <returns>The ID of created auxiliary hint, or 0 on failure.</returns> /// <since_tizen> 3 </since_tizen> public uint AddAuxiliaryHint(string hint, string value) { uint ret = Interop.Window.AddAuxiliaryHint(swigCPtr, hint, value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Removes an auxiliary hint of the window. /// </summary> /// <param name="id">The ID of the auxiliary hint.</param> /// <returns>True if no error occurred, false otherwise.</returns> /// <since_tizen> 3 </since_tizen> public bool RemoveAuxiliaryHint(uint id) { bool ret = Interop.Window.RemoveAuxiliaryHint(swigCPtr, id); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Changes a value of the auxiliary hint. /// </summary> /// <param name="id">The auxiliary hint ID.</param> /// <param name="value">The value string to be set.</param> /// <returns>True if no error occurred, false otherwise.</returns> /// <since_tizen> 3 </since_tizen> public bool SetAuxiliaryHintValue(uint id, string value) { bool ret = Interop.Window.SetAuxiliaryHintValue(swigCPtr, id, value); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets a value of the auxiliary hint. /// </summary> /// <param name="id">The auxiliary hint ID.</param> /// <returns>The string value of the auxiliary hint ID, or an empty string if none exists.</returns> /// <since_tizen> 3 </since_tizen> public string GetAuxiliaryHintValue(uint id) { string ret = Interop.Window.GetAuxiliaryHintValue(swigCPtr, id); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets an ID of the auxiliary hint string. /// </summary> /// <param name="hint">The auxiliary hint string.</param> /// <returns>The ID of auxiliary hint string, or 0 on failure.</returns> /// <since_tizen> 3 </since_tizen> public uint GetAuxiliaryHintId(string hint) { uint ret = Interop.Window.GetAuxiliaryHintId(swigCPtr, hint); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets a region to accept input events. /// </summary> /// <param name="inputRegion">The region to accept input events.</param> /// <since_tizen> 3 </since_tizen> public void SetInputRegion(Rectangle inputRegion) { Interop.Window.SetInputRegion(swigCPtr, Rectangle.getCPtr(inputRegion)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets a priority level for the specified notification window. /// </summary> /// <param name="level">The notification window level.</param> /// <returns>True if no error occurred, false otherwise.</returns> /// <since_tizen> 3 </since_tizen> public bool SetNotificationLevel(NotificationLevel level) { bool ret = Interop.Window.SetNotificationLevel(swigCPtr, (int)level); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets a priority level for the specified notification window. /// </summary> /// <returns>The notification window level.</returns> /// <since_tizen> 3 </since_tizen> public NotificationLevel GetNotificationLevel() { NotificationLevel ret = (NotificationLevel)Interop.Window.GetNotificationLevel(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets a transparent window's visual state to opaque. <br /> /// If a visual state of a transparent window is opaque, <br /> /// then the window manager could handle it as an opaque window when calculating visibility. /// </summary> /// <param name="opaque">Whether the window's visual state is opaque.</param> /// <remarks>This will have no effect on an opaque window. <br /> /// It doesn't change transparent window to opaque window but lets the window manager know the visual state of the window. /// </remarks> /// <since_tizen> 3 </since_tizen> public void SetOpaqueState(bool opaque) { Interop.Window.SetOpaqueState(swigCPtr, opaque); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Returns whether a transparent window's visual state is opaque or not. /// </summary> /// <returns>True if the window's visual state is opaque, false otherwise.</returns> /// <remarks> The return value has no meaning on an opaque window. </remarks> /// <since_tizen> 3 </since_tizen> public bool IsOpaqueState() { bool ret = Interop.Window.IsOpaqueState(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets a window's screen off mode. /// </summary> /// <param name="screenOffMode">The screen mode.</param> /// <returns>True if no error occurred, false otherwise.</returns> /// <since_tizen> 4 </since_tizen> public bool SetScreenOffMode(ScreenOffMode screenOffMode) { bool ret = Interop.Window.SetScreenOffMode(swigCPtr, (int)screenOffMode); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the screen mode of the window. /// </summary> /// <returns>The screen off mode.</returns> /// <since_tizen> 4 </since_tizen> public ScreenOffMode GetScreenOffMode() { ScreenOffMode ret = (ScreenOffMode)Interop.Window.GetScreenOffMode(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets preferred brightness of the window. /// </summary> /// <param name="brightness">The preferred brightness (0 to 100).</param> /// <returns>True if no error occurred, false otherwise.</returns> /// <since_tizen> 3 </since_tizen> public bool SetBrightness(int brightness) { bool ret = Interop.Window.SetBrightness(swigCPtr, brightness); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the preferred brightness of the window. /// </summary> /// <returns>The preferred brightness.</returns> /// <since_tizen> 3 </since_tizen> public int GetBrightness() { int ret = Interop.Window.GetBrightness(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the window name and the class string. /// </summary> /// <param name="name">The name of the window.</param> /// <param name="klass">The class of the window.</param> /// <since_tizen> 4 </since_tizen> public void SetClass(string name, string klass) { Interop.Window.Window_SetClass(swigCPtr, name, klass); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Raises the window to the top of the window stack. /// </summary> /// <since_tizen> 3 </since_tizen> public void Raise() { Interop.Window.Window_Raise(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Lowers the window to the bottom of the window stack. /// </summary> /// <since_tizen> 3 </since_tizen> public void Lower() { Interop.Window.Window_Lower(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Activates the window to the top of the window stack even it is iconified. /// </summary> /// <since_tizen> 3 </since_tizen> public void Activate() { Interop.Window.Window_Activate(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the default ( root ) layer. /// </summary> /// <returns>The root layer.</returns> /// <since_tizen> 3 </since_tizen> public Layer GetDefaultLayer() { return this.GetRootLayer(); } /// <summary> /// Add a child view to window. /// </summary> /// <param name="view">the child should be added to the window.</param> /// <since_tizen> 3 </since_tizen> public void Add(View view) { Interop.Actor.Actor_Add(Layer.getCPtr(GetRootLayer()), View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); this.GetRootLayer().AddViewToLayerList(view); // Maintain the children list in the Layer view.InternalParent = this.GetRootLayer(); } /// <summary> /// Remove a child view from window. /// </summary> /// <param name="view">the child to be removed.</param> /// <since_tizen> 3 </since_tizen> public void Remove(View view) { Interop.Actor.Actor_Remove(Layer.getCPtr(GetRootLayer()), View.getCPtr(view)); this.GetRootLayer().RemoveViewFromLayerList(view); // Maintain the children list in the Layer view.InternalParent = null; } /// <summary> /// Retrieves the layer at a specified depth. /// </summary> /// <param name="depth">The layer's depth index.</param> /// <returns>The layer found at the given depth.</returns> /// <since_tizen> 3 </since_tizen> public Layer GetLayer(uint depth) { if (depth < LayersChildren?.Count) { Layer ret = LayersChildren?[Convert.ToInt32(depth)]; return ret; } else { return null; } } /// <summary> /// Destroy the window immediately. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void Destroy() { this.Dispose(); } /// <summary> /// Keep rendering for at least the given amount of time. /// </summary> /// <param name="durationSeconds">Time to keep rendering, 0 means render at least one more frame.</param> /// <since_tizen> 3 </since_tizen> public void KeepRendering(float durationSeconds) { Interop.Stage.Stage_KeepRendering(stageCPtr, durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Grabs the key specified by a key for a window only when a window is the topmost window.<br /> /// This function can be used for following example scenarios: <br /> /// - Mobile - Using volume up or down as zoom up or down in camera apps.<br /> /// </summary> /// <param name="DaliKey">The key code to grab.</param> /// <returns>True if the grab succeeds.</returns> /// <since_tizen> 3 </since_tizen> public bool GrabKeyTopmost(int DaliKey) { bool ret = Interop.Window.GrabKeyTopmost(HandleRef.ToIntPtr(this.swigCPtr), DaliKey); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Ungrabs the key specified by a key for the window.<br /> /// Note: If this function is called between key down and up events of a grabbed key, an application doesn't receive the key up event.<br /> /// </summary> /// <param name="DaliKey">The key code to ungrab.</param> /// <returns>True if the ungrab succeeds.</returns> /// <since_tizen> 3 </since_tizen> public bool UngrabKeyTopmost(int DaliKey) { bool ret = Interop.Window.UngrabKeyTopmost(HandleRef.ToIntPtr(this.swigCPtr), DaliKey); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Grabs the key specified by a key for a window in a GrabMode. <br /> /// Details: This function can be used for following example scenarios: <br /> /// - TV - A user might want to change the volume or channel of the background TV contents while focusing on the foregrund app. <br /> /// - Mobile - When a user presses the Home key, the homescreen appears regardless of the current foreground app. <br /> /// - Mobile - Using the volume up or down as zoom up or down in camera apps. <br /> /// </summary> /// <param name="DaliKey">The key code to grab.</param> /// <param name="GrabMode">The grab mode for the key.</param> /// <returns>True if the grab succeeds.</returns> /// <since_tizen> 3 </since_tizen> public bool GrabKey(int DaliKey, KeyGrabMode GrabMode) { bool ret = Interop.Window.GrabKey(HandleRef.ToIntPtr(this.swigCPtr), DaliKey, (int)GrabMode); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Ungrabs the key specified by a key for a window.<br /> /// Note: If this function is called between key down and up events of a grabbed key, an application doesn't receive the key up event. <br /> /// </summary> /// <param name="DaliKey">The key code to ungrab.</param> /// <returns>True if the ungrab succeeds.</returns> /// <since_tizen> 3 </since_tizen> public bool UngrabKey(int DaliKey) { bool ret = Interop.Window.UngrabKey(HandleRef.ToIntPtr(this.swigCPtr), DaliKey); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the keyboard repeat information. /// </summary> /// <param name="rate">The key repeat rate value in seconds.</param> /// <param name="delay">The key repeat delay value in seconds.</param> /// <returns>True if setting the keyboard repeat succeeds.</returns> /// <since_tizen> 5 </since_tizen> public bool SetKeyboardRepeatInfo(float rate, float delay) { bool ret = Interop.Window.SetKeyboardRepeatInfo(rate, delay); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the keyboard repeat information. /// </summary> /// <param name="rate">The key repeat rate value in seconds.</param> /// <param name="delay">The key repeat delay value in seconds.</param> /// <returns>True if setting the keyboard repeat succeeds.</returns> /// <since_tizen> 5 </since_tizen> public bool GetKeyboardRepeatInfo(out float rate, out float delay) { bool ret = Interop.Window.GetKeyboardRepeatInfo(out rate, out delay); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Adds a layer to the stage. /// </summary> /// <param name="layer">Layer to add.</param> /// <since_tizen> 3 </since_tizen> public void AddLayer(Layer layer) { Add(layer); } /// <summary> /// Removes a layer from the stage. /// </summary> /// <param name="layer">Layer to remove.</param> /// <since_tizen> 3 </since_tizen> public void RemoveLayer(Layer layer) { Remove(layer); } /// <summary> /// Feeds a key event into the window. /// </summary> /// <param name="keyEvent">The key event to feed.</param> /// <since_tizen> 5 </since_tizen> public void FeedKey(Key keyEvent) { Interop.Window.Window_FeedKeyEvent(Key.getCPtr(keyEvent)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Allows at least one more render, even when paused. /// The window should be shown, not minimised. /// </summary> /// <since_tizen> 4 </since_tizen> public void RenderOnce() { Interop.Window.Window_RenderOnce(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets whether the window is transparent or not. /// </summary> /// <param name="transparent">Whether the window is transparent or not.</param> /// <since_tizen> 5 </since_tizen> public void SetTransparency(bool transparent) { Interop.Window.SetTransparency(swigCPtr, transparent); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); // Setting transparency of the window should request a relayout of the tree in the case the window changes from fully transparent. } /// <summary> /// Sets parent window of the window. /// After setting that, these windows do together when raise-up, lower and iconified/deiconified. /// Initially, the window is located on top of the parent. The window can go below parent by calling Lower(). /// If parent's window stack is changed by calling Raise() or Lower(), child windows are located on top of the parent again. /// </summary> /// <param name="parent">The parent window.</param> /// <since_tizen> 6 </since_tizen> /// <feature> http://tizen.org/feature/opengles.surfaceless_context </feature> /// <exception cref="NotSupportedException">The required feature is not supported.</exception> public void SetParent(Window parent) { if (IsSupportedMultiWindow() == false) { NUILog.Error("This device does not support surfaceless_context. So Window cannot be created. "); } Interop.Window.SetParent(swigCPtr, Window.getCPtr(parent)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Unsets parent window of the window. /// After unsetting, the window is disconnected his parent window. /// </summary> /// <since_tizen> 6 </since_tizen> /// <feature> http://tizen.org/feature/opengles.surfaceless_context </feature> /// <exception cref="NotSupportedException">The required feature is not supported.</exception> public void Unparent() { if (IsSupportedMultiWindow() == false) { NUILog.Error("Fail to create window. because this device does not support opengles.surfaceless_context."); } Interop.Window.Unparent(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets parent window of the window. /// </summary> /// <returns>The parent window of the window.</returns> /// <since_tizen> 6 </since_tizen> /// <feature> http://tizen.org/feature/opengles.surfaceless_context </feature> /// <exception cref="NotSupportedException">The required feature is not supported.</exception> public Window GetParent() { if (IsSupportedMultiWindow() == false) { NUILog.Error("This device does not support surfaceless_context. So Window cannot be created. "); } Window ret = Registry.GetManagedBaseHandleFromNativePtr(Interop.Window.GetParent(swigCPtr)) as Window; if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// This will be public opened in tizen_next after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void ObjectDump() { Layer rootLayer = GetRootLayer(); foreach (View view in rootLayer.Children) { view.ObjectDump(); } } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Window obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } internal static bool IsInstalled() { bool ret = Interop.Stage.Stage_IsInstalled(); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Adds an orientation to the list of available orientations. /// </summary> /// <param name="orientation">The available orientation to add</param> /// <since_tizen> 6 </since_tizen> public void AddAvailableOrientation(Window.WindowOrientation orientation) { Interop.Window.Window_AddAvailableOrientation(swigCPtr, (int)orientation); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Removes an orientation from the list of available orientations. /// </summary> /// <param name="orientation">The available orientation to remove.</param> /// <since_tizen> 6 </since_tizen> public void RemoveAvailableOrientation(Window.WindowOrientation orientation) { Interop.Window.Window_RemoveAvailableOrientation(swigCPtr, (int)orientation); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets a preferred orientation. /// </summary> /// <param name="orientation">The preferred orientation.</param> /// <since_tizen> 6 </since_tizen> public void SetPreferredOrientation(Window.WindowOrientation orientation) { Interop.Window.Window_SetPreferredOrientation(swigCPtr, (int)orientation); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the preferred orientation. /// </summary> /// <since_tizen> 6 </since_tizen> /// <returns>The preferred orientation if previously set, or none.</returns> public Window.WindowOrientation GetPreferredOrientation() { Window.WindowOrientation ret = (Window.WindowOrientation)Interop.Window.Window_GetPreferredOrientation(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets current orientation of the window. /// </summary> /// <since_tizen> 6 </since_tizen> /// <returns>The current window orientation if previously set, or none.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public Window.WindowOrientation GetCurrentOrientation() { Window.WindowOrientation ret = (Window.WindowOrientation)Interop.Window.Window_GetCurrentOrientation(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets available orientations of the window. /// This API is for setting several orientations one time. /// </summary> /// <param name="orientations">The list of orientations.</param> /// <since_tizen> 6 </since_tizen> [EditorBrowsable(EditorBrowsableState.Never)] public void SetAvailableOrientations(List<Window.WindowOrientation> orientations) { PropertyArray orientationArray = new PropertyArray(); for (int i = 0; i < orientations.Count; i++) { orientationArray.PushBack(new PropertyValue((int)orientations[i])); } Interop.Window.Window_SetAvailableOrientations(swigCPtr, PropertyArray.getCPtr(orientationArray)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Get native window ID /// </summary> /// <returns>native window ID</returns> [EditorBrowsable(EditorBrowsableState.Never)] public int GetNativeId() { int ret = Interop.Window.GetNativeId(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal Any GetNativeHandle() { Any ret = new Any(Interop.WindowInternal.Window_GetNativeHandle(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void Add(Layer layer) { Interop.Window.Add(swigCPtr, Layer.getCPtr(layer)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); LayersChildren?.Add(layer); layer.SetWindow(this); } internal void Remove(Layer layer) { Interop.Window.Remove(swigCPtr, Layer.getCPtr(layer)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); LayersChildren?.Remove(layer); layer.SetWindow(null); } internal Vector2 GetSize() { var val = new Uint16Pair(Interop.Window.GetSize(swigCPtr), false); Vector2 ret = new Vector2(val.GetWidth(), val.GetHeight()); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal RenderTaskList GetRenderTaskList() { RenderTaskList ret = new RenderTaskList(Interop.Stage.Stage_GetRenderTaskList(stageCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Queries the number of on-window layers. /// </summary> /// <returns>The number of layers.</returns> /// <remarks>Note that a default layer is always provided (count >= 1).</remarks> internal uint GetLayerCount() { if (LayersChildren == null || LayersChildren.Count < 0) return 0; return (uint)LayersChildren.Count; } internal Layer GetRootLayer() { // Window.IsInstalled() is actually true only when called from event thread and // Core has been initialized, not when Stage is ready. if (_rootLayer == null && Window.IsInstalled()) { _rootLayer = new Layer(Interop.Window.GetRootLayer(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); LayersChildren?.Add(_rootLayer); _rootLayer.SetWindow(this); } return _rootLayer; } internal void SetBackgroundColor(Vector4 color) { Interop.Window.SetBackgroundColor(swigCPtr, Vector4.getCPtr(color)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal Vector4 GetBackgroundColor() { Vector4 ret = new Vector4(Interop.Window.GetBackgroundColor(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal Vector2 GetDpi() { Vector2 ret = new Vector2(Interop.Stage.Stage_GetDpi(stageCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal ObjectRegistry GetObjectRegistry() { ObjectRegistry ret = new ObjectRegistry(Interop.Stage.Stage_GetObjectRegistry(stageCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void SetRenderingBehavior(RenderingBehaviorType renderingBehavior) { Interop.Stage.Stage_SetRenderingBehavior(stageCPtr, (int)renderingBehavior); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal RenderingBehaviorType GetRenderingBehavior() { RenderingBehaviorType ret = (RenderingBehaviorType)Interop.Stage.Stage_GetRenderingBehavior(stageCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void SetWindowSize(Size2D size) { var val = new Uint16Pair((uint)size.Width, (uint)size.Height); Interop.Window.SetSize(swigCPtr, Uint16Pair.getCPtr(val)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); // Resetting Window size should request a relayout of the tree. } internal Size2D GetWindowSize() { var val = new Uint16Pair(Interop.Window.GetSize(swigCPtr), false); Size2D ret = new Size2D(val.GetWidth(), val.GetHeight()); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void SetPosition(Position2D position) { var val = new Uint16Pair((uint)position.X, (uint)position.Y); Interop.Window.SetPosition(swigCPtr, Uint16Pair.getCPtr(val)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); // Setting Position of the window should request a relayout of the tree. } internal Position2D GetPosition() { var val = new Uint16Pair(Interop.Window.GetPosition(swigCPtr), true); Position2D ret = new Position2D(val.GetX(), val.GetY()); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal void SetPositionSize(Rectangle positionSize) { Interop.Window.Window_SetPositionSize(swigCPtr, Rectangle.getCPtr(positionSize)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); // Setting Position of the window should request a relayout of the tree. } /// <summary> /// Add FrameCallback /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void AddFrameCallback(FrameCallbackInterface frameCallback) { frameCallback?.AddFrameCallback(stageCPtr, Layer.getCPtr(GetRootLayer())); } /// <summary> /// Remove FrameCallback /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public void RemoveFrameCallback(FrameCallbackInterface frameCallback) { frameCallback?.RemoveFrameCallback(stageCPtr); } /// <summary> /// Dispose for Window /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected override void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Called by User //Release your own managed resources here. //You should release all of your own disposable objects here. _rootLayer.Dispose(); localController.Dispose(); foreach (var layer in _childLayers) { layer.Dispose(); } _childLayers.Clear(); } this.DisconnectNativeSignals(); base.Dispose(type); } /// This will not be public opened. [EditorBrowsable(EditorBrowsableState.Never)] protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr) { Interop.Window.delete_Window(swigCPtr); } private static Dictionary<int, internalHookCallbackType> frameCallbackList = new Dictionary<int, internalHookCallbackType>(); private static readonly object locker = new object(); private static int key = 0; private static FrameCallbackType internalHookFrameCallback = OnInternalHookFrameCallback; private struct internalHookCallbackType { public FrameCallbackType userCallback; public int frameId; } private static void OnInternalHookFrameCallback(int id) { lock (locker) { if (frameCallbackList.ContainsKey(id)) { if (frameCallbackList[id].userCallback != null) { frameCallbackList[id].userCallback.Invoke(frameCallbackList[id].frameId); frameCallbackList.Remove(id); } else { NUILog.Error($"found userCallback is NULL"); frameCallbackList.Remove(id); } } } } private int AddInterHookCallback(FrameCallbackType callback, int frameId) { if (null == callback) { throw new ArgumentNullException(nameof(callback), "FrameCallbackType should not be null"); } var assignedKey = 0; lock (locker) { key++; assignedKey = key; frameCallbackList.Add(assignedKey, new internalHookCallbackType() { userCallback = callback, frameId = frameId, }); } return assignedKey; } /// <summary> /// Type of callback which is called when the frame rendering is done by graphics driver or when the frame is displayed on display. /// </summary> /// <param name="frameId">The Id to specify the frame. It will be passed when the callback is called.</param> [EditorBrowsable(EditorBrowsableState.Never)] public delegate void FrameCallbackType(int frameId); /// <summary> /// Adds a callback that is called when the frame rendering is done by the graphics driver. /// A callback of the following type may be used: /// <code> /// void MyFunction( int frameId ) /// </code> /// This callback will be deleted once it is called. /// <remarks> /// Ownership of the callback is passed onto this class /// </remarks> /// </summary> /// <param name="callback">The function to call</param> /// <param name="frameId">The Id to specify the frame. It will be passed when the callback is called.</param> /// <exception cref="ArgumentNullException">This exception can occur by the callback is null.</exception> [EditorBrowsable(EditorBrowsableState.Never)] public void AddFrameRenderedCallback(FrameCallbackType callback, int frameId) { var assignedKey = AddInterHookCallback(callback, frameId); Interop.WindowInternal.AddFrameRenderedCallback(swigCPtr, new HandleRef(this, Marshal.GetFunctionPointerForDelegate<Delegate>(internalHookFrameCallback)), assignedKey); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Adds a callback that is called when the frame is displayed on the display. /// A callback of the following type may be used: /// <code> /// void MyFunction( int frameId ) /// </code> /// This callback will be deleted once it is called. /// <remarks> /// Ownership of the callback is passed onto this class /// </remarks> /// </summary> /// <param name="callback">The function to call</param> /// <param name="frameId">The Id to specify the frame. It will be passed when the callback is called.</param> /// <exception cref="ArgumentNullException">This exception can occur by the callback is null.</exception> [EditorBrowsable(EditorBrowsableState.Never)] public void AddFramePresentedCallback(FrameCallbackType callback, int frameId) { var assignedKey = AddInterHookCallback(callback, frameId); Interop.WindowInternal.AddFramePresentedCallback(swigCPtr, new HandleRef(this, Marshal.GetFunctionPointerForDelegate<Delegate>(internalHookFrameCallback)), assignedKey); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } } }
40.613194
199
0.594703
[ "Apache-2.0", "MIT" ]
chauhan321/TizenFX
src/Tizen.NUI/src/public/Window.cs
58,483
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Collections_Generic_ICollection_1_Int32_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Collections.Generic.ICollection<System.Int32>); args = new Type[]{}; method = type.GetMethod("get_Count", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Count_0); args = new Type[]{typeof(System.Int32)}; method = type.GetMethod("Contains", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Contains_1); args = new Type[]{typeof(System.Int32)}; method = type.GetMethod("Remove", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Remove_2); args = new Type[]{typeof(System.Int32)}; method = type.GetMethod("Add", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Add_3); } static StackObject* get_Count_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Collections.Generic.ICollection<System.Int32> instance_of_this_method = (System.Collections.Generic.ICollection<System.Int32>)typeof(System.Collections.Generic.ICollection<System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Count; __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method; return __ret + 1; } static StackObject* Contains_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @item = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.ICollection<System.Int32> instance_of_this_method = (System.Collections.Generic.ICollection<System.Int32>)typeof(System.Collections.Generic.ICollection<System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Contains(@item); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* Remove_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @item = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.ICollection<System.Int32> instance_of_this_method = (System.Collections.Generic.ICollection<System.Int32>)typeof(System.Collections.Generic.ICollection<System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = instance_of_this_method.Remove(@item); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* Add_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Int32 @item = ptr_of_this_method->Value; ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Collections.Generic.ICollection<System.Int32> instance_of_this_method = (System.Collections.Generic.ICollection<System.Int32>)typeof(System.Collections.Generic.ICollection<System.Int32>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); instance_of_this_method.Add(@item); return __ret; } } }
46.619835
282
0.690835
[ "MIT" ]
594270461/fivestar
Unity/Assets/Model/ILBinding/System_Collections_Generic_ICollection_1_Int32_Binding.cs
5,641
C#
using System; using System.IO; using System.Linq.Expressions; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using Zyan.Communication; namespace Zyan.InterLinq.Expressions { /// <summary> /// Serialization handler for Linq expressions /// </summary> public class ExpressionSerializationHandler : ISerializationHandler { BinaryFormatter Formatter { get; set; } /// <summary> /// Initializes Linq expressions serialization handler /// </summary> public ExpressionSerializationHandler() { Formatter = new BinaryFormatter(); Formatter.AssemblyFormat = FormatterAssemblyStyle.Simple; Formatter.FilterLevel = TypeFilterLevel.Low; } /// <summary> /// Serializes Linq expression into raw byte array /// </summary> /// <param name="data">Linq expression</param> /// <returns>Raw data</returns> public byte[] Serialize(object data) { var expression = data as Expression; if (expression == null) { return new byte[0]; } var sx = expression.MakeSerializable(); using (var ms = new MemoryStream()) { Formatter.Serialize(ms, sx); return ms.ToArray(); } } /// <summary> /// Deserializes raw byte array /// </summary> /// <param name="dataType"></param> /// <param name="data"></param> /// <returns></returns> public object Deserialize(Type dataType, byte[] data) { if (!typeof(Expression).IsAssignableFrom(dataType)) { throw new InvalidOperationException(); } if (data == null || data.Length < 1) { return null; } using (var ms = new MemoryStream(data)) { var sx = Formatter.Deserialize(ms) as SerializableExpression; return sx.Deserialize(); } } } }
24.5
69
0.6492
[ "MIT" ]
ErrCode/Zyan.Core.LocalIPC
branches/withoutremoting/Zyan.Communication/InterLinq/Expressions/ExpressionSerializationHandler.cs
1,815
C#
/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.Xml; using System.IO; using System.Text; using System.Reflection; using System.Threading; using System.Globalization; using Opc.Ua; using Opc.Ua.Server; namespace TestData { /// <summary> /// A class used to read values from a history data source. /// </summary> public class HistoryDataReader : IDisposable { #region Constructors /// <summary> /// Constructs a reader for the source. /// </summary> /// <param name="source">The source of the history data.</param> public HistoryDataReader(NodeId variableId, IHistoryDataSource source) { m_id = Guid.NewGuid(); m_variableId = variableId; m_source = source; } #endregion #region IDisposable Members /// <summary> /// Frees any unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// An overrideable version of the Dispose. /// </summary> protected virtual void Dispose(bool disposing) { // nothing to do. } #endregion #region Public Interface /// <summary> /// A globally unique identifier for the instance. /// </summary> public Guid Id { get { return m_id; } } /// <summary> /// The identifier for the variable being read. /// </summary> public NodeId VariableId { get { return m_variableId; } } /// <summary> /// Starts reading raw values. /// </summary> /// <param name="context">The context for the operation.</param> /// <param name="request">The request parameters.</param> /// <param name="timestampsToReturn">The timestamps to return with the value.</param> /// <param name="indexRange">The range to return for array values.</param> /// <param name="dataEncoding">The data encoding to use for structured values.</param> /// <param name="values">The values to return.</param> public void BeginReadRaw( ServerSystemContext context, ReadRawModifiedDetails request, TimestampsToReturn timestampsToReturn, NumericRange indexRange, QualifiedName dataEncoding, DataValueCollection values) { m_request = request; // initialize start and end. m_startTime = m_request.StartTime; m_endTime = m_request.EndTime; if (m_endTime == DateTime.MinValue) { m_endTime = DateTime.MaxValue; } // check the direction. m_isForward = m_startTime < m_endTime; m_position = -1; DataValue value = null; // get first bound. if (m_request.ReturnBounds) { value = m_source.FirstRaw(m_startTime, !m_isForward, m_request.IsReadModified, out m_position); if (value != null) { AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); } } } /// <summary> /// Continues a read raw operation. /// </summary> /// <param name="context">The context for the operation.</param> /// <param name="timestampsToReturn">The timestamps to return with the value.</param> /// <param name="indexRange">The range to return for array values.</param> /// <param name="dataEncoding">The data encoding to use for structured values.</param> /// <param name="values">The values to return.</param> /// <returns>False if the operation halted because the maximum number of values was discovered.</returns> public bool NextReadRaw( ServerSystemContext context, TimestampsToReturn timestampsToReturn, NumericRange indexRange, QualifiedName dataEncoding, DataValueCollection values) { DataValue value = null; do { // check for limit. if (m_request.NumValuesPerNode > 0 && values.Count >= m_request.NumValuesPerNode) { return false; } value = m_source.NextRaw(m_lastTime, m_isForward, m_request.IsReadModified, ref m_position); // no more data. if (value == null) { return true; } // check for bound. if ((m_isForward && value.ServerTimestamp >= m_endTime) || (!m_isForward && value.ServerTimestamp <= m_endTime)) { if (m_request.ReturnBounds) { AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); return true; } } // add value. AddValue(timestampsToReturn, indexRange, dataEncoding, values, value); } while (value != null); return true; } #endregion #region Private Methods /// <summary> /// Adds a DataValue to a list of values to return. /// </summary> private void AddValue( TimestampsToReturn timestampsToReturn, NumericRange indexRange, QualifiedName dataEncoding, DataValueCollection values, DataValue value) { // ignore invalid case. if (value == null) { return; } // save the last timestamp returned. m_lastTime = value.ServerTimestamp; // check if the index range or data encoding can be applied. if (StatusCode.IsGood(value.StatusCode)) { object valueToReturn = value.Value; // apply the index range. if (indexRange != NumericRange.Empty) { StatusCode error = indexRange.ApplyRange(ref valueToReturn); if (StatusCode.IsBad(error)) { value.Value = null; value.StatusCode = error; } else { value.Value = valueToReturn; } } // apply the data encoding. if (!QualifiedName.IsNull(dataEncoding)) { value.Value = null; value.StatusCode = StatusCodes.BadDataEncodingUnsupported; } } // apply the timestamps filter. if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Server) { value.SourceTimestamp = DateTime.MinValue; } if (timestampsToReturn == TimestampsToReturn.Neither || timestampsToReturn == TimestampsToReturn.Source) { value.ServerTimestamp = DateTime.MinValue; } // add result. values.Add(value); } #endregion #region Private Fields private Guid m_id; private NodeId m_variableId; private IHistoryDataSource m_source; private ReadRawModifiedDetails m_request; private DateTime m_startTime; private DateTime m_endTime; private bool m_isForward; private int m_position; private DateTime m_lastTime; #endregion } }
34.901099
128
0.539358
[ "MIT" ]
AlexanderSemenyak/UA-.NETStandard-Samples
Samples/Opc.Ua.Sample/TestData/HistoryDataReader.cs
9,528
C#
using System; using Bibliotheca.Server.Mvc.Middleware.Diagnostics.Exceptions; namespace Bibliotheca.Server.Depository.AzureStorage.Core.Exceptions { public class BranchAlreadyExistsException : BibliothecaException { public BranchAlreadyExistsException(string message) : base(message) { } } }
27.333333
75
0.75
[ "MIT" ]
BibliothecaTeam/Bibliotheca.Server.Depository.AzureStorage
src/Bibliotheca.Server.Depository.AzureStorage.Core/Exceptions/BranchAlreadyExistsException.cs
328
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SyNet.MessageTypes { class MsgZigbeeTxStatus : MsgZigbee { /// <summary> /// Copy Constructor /// </summary> /// <param name="p_msg"></param> public MsgZigbeeTxStatus(Msg p_msg) : base(p_msg) { } /// <summary> /// Return a string representation of the message type /// </summary> public override string MsgType { get { return "ZigbeeTxStatus"; } } } }
18.516129
61
0.560976
[ "Apache-2.0" ]
mkurdziel/BitHome-Hub-CSharp-V1
SyNet Controller/MessageTypes/MsgZigbeeTxStatus.cs
576
C#
using System.Collections.Generic; namespace IdSrvEf.Web.Models.Consent { public class ConsentInputModel { public string Button { get; set; } public IEnumerable<string> ScopesConsented { get; set; } public bool RememberConsent { get; set; } public string ReturnUrl { get; set; } } }
25.230769
64
0.655488
[ "MIT" ]
nagasudhirpulla/wrldc_identity_server
src/IdSrvEf.Web/Models/Consent/ConsentInputModel.cs
330
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 s3control-2018-08-20.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.S3Control.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.S3Control.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for EstablishedMultiRegionAccessPointPolicy Object /// </summary> public class EstablishedMultiRegionAccessPointPolicyUnmarshaller : IUnmarshaller<EstablishedMultiRegionAccessPointPolicy, XmlUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public EstablishedMultiRegionAccessPointPolicy Unmarshall(XmlUnmarshallerContext context) { EstablishedMultiRegionAccessPointPolicy unmarshalledObject = new EstablishedMultiRegionAccessPointPolicy(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Policy", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Policy = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } private static EstablishedMultiRegionAccessPointPolicyUnmarshaller _instance = new EstablishedMultiRegionAccessPointPolicyUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static EstablishedMultiRegionAccessPointPolicyUnmarshaller Instance { get { return _instance; } } } }
36.290698
153
0.636975
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/S3Control/Generated/Model/Internal/MarshallTransformations/EstablishedMultiRegionAccessPointPolicyUnmarshaller.cs
3,121
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DeepdreamGui.Model { /// <summary> /// Trace Listener for debug messages. Writes Messages to File. /// </summary> public class LocalTraceListener:TraceListener { private readonly string _localLogFilePath; /// <summary> /// Constructor for Local Trace Listener /// </summary> public LocalTraceListener() { //http://stackoverflow.com/questions/4765789/getting-files-by-creation-date-in-net DirectoryInfo info = new DirectoryInfo(Environment.CurrentDirectory); //Order logfiles ascending FileInfo[] files = info.GetFiles("*.log").OrderBy(f => f.CreationTime).ToArray(); if (files.Length > 10) { //if more than 10 delete the oldest 10 for (int i = 0; i < 10; i++) { File.Delete(files[i].FullName); } } string fileName = "DeepDreamGui_" + DateTime.Now.ToString("yyyy_MM_dd-hh_mm") + ".log"; _localLogFilePath = Path.Combine(Environment.CurrentDirectory, fileName); if (!File.Exists(_localLogFilePath)) { File.Create(_localLogFilePath).Close(); } } /// <summary> /// Write Message to Trace Listener /// </summary> /// <param name="message"></param> public override void Write(string message) { lock (this) { File.AppendAllText(_localLogFilePath, DateTime.Now + @":" + message); } } /// <summary> /// Write Line to Trace Listener /// </summary> /// <param name="message"></param> public override void WriteLine(string message) { this.Write(message + Environment.NewLine); } } }
31
99
0.553763
[ "MIT" ]
neuralartgui/neuralartgui
_Application/DeepdreamGui/ExtensionMethods/LocalTraceListener.cs
2,048
C#
using System; namespace org.pescuma.progressmonitor.utils { /// <summary> /// Throws an OperationCanceledException when a request was requested and a step related method is called. /// </summary> public class ThrowOnCancelledProgressMonitor : ProgressMonitor { private readonly ProgressMonitor next; public ThrowOnCancelledProgressMonitor(ProgressMonitor next) { this.next = next; } private void ThrowOnCancel() { if (WasCanceled) throw new OperationCanceledException(); } public IDisposable ConfigureSteps(params int[] steps) { ThrowOnCancel(); return next.ConfigureSteps(steps); } public void StartStep(string stepName = null, params object[] args) { ThrowOnCancel(); next.StartStep(stepName, args); } public ProgressMonitor CreateSubMonitor() { ThrowOnCancel(); return new ThrowOnCancelledProgressMonitor(next.CreateSubMonitor()); } public void Finished() { ThrowOnCancel(); next.Finished(); } public void Report(string message, params object[] args) { next.Report(message, args); } public void ReportDetail(string message, params object[] args) { next.ReportDetail(message, args); } public void ReportWarning(string message, params object[] args) { next.ReportWarning(message, args); } public void ReportError(string message, params object[] args) { next.ReportError(message, args); } public bool WasCanceled { get { return next.WasCanceled; } } } }
25.181818
111
0.545126
[ "MIT" ]
pescuma/progressmonitor
csharp/ProgressMonitor/utils/ThrowOnCancelledProgressMonitor.cs
1,941
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("DapperWrapper.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DapperWrapper.Tests")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("07afcdc8-c128-4da7-a93d-1aa046309387")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.135135
84
0.746279
[ "MIT" ]
jshurst/dapper-wrapper
DapperWrapper.Tests/Properties/AssemblyInfo.cs
1,414
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 BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; using MicroBenchmarks; namespace Microsoft.Extensions.Logging { [BenchmarkCategory(Categories.Libraries)] public class LoggingOverhead : LoggingBenchmarkBase { private ILogger _logger; [GlobalSetup] public void Setup() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton<ILoggerProvider, LoggerProvider<NoopLogger>>(); _logger = services.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger("Logger"); } [Benchmark] public void NoArguments_FilteredByLevel() { _logger.LogTrace(Exception, "Message"); } // Baseline as this is the fastest way to do nothing [Benchmark(Baseline = true)] public void NoArguments_DefineMessage_FilteredByLevel() { NoArgumentTraceMessage(_logger, Exception); } [Benchmark] public void NoArguments() { _logger.LogError(Exception, "Message"); } [Benchmark] public void NoArguments_DefineMessage() { NoArgumentErrorMessage(_logger, Exception); } [Benchmark] public void TwoArguments() { _logger.LogError(Exception, "Message {Argument1} {Argument2}", 1, "string"); } [Benchmark] public void TwoArguments_FilteredByLevel() { _logger.LogTrace(Exception, "Message {Argument1} {Argument2}", 1, "string"); } [Benchmark] public void TwoArguments_DefineMessage() { TwoArgumentErrorMessage(_logger, 1, "string", Exception); } [Benchmark] public void TwoArguments_DefineMessage_FilteredByLevel() { TwoArgumentTraceMessage(_logger, 1, "string", Exception); } } }
29.106667
106
0.621164
[ "MIT" ]
BruceForstall/performance
src/benchmarks/micro/libraries/Microsoft.Extensions.Logging/LoggingOverheadBenchmark.cs
2,183
C#
using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityEngine.Events; using Zeltex.Generators; using Zeltex.Util; using Zeltex.Combat; using Zeltex.Voxels; using Zeltex.Items; using Zeltex.Skeletons; namespace Zeltex { /// <summary> /// GUI Class for data manager /// </summary> public class DataGUI : ManagerBase<DataGUI> { public bool IsDebugGui; private int MapNameSelected = 0; private List<string> MapNames = new List<string>(); private Vector2 scrollPosition; private string OpenedFolderName = ""; private int OpenedFolderIndex = -1; private string OpenedFileName = ""; private int OpenedFileIndex = -1; private Element OpenedElement; private bool IsDrawAllFields; private string RenameName = "Null"; // Folders //private Zexel OpenedTexture; private bool IsOpenedElementFolder; private ElementFolder OpenedFolder; private RenderTexture PolyRenderTexture; private Level MyLevel; private bool IsExtraOptions; #region Main #if UNITY_EDITOR public static void PrepareDataForReload() { Debug.Log("Custom Serializing DataManager Data as manual refresh of code detected."); if (DataManager.Get()) { for (int i = 0; i < DataManager.Get().GetSize(); i++) { DataManager.Get().GetFolder(i).Serialize(); } } } [UnityEditor.Callbacks.DidReloadScripts] private static void OnScriptsReloaded() { Debug.Log("Reloaded scripts, so custom deserialized the DataManager Data."); // bum! if (DataManager.Get() != null && DataManager.Get().GetIsLoaded()) { for (int i = 0; i < DataManager.Get().GetFolders().Count; i++) { DataManager.Get().GetFolder(i).Deserialize(); } } DataGUI.Get().Repaint(); } #endif public new static DataGUI Get() { if (MyManager == null) { MyManager = GameObject.Find("DataManager").GetComponent<DataGUI>(); } return MyManager; } void OnGUI() { if (IsDebugGui) { if (GUILayout.Button("Close")) { IsDebugGui = false; } DrawGui(); } } #if UNITY_EDITOR UnityEditor.EditorWindow MyWindow = null; public void Repaint() { if (MyWindow != null) { MyWindow.Repaint(); } } #else public void Repaint() { } #endif public void DrawGui(object NewWindow = null) { #if UNITY_EDITOR MyWindow = NewWindow as UnityEditor.EditorWindow; #endif try { scrollPosition = GUILayout.BeginScrollView(scrollPosition); } catch (System.ArgumentException) { return; } MyLevel = OpenedElement as Level; if (DataManager.Get().IsLoading()) { GUILabel("=================="); IncreaseIndent(); GUILabel("Loading [" + DataManager.Get().MapName + "]"); DecreaseIndent(); GUILabel("=================="); IncreaseIndent(); if (GUIButton("===== Cancel ( ===== ")) { DataManager.Get().CancelLoading(); } DecreaseIndent(); GUILayout.Label("=================="); } else if (MyLevel != null && MyLevel.IsSpawning) { GUILayout.Label("=================="); GUILayout.Label("Loading Level [" + MyLevel.Name + "]"); GUILayout.Label("=================="); } else { //IsJSONFormat = GUILayout.Toggle(IsJSONFormat, "JSON"); if (DataManager.Get().GetIsLoaded()) { LoadedDataGui(); } else { NotLoadedGui(); } } GUILayout.EndScrollView(); } public void NotLoadedGui() { //GUILayout.Label("Selected [" + DataManager.Get().MapName + "]"); //GUILabel("MapName:"); string MapName = "None"; if (MapNames.Count > 0) { MapName = MapNames[MapNameSelected]; } if (GUIButton("Load [" + MapName + "]")) { DataManager.Get().InitializeFolders(); DataManager.Get().LoadAll( () => { Repaint(); }); DataManager.Get().WasPlayingOnLoad = false; } // List of map names! //GUILayout.Space(30); GUILabel("Select from " + MapNames.Count + " different Resources."); IncreaseIndent(); //int NewMapNameSelected = GUILayout.SelectionGrid(MapNameSelected, MapNames.ToArray(), 1); int NewMapNameSelected = MapNameSelected; for (int i = 0; i < MapNames.Count; i++) { if (MapNames[i] == MapName) { GUI.enabled = false; } if (GUIButton(MapNames[i])) { NewMapNameSelected = i; } GUI.enabled = true; } if (MapNameSelected != NewMapNameSelected) { MapNameSelected = NewMapNameSelected; DataManager.Get().MapName = MapNames[MapNameSelected]; } DecreaseIndent(); // Extra Options //GUILabel("Extra Options"); GUILayout.Space(30); IsExtraOptions = GUIToggle("Extra Options", IsExtraOptions); if (IsExtraOptions) { GUILabel("DataPath [" + DataManager.Get().DataPath + "]"); GUILabel("PersistentDataPath [" + DataManager.Get().PersistentDataPath + "]"); if (GUIButton("Refresh Path")) { DataManager.Get().DataPath = Application.dataPath; DataManager.Get().PersistentDataPath = Application.persistentDataPath; RefreshGuiMapNames(); } if (GUIButton("Open Resources Folder")) { FileUtil.OpenPathInWindows(DataManager.Get().GetResourcesPath()); } if (MapNames == null || GUILayout.Button("Refresh List")) { RefreshGuiMapNames(); } GUILabel("PathType: " + DataManager.Get().MyFilePathType); //MyFilePathType = (FilePathType)int.Parse(GUILayout.TextField(((int)MyFilePathType).ToString())); GUI.enabled = (DataManager.Get().MyFilePathType != FilePathType.Normal); if (GUILayout.Button("Normal")) { DataManager.Get().MyFilePathType = FilePathType.Normal; RefreshGuiMapNames(); } GUI.enabled = (DataManager.Get().MyFilePathType != FilePathType.PersistentPath); if (GUILayout.Button("Persistent")) { DataManager.Get().MyFilePathType = FilePathType.PersistentPath; RefreshGuiMapNames(); } GUI.enabled = (DataManager.Get().MyFilePathType != FilePathType.StreamingPath); if (GUILayout.Button("Streaming")) { DataManager.Get().MyFilePathType = FilePathType.StreamingPath; RefreshGuiMapNames(); } GUI.enabled = true; } } private void RefreshGuiMapNames() { MapNames = Guis.Maker.ResourcesMaker.GetResourceNames(); if (MapNames.Count == 0) { MapNameSelected = 0; DataManager.Get().MapName = ""; } else { MapNameSelected = Mathf.Clamp(MapNameSelected, 0, MapNames.Count - 1); DataManager.Get().MapName = MapNames[MapNameSelected]; } CloseAll (); } private void CloseAll() { OpenedFileName = ""; OpenedFileIndex = -1; OpenedFolderIndex = -1; OpenedFolderName = ""; } private void LoadedDataGui() { GUILayout.Label("Loaded [" + RenameName + "]"); if (OpenedFileName != "") { DrawFile(); } else if (OpenedFolderIndex != -1) { DrawSelectedFolder(); } else { DrawResourcesMainGui(); } } private void DrawResourcesMainGui() { if (GUILayout.Button("UnLoad")) { // go back! DataManager.Get().UnloadAll(); CloseAll(); } DrawFolders(); GUILayout.Space(30); IsExtraOptions = GUIToggle("Extra Options", IsExtraOptions); if (IsExtraOptions) { IncreaseIndent(); if (GUIButton("Open Folder")) { FileUtil.OpenPathInWindows(DataManager.Get().GetMapPathNS()); } if (GUIButton("Save All")) { DataManager.Get().SaveAll(); } if (GUIButton("Erase")) { DataManager.Get().DeleteAll(); } if (GUIButton("Generate")) { GameObject.Find("Generators").GetComponent<MapGenerator>().GenerateMap(); } if (GUIButton("Generate TileMap")) { VoxelManager.Get().GenerateTileMap(); } if (RenameName == "Null") { RenameName = DataManager.Get().MapName; } RenameName = GUIText(RenameName); if (GUIButton("Rename")) { if (RenameName != DataManager.Get().MapName) { RenameResourcesFolder(RenameName); } } DecreaseIndent(); } } /// <summary> /// Rename the entire resources directory /// </summary> private void RenameResourcesFolder(string NewName) { string OldFolderPath = DataManager.Get().GetResourcesPath() + DataManager.Get().MapName + "/"; string NewFolderPath = DataManager.Get().GetResourcesPath() + NewName + "/"; if (FileManagement.DirectoryExists(NewFolderPath, true, true) == false) { System.IO.Directory.Move(OldFolderPath, NewFolderPath); DataManager.Get().MapName = NewName; } else { Debug.Log("Cannot move to " + NewFolderPath + " as already exists."); } } #endregion #region Folders private void DrawSelectedFolder() { if (GUIButton("Back")) { OpenedFolderIndex = -1; OpenedFolderName = ""; } GUILayout.Label("Opened Folder [" + OpenedFolderName + "] of Type: " + DataFolderNames.GetDataType(OpenedFolderName).ToString()); // Show folder files if (OpenedFolder.CanSave() == false) { GUI.enabled = false; } if (GUIButton("Save")) { OpenedFolder.SaveAllElements(); } GUI.enabled = true; GUILayout.Space(30); DrawFolderFiles(); GUILayout.Space(30); IsExtraOptions = GUIToggle("Extra Options", IsExtraOptions); if (IsExtraOptions) { if (GUIButton("New File")) { DataManager.Get().AddNew(OpenedFolderName); } if (GUIButton("Revert Folder To Last Saved")) { RevertFolder(OpenedFolderName); } if (GUIButton("Open Folder [" + OpenedFolderName + "] In Windows")) { string FolderPath = DataManager.Get().GetMapPathNS() + OpenedFolderName + "/"; if (FileManagement.DirectoryExists(FolderPath, true, true) == false) { FileManagement.CreateDirectory(FolderPath, true); } FileUtil.OpenPathInWindows(FolderPath); } if (GUIButton("Force Save All Files")) { OpenedFolder.ForceSaveAllElements(); } } /*if (GUILayout.Button("New " + DataFolderNames.GetDataType(OpenedFolderName).ToString())) { ElementFolder MyFolder = DataManager.Get().GetElementFolder(OpenedFolderName); if (MyFolder != null) { MyFolder.AddNewElement(); } }*/ } private void RevertFolder(string FolderName) { ElementFolder MyFolder = DataManager.Get().GetElementFolder(FolderName); if (MyFolder != null) { MyFolder.Revert(); } //DataFolder<Texture2D> MyFolder2 = GetTextureFolder(FolderName); //if (MyFolder2 != null) { //MyFolder2.Revert(IsJSONFormat); } } private void DrawFolderFiles() { IncreaseIndent(); if (IsOpenedElementFolder && OpenedFolder != null) { int ElementCount = 0; try { foreach (KeyValuePair<string, Element> MyKeyValuePair in OpenedFolder.Data) { if (GUIButton(MyKeyValuePair.Key)) { // open file OpenedElement = MyKeyValuePair.Value; OpenedFileName = MyKeyValuePair.Key; OpenedFileIndex = ElementCount; /*if (HasOpenedZexels()) { OpenedTexture = MyKeyValuePair.Value as Zexel; }*/ OpenedElement.IsDrawGui = true; } ElementCount++; } } catch (System.ObjectDisposedException) { } } DecreaseIndent(); } /// <summary> /// Draws the folders. /// </summary> private void DrawFolders() { // Show folders List<ElementFolder> ElementFolders = DataManager.Get().GetFolders(); GUILayout.Space(20); GUILabel("Resource Folders: " + ElementFolders.Count); IncreaseIndent(); for (int i = 0; i < ElementFolders.Count; i++) { if (GUIButton(ElementFolders[i].FolderName + " [" + DataManager.Get().GetSize(ElementFolders[i].FolderName) + "]")) { OpenedFolderName = ElementFolders[i].FolderName; OpenedFolderIndex = i; OpenedFolder = ElementFolders[i]; IsOpenedElementFolder = true; } } DecreaseIndent(); } #endregion #region DrawFiles private bool HasOpenedZexels() { return DataFolderNames.GetDataType(OpenedFolderName) == typeof(Zexel); } private void CloseFile() { OpenedFileName = ""; OpenedElement.IsDrawGui = true; OpenedElement = null; } private void DrawFile() { if (GUIButton("Back")) { CloseFile(); } if (OpenedElement == null) { GUILabel("Null Element"); return; } GUILabel("File [" + OpenedFileName + "]" + " Of Type [" + OpenedElement.GetType() + "] " + " In Folder [" + OpenedFolderName + "]"); if (OpenedElement.CanSave() == false) { GUI.enabled = false; } if (GUIButton("Save")) { if (IsOpenedElementFolder) { OpenedElement.Save(); } } GUI.enabled = true; GUILayout.Space(10); IsDrawAllFields = GUILayout.Toggle(IsDrawAllFields, "IsDrawAllFields"); try { DrawFieldsForObject(OpenedElement as object, null, null, true); if (OpenedElement.GetType() == typeof(Level)) { Level MyLevel = OpenedElement as Level; if (MyLevel.Characters.Count > 0) { for (int i = 0; i < MyLevel.Characters.Count; i++) { Characters.Character LevelCharacter = MyLevel.GetSpawnedCharacter(i); if (LevelCharacter) { DrawFieldsForObject(LevelCharacter.GetData() as object, null, null, true); } } } } } catch (System.StackOverflowException e) { Debug.LogError("Overflow inside element: " + OpenedElement.Name + " - " + e.ToString()); } if (OpenedElement.GetType() == typeof(Voxels.PolyModel)) { DrawPolyModel(); } else if (OpenedElement.GetType() == typeof(Voxels.VoxelModel)) { DrawVoxelModel(); } else if(OpenedElement.GetType() == typeof(Sound.Zound)) { DrawZound(); } GUILayout.Space(30); IsExtraOptions = GUIToggle("Extra Options", IsExtraOptions); if (IsExtraOptions) { if (IsOpenedElementFolder) { GUILabel(OpenedElement.Name + " - [" + OpenedElement.CanSave().ToString() + "]"); } /*if (GUIButton("ForceSave")) { if (IsOpenedElementFolder) { OpenedElement.OnModified(); OpenedElement.Save(); } }*/ if (GUIButton("Reload From File")) { if (IsOpenedElementFolder) { OpenedElement = DataManager.Get().RevertElement(OpenedElement); } } if (GUIButton("Delete")) { OpenedElement.Delete(); } if (GUIButton("Check Size")) { long StopBytes = 0; long StartBytes = System.GC.GetTotalMemory(true); Element ClonedElement = OpenedElement.Clone(); StopBytes = System.GC.GetTotalMemory(true); //System.GC.KeepAlive (ClonedElement); // This ensure a reference to object keeps object in memory #if UNITY_EDITOR int TotalBytes = (int)(StopBytes - StartBytes); int KiloBytes = TotalBytes / 1024; TotalBytes = TotalBytes % 1024; int MegaBytes = KiloBytes / 1024; KiloBytes = KiloBytes % 1024; UnityEditor.EditorUtility.DisplayDialog(OpenedElement.GetType().ToString() + " Size Check", "Your element [" + ClonedElement.Name + "] is " + MegaBytes.ToString() + " Megabytes, " + KiloBytes.ToString() + " Kilobytes, " + TotalBytes.ToString() + " Bytes in Size.", "Thanks"); #endif } if (GUIButton("Clone")) { string NewName = CloneName; if (NewName == "") { NewName = NameGenerator.GenerateVoxelName(); } Element Clone = OpenedElement.Clone(); Clone.SetNameOfClone(NewName); OpenedFolder.AddElement(Clone); CloseFile(); } GUILabel("Clone As:"); CloneName = GUIText(CloneName); } } private string CloneName = ""; private void DrawPolyModel() { GUILayout.Label("PolyModel"); if (PolyRenderTexture == null) { PolyRenderTexture = Resources.Load("TestRenderTexture") as RenderTexture; } GUITexture(PolyRenderTexture); if (GUIButton("Import")) { DataManager.Get().ImportPolygon(OpenedFileIndex); } if (GUIButton("Export")) { DataManager.Get().ExportPolygon(OpenedElement as Voxels.PolyModel); } } private void DrawZound() { GUILayout.Space(30); GUILabel("Zound: " + (OpenedElement as Sound.Zound).GetSize()); // buttons if (GUIButton("Import")) { #if UNITY_EDITOR// || UNITY_STANDALONE_WIN DataManager.Get().ImportZound(OpenedFolderName, OpenedElement as Sound.Zound); #else Debug.LogError("Platform not supported."); #endif } if (GUIButton("Play")) { DataManager.Get().PlayClip((OpenedElement as Sound.Zound).GetAudioClip()); } } private void DrawVoxelModel() { GUILayout.Space(30); GUILabel("VoxelModel"); if (GUIButton("Import")) { UniversalCoroutine.CoroutineManager.StartCoroutine(DataManager.Get().LoadVoxFile((OpenedElement as Voxels.VoxelModel))); } GUILabel(OpenedElement.Name + " - Size: " + (OpenedElement as Voxels.VoxelModel).VoxelData.Length);// + ":" + (OpenedElement as Voxels.VoxelModel).VoxelData); } private void GUITexture(Texture MyTexture, float Multiple = 1f) { if (GUI.skin == null) { Debug.LogError("Skin is null in GUITexture DataGUI"); return; } GUILayout.Space(30); if (MyTexture == null) { MyTexture = Texture2D.blackTexture as Texture; } Rect OtherRect = GUILayoutUtility.GetRect(new GUIContent("Blargnugg"), GUI.skin.button); Rect MyRect = new Rect(0, 0, MyTexture.width * Multiple, MyTexture.height * Multiple); MyRect.x = GUIIndentPositionX() + MyTexture.width * (Multiple / 2f);// OtherRect.width / 2f - MyZexel.GetWidth() * 2f; MyRect.y = OtherRect.y; int BorderSize = 20; Rect BackgroundRect = new Rect(MyRect.x - BorderSize, MyRect.y - BorderSize, MyRect.width + BorderSize * 2f, MyRect.height + BorderSize * 2f); GUI.color = Color.gray; GUI.DrawTexture(BackgroundRect, Texture2D.whiteTexture); GUI.color = Color.white; GUI.DrawTexture(MyRect, MyTexture); GUILayout.Space(MyRect.height); } public void GUILabel(string MyLabelText) { #if UNITY_EDITOR UnityEditor.EditorGUILayout.LabelField(MyLabelText); #else GUILayout.Label(MyLabelText); #endif } public string GUIText(string OldValue) { try { #if UNITY_EDITOR return UnityEditor.EditorGUILayout.TextField(OldValue); #else return GUILayout.TextField(OldValue); #endif } catch (System.ArgumentException e) { Debug.LogError("DataGui GUIText: " + e.ToString()); return ""; } } public bool GUIToggle(string Label, bool OldValue) { #if UNITY_EDITOR return UnityEditor.EditorGUILayout.Toggle(Label, OldValue); #else return GUILayout.Toggle(OldValue, Label); #endif } public int GUIIndentPositionX() { #if UNITY_EDITOR return UnityEditor.EditorGUI.indentLevel * 16; #else return 0; #endif } public bool GUIButton(string ButtonLabel) { #if UNITY_EDITOR Rect MyRect = GUILayoutUtility.GetRect(new GUIContent(ButtonLabel), GUI.skin.GetStyle("button")); //Rect MyRect = UnityEditor.EditorGUILayout. //return UnityEditor.EditorGUILayout.By(OldValue); MyRect.position = new Vector2(GUIIndentPositionX() + MyRect.position.x, MyRect.position.y); return GUI.Button(MyRect, ButtonLabel); #else return GUILayout.Button(ButtonLabel); #endif } public bool GUIFoldout(bool OldValue, string MyLabelText) { #if UNITY_EDITOR return UnityEditor.EditorGUILayout.Foldout(OldValue, MyLabelText); #else return GUILayout.Toggle(OldValue, MyLabelText); #endif } public void IncreaseIndent() { #if UNITY_EDITOR UnityEditor.EditorGUI.indentLevel++; #endif } public void DecreaseIndent() { #if UNITY_EDITOR UnityEditor.EditorGUI.indentLevel--; #endif } /// <summary> /// Dynamically creates a gui for an object /// </summary> public object DrawFieldsForObject(object MyObject, object ParentObject, FieldInfo MyField, bool IsFirstField = false) { if (MyObject == null) { return null; } var Fields = (MyObject.GetType()).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); object ReturnObject = null; Element MyElement = MyObject as Element; if (MyElement != null) { MyElement.IsDrawGui = GUIFoldout(MyElement.IsDrawGui, "[" + MyElement.Name + "] " + MyObject.GetType().ToString() + " -Parent? " + (MyElement.ParentElement != null).ToString()); if (MyElement.IsDrawGui == false) { return null; } } else { GUILabel("Object: " + MyObject.ToString()); } #if UNITY_EDITOR if (UnityEditor.EditorGUI.indentLevel > 5) { return ReturnObject; } #endif IncreaseIndent(); // If has header if (MyField != null) { object[] MyAttributes = MyField.GetCustomAttributes(true); // false for (int j = 0; j < MyAttributes.Length; j++) { if (MyAttributes[j].GetType() == typeof(HeaderAttribute)) { GUILabel(MyAttributes[j].ToString()); break; } } } if (IsDrawAllFields) { GUILabel("Fields: [" + Fields.Length + "]"); for (int i = 0; i < Fields.Length; i++) { GUILabel((i + 1) + " [" + Fields[i].Name + "]"); } var Members = (MyObject.GetType()).GetMembers(); GUILayout.Space(30); GUILabel("Members: [" + Members.Length + "]"); for (int i = 0; i < Members.Length; i++) { GUILabel((i + 1) + " [" + Members[i].Name + "]"); } var Properties = (MyObject.GetType()).GetProperties(); GUILabel("Properties: [" + Properties.Length + "]"); for (int i = 0; i < Properties.Length; i++) { GUILabel((i + 1) + " [" + Properties[i].Name + "]"); } } else { //for (int i = Fields.Length - 1; i >= 0; i--) for (int i = 0; i < Fields.Length; i++) { object value = Fields[i].GetValue(MyObject); /*if (Fields[i].FieldType == typeof(Texture)) { Texture OldValue = Fields[i].GetValue(MyObject) as Texture; GUILayout.Label(OldValue); } else if (Fields[i].FieldType == typeof(Texture2D)) { Texture2D OldValue = Fields[i].GetValue(MyObject) as Texture2D; GUILayout.Label(OldValue); } else (*/ /*if (Fields[i].FieldType == typeof(CharacterStats)) { GUILabel(Fields[i].Name + " is null? " + (value == null).ToString() + " has json ignore? " + (HasJsonIgnore(Fields[i])).ToString() + " is value null? " + ((value == null)).ToString() + " is static? " + Fields[i].IsStatic.ToString()); }*/ bool IsIgnoreJson = HasJsonIgnore(Fields[i]); if (IsIgnoreJson) { // nothing } else if (value == null) { if (GUIButton("Spawn [" + Fields[i].Name + "]?")) { object NewValue = System.Activator.CreateInstance(Fields[i].FieldType); Fields[i].SetValue(MyObject, NewValue); MyElement = NewValue as Element; if (MyElement != null) { MyElement.OnModified(); MyElement.ParentElement = ParentObject as Element; } } } // For normal fields! else if (Fields[i] != null && Fields[i].IsStatic == false) { if (Fields[i].FieldType == typeof(string) || Fields[i].FieldType == typeof(float) || Fields[i].FieldType == typeof(int)) { string OldValue = value.ToString(); GUILabel("[" + Fields[i].Name + "]: " + OldValue); string NewValue = GUIText(OldValue); if (OldValue != NewValue) { if (Fields[i].FieldType == typeof(float)) { Fields[i].SetValue(MyObject, float.Parse(NewValue)); } else if (Fields[i].FieldType == typeof(int)) { Fields[i].SetValue(MyObject, int.Parse(NewValue)); } else { Fields[i].SetValue(MyObject, NewValue); } if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(bool)) { bool OldValue = (bool)value; bool NewValue = GUIToggle(Fields[i].Name, OldValue); if (NewValue != OldValue) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(Int3)) { Int3 OldValue = Fields[i].GetValue(MyObject) as Int3; //GUILayout.Label(" List<float> [" + Fields[i].Name + "]"); #if UNITY_EDITOR Int3 NewValue = UnityEditor.EditorGUILayout.Vector3Field(Fields[i].Name + ": ", OldValue.GetVector()).ToInt3(); if (OldValue != NewValue) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } #endif } else if (Fields[i].FieldType == typeof(Vector3)) { Vector3 OldValue = (Vector3)Fields[i].GetValue(MyObject); #if UNITY_EDITOR Vector3 NewValue = UnityEditor.EditorGUILayout.Vector3Field(Fields[i].Name + ": ", OldValue); if (OldValue != NewValue) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } #endif } else if (Fields[i].FieldType == typeof(List<float>)) { bool WasModified; List<float> OldValue = Fields[i].GetValue(MyObject) as List<float>; GUILabel(" List<float> [" + Fields[i].Name + "]: " + OldValue.Count); List<float> NewValue = DrawListGui(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(List<string>)) { bool WasModified; List<string> OldValue = Fields[i].GetValue(MyObject) as List<string>; GUILabel(" List<string> [" + Fields[i].Name + "]: " + OldValue.Count); List<string> NewValue = DrawListGui(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(List<int>)) { bool WasModified; List<int> OldValue = Fields[i].GetValue(MyObject) as List<int>; GUILabel(" List<int> [" + Fields[i].Name + "]: " + OldValue.Count); List<int> NewValue = DrawListGui(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(List<bool>)) { bool WasModified; List<bool> OldValue = Fields[i].GetValue(MyObject) as List<bool>; GUILabel(" List<bool> [" + Fields[i].Name + "]: " + OldValue.Count); List<bool> NewValue = DrawListGui(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else if (Fields[i].FieldType == typeof(IntDictionary)) { bool WasModified; IntDictionary OldValue = Fields[i].GetValue(MyObject) as IntDictionary; if (OldValue != null) { GUILabel(" IntDictionary [" + Fields[i].Name + "]: " + OldValue.Count); IntDictionary NewValue = DrawIntDictionary(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else { GUILabel(" IntDictionary [" + Fields[i].Name + "] null!"); } } else if (Fields[i].FieldType == typeof(FloatDictionary)) { bool WasModified; FloatDictionary OldValue = Fields[i].GetValue(MyObject) as FloatDictionary; if (OldValue != null) { GUILabel(" FloatDictionary [" + Fields[i].Name + "]: " + OldValue.Count); FloatDictionary NewValue = DrawFloatDictionary(OldValue, MyObject, Fields[i], out WasModified); if (WasModified) { Fields[i].SetValue(MyObject, NewValue); if (MyElement != null) { MyElement.OnModified(); } } } else { GUILabel(" FloatDictionary [" + Fields[i].Name + "] null!"); } } else if (Fields[i].FieldType == typeof(StatType)) { int OldValue = (int)value; GUILabel("[" + Fields[i].Name + "]: " + OldValue); int NewValue = int.Parse(GUILayout.TextField(OldValue.ToString())); if (OldValue != NewValue) { Fields[i].SetValue(MyObject, NewValue); (MyObject as Element).OnModified(); } } else if (DrawListGui<Item>(Fields[i], MyObject)) { } else if (DrawListGui<Stat>(Fields[i], MyObject)) { } else if (DrawListGui<Bone>(Fields[i], MyObject)) { } else if (DrawListGui<ZeltexTransformCurve>(Fields[i], MyObject)) { } // Draw for elements! if (!IsIgnoreJson && (Fields[i].FieldType.BaseType == typeof(Element) || Fields[i].FieldType.BaseType == typeof(ElementCore))) { //GUILabel(Fields[i].FieldType.ToString() + ": " + i + ": " + Fields[i].Name); DrawFieldsForObject(value, MyObject, Fields[i]); } /*else if (Fields[i].FieldType.BaseType == typeof(Stats)) { DrawFieldsForObject(value, Fields[i]); }*/ } //Fields[i].SetValue(GUILayout.TextField(Fields[i].GetValue())); } //Element FieldElement = Fields[i].GetValue(MyObject) as Element; if (MyElement != null) { ReturnObject = DrawElementGui(MyElement, IsFirstField, ParentObject, MyField, ReturnObject); DrawSpawnGUI<Level>(MyElement); DrawSpawnGUI<CharacterData>(MyElement); DrawSpawnGUI<SaveGame>(MyElement); DrawZexelGui(MyElement); DrawSpawnGUI<VoxelMeta>(MyElement); DrawSpawnGUI<PolyModel>(MyElement); DrawVoxelModelGUI(MyElement); DrawSpawnGUI<Skeleton>(MyElement); DrawSpawnGUI<Zanimation>(MyElement); DrawSpawnGUI<Item>(MyElement); DrawSpawnGUI<Spell>(MyElement); DrawSpawnGUI<ZoneData>(MyElement); DrawSpawnGUI<Lore>(MyElement); DrawSpawnGUI<Quests.Quest>(MyElement); DrawSpawnGUI<Dialogue.DialogueTree>(MyElement); if (MyElement.GetType() == typeof(Stat)) { Stat MyStat = MyElement as Stat; GUILabel("-----"); GUILabel(MyStat.GetGuiString()); GUILabel("-----"); if (MyStat.GetStatType() != StatType.Base && GUIButton("Change To Type [" + StatType.Base + "]")) { MyStat.SetValuesAsType(StatType.Base); } if (MyStat.GetStatType() != StatType.Modifier && GUIButton("Change To Type [" + StatType.Modifier + "]")) { MyStat.SetValuesAsType(StatType.Modifier); } if (MyStat.GetStatType() != StatType.Regen && GUIButton("Change To Type [" + StatType.Regen + "]")) { MyStat.SetValuesAsType(StatType.Regen); } if (MyStat.GetStatType() != StatType.State && GUIButton("Change To Type [" + StatType.State + "]")) { MyStat.SetValuesAsType(StatType.State); } if (MyStat.GetStatType() != StatType.TemporaryModifier && GUIButton("Change To Type [" + StatType.TemporaryModifier + "]")) { MyStat.SetValuesAsType(StatType.TemporaryModifier); } if (MyStat.GetStatType() != StatType.TemporaryRegen && GUIButton("Change To Type [" + StatType.TemporaryRegen + "]")) { MyStat.SetValuesAsType(StatType.TemporaryRegen); } } } if (MyElement != null && MyElement.ParentElement != null) { GUILayout.Space(6); if (GUIButton("Erase [" + MyElement.Name + "] to become Null")) { MyField.SetValue(ParentObject, null); } GUILayout.Space(6); } } DecreaseIndent(); return ReturnObject; } private object DrawElementGui(Element MyElement, bool IsFirstField, object ParentObject, FieldInfo MyField, object ReturnObject) { if (MyElement.ParentElement != null) { // At the moment this only supports single positioning, but later on it will support more MyElement.ElementLink = GUIText(MyElement.ElementLink); if (MyElement.ElementLink == "") { if (IsFirstField) { MyElement.ElementLink = MyElement.GetFolder(); } else { MyElement.ElementLink = DataFolderNames.DataTypeToFolderName(MyElement.GetType()); } } GUILabel("Pull Data From DataManager"); if (GUIButton("From [" + MyElement.ElementLink + "]")) { ReturnObject = PullElement(MyElement, MyField, ParentObject, ReturnObject); } GUILabel("Push Data To the DataManager"); if (GUIButton("Push To [" + MyElement.ElementLink + "]")) { //Element MyValue = Fields[i].GetValue(MyObject) as Element; DataManager.Get().PushElement(MyElement.ElementLink, MyElement); } } return ReturnObject; } /// <summary> /// Pulls one element over another, needs fieldinfo and objects in order to set the value /// </summary> private object PullElement(Element MyElement, FieldInfo MyField, object ParentObject, object ReturnObject) { //Element OldValue = Fields[i].GetValue(MyObject) as Element; //Debug.Log(MyElement.Name + " is being overwritten from an element in database folder: " + MyElement.ElementLink); Element DataClone = DataManager.Get().GetElement(MyElement.ElementLink, MyElement.Name); if (DataClone != null) { DataClone = DataClone.Clone(); ElementFolder MyFolder = MyElement.MyFolder; DataClone.IsDrawGui = MyElement.IsDrawGui; DataClone.MyFolder = MyElement.MyFolder; DataClone.ElementLink = MyElement.ElementLink; DataClone.ParentElement = MyElement.ParentElement; DataClone.ResetName(); if (MyFolder != null) { MyFolder.SetElement(DataClone); } if (MyField != null) { try { MyField.SetValue(ParentObject, DataClone); Debug.Log(MyElement.Name + " is using MyField.SetValue"); } catch (System.ArgumentException e) { // From a list of elements Debug.LogError(e.ToString()); Debug.LogError(DataClone.GetType() + " compared to: " + MyElement.GetType() + " Field: " + MyField.Name + " of object " + MyElement.ToString()); ReturnObject = DataClone as object; Debug.Log(MyElement.Name + " is using ReturnObject to a list"); } DataClone.OnModified(); } else { Debug.LogError("Could not pull element as FieldInfo is null."); } /*else if (IsFirstField) { OpenedFolder.SetElement(NewElement); }*/ } else { Debug.LogError("Could not find file " + MyElement.Name + " in folder " + MyElement.ElementLink); } return ReturnObject; } private void DrawVoxelModelGUI(Element MyElement) { if (MyElement.GetType() == typeof(VoxelModel)) { VoxelModel MyVoxelModel = MyElement as VoxelModel; if (MyVoxelModel != null) { if (GUIButton("Import")) { DataManager.Get().ImportVox(MyVoxelModel); } } if (MyElement.ParentElement == null) { DrawSpawnGUI<VoxelModel>(MyElement); } } } private void DrawZexelGui(Element MyElement) { if (MyElement.GetType() == typeof(Zexel)) { Zexel MyZexel = MyElement as Zexel; if (MyZexel != null) { GUITexture(MyZexel.GetTexture(), 4); if (GUIButton("Import")) { DataManager.Get().ImportImage(MyZexel); } if (GUIButton("Export")) { DataManager.Get().ExportZexel(MyZexel); } } } } private void DrawLevelGui(Element MyElement) { if (MyElement.GetType() == typeof(Level)) { Level MyLevel = MyElement as Level; if (!MyLevel.HasSpawned()) { if (GUIButton("Spawn")) { MyLevel.Spawn(); } } else { if (GUIButton("DeSpawn")) { MyLevel.DeSpawn(); } } } } private void DrawSkeletonGui(Element MyElement) { if (MyElement.GetType() == typeof(Skeletons.Skeleton)) { Skeletons.Skeleton MySkeleton = MyElement as Skeletons.Skeleton; if (!MySkeleton.HasSpawned()) { if (GUIButton("Spawn")) { MySkeleton.Spawn(); } } else { if (GUIButton("DeSpawn")) { MySkeleton.DeSpawn(); } } } } private string SpawnZanimationWithSkeletonName = ""; private string SpawnInLevelName = ""; private void DrawSpawnGUI<T>(Element MyElement) where T : Element { if (MyElement.GetType() == typeof(T)) { T MyElementConverted = MyElement as T; if (!MyElementConverted.HasSpawned()) { if (GUIButton("Spawn")) { MyElementConverted.Spawn(); } if (typeof(T) == typeof(Zanimation)) { GUILabel("Spawn with Skeleton:"); SpawnZanimationWithSkeletonName = GUIText(SpawnZanimationWithSkeletonName); if (GUIButton("Spawn With Skeleton")) { Zanimation MyZanimation = MyElementConverted as Zanimation; MyZanimation.SpawnWithSkeleton(SpawnZanimationWithSkeletonName); } } else if (typeof(T) == typeof(PolyModel)) { PolyModel lyModel = MyElementConverted as PolyModel; GUILabel("Models Parts: " + lyModel.MyModels.Count); if (GUIButton("GenerateCube")) { lyModel.GenerateCubeMesh(); } } else if (typeof(T) == typeof(ZoneData)) { GUILabel("Spawn in Level:"); SpawnInLevelName = GUIText(SpawnInLevelName); if (GUIButton("Spawn in " + SpawnInLevelName)) { ZoneData Data = MyElementConverted as ZoneData; Data.SpawnInLevel(SpawnInLevelName); } } else if (typeof(T) == typeof(Level)) { GUILabel("Characters Spawn with Level:"); Level MyLevel = MyElementConverted as Level; for (int i = 0; i < MyLevel.CharacterNames.Count; i++) { if (MyLevel.CanSpawnCharacterInEditor(i)) { if (GUIButton("Spawn Character [" + MyLevel.CharacterNames[i] + "]")) { MyLevel.SpawnCharacterInEditor(i); } } else { if (GUIButton("Despawn Character [" + MyLevel.CharacterNames[i] + "]")) { MyLevel.DespawnCharacterInEditor(i); } } } } } else { if (GUIButton("DeSpawn")) { MyElementConverted.DeSpawn(); } } } } /// <summary> /// Draws for a list of type T /// </summary> private bool DrawListGui<T>(FieldInfo MyField, object MyObject) { if (MyField.FieldType == typeof(List<T>)) { bool WasModified; List<T> OldValue = MyField.GetValue(MyObject) as List<T>; GUILabel(" List<" + typeof(T).ToString() + "> [" + MyField.Name + "]: " + OldValue.Count); List<T> NewValue = DrawListGui(OldValue, MyObject, MyField, out WasModified); if (WasModified) { MyField.SetValue(MyObject, NewValue); } return true; } return false; } public bool HasJsonIgnore(FieldInfo MyField) { return HasAttribute(MyField, typeof(Newtonsoft.Json.JsonIgnoreAttribute)); } public bool HasAttribute(FieldInfo MyField, System.Type AttributeType) { object[] attributes = MyField.GetCustomAttributes(true); // false for (int i = 0; i < attributes.Length; i++) { if (attributes[i].GetType() == AttributeType) { return true; } } return false; } List<T> DrawListGui<T>(List<T> MyList, object MyObject, FieldInfo MyField, out bool WasModified) { WasModified = false; //GUILayout.Label("[" + MyList.Count + "]"); List<string> ListString = MyList as List<string>; List<float> ListFloat = MyList as List<float>; List<bool> ListBool = MyList as List<bool>; List<T> ListElements = MyList as List<T>; if (GUIButton("Add")) { if (typeof(T) == typeof(string)) { ListString.Add(""); } else if (typeof(T) == typeof(float)) { ListFloat.Add(0); } else if (typeof(T) == typeof(bool)) { ListBool.Add(false); } else if (typeof(T).BaseType == typeof(Element) || typeof(T).BaseType == typeof(ElementCore)) { #if NET_4_6 ConstructorInfo MyConstructor = typeof(T).GetConstructor(System.Type.EmptyTypes); dynamic NewValue = MyConstructor.Invoke(null); //if (NewValue != null) { ListElements.Add(NewValue); } #else object NewValue = System.Activator.CreateInstance(typeof(T)); ListElements.Add((T)NewValue); #endif Element ParentOfList = MyObject as Element; (ListElements[ListElements.Count - 1] as Element).ParentElement = ParentOfList; ParentOfList.OnModified(); } WasModified = true; } for (int j = 0; j < MyList.Count; j++) { //GUILayout.Label("\t" + (j + 1) + ": [" + MyList[j] + "]"); if (typeof(T) == typeof(string)) { string NewValue = GUIText(ListString[j]); if (ListString[j] != NewValue) { ListString[j] = NewValue; WasModified = true; } } else if (typeof(T) == typeof(float)) { float NewValue = float.Parse(GUIText(ListFloat[j].ToString())); if (ListFloat[j] != NewValue) { ListFloat[j] = NewValue; WasModified = true; } } else if (typeof(T) == typeof(bool)) { bool NewValue = GUIToggle(MyField.Name + "[" + j + "]", (bool)ListBool[j]); if (ListBool[j] != NewValue) { ListBool[j] = NewValue; WasModified = true; } } else if (typeof(T).BaseType == typeof(Element) || typeof(T).BaseType == typeof(ElementCore)) { T NewElement = (T) DrawFieldsForObject(ListElements[j], MyObject, MyField); if (NewElement != null) { ListElements[j] = NewElement; WasModified = true; } } } if (typeof(T) == typeof(string)) { MyList = ListString as List<T>; } else if (typeof(T) == typeof(float)) { MyList = ListFloat as List<T>; } else if (typeof(T) == typeof(bool)) { MyList = ListBool as List<T>; } else if (typeof(T).BaseType == typeof(Element) || typeof(T).BaseType == typeof(ElementCore)) { MyList = ListElements as List<T>; } return MyList; } Int3 GUIInt3(Int3 OldInt3) { Rect OldRect = GUILayoutUtility.GetRect(new GUIContent("Blargnugg"), GUI.skin.button); OldRect.position = new Vector2(OldRect.position.x + GUIIndentPositionX(), OldRect.position.y); OldRect.width -= GUIIndentPositionX(); Rect PartA = new Rect(OldRect.x + OldRect.width * 1f / 4f, OldRect.y, OldRect.width / 4f, OldRect.height); Rect PartB = new Rect(OldRect.x + OldRect.width * 2f / 4f, OldRect.y, OldRect.width / 4f, OldRect.height); Rect PartC = new Rect(OldRect.x + OldRect.width * 3f / 4f, OldRect.y, OldRect.width / 4f, OldRect.height); Int3 NewInt3 = new Int3(); NewInt3.x = int.Parse(GUI.TextField(PartA, OldInt3.x.ToString())); NewInt3.y = int.Parse(GUI.TextField(PartB, OldInt3.y.ToString())); NewInt3.z = int.Parse(GUI.TextField(PartC, OldInt3.z.ToString())); return NewInt3; } string GUIInt3Text(string OldText) { Rect OldRect = GUILayoutUtility.GetLastRect();//(new GUIContent("Blargnugg"), GUI.skin.button); OldRect.position = new Vector2(OldRect.position.x + GUIIndentPositionX(), OldRect.position.y); OldRect.width -= GUIIndentPositionX(); //Rect PartA = new Rect(OldRect.x, OldRect.y, OldRect.width / 4f, OldRect.height); return GUI.TextField(OldRect, OldText); } public FloatDictionary DrawFloatDictionary(FloatDictionary MyDictionary, object MyObject, FieldInfo MyField, out bool WasModified) { WasModified = false; MyDictionary.IsEditing = GUIToggle("Is Editing?", MyDictionary.IsEditing); if (GUIButton("Add")) { MyDictionary.Add(Random.Range(0f, 1f), 0); WasModified = true; } if (MyDictionary != null) { try { foreach (KeyValuePair<float, float> MyPair in MyDictionary) { if (MyDictionary.IsEditing == false) { GUILabel(MyPair.Key + ":" + MyPair.Value); } else { float NewKey = float.Parse( GUIText(MyPair.Key.ToString())); if (MyPair.Key != NewKey) { MyDictionary.Remove(MyPair.Key); MyDictionary.Add(NewKey, MyPair.Value); WasModified = true; } else { float NewValue = float.Parse(GUIText(MyPair.Value.ToString())); if (MyPair.Value != NewValue) { MyDictionary[MyPair.Key] = NewValue; WasModified = true; } } } } } catch (System.ObjectDisposedException) { //Debug.LogError("DrawIntDictionary: " + e.ToString()); } } return MyDictionary; } public IntDictionary DrawIntDictionary(IntDictionary MyDictionary, object MyObject, FieldInfo MyField, out bool WasModified) { WasModified = false; MyDictionary.IsEditing = GUIToggle("Is Editing?", MyDictionary.IsEditing); if (GUIButton("Add")) { MyDictionary.Add(new Int3(0, 0, Random.Range(-100, -1)), "Empty"); WasModified = true; } if (MyDictionary != null) { try { foreach (KeyValuePair<Int3, string> MyPair in MyDictionary) { if (MyDictionary.IsEditing == false) { GUILabel(MyPair.Key + ":" + MyPair.Value); } else { Int3 NewKey = GUIInt3(MyPair.Key); if (MyPair.Key != NewKey) { MyDictionary.Remove(MyPair.Key); MyDictionary.Add(NewKey, MyPair.Value); WasModified = true; } else { string NewValue = GUIInt3Text(MyPair.Value); if (MyPair.Value != NewValue) { MyDictionary[MyPair.Key] = NewValue; WasModified = true; } } } } } catch (System.ObjectDisposedException) { //Debug.LogError("DrawIntDictionary: " + e.ToString()); } } return MyDictionary; } #endregion } }
36.550877
193
0.456385
[ "Apache-2.0" ]
Deus0/Zeltexium
Assets/Scripts/Data/DataGUI.cs
62,504
C#
using Cirilla.Core.Models; using Cirilla.Core.Structs.Native; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Runtime.InteropServices; namespace Cirilla.Core.Test.Tests { [TestClass] public class SaveDataTests { [TestMethod] public void SizeOf__SaveData_Header() { Assert.AreEqual(64, Marshal.SizeOf<SaveData_Header>()); } [TestMethod] public void SizeOf__SaveData_SaveSlot() { Assert.AreEqual(2136768, Marshal.SizeOf<SaveData_SaveSlot>()); } [TestMethod] public void SizeOf__SaveData_Appearance() { Assert.AreEqual(168, Marshal.SizeOf<CharacterAppearance>()); } [TestMethod] public void SizeOf__SaveData_GuildCard() { Assert.AreEqual(7787, Marshal.SizeOf<SaveData_GuildCard>()); } [TestMethod] public void SizeOf__SaveData_PalicoAppearance() { Assert.AreEqual(44, Marshal.SizeOf<PalicoAppearance>()); } [DataTestMethod] [DataRow("IceborneSave1")] [DataRow("IceborneSaveDec1")] [DataRow("IceborneSaveDec2")] public void Load__SAVEDATA1000(string filename) { SaveData save = new SaveData(Utility.GetTestAsset(@"saves/" + filename)); Assert.AreEqual("Fusion", save.SaveSlots[0].HunterName); Assert.AreEqual("Sjonnie Jan", save.SaveSlots[0].PalicoName); Assert.AreEqual("Fusion", save.SaveSlots[1].HunterName); Assert.AreEqual("Knor", save.SaveSlots[1].PalicoName); } //[TestMethod] //public void Load__SAVEDATA1000_remote() //{ // SaveData save = new SaveData(@"C:\Steam\userdata\112073240\582010\remote\SAVEDATA1000"); // Assert.AreEqual("Fusion", save.SaveSlots[0].HunterName); //} [DataTestMethod] [DataRow("IceborneSave1", true)] [DataRow("IceborneSaveDec1", false)] [DataRow("IceborneSaveDec2", false)] public void Rebuild__SAVEDATA1000(string filename, bool encrypt) { string origPath = Utility.GetTestAsset(@"saves/" + filename); string rebuildPath = "rebuild__" + filename + "_" + (encrypt ? "enc" : "dec"); SaveData save = new SaveData(origPath); save.Save(rebuildPath, encrypt, false); if (!Utility.CheckFilesAreSame(origPath, rebuildPath)) Assert.Fail("Hash doesn't match!"); File.Delete(rebuildPath); } //[TestMethod] //public void Rebuild__SAVEDATA1000_remote() //{ // string origPath = @"C:\Steam\userdata\112073240\582010\remote\SAVEDATA1000"; // string rebuildPath = "rebuild__SAVEDATA1000_remote"; // SaveData save = new SaveData(origPath); // save.Save(rebuildPath); // if (!Utility.CheckFilesAreSame(origPath, rebuildPath)) // Assert.Fail("Hash doesn't match!"); //} } }
32.861702
102
0.602784
[ "MIT" ]
Fusion86/Cirilla
src/Cirilla.Core.Test/Tests/SaveDataTests.cs
3,091
C#
/* * Copyright(c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using Tizen.NUI.BaseComponents; namespace Tizen.NUI { using System; using System.Runtime.InteropServices; internal class ItemView : Scrollable { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal ItemView(global::System.IntPtr cPtr, bool cMemoryOwn) : base(NDalicPINVOKE.ItemView_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ItemView obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } protected override void Dispose(DisposeTypes type) { if (disposed) { return; } if (type == DisposeTypes.Explicit) { //Called by User //Release your own managed resources here. //You should release all of your own disposable objects here. } //Release your own unmanaged resources here. //You should not access any managed member here except static instance. //because the execution order of Finalizes is non-deterministic. if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; NDalicPINVOKE.delete_ItemView(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } base.Dispose(type); } public Tizen.NUI.PropertyArray Layout { get { Tizen.NUI.PropertyArray temp = new Tizen.NUI.PropertyArray(); GetProperty(ItemView.Property.LAYOUT).Get(temp); return temp; } set { SetProperty(ItemView.Property.LAYOUT, new Tizen.NUI.PropertyValue(value)); } } /// <since_tizen> 3 </since_tizen> public new class Property { /// <since_tizen> 3 </since_tizen> public static readonly int LAYOUT = NDalicManualPINVOKE.ItemView_Property_LAYOUT_get(); /// <since_tizen> 3 </since_tizen> public static readonly int MINIMUM_SWIPE_SPEED = NDalicPINVOKE.ItemView_Property_MINIMUM_SWIPE_SPEED_get(); /// <since_tizen> 3 </since_tizen> public static readonly int MINIMUM_SWIPE_DISTANCE = NDalicPINVOKE.ItemView_Property_MINIMUM_SWIPE_DISTANCE_get(); /// <since_tizen> 3 </since_tizen> public static readonly int WHEEL_SCROLL_DISTANCE_STEP = NDalicPINVOKE.ItemView_Property_WHEEL_SCROLL_DISTANCE_STEP_get(); /// <since_tizen> 3 </since_tizen> public static readonly int SNAP_TO_ITEM_ENABLED = NDalicPINVOKE.ItemView_Property_SNAP_TO_ITEM_ENABLED_get(); /// <since_tizen> 3 </since_tizen> public static readonly int REFRESH_INTERVAL = NDalicPINVOKE.ItemView_Property_REFRESH_INTERVAL_get(); /// <since_tizen> 3 </since_tizen> public static readonly int LAYOUT_POSITION = NDalicPINVOKE.ItemView_Property_LAYOUT_POSITION_get(); /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_SPEED = NDalicPINVOKE.ItemView_Property_SCROLL_SPEED_get(); /// <since_tizen> 3 </since_tizen> public static readonly int OVERSHOOT = NDalicPINVOKE.ItemView_Property_OVERSHOOT_get(); /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_DIRECTION = NDalicPINVOKE.ItemView_Property_SCROLL_DIRECTION_get(); /// <since_tizen> 3 </since_tizen> public static readonly int LAYOUT_ORIENTATION = NDalicPINVOKE.ItemView_Property_LAYOUT_ORIENTATION_get(); /// <since_tizen> 3 </since_tizen> public static readonly int SCROLL_CONTENT_SIZE = NDalicPINVOKE.ItemView_Property_SCROLL_CONTENT_SIZE_get(); } public ItemView(ItemFactory factory) : this(NDalicPINVOKE.ItemView_New(ItemFactory.getCPtr(factory)), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal static ItemView DownCast(BaseHandle handle) { ItemView ret = Registry.GetManagedBaseHandleFromNativePtr(handle) as ItemView; if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public uint GetLayoutCount() { uint ret = NDalicPINVOKE.ItemView_GetLayoutCount(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void AddLayout(ItemLayout layout) { NDalicPINVOKE.ItemView_AddLayout(swigCPtr, ItemLayout.getCPtr(layout)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void RemoveLayout(uint layoutIndex) { NDalicPINVOKE.ItemView_RemoveLayout(swigCPtr, layoutIndex); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t GetLayout(uint layoutIndex) { SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t ret = new SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t(NDalicPINVOKE.ItemView_GetLayout(swigCPtr, layoutIndex), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t GetActiveLayout() { SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t ret = new SWIGTYPE_p_Dali__IntrusivePtrT_Dali__Toolkit__ItemLayout_t(NDalicPINVOKE.ItemView_GetActiveLayout(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public float GetCurrentLayoutPosition(uint itemId) { float ret = NDalicPINVOKE.ItemView_GetCurrentLayoutPosition(swigCPtr, itemId); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void ActivateLayout(uint layoutIndex, Vector3 targetSize, float durationSeconds) { NDalicPINVOKE.ItemView_ActivateLayout(swigCPtr, layoutIndex, Vector3.getCPtr(targetSize), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void DeactivateCurrentLayout() { NDalicPINVOKE.ItemView_DeactivateCurrentLayout(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void SetMinimumSwipeSpeed(float speed) { NDalicPINVOKE.ItemView_SetMinimumSwipeSpeed(swigCPtr, speed); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public float GetMinimumSwipeSpeed() { float ret = NDalicPINVOKE.ItemView_GetMinimumSwipeSpeed(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetMinimumSwipeDistance(float distance) { NDalicPINVOKE.ItemView_SetMinimumSwipeDistance(swigCPtr, distance); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public float GetMinimumSwipeDistance() { float ret = NDalicPINVOKE.ItemView_GetMinimumSwipeDistance(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetWheelScrollDistanceStep(float step) { NDalicPINVOKE.ItemView_SetWheelScrollDistanceStep(swigCPtr, step); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public float GetWheelScrollDistanceStep() { float ret = NDalicPINVOKE.ItemView_GetWheelScrollDistanceStep(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetAnchoring(bool enabled) { NDalicPINVOKE.ItemView_SetAnchoring(swigCPtr, enabled); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public bool GetAnchoring() { bool ret = NDalicPINVOKE.ItemView_GetAnchoring(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetAnchoringDuration(float durationSeconds) { NDalicPINVOKE.ItemView_SetAnchoringDuration(swigCPtr, durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public float GetAnchoringDuration() { float ret = NDalicPINVOKE.ItemView_GetAnchoringDuration(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void ScrollToItem(uint itemId, float durationSeconds) { NDalicPINVOKE.ItemView_ScrollToItem(swigCPtr, itemId, durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void SetRefreshInterval(float intervalLayoutPositions) { NDalicPINVOKE.ItemView_SetRefreshInterval(swigCPtr, intervalLayoutPositions); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public float GetRefreshInterval() { float ret = NDalicPINVOKE.ItemView_GetRefreshInterval(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void Refresh() { NDalicPINVOKE.ItemView_Refresh(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public View GetItem(uint itemId) { View ret = new View(NDalicPINVOKE.ItemView_GetItem(swigCPtr, itemId), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public uint GetItemId(View view) { uint ret = NDalicPINVOKE.ItemView_GetItemId(swigCPtr, View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void InsertItem(Item newItem, float durationSeconds) { NDalicPINVOKE.ItemView_InsertItem(swigCPtr, Item.getCPtr(newItem), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void InsertItems(ItemContainer newItems, float durationSeconds) { NDalicPINVOKE.ItemView_InsertItems(swigCPtr, ItemContainer.getCPtr(newItems), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void RemoveItem(uint itemId, float durationSeconds) { NDalicPINVOKE.ItemView_RemoveItem(swigCPtr, itemId, durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void RemoveItems(ItemIdContainer itemIds, float durationSeconds) { NDalicPINVOKE.ItemView_RemoveItems(swigCPtr, ItemIdContainer.getCPtr(itemIds), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void ReplaceItem(Item replacementItem, float durationSeconds) { NDalicPINVOKE.ItemView_ReplaceItem(swigCPtr, Item.getCPtr(replacementItem), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void ReplaceItems(ItemContainer replacementItems, float durationSeconds) { NDalicPINVOKE.ItemView_ReplaceItems(swigCPtr, ItemContainer.getCPtr(replacementItems), durationSeconds); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public void SetItemsParentOrigin(Vector3 parentOrigin) { NDalicPINVOKE.ItemView_SetItemsParentOrigin(swigCPtr, Vector3.getCPtr(parentOrigin)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public Vector3 GetItemsParentOrigin() { Vector3 ret = new Vector3(NDalicPINVOKE.ItemView_GetItemsParentOrigin(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void SetItemsAnchorPoint(Vector3 anchorPoint) { NDalicPINVOKE.ItemView_SetItemsAnchorPoint(swigCPtr, Vector3.getCPtr(anchorPoint)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public Vector3 GetItemsAnchorPoint() { Vector3 ret = new Vector3(NDalicPINVOKE.ItemView_GetItemsAnchorPoint(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public void GetItemsRange(ItemRange range) { NDalicPINVOKE.ItemView_GetItemsRange(swigCPtr, ItemRange.getCPtr(range)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } public VoidSignal LayoutActivatedSignal() { VoidSignal ret = new VoidSignal(NDalicPINVOKE.ItemView_LayoutActivatedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } public float MinimumSwipeSpeed { get { float temp = 0.0f; GetProperty(ItemView.Property.MINIMUM_SWIPE_SPEED).Get(out temp); return temp; } set { SetProperty(ItemView.Property.MINIMUM_SWIPE_SPEED, new Tizen.NUI.PropertyValue(value)); } } public float MinimumSwipeDistance { get { float temp = 0.0f; GetProperty(ItemView.Property.MINIMUM_SWIPE_DISTANCE).Get(out temp); return temp; } set { SetProperty(ItemView.Property.MINIMUM_SWIPE_DISTANCE, new Tizen.NUI.PropertyValue(value)); } } public float WheelScrollDistanceStep { get { float temp = 0.0f; GetProperty(ItemView.Property.WHEEL_SCROLL_DISTANCE_STEP).Get(out temp); return temp; } set { SetProperty(ItemView.Property.WHEEL_SCROLL_DISTANCE_STEP, new Tizen.NUI.PropertyValue(value)); } } public bool SnapToItemEnabled { get { bool temp = false; GetProperty(ItemView.Property.SNAP_TO_ITEM_ENABLED).Get(out temp); return temp; } set { SetProperty(ItemView.Property.SNAP_TO_ITEM_ENABLED, new Tizen.NUI.PropertyValue(value)); } } public float RefreshInterval { get { float temp = 0.0f; GetProperty(ItemView.Property.REFRESH_INTERVAL).Get(out temp); return temp; } set { SetProperty(ItemView.Property.REFRESH_INTERVAL, new Tizen.NUI.PropertyValue(value)); } } public float LayoutPosition { get { float temp = 0.0f; GetProperty(ItemView.Property.LAYOUT_POSITION).Get(out temp); return temp; } set { SetProperty(ItemView.Property.LAYOUT_POSITION, new Tizen.NUI.PropertyValue(value)); } } public float ScrollSpeed { get { float temp = 0.0f; GetProperty(ItemView.Property.SCROLL_SPEED).Get(out temp); return temp; } set { SetProperty(ItemView.Property.SCROLL_SPEED, new Tizen.NUI.PropertyValue(value)); } } public float Overshoot { get { float temp = 0.0f; GetProperty(ItemView.Property.OVERSHOOT).Get(out temp); return temp; } set { SetProperty(ItemView.Property.OVERSHOOT, new Tizen.NUI.PropertyValue(value)); } } public Vector2 ScrollDirection { get { Vector2 temp = new Vector2(0.0f, 0.0f); GetProperty(ItemView.Property.SCROLL_DIRECTION).Get(temp); return temp; } set { SetProperty(ItemView.Property.SCROLL_DIRECTION, new Tizen.NUI.PropertyValue(value)); } } public int LayoutOrientation { get { int temp = 0; GetProperty(ItemView.Property.LAYOUT_ORIENTATION).Get(out temp); return temp; } set { SetProperty(ItemView.Property.LAYOUT_ORIENTATION, new Tizen.NUI.PropertyValue(value)); } } public float ScrollContentSize { get { float temp = 0.0f; GetProperty(ItemView.Property.SCROLL_CONTENT_SIZE).Get(out temp); return temp; } set { SetProperty(ItemView.Property.SCROLL_CONTENT_SIZE, new Tizen.NUI.PropertyValue(value)); } } } }
40.280079
203
0.635834
[ "Apache-2.0" ]
Reni-90/TizenFX
src/Tizen.NUI/src/internal/ItemView.cs
20,422
C#
using System.Collections.Generic; using Horizon.Payment.Alipay.Response; namespace Horizon.Payment.Alipay.Request { /// <summary> /// alipay.ins.marketing.experience.account.query /// </summary> public class AlipayInsMarketingExperienceAccountQueryRequest : IAlipayRequest<AlipayInsMarketingExperienceAccountQueryResponse> { /// <summary> /// 寿险体验金账户查询 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.ins.marketing.experience.account.query"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.895161
131
0.551603
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Request/AlipayInsMarketingExperienceAccountQueryRequest.cs
2,859
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /// Event effect: Spawn Projectiles [AddComponentMenu("Game/Event Effect: Spawn Projectiles")] public class EventEffect_SpawnProjectiles : MonoBehaviour, IEventEffect { [SerializeField, Tooltip("Serialized Parameters for projectiles to spawn")] private ProjectileSpawnSerializedParameters[] spawnSerializedParameters; public void Trigger() { foreach (ProjectileSpawnSerializedParameters spawnSerializedParameter in spawnSerializedParameters) { Vector2 spawnPosition = (Vector2) transform.position + spawnSerializedParameter.relativePosition; SpawnProjectile(spawnSerializedParameter.projectilePrefab.name, spawnPosition, spawnSerializedParameter.velocity); } } private void SpawnProjectile(string projectileName, Vector2 position, Vector2 velocity) { ProjectilePoolManager.Instance.SpawnProjectile(projectileName, position, velocity); } }
39.115385
126
0.768928
[ "MIT" ]
hsandt/dragon-raid
Assets/Scripts/InGame/Event/EventEffect_SpawnProjectiles.cs
1,017
C#
namespace ClearHl7.Codes.V280 { /// <summary> /// HL7 Version 2 Table 0282 - Referral Disposition. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0282</remarks> public enum CodeReferralDisposition { /// <summary> /// AM - Assume Management. /// </summary> AssumeManagement, /// <summary> /// RP - Return Patient After Evaluation. /// </summary> ReturnPatientAfterEvaluation, /// <summary> /// SO - Second Opinion. /// </summary> SecondOpinion, /// <summary> /// WR - Send Written Report. /// </summary> SendWrittenReport } }
24.724138
59
0.504881
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V280/CodeReferralDisposition.cs
719
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace TcpMethodServer { internal class MRequest { [JsonIgnore] internal string Address { get; set; } [JsonProperty("RequestID")] internal Guid RequestID { get; set; } [JsonProperty("CliendID")] internal Guid ClientID { get; set; } [JsonProperty("RequestType"), JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] internal ERequestType RequestType { get; set; } [JsonProperty("Service")] internal string Service { get; set; } [JsonProperty("Method")] internal string Method { get; set; } [JsonProperty("Arguments")] internal object[] Arguments { get; set; } [JsonProperty("Headers")] internal Dictionary<string, string> Headers { get; set; } } }
31.633333
108
0.646997
[ "MIT" ]
ECourant/TcpMethodService
TcpMethodServer/MRequest.cs
951
C#
using System; using Xamarin.Forms; namespace TodoREST { public partial class TodoItemPage : ContentPage { bool isNewItem; public TodoItemPage (bool isNew = false) { InitializeComponent (); isNewItem = isNew; } async void OnSaveActivated (object sender, EventArgs e) { var todoItem = (TodoItem)BindingContext; await App.TodoManager.SaveTaskAsync (todoItem, isNewItem); await Navigation.PopAsync (); } async void OnDeleteActivated (object sender, EventArgs e) { var todoItem = (TodoItem)BindingContext; await App.TodoManager.DeleteTaskAsync (todoItem); await Navigation.PopAsync (); } void OnCancelActivated (object sender, EventArgs e) { Navigation.PopAsync (); } void OnSpeakActivated (object sender, EventArgs e) { var todoItem = (TodoItem)BindingContext; App.Speech.Speak (todoItem.name + " " + todoItem.neptun); } } }
21.333333
61
0.710938
[ "Apache-2.0" ]
tibi0930/xamarin-forms-samples
WebServices/TodoREST/TodoREST/Views/TodoItemPage.xaml.cs
898
C#
// -- // -- TestCop http://github.com/testcop // -- License http://github.com/testcop/license // -- Copyright 2014 // -- using System.IO; using JetBrains.Application.Settings; using JetBrains.Application.UI.ActionsRevised.Menu; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi; using NUnit.Framework; namespace TestCop.Plugin.Tests.MultipleTestProjectToSingleCodeProjectViaProjectName { [TestFixture] public class ClassToTestFileNavigationTests : CSharpHighlightingWithinSolutionTestBase { protected override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile, IContextBoundSettingsStore settingsStore) { return highlighting.GetType().Namespace.Contains("TestCop"); } protected override string RelativeTestDataPath { get { return @"MultipleTestProjectToSingleCodeProjectViaName\ClassToTestNavigation"; } } protected override IExecutableAction GetShortcutAction(TextWriter textwriter) { var jumpToTestFileAction = JumpToTestFileAction.CreateWith(CreateJetPopMenuShowToWriterAction(textwriter)); return jumpToTestFileAction; } protected override string SolutionName { get { return @"MyCorp.TestApplication4.sln"; } } [Test] [TestCase(@"<API>\ClassA.cs")] [TestCase(@"<API>\NS1\APIClassBWithNoTest.cs")] [TestCase(@"<API>\NS1\ClassA.cs")] [TestCase(@"<API>\Properties\AssemblyInfo.cs")] [TestCase(@"<API>\NS1\NonNamespaceFolder\NS2\ClassEInNonNamespace.cs")] [TestCase(@"<API>\NonNamespaceFolder\ClassDInNonNamespace.cs")] public void Test(string testName) { ExecuteWithinSettingsTransaction((settingsStore => { RunGuarded( () => { SetupTestCopSettings(settingsStore); } ); DoTestFiles(testName); })); } internal static void SetupTestCopSettings(IContextBoundSettingsStore settingsStore) { ClearRegExSettingsPriorToRun(settingsStore); const string altRegEx = "^(.*?)\\.?(Integration)*Tests$"; settingsStore.SetValue<TestFileAnalysisSettings, TestProjectStrategy>( s => s.TestCopProjectStrategy, TestProjectStrategy.TestProjectHasSameNamespaceAsCodeProject); settingsStore.SetValue<TestFileAnalysisSettings, bool>( s => s.FindOrphanedProjectFiles, true); settingsStore.SetValue<TestFileAnalysisSettings, string>( s => s.TestClassSuffix, "Tests,IntegrationTests"); settingsStore.SetValue<TestFileAnalysisSettings, string>( s => s.TestProjectNameToCodeProjectNameRegEx, altRegEx); settingsStore.SetValue<TestFileAnalysisSettings, string>( s => s.TestProjectNameToCodeProjectNameRegExReplace, ""); } } }
40.468354
151
0.627463
[ "BSD-3-Clause" ]
SirDuke/Resharper.TestCop
Project/Src/TestCop.Plugin.Tests/MultipleTestProjectToSingleCodeProjectViaProjectName/ClassToTestFileNavigationTests.cs
3,197
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Route53 { public static partial class Invokes { /// <summary> /// `aws.route53.DelegationSet` provides details about a specific Route 53 Delegation Set. /// /// This data source allows to find a list of name servers associated with a specific delegation set. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/d/route53_delegation_set.html.markdown. /// </summary> [Obsolete("Use GetDelegationSet.InvokeAsync() instead")] public static Task<GetDelegationSetResult> GetDelegationSet(GetDelegationSetArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetDelegationSetResult>("aws:route53/getDelegationSet:getDelegationSet", args ?? InvokeArgs.Empty, options.WithVersion()); } public static class GetDelegationSet { /// <summary> /// `aws.route53.DelegationSet` provides details about a specific Route 53 Delegation Set. /// /// This data source allows to find a list of name servers associated with a specific delegation set. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/d/route53_delegation_set.html.markdown. /// </summary> public static Task<GetDelegationSetResult> InvokeAsync(GetDelegationSetArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetDelegationSetResult>("aws:route53/getDelegationSet:getDelegationSet", args ?? InvokeArgs.Empty, options.WithVersion()); } public sealed class GetDelegationSetArgs : Pulumi.InvokeArgs { /// <summary> /// The Hosted Zone id of the desired delegation set. /// </summary> [Input("id", required: true)] public string Id { get; set; } = null!; public GetDelegationSetArgs() { } } [OutputType] public sealed class GetDelegationSetResult { public readonly string CallerReference; public readonly string Id; public readonly ImmutableArray<string> NameServers; [OutputConstructor] private GetDelegationSetResult( string callerReference, string id, ImmutableArray<string> nameServers) { CallerReference = callerReference; Id = id; NameServers = nameServers; } } }
39.594595
176
0.659044
[ "ECL-2.0", "Apache-2.0" ]
Dominik-K/pulumi-aws
sdk/dotnet/Route53/GetDelegationSet.cs
2,930
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.Services.Processor.Telemetry.Ux { using Microsoft.Azure.IIoT.Diagnostics; /// <summary> /// Service information /// </summary> public class ServiceInfo : IProcessIdentity { /// <summary> /// ID /// </summary> public string ServiceId => "TELEMERTYUXPROCESSORHOST"; /// <summary> /// Process id /// </summary> public string Id => System.Guid.NewGuid().ToString(); /// <summary> /// Name of service /// </summary> public string Name => "Telemetry-Ux-Processor-Host"; /// <summary> /// Description of service /// </summary> public string Description => "Azure Industrial IoT Telemetry Ui Processor Host"; } }
31
99
0.526267
[ "MIT" ]
bamajeed/Industrial-IoT
services/src/Microsoft.Azure.IIoT.Services.Processor.Telemetry.Ux/src/Runtime/ServiceInfo.cs
1,085
C#
using System; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; namespace BrawlLib.Internal { [StructLayout(LayoutKind.Sequential, Pack = 1)] public unsafe struct Vector2 : IComparable { public float _x; public float _y; public Vector2(float x, float y) { _x = x; _y = y; } public Vector2(float s) { _x = s; _y = s; } public static Vector2 operator -(Vector2 v) { return new Vector2(-v._x, -v._y); } public static Vector2 operator +(Vector2 v1, Vector2 v2) { return new Vector2(v1._x + v2._x, v1._y + v2._y); } public static Vector2 operator -(Vector2 v1, Vector2 v2) { return new Vector2(v1._x - v2._x, v1._y - v2._y); } public static Vector2 operator -(Vector2 v1, float f) { return new Vector2(v1._x - f, v1._y - f); } public static Vector2 operator *(Vector2 v1, Vector2 v2) { return new Vector2(v1._x * v2._x, v1._y * v2._y); } public static Vector2 operator *(Vector2 v1, float s) { return new Vector2(v1._x * s, v1._y * s); } public static Vector2 operator *(float s, Vector2 v1) { return new Vector2(v1._x * s, v1._y * s); } public static Vector2 operator /(Vector2 v1, Vector2 v2) { return new Vector2(v1._x / v2._x, v1._y / v2._y); } public static Vector2 operator /(Vector2 v1, float s) { return new Vector2(v1._x / s, v1._y / s); } public static Vector2 operator +(Vector2 v1, Vector3 v2) { return new Vector2(v1._x + v2._x, v1._y + v2._y); } public static Vector2 operator +(Vector3 v1, Vector2 v2) { return new Vector2(v1._x + v2._x, v1._y + v2._y); } public static bool operator ==(Vector2 v1, Vector2 v2) { return v1._x == v2._x && v1._y == v2._y; } public static bool operator <=(Vector2 v1, Vector2 v2) { return v1._x <= v2._x && v1._y <= v2._y; } public static bool operator >=(Vector2 v1, Vector2 v2) { return v1._x >= v2._x && v1._y >= v2._y; } public static bool operator !=(Vector2 v1, Vector2 v2) { return v1._x != v2._x || v1._y != v2._y; } public static float Dot(Vector2 v1, Vector2 v2) { return v1._x * v2._x + v1._y * v2._y; } public float Dot(Vector2 v) { return _x * v._x + _y * v._y; } public static Vector2 Clamp(Vector2 v1, float min, float max) { v1.Clamp(min, max); return v1; } public void Clamp(float min, float max) { Max(min); Min(max); } public static Vector2 Min(Vector2 v1, Vector2 v2) { return new Vector2(Math.Min(v1._x, v2._x), Math.Min(v1._y, v2._y)); } public static Vector2 Min(Vector2 v1, float f) { return new Vector2(Math.Min(v1._x, f), Math.Min(v1._y, f)); } public void Min(Vector2 v) { if (_x > v._x) { _x = v._x; } if (_y > v._y) { _y = v._y; } } public void Min(float f) { _x = Math.Min(_x, f); _y = Math.Min(_y, f); } public static Vector2 Max(Vector2 v1, Vector2 v2) { return new Vector2(Math.Max(v1._x, v2._x), Math.Max(v1._y, v2._y)); } public static Vector2 Max(Vector2 v1, float f) { return new Vector2(Math.Max(v1._x, f), Math.Max(v1._y, f)); } public void Max(Vector2 v) { if (_x < v._x) { _x = v._x; } if (_y < v._y) { _y = v._y; } } public void Max(float f) { _x = Math.Max(_x, f); _y = Math.Max(_y, f); } public float DistanceTo(Vector2 v) { Vector2 v1 = this - v; return Dot(v1, v1); } public static Vector2 Lerp(Vector2 v1, Vector2 v2, float median) { return v1 * median + v2 * (1.0f - median); } public static explicit operator Vector2(Vector3 v) { return new Vector2(v._x, v._y); } public static explicit operator Vector3(Vector2 v) { return new Vector3(v._x, v._y, 0.0f); } public static explicit operator PointF(Vector2 v) { return new PointF(v._x, v._y); } public static explicit operator Vector2(PointF v) { return new Vector2(v.X, v.Y); } public static explicit operator Point(Vector2 v) { Vector2 t = Truncate(v); return new Point((int) t._x, (int) t._y); } public static explicit operator Vector2(Point v) { return new Vector2(v.X, v.Y); } public static Vector2 Truncate(Vector2 v) { return new Vector2( v._x > 0.0f ? (float) Math.Floor(v._x) : (float) Math.Ceiling(v._x), v._y > 0.0f ? (float) Math.Floor(v._y) : (float) Math.Ceiling(v._y)); } public override string ToString() { return CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.Contains(",") ? $"({_x} {_y})" : $"({_x},{_y})"; } public bool Contained(Vector2 start, Vector2 end, float expansion) { return Contained(this, start, end, expansion); } public static bool Contained(Vector2 point, Vector2 start, Vector2 end, float expansion) { float* sPtr = (float*) &point; float* s1 = (float*) &start, s2 = (float*) &end; float* temp; for (int i = 0; i < 2; i++) { if (s1[i] > s2[i]) { temp = s1; s1 = s2; s2 = temp; } if (sPtr[i] < s1[i] - expansion || sPtr[i] > s2[i] + expansion) { return false; } } return true; } public float TrueDistance(Vector2 p) { float lenX = Math.Abs(p._x - _x); float lenY = Math.Abs(p._y - _y); if (lenX == 0.0f) { return lenY; } else if (lenY == 0.0f) { return lenX; } else { return (float) (lenX / Math.Cos(Math.Atan(lenY / lenX))); } } public void RemapToRange(float min, float max) { _x = _x.RemapToRange(min, max); _y = _y.RemapToRange(min, max); } public Vector2 RemappedToRange(float min, float max) { return new Vector2(_x.RemapToRange(min, max), _y.RemapToRange(min, max)); } public override int GetHashCode() { fixed (Vector2* p = &this) { int* p2 = (int*) p; return p2[0] ^ p2[1]; } } public override bool Equals(object obj) { if (obj is Vector2 vector2) { return this == vector2; } return false; } public int CompareTo(object obj) { if (obj is Vector2) { Vector2 o = (Vector2) obj; if (_x > o._x) { return 1; } else if (_x < o._x) { return -1; } else if (_y > o._y) { return 1; } else if (_y < o._y) { return -1; } return 0; } return 1; } } }
25.061404
96
0.436939
[ "MIT" ]
kitlith/BrawlCrate
BrawlLib/Internal/Vector2.cs
8,573
C#