content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Avalonia.Controls; using Avalonia.VisualTree; using DynamicData; using DynamicData.Alias; using ReactiveUI.Fody.Helpers; using Splat; using SS14.Launcher.Models.Data; using SS14.Launcher.Models.ServerStatus; using SS14.Launcher.Utility; using SS14.Launcher.Views; namespace SS14.Launcher.ViewModels.MainWindowTabs; public class HomePageViewModel : MainWindowTabViewModel { public MainWindowViewModel MainWindowViewModel { get; } private readonly DataManager _cfg; private readonly ServerStatusCache _statusCache = new ServerStatusCache(); public HomePageViewModel(MainWindowViewModel mainWindowViewModel) { MainWindowViewModel = mainWindowViewModel; _cfg = Locator.Current.GetRequiredService<DataManager>(); _cfg.FavoriteServers .Connect() .Select(x => new ServerEntryViewModel(MainWindowViewModel, _statusCache.GetStatusFor(x.Address), x)) .OnItemAdded(a => { if (IsSelected) { _statusCache.InitialUpdateStatus(a.CacheData); } }) .Sort(Comparer<ServerEntryViewModel>.Create((a, b) => string.Compare(a.Name, b.Name, StringComparison.CurrentCultureIgnoreCase))) .Bind(out var favorites) .Subscribe(_ => FavoritesEmpty = favorites.Count == 0); Favorites = favorites; } public ReadOnlyObservableCollection<ServerEntryViewModel> Favorites { get; } [Reactive] public bool FavoritesEmpty { get; private set; } = true; public override string Name => "Home"; public Control? Control { get; set; } public async void DirectConnectPressed() { if (!TryGetWindow(out var window)) { return; } var res = await new DirectConnectDialog().ShowDialog<string>(window); if (res == null) { return; } ConnectingViewModel.StartConnect(MainWindowViewModel, res); } public async void AddFavoritePressed() { if (!TryGetWindow(out var window)) { return; } var (name, address) = await new AddFavoriteDialog().ShowDialog<(string name, string address)>(window); try { _cfg.AddFavoriteServer(new FavoriteServer(name, address)); _cfg.CommitConfig(); } catch (ArgumentException) { // Happens if address already a favorite, so ignore. // TODO: Give a popup to the user? } } private bool TryGetWindow([MaybeNullWhen(false)] out Window? window) { window = Control?.GetVisualRoot() as Window; return window != null; } public void RefreshPressed() { _statusCache.Refresh(); } public override void Selected() { foreach (var favorite in Favorites) { _statusCache.InitialUpdateStatus(favorite.CacheData); } } }
28.449541
141
0.636246
[ "MIT" ]
Veritius/SS14.Launcher
SS14.Launcher/ViewModels/MainWindowTabs/HomePageViewModel.cs
3,101
C#
using TMPro; using UnityEngine; public class Clock : MonoBehaviour { //References to updateable objects in the scene public Transform minuteClockHandTransform; public Transform hourClockHandTransform; public TMP_Text timeText; //The current day private float day; //Total number of real seconds per in game day public float realSecondsPerGameDay = 60.0f; //The total hours, minutes, and number of full rotations for the hour arm each day public float fullRotationsPerGameDay = 720.0f; public float hoursPerDay = 24.0f; public float minutesPerHour = 60.0f; /// <summary> /// Update this instance. /// </summary> private void Update() { //The current day time day += Time.deltaTime / realSecondsPerGameDay; //Normalize the day to show a whole value float dayNormalized = day % 1.0f; //Rotate the arms on the clock based on the time variables given hourClockHandTransform.eulerAngles = new Vector3(0, 0, -dayNormalized * fullRotationsPerGameDay); minuteClockHandTransform.eulerAngles = new Vector3(0, 0, -dayNormalized * fullRotationsPerGameDay * hoursPerDay); //Get the normalized time and trim it to represent the correct hour and minute string hoursString = Mathf.Floor(dayNormalized * 24.0f).ToString("00"); string minutesString = Mathf.Floor(((dayNormalized * hoursPerDay) % 1.0f) * minutesPerHour).ToString("00"); //Update the time text to show the correct time based on the variables given timeText.text = hoursString + ":" + minutesString; } }
36.977273
121
0.693915
[ "MIT" ]
MIT-Reality-Hack-2020/FocusField
handtest2/Assets/Scripts/Clock.cs
1,629
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Mvc { /// <summary> /// An <see cref="StatusCodeResult"/> that when executed will produce an empty /// <see cref="StatusCodes.Status200OK"/> response. /// </summary> public class OkResult : StatusCodeResult { /// <summary> /// Initializes a new instance of the <see cref="OkResult"/> class. /// </summary> public OkResult() : base(StatusCodes.Status200OK) { } } }
31.090909
111
0.634503
[ "Apache-2.0" ]
Elfocrash/Mvc
src/Microsoft.AspNetCore.Mvc.Core/OkResult.cs
684
C#
using System; using System.Collections.Generic; using Neo.IronLua; namespace NeiraEngine.Scripting { public class LuaScriptBase { private Lua _context; private Dictionary<string, LuaScriptEnvironment> _environments; public LuaScriptBase() { try { _context = new Lua(LuaIntegerType.Int32, LuaFloatType.Double); _environments = new Dictionary<string, LuaScriptEnvironment>(); } catch(Exception e) { Debug.logError("LuaScriptBase()", e.Message); throw new Exception("Error, unable to intialize ScriptBase: " + e.Message); } } /// <summary> /// Add a script environment (isolated) to collection /// </summary> /// <param name="name">Name of the environment to add.</param> public void CreateEnvironment(string name) { try { _environments[name] = new LuaScriptEnvironment(ref _context); } catch(Exception e) { Debug.logError("CreateEnvironment()", e.Message); throw e; } } /// <summary> /// Add a script to the given environment /// </summary> /// <param name="environment">Name of script environment.</param> /// <param name="name">Name of script.</param> /// <param name="fileOrSource">File if next parameter is false (default), or literal source if true.</param> /// <param name="isSource">Preceeding argument is source code? Else, it's a filename.</param> /// <param name="par">Optional list of parameters for chunk. You are required to pass any parameters defined here /// when running the script.</param> public void AddScript(string environment, string name, string fileOrSource, bool isSource = false, params KeyValuePair<string, Type>[] par) { try { // Compile script text or file to a LuaChunk, add to provided LuaPortableGlobal environment if (isSource) { var chunk = _context.CompileChunk(fileOrSource, name, new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }, par); _environments[environment].AddScript(name, chunk); } else { var chunk = _context.CompileChunk(fileOrSource, new LuaCompileOptions() { DebugEngine = LuaStackTraceDebugger.Default }, par); _environments[environment].AddScript(name, chunk); } } catch(Exception e) { Debug.logError("AddScript()", e.Message); throw e; } } /// <summary> /// Add a C# function to a Lua environment's global space /// </summary> /// <typeparam name="R">Return type of function.</typeparam> /// <param name="environment">Name of script environment.</param> /// <param name="name">Name of script.</param> /// <param name="funcName">Name of the function callable within Lua.</param> /// <param name="func">C# Function to add.</param> public void AddFunction<R>(string environment, string funcName, Func<R> func) { try { _environments[environment].AddFunction(funcName, func); } catch (Exception e) { throw e; } } public void AddFunction<R, T>(string environment, string funcName, Func<T, R> func) { try { _environments[environment].AddFunction(funcName, func); } catch (Exception e) { throw e; } } public void AddFunction<R, T1, T2>(string environment, string funcName, Func<T1, T2, R> func) { try { _environments[environment].AddFunction(funcName, func); } catch (Exception e) { throw e; } } public void AddFunction<R, T1, T2, T3>(string environment, string funcName, Func<T1, T2, T3, R> func) { try { _environments[environment].AddFunction(funcName, func); } catch (Exception e) { throw e; } } public void AddFunction<R, T1, T2, T3, T4>(string environment, string funcName, Func<T1, T2, T3, T4, R> func) { try { _environments[environment].AddFunction(funcName, func); } catch (Exception e) { throw e; } } /// <summary> /// Get a function by name from the Lua environment. /// </summary> /// <param name="environment">Environment to search.</param> /// <param name="funcName">The name of the function (case sensitive).</param> /// <returns></returns> public Func<LuaResult> GetFunction(string environment, string funcName) { try { return _environments[environment].GetFunction(funcName); } catch(Exception e) { throw e; } } public Func<T, LuaResult> GetFunction<T>(string environment, string funcName) { try { return _environments[environment].GetFunction<T>(funcName); } catch (Exception e) { throw e; } } public Func<T1, T2, LuaResult> GetFunction<T1, T2>(string environment, string funcName) { try { return _environments[environment].GetFunction<T1, T2>(funcName); } catch (Exception e) { throw e; } } public Func<T1, T2, T3, LuaResult> GetFunction<T1, T2, T3>(string environment, string funcName) { try { return _environments[environment].GetFunction<T1, T2, T3>(funcName); } catch (Exception e) { throw e; } } public Func<T1, T2, T3, T4, LuaResult> GetFunction<T1, T2, T3, T4>(string environment, string funcName) { try { return _environments[environment].GetFunction<T1, T2, T3, T4>(funcName); } catch (Exception e) { throw e; } } /// <summary> /// Helper method to call a Lua function and extract the result. /// </summary> /// <typeparam name="R">The return type of the function.</typeparam> /// <param name="environment">Environment to search.</param> /// <param name="funcName">The name of the function (case sensitive).</param> /// <returns></returns> public R CallFunction<R>(string environment, string funcName) { try { var f = GetFunction(environment, funcName); var result = f(); return (R)result.ToType(typeof(R)); } catch (Exception e) { throw e; } } public R CallFunction<R, T>(string environment, string funcName, T arg) { try { var f = GetFunction<T>(environment, funcName); var result = f(arg); return (R)result.ToType(typeof(R)); } catch (Exception e) { throw e; } } public R CallFunction<R, T1, T2>(string environment, string funcName, T1 arg1, T2 arg2) { try { var f = GetFunction<T1, T2>(environment, funcName); var result = f(arg1, arg2); return (R)result.ToType(typeof(R)); } catch (Exception e) { throw e; } } public R CallFunction<R, T1, T2, T3>(string environment, string funcName, T1 arg1, T2 arg2, T3 arg3) { try { var f = GetFunction<T1, T2, T3>(environment, funcName); var result = f(arg1, arg2, arg3); return (R)result.ToType(typeof(R)); } catch (Exception e) { throw e; } } public R CallFunction<R, T1, T2, T3, T4>(string environment, string funcName, T1 arg1, T2 arg2, T3 arg3, T4 arg4) { try { var f = GetFunction<T1, T2, T3, T4>(environment, funcName); var result = f(arg1, arg2, arg3, arg4); return (R)result.ToType(typeof(R)); } catch (Exception e) { throw e; } } /// <summary> /// Run a script that doesn't return anything. /// </summary> /// <param name="environment"></param> /// <param name="environment">Name of script environment.</param> /// <param name="name">Name of script.</param> /// <param name="args">Optional list of arguments for lua func.</param> public void RunScript(string environment, string name, params object[] args) { try { _environments[environment].ExecuteScript(name, args); } catch(Exception e) { throw e; } } /// <summary> /// Run a script that returns a single value. /// </summary> /// <typeparam name="T">Type to return.</typeparam> /// <param name="environment">Name of script environment.</param> /// <param name="name">Name of script.</param> /// <param name="args">Optional list of arguments for lua func.</param> /// <returns></returns> public T RunScript<T>(string environment, string name, params object[] args) { try { T res = _environments[environment].ExecuteScript<T>(name, args); return res; } catch (Exception e) { throw e; } } public void SetGlobal<T>(string environment, string globalName, T value) { try { _environments[environment].SetGlobal(globalName, value); } catch(Exception e) { throw e; } } public void Reset(string environment) { try { _environments[environment].Reset(ref _context); } catch(Exception e) { throw e; } } public Dictionary<string, LuaScriptEnvironment> Environments { get { return _environments; } } } }
32
122
0.482416
[ "MIT" ]
dima13230/neira-engine
NeiraEngine/Scripting/LuaScriptBase.cs
11,490
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("01. Box")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Box")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fcfa7d21-0f2c-48a9-90a6-0003b5e19591")] // 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.743126
[ "MIT" ]
krasiymihajlov/Soft-Uni-practices
C# OOP Advanced/02.Generics - Lab/01. Box/Properties/AssemblyInfo.cs
1,385
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// Interface IPivotItemList /// SupportByVersion Excel, 10,11,12,14,15 ///</summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] [EntityTypeAttribute(EntityType.IsInterface)] public class IPivotItemList : COMObject ,IEnumerable<NetOffice.ExcelApi.PivotItem> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IPivotItemList); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IPivotItemList(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IPivotItemList(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// </summary> /// <param name="field">object Field</param> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public NetOffice.ExcelApi.PivotItem this[object field] { get { object[] paramsArray = Invoker.ValidateParamsArray(field); object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray); NetOffice.ExcelApi.PivotItem newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.PivotItem.LateBindingApiWrapperType) as NetOffice.ExcelApi.PivotItem; return newObject; } } #endregion #region Methods #endregion #region IEnumerable<NetOffice.ExcelApi.PivotItem> Member /// <summary> /// SupportByVersionAttribute Excel, 10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public IEnumerator<NetOffice.ExcelApi.PivotItem> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.ExcelApi.PivotItem item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Excel, 10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsMethod(this); } #endregion #pragma warning restore } }
32.816038
194
0.676585
[ "MIT" ]
NetOffice/NetOffice
Source/Excel/Interfaces/IPivotItemList.cs
6,957
C#
using ExternalProject.Net6.Constructors.Sample.BaseClasses; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ExternalProject.Net6.UnitTestMocks.MSTest.Constructors.Linked.Tests.BaseClasses { [TestClass] [SlowFox.InjectMocks(typeof(DerivedBaseClassWithMultipleDependencies))] public partial class DerivedBaseClassWithMultipleDependenciesTestse { [TestMethod] public void HasDependency() { DerivedBaseClassWithMultipleDependencies model = Create(); Assert.AreEqual(_userWriter.Object, model.UserWriter); Assert.AreEqual(_userReader.Object, model.UserReader); Assert.AreEqual(_dataReader.Object, model.DataReader); } } }
34.952381
89
0.734332
[ "Apache-2.0" ]
Bungalow64/SlowFox
tests/ExternalProject.Net6.UnitTestMocks.MSTest.Constructors.Linked.Tests/BaseClasses/DerivedBaseClassWithMultipleDependenciesTests.cs
736
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 devops-guru-2020-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DevOpsGuru.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DevOpsGuru.Model.Internal.MarshallTransformations { /// <summary> /// GetResourceCollection Request Marshaller /// </summary> public class GetResourceCollectionRequestMarshaller : IMarshaller<IRequest, GetResourceCollectionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetResourceCollectionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetResourceCollectionRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DevOpsGuru"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2020-12-01"; request.HttpMethod = "GET"; if (!publicRequest.IsSetResourceCollectionType()) throw new AmazonDevOpsGuruException("Request object does not have required field ResourceCollectionType set"); request.AddPathResource("{ResourceCollectionType}", StringUtils.FromString(publicRequest.ResourceCollectionType)); if (publicRequest.IsSetNextToken()) request.Parameters.Add("NextToken", StringUtils.FromString(publicRequest.NextToken)); request.ResourcePath = "/resource-collections/{ResourceCollectionType}"; request.UseQueryString = true; return request; } private static GetResourceCollectionRequestMarshaller _instance = new GetResourceCollectionRequestMarshaller(); internal static GetResourceCollectionRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetResourceCollectionRequestMarshaller Instance { get { return _instance; } } } }
36.769231
157
0.67095
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/DevOpsGuru/Generated/Model/Internal/MarshallTransformations/GetResourceCollectionRequestMarshaller.cs
3,346
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using System.Windows; [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
48.888889
97
0.784091
[ "MIT" ]
Ethereal77/stride
sources/presentation/Stride.Core.Presentation.Dialogs/Properties/AssemblyInfo.cs
440
C#
using System; using System.Linq; using DdfGuide.Core; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DdfGuide.Test { [TestClass] public class AudioDramaDtoTests { [TestMethod] public void GivenSpotifyId_CorrectSpotifyUri() { var sut = new AudioDramaDto(Guid.Empty, string.Empty, -1, DateTime.Now, string.Empty, string.Empty, string.Empty, Enumerable.Empty<RoleDto>(), "HomerSimpson", string.Empty, string.Empty); var uri = sut.SpotifyUri; Assert.AreEqual(@"https://open.spotify.com/album/HomerSimpson", uri.ToString()); } } }
33.16129
92
0.411479
[ "MIT" ]
selmaohneh/DdfGuide
DdfGuide.Test/AudioDramaDtoTests.cs
1,030
C#
//Apache2, 2012, Hernan J Gonzalez, https://github.com/leonbloy/pngcs namespace Hjg.Pngcs { using System; /// <summary> /// Lightweight wrapper for an image scanline, for read and write /// </summary> /// <remarks>It can be (usually it is) reused while iterating over the image lines /// See <c>scanline</c> field doc, to understand the format. ///</remarks> public class ImageLine { /// <summary> /// ImageInfo (readonly inmutable) /// </summary> public ImageInfo ImgInfo { get; private set; } /// <summary> /// Samples of an image line /// </summary> /// <remarks> /// /// The 'scanline' is an array of integers, corresponds to an image line (row) /// Except for 'packed' formats (gray/indexed with 1-2-4 bitdepth) each int is a /// "sample" (one for channel), (0-255 or 0-65535) in the respective PNG sequence /// sequence : (R G B R G B...) or (R G B A R G B A...) or (g g g ...) or ( i i i /// ) (palette index) /// /// For bitdepth 1/2/4 ,and if samplesUnpacked=false, each value is a PACKED byte! To get an unpacked copy, /// see <c>Pack()</c> and its inverse <c>Unpack()</c> /// /// To convert a indexed line to RGB balues, see ImageLineHelper.PalIdx2RGB() /// (cant do the reverse) /// </remarks> public int[] Scanline { get; private set; } /// <summary> /// Same as Scanline, but with one byte per sample. Only one of Scanline and ScanlineB is valid - this depends /// on SampleType} /// </summary> public byte[] ScanlineB { get; private set; } /// <summary> /// tracks the current row number (from 0 to rows-1) /// </summary> public int Rown { get; set; } internal readonly int channels; // copied from imgInfo, more handy internal readonly int bitDepth; // copied from imgInfo, more handy /// <summary> /// Hown many elements has the scanline array /// =imgInfo.samplePerRowPacked, if packed, imgInfo.samplePerRow elsewhere /// </summary> public int ElementsPerRow { get; private set; } /// <summary> /// Maximum sample value that this line admits: typically 255; less if bitdepth less than 8, 65535 if 16bits /// </summary> public int maxSampleVal { get; private set; } public enum ESampleType { INT, // 4 bytes per sample BYTE // 1 byte per sample } /// <summary> /// Determines if samples are stored in integers or in bytes /// </summary> public ESampleType SampleType { get; private set; } /// <summary> /// True: each scanline element is a sample. /// False: each scanline element has severals samples packed in a byte /// </summary> public bool SamplesUnpacked { get; private set; } /// <summary> /// informational only ; filled by the reader /// </summary> public FilterType FilterUsed { get; set; } public ImageLine(ImageInfo imgInfo) : this(imgInfo, ESampleType.INT, false) { } public ImageLine(ImageInfo imgInfo, ESampleType stype) : this(imgInfo, stype, false) { } /// <summary> /// Constructs an ImageLine /// </summary> /// <param name="imgInfo">Inmutable copy of PNG ImageInfo</param> /// <param name="stype">Storage for samples:INT (default) or BYTE</param> /// <param name="unpackedMode">If true and bitdepth less than 8, samples are unpacked. This has no effect if biddepth 8 or 16</param> public ImageLine(ImageInfo imgInfo, ESampleType stype, bool unpackedMode) : this(imgInfo, stype, unpackedMode, null, null) { } internal ImageLine(ImageInfo imgInfo, ESampleType stype, bool unpackedMode, int[] sci, byte[] scb) { this.ImgInfo = imgInfo; channels = imgInfo.Channels; this.bitDepth = imgInfo.BitDepth; this.FilterUsed = FilterType.FILTER_UNKNOWN; this.SampleType = stype; this.SamplesUnpacked = unpackedMode || !imgInfo.Packed; ElementsPerRow = this.SamplesUnpacked ? imgInfo.SamplesPerRow : imgInfo.SamplesPerRowPacked; if (stype == ESampleType.INT) { Scanline = sci != null ? sci : new int[ElementsPerRow]; ScanlineB = null; maxSampleVal = bitDepth == 16 ? 0xFFFF : GetMaskForPackedFormatsLs(bitDepth); } else if (stype == ESampleType.BYTE) { ScanlineB = scb != null ? scb : new byte[ElementsPerRow]; Scanline = null; maxSampleVal = bitDepth == 16 ? 0xFF : GetMaskForPackedFormatsLs(bitDepth); } else throw new PngjExceptionInternal("bad ImageLine initialization"); this.Rown = -1; } static internal void unpackInplaceInt(ImageInfo iminfo, int[] src, int[] dst, bool Scale) { int bitDepth = iminfo.BitDepth; if (bitDepth >= 8) return; // nothing to do int mask0 = GetMaskForPackedFormatsLs(bitDepth); int scalefactor = 8 - bitDepth; int offset0 = 8 * iminfo.SamplesPerRowPacked - bitDepth * iminfo.SamplesPerRow; int mask, offset, v; if (offset0 != 8) { mask = mask0 << offset0; offset = offset0; // how many bits to shift the mask to the right to recover mask0 } else { mask = mask0; offset = 0; } for (int j = iminfo.SamplesPerRow - 1, i = iminfo.SamplesPerRowPacked - 1; j >= 0; j--) { v = (src[i] & mask) >> offset; if (Scale) v <<= scalefactor; dst[j] = v; mask <<= bitDepth; offset += bitDepth; if (offset == 8) { mask = mask0; offset = 0; i--; } } } static internal void packInplaceInt(ImageInfo iminfo, int[] src, int[] dst, bool scaled) { int bitDepth = iminfo.BitDepth; if (bitDepth >= 8) return; // nothing to do int mask0 = GetMaskForPackedFormatsLs(bitDepth); int scalefactor = 8 - bitDepth; int offset0 = 8 - bitDepth; int v, v0; int offset = 8 - bitDepth; v0 = src[0]; // first value is special for in place dst[0] = 0; if (scaled) v0 >>= scalefactor; v0 = ((v0 & mask0) << offset); for (int i = 0, j = 0; j < iminfo.SamplesPerRow; j++) { v = src[j]; if (scaled) v >>= scalefactor; dst[i] |= ((v & mask0) << offset); offset -= bitDepth; if (offset < 0) { offset = offset0; i++; dst[i] = 0; } } dst[0] |= v0; } static internal void unpackInplaceByte(ImageInfo iminfo, byte[] src, byte[] dst, bool scale) { int bitDepth = iminfo.BitDepth; if (bitDepth >= 8) return; // nothing to do int mask0 = GetMaskForPackedFormatsLs(bitDepth); int scalefactor = 8 - bitDepth; int offset0 = 8 * iminfo.SamplesPerRowPacked - bitDepth * iminfo.SamplesPerRow; int mask, offset, v; if (offset0 != 8) { mask = mask0 << offset0; offset = offset0; // how many bits to shift the mask to the right to recover mask0 } else { mask = mask0; offset = 0; } for (int j = iminfo.SamplesPerRow - 1, i = iminfo.SamplesPerRowPacked - 1; j >= 0; j--) { v = (src[i] & mask) >> offset; if (scale) v <<= scalefactor; dst[j] = (byte)v; mask <<= bitDepth; offset += bitDepth; if (offset == 8) { mask = mask0; offset = 0; i--; } } } /** size original: samplesPerRow sizeFinal: samplesPerRowPacked (trailing elements are trash!) **/ static internal void packInplaceByte(ImageInfo iminfo, byte[] src, byte[] dst, bool scaled) { int bitDepth = iminfo.BitDepth; if (bitDepth >= 8) return; // nothing to do byte mask0 = (byte)GetMaskForPackedFormatsLs(bitDepth); byte scalefactor = (byte)(8 - bitDepth); byte offset0 = (byte)(8 - bitDepth); byte v, v0; int offset = 8 - bitDepth; v0 = src[0]; // first value is special dst[0] = 0; if (scaled) v0 >>= scalefactor; v0 = (byte)((v0 & mask0) << offset); for (int i = 0, j = 0; j < iminfo.SamplesPerRow; j++) { v = src[j]; if (scaled) v >>= scalefactor; dst[i] |= (byte)((v & mask0) << offset); offset -= bitDepth; if (offset < 0) { offset = offset0; i++; dst[i] = 0; } } dst[0] |= v0; } /// <summary> /// Makes a deep copy /// </summary> /// <remarks>You should rarely use this</remarks> /// <param name="b"></param> internal void SetScanLine(int[] b) { // makes copy System.Array.Copy((Array)(b), 0, (Array)(Scanline), 0, Scanline.Length); } /// <summary> /// Makes a deep copy /// </summary> /// <remarks>You should rarely use this</remarks> /// <param name="b"></param> internal int[] GetScanLineCopy(int[] b) { if (b == null || b.Length < Scanline.Length) b = new int[Scanline.Length]; System.Array.Copy((Array)(Scanline), 0, (Array)(b), 0, Scanline.Length); return b; } public ImageLine unpackToNewImageLine() { ImageLine newline = new ImageLine(ImgInfo, SampleType, true); if (SampleType == ESampleType.INT) unpackInplaceInt(ImgInfo, Scanline, newline.Scanline, false); else unpackInplaceByte(ImgInfo, ScanlineB, newline.ScanlineB, false); return newline; } public ImageLine packToNewImageLine() { ImageLine newline = new ImageLine(ImgInfo, SampleType, false); if (SampleType == ESampleType.INT) packInplaceInt(ImgInfo, Scanline, newline.Scanline, false); else packInplaceByte(ImgInfo, ScanlineB, newline.ScanlineB, false); return newline; } public int[] GetScanlineInt() { return Scanline; } public byte[] GetScanlineByte() { return ScanlineB; } public bool IsInt() { return SampleType == ESampleType.INT; } public bool IsByte() { return SampleType == ESampleType.BYTE; } public override String ToString() { return "row=" + Rown + " cols=" + ImgInfo.Cols + " bpc=" + ImgInfo.BitDepth + " size=" + Scanline.Length; } internal static int GetMaskForPackedFormats(int bitDepth) { // Utility function for pack/unpack if (bitDepth == 4) return 0xf0; else if (bitDepth == 2) return 0xc0; else if (bitDepth == 1) return 0x80; else return 0xff; } internal static int GetMaskForPackedFormatsLs(int bitDepth) { // Utility function for pack/unpack if (bitDepth == 4) return 0x0f; else if (bitDepth == 2) return 0x03; else if (bitDepth == 1) return 0x01; else return 0xff; } } }
35.602778
141
0.495826
[ "MIT" ]
LayoutFarm/PixelFarm
src/PixelFarm/ImgCodec.PngCs/ImgCodec.PngCs/ImageLine.cs
12,817
C#
namespace Md.Tga.Common.TestData.Generators { public class SurveyStatusGeneratorConfiguration : BaseGeneratorConfiguration { public bool IsClosed { get; set; } = false; } }
25.125
81
0.686567
[ "MIT" ]
MichaelDiers/TabletopGameAdmin
nugets/Md.Tga.Common.TestData/Md.Tga.Common.TestData/Generators/SurveyStatusGeneratorConfiguration.cs
203
C#
using System.Threading.Tasks; namespace Aju.Carefree.Cache { public interface ICacheService { #region Get /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存key</param> /// <returns></returns> string Get(string key); /// <summary> /// 获取缓存 /// </summary> /// <param name="key">缓存key</param> /// <returns></returns> Task<string> GetAsync(string key); /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> string GetString(string key); /// <summary> /// /// </summary> /// <param name="key"></param> /// <returns></returns> Task<string> GetStringAsync(string key); #endregion #region Set /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> void SetString(string key, string value); /// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> Task SetStringAsync(string key, string value); /// <summary> /// 添加缓存 /// </summary> /// <param name="key">缓存key</param> /// <param name="value">缓存值</param> /// <param name="expirationTime">绝对过期时间(分钟)</param> void Set(string key, string value, int expirationTime = 20); /// <summary> /// 添加缓存 /// </summary> /// <param name="key">缓存key</param> /// <param name="value">缓存值</param> /// <param name="expirationTime">绝对过期时间(分钟)</param> Task SetAsync(string key, string value, int expirationTime = 20); #endregion #region Remove /// <summary> /// 移除缓存 /// </summary> /// <param name="key"></param> void Remove(string key); /// <summary> /// 移除缓存 /// </summary> /// <param name="key"></param> Task RemoveAsync(string key); #endregion #region Modify /// <summary> /// 更新缓存 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expirationTime"></param> void Modify(string key, string value, int expirationTime = 20); /// <summary> /// 更新缓存 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expirationTime"></param> Task ModifyAsync(string key, string value, int expirationTime = 20); #endregion } }
26.77451
76
0.476016
[ "MIT" ]
lenkasetGitHub/Aju.Carefree
Aju.Carefree.Cache/ICacheService.cs
2,857
C#
namespace InfluencerWannaBeUnitTest.Mocks { using Moq; using InfluencerWannaBe.Services; public static class EmailSenderMock { public static IEmailSender Instance { get { var mock = new Mock<IEmailSender>(); mock.Setup(x => x.SendEmail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Verifiable(); return mock.Object; } } } }
23.5
118
0.542553
[ "MIT" ]
stelianraev/InfluencerWannaBe
InfluencerWannaBeUnitTest/Mocks/EmailSenderMock.cs
472
C#
using MiddleweightReflection; using System; namespace Codegen { public class SyntheticProperty : IEquatable<SyntheticProperty> { public string Name { get; set; } public MrType DeclaringType { get; set; } public MrProperty Property { get; set; } public MrType PropertyType { get; set; } public string FakePropertyType { get; set; } public string Comment { get; set; } public string SimpleName { get => Name.Substring(Name.LastIndexOf('.') + 1); } public string SimpleNameForJs { get { if (Property != null) { string fullPropertyName = Property.DeclaringType.GetFullName() + "." + Property.GetName(); if (Util.propNameMap.TryGetValue(fullPropertyName, out string realName)) { return realName.Substring(realName.LastIndexOf('.') + 1); } else if (Util.IsDependencyProperty(Property)) { return Property.DeclaringType.GetName() + SimpleName; } } return SimpleName; } } public bool Equals(SyntheticProperty other) { return SimpleName == other.SimpleName; } } }
32.25
111
0.506695
[ "MIT" ]
angelazhangmsft/react-native-xaml
package/Codegen/SyntheticProperty.cs
1,378
C#
using System; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; namespace Lykke.MatchingEngine.Connector.Helpers { internal static class TelemetryHelper { private static readonly TelemetryClient _telemetry = new TelemetryClient(); private const string _telemetryType = "Me Connector"; internal static IOperationHolder<DependencyTelemetry> InitTelemetryOperation( string target, string name, string data) { var operation = _telemetry.StartOperation<DependencyTelemetry>(name); operation.Telemetry.Type = _telemetryType; operation.Telemetry.Target = target; operation.Telemetry.Name = name; operation.Telemetry.Data = data; return operation; } internal static void SubmitException(Exception e) { _telemetry.TrackException(e); } internal static void SubmitOperationFail(IOperationHolder<DependencyTelemetry> telemtryOperation) { telemtryOperation.Telemetry.Success = false; } internal static void SubmitOperationResult(IOperationHolder<DependencyTelemetry> telemtryOperation) { _telemetry.StopOperation(telemtryOperation); } } }
31.613636
107
0.677211
[ "MIT" ]
JTOne123/MatchingEngineConnector
src/Lykke.MatchingEngine.Connector/Helpers/TelemetryHelper.cs
1,393
C#
using System; using AVFoundation; using CoreAnimation; using CoreGraphics; using CoreVideo; using Foundation; using ObjCRuntime; using ZXingObjC; #if __MACOS__ namespace ZXingObjC.OSX.Binding #else namespace ZXingObjC.iOS.Binding #endif { // @interface ZXCapture : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate, CAAction, CALayerDelegate> [BaseType(typeof(NSObject))] interface ZXCapture : IAVCaptureVideoDataOutputSampleBufferDelegate, ICAAction, ICALayerDelegate { // @property (assign, nonatomic) int camera; [Export("camera")] int Camera { get; set; } // @property (nonatomic, strong) AVCaptureDevice * captureDevice; [Export("captureDevice", ArgumentSemantic.Strong)] AVCaptureDevice CaptureDevice { get; set; } // @property (copy, nonatomic) NSString * captureToFilename; [Export("captureToFilename")] string CaptureToFilename { get; set; } [Wrap("WeakDelegate")] ZXCaptureDelegate Delegate { get; set; } // @property (nonatomic, weak) id<ZXCaptureDelegate> delegate; [NullAllowed, Export("delegate", ArgumentSemantic.Weak)] NSObject WeakDelegate { get; set; } // @property (assign, nonatomic) AVCaptureFocusMode focusMode; [Export("focusMode", ArgumentSemantic.Assign)] AVCaptureFocusMode FocusMode { get; set; } // @property (nonatomic, strong) ZXDecodeHints * hints; [Export("hints", ArgumentSemantic.Strong)] ZXDecodeHints Hints { get; set; } // @property (assign, nonatomic) CGImageRef lastScannedImage; [Export("lastScannedImage", ArgumentSemantic.Assign)] unsafe CGImage LastScannedImage { get; set; } // @property (assign, nonatomic) BOOL invert; [Export("invert")] bool Invert { get; set; } // @property (readonly, nonatomic, strong) CALayer * layer; [Export("layer", ArgumentSemantic.Strong)] CALayer Layer { get; } // @property (assign, nonatomic) BOOL mirror; [Export("mirror")] bool Mirror { get; set; } // @property (readonly, nonatomic, strong) AVCaptureVideoDataOutput * output; [Export("output", ArgumentSemantic.Strong)] AVCaptureVideoDataOutput Output { get; } // @property (nonatomic, strong) id<ZXReader> reader; [Export("reader", ArgumentSemantic.Strong)] IZXReader Reader { get; set; } // @property (assign, nonatomic) CGFloat rotation; [Export("rotation")] nfloat Rotation { get; set; } // @property (readonly, assign, nonatomic) BOOL running; [Export("running")] bool Running { get; } // @property (assign, nonatomic) CGRect scanRect; [Export("scanRect", ArgumentSemantic.Assign)] CGRect ScanRect { get; set; } // @property (copy, nonatomic) NSString * sessionPreset; [Export("sessionPreset")] string SessionPreset { get; set; } // @property (assign, nonatomic) BOOL torch; [Export("torch")] bool Torch { get; set; } // @property (assign, nonatomic) CGAffineTransform transform; [Export("transform", ArgumentSemantic.Assign)] CGAffineTransform Transform { get; set; } // -(int)back; [Export("back")] int Back { get; } // -(int)front; [Export("front")] int Front { get; } // -(BOOL)hasBack; [Export("hasBack")] bool HasBack { get; } // -(BOOL)hasFront; [Export("hasFront")] bool HasFront { get; } // -(BOOL)hasTorch; [Export("hasTorch")] bool HasTorch { get; } // -(CALayer *)binary; [Export("binary")] CALayer Binary { get; } // -(void)setBinary:(BOOL)on_off; [Export("setBinary:")] void SetBinary(bool on_off); // -(CALayer *)luminance; [Export("luminance")] CALayer Luminance { get; } // -(void)setLuminance:(BOOL)on_off; [Export("setLuminance:")] void SetLuminance(bool on_off); // -(void)hard_stop; [Export("hard_stop")] void Hard_stop(); // -(void)order_skip; [Export("order_skip")] void Order_skip(); // -(void)start; [Export("start")] void Start(); // -(void)stop; [Export("stop")] void Stop(); } public interface IZXCaptureDelegate { } // @protocol ZXCaptureDelegate <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface ZXCaptureDelegate { // @required -(void)captureResult:(ZXCapture *)capture result:(ZXResult *)result; [Abstract] [Export("captureResult:result:")] void CaptureResult(ZXCapture capture, ZXResult result); // @optional -(void)captureSize:(ZXCapture *)capture width:(NSNumber *)width height:(NSNumber *)height; [Export("captureSize:width:height:")] void CaptureSize(ZXCapture capture, NSNumber width, NSNumber height); // @optional -(void)captureCameraIsReady:(ZXCapture *)capture; [Export("captureCameraIsReady:")] void CaptureCameraIsReady(ZXCapture capture); } // @interface ZXLuminanceSource : NSObject [BaseType(typeof(NSObject))] interface ZXLuminanceSource { // @property (readonly, assign, nonatomic) int width; [Export("width")] int Width { get; } // @property (readonly, assign, nonatomic) int height; [Export("height")] int Height { get; } // @property (readonly, assign, nonatomic) BOOL cropSupported; [Export("cropSupported")] bool CropSupported { get; } // @property (readonly, assign, nonatomic) BOOL rotateSupported; [Export("rotateSupported")] bool RotateSupported { get; } // -(id)initWithWidth:(int)width height:(int)height; [Export("initWithWidth:height:")] IntPtr Constructor(int width, int height); // -(ZXByteArray *)rowAtY:(int)y row:(ZXByteArray *)row; [Export("rowAtY:row:")] ZXByteArray RowAtY(int y, ZXByteArray row); // -(ZXByteArray *)matrix; [Export("matrix")] ZXByteArray Matrix { get; } // -(ZXLuminanceSource *)crop:(int)left top:(int)top width:(int)width height:(int)height; [Export("crop:top:width:height:")] ZXLuminanceSource Crop(int left, int top, int width, int height); // -(ZXLuminanceSource *)invert; [Export("invert")] ZXLuminanceSource Invert { get; } // -(ZXLuminanceSource *)rotateCounterClockwise; [Export("rotateCounterClockwise")] ZXLuminanceSource RotateCounterClockwise { get; } // -(ZXLuminanceSource *)rotateCounterClockwise45; [Export("rotateCounterClockwise45")] ZXLuminanceSource RotateCounterClockwise45 { get; } } // @interface ZXCGImageLuminanceSource : ZXLuminanceSource [BaseType(typeof(ZXLuminanceSource))] interface ZXCGImageLuminanceSource { // +(CGImageRef)createImageFromBuffer:(CVImageBufferRef)buffer __attribute__((cf_returns_retained)); [Static] [Export("createImageFromBuffer:")] unsafe CGImage CreateImageFromBuffer(CVImageBuffer buffer); // +(CGImageRef)createImageFromBuffer:(CVImageBufferRef)buffer left:(size_t)left top:(size_t)top width:(size_t)width height:(size_t)height __attribute__((cf_returns_retained)); [Static] [Export("createImageFromBuffer:left:top:width:height:")] unsafe CGImage CreateImageFromBuffer(CVImageBuffer buffer, nuint left, nuint top, nuint width, nuint height); // -(id)initWithZXImage:(ZXImage *)image left:(size_t)left top:(size_t)top width:(size_t)width height:(size_t)height; [Export("initWithZXImage:left:top:width:height:")] IntPtr Constructor(ZXImage image, nuint left, nuint top, nuint width, nuint height); // -(id)initWithZXImage:(ZXImage *)image; [Export("initWithZXImage:")] IntPtr Constructor(ZXImage image); // -(id)initWithCGImage:(CGImageRef)image left:(size_t)left top:(size_t)top width:(size_t)width height:(size_t)height; [Export("initWithCGImage:left:top:width:height:")] unsafe IntPtr Constructor(CGImage image, nuint left, nuint top, nuint width, nuint height); // -(id)initWithCGImage:(CGImageRef)image; [Export("initWithCGImage:")] unsafe IntPtr Constructor(CGImage image); // -(id)initWithBuffer:(CVPixelBufferRef)buffer left:(size_t)left top:(size_t)top width:(size_t)width height:(size_t)height; [Export("initWithBuffer:left:top:width:height:")] unsafe IntPtr Constructor(CVPixelBuffer buffer, nuint left, nuint top, nuint width, nuint height); // -(id)initWithBuffer:(CVPixelBufferRef)buffer; [Export("initWithBuffer:")] unsafe IntPtr Constructor(CVPixelBuffer buffer); // -(CGImageRef)image; [Export("image")] unsafe CGImage Image { get; } } // @interface ZXImage : NSObject [BaseType(typeof(NSObject))] interface ZXImage { // @property (readonly, assign, nonatomic) CGImageRef cgimage; [Export("cgimage", ArgumentSemantic.Assign)] unsafe CGImage Cgimage { get; } // -(ZXImage *)initWithCGImageRef:(CGImageRef)image; [Export("initWithCGImageRef:")] unsafe IntPtr Constructor(CGImage image); // -(ZXImage *)initWithURL:(const NSURL *)url; [Export("initWithURL:")] IntPtr Constructor(NSUrl url); // -(size_t)width; [Export("width")] nuint Width { get; } // -(size_t)height; [Export("height")] nuint Height { get; } // +(ZXImage *)imageWithMatrix:(ZXBitMatrix *)matrix; [Static] [Export("imageWithMatrix:")] ZXImage ImageWithMatrix(ZXBitMatrix matrix); // +(ZXImage *)imageWithMatrix:(ZXBitMatrix *)matrix onColor:(CGColorRef)onColor offColor:(CGColorRef)offColor; [Static] [Export("imageWithMatrix:onColor:offColor:")] unsafe ZXImage ImageWithMatrix(ZXBitMatrix matrix, CGColor onColor, CGColor offColor); } // @interface ZXBitArray : NSObject <NSCopying> [BaseType(typeof(NSObject))] interface ZXBitArray : INSCopying { //// @property (readonly, assign, nonatomic) int32_t * bits; //[Export("bits", ArgumentSemantic.Assign)] //unsafe int* Bits { get; } // @property (readonly, assign, nonatomic) int size; [Export("size")] int Size { get; } // -(id)initWithSize:(int)size; [Export("initWithSize:")] IntPtr Constructor(int size); // -(int)sizeInBytes; [Export("sizeInBytes")] int SizeInBytes { get; } // -(BOOL)get:(int)i; [Export("get:")] bool Get(int i); // -(void)set:(int)i; [Export("set:")] void Set(int i); // -(void)flip:(int)i; [Export("flip:")] void Flip(int i); // -(int)nextSet:(int)from; [Export("nextSet:")] int NextSet(int from); // -(int)nextUnset:(int)from; [Export("nextUnset:")] int NextUnset(int from); // -(void)setBulk:(int)i newBits:(int32_t)newBits; [Export("setBulk:newBits:")] void SetBulk(int i, int newBits); // -(void)setRange:(int)start end:(int)end; [Export("setRange:end:")] void SetRange(int start, int end); // -(void)clear; [Export("clear")] void Clear(); // -(BOOL)isRange:(int)start end:(int)end value:(BOOL)value; [Export("isRange:end:value:")] bool IsRange(int start, int end, bool value); // -(void)appendBit:(BOOL)bit; [Export("appendBit:")] void AppendBit(bool bit); // -(void)appendBits:(int32_t)value numBits:(int)numBits; [Export("appendBits:numBits:")] void AppendBits(int value, int numBits); // -(void)appendBitArray:(ZXBitArray *)other; [Export("appendBitArray:")] void AppendBitArray(ZXBitArray other); // -(void)xor:(ZXBitArray *)other; [Export("xor:")] void Xor(ZXBitArray other); // -(void)toBytes:(int)bitOffset array:(ZXByteArray *)array offset:(int)offset numBytes:(int)numBytes; [Export("toBytes:array:offset:numBytes:")] void ToBytes(int bitOffset, ZXByteArray array, int offset, int numBytes); // -(ZXIntArray *)bitArray; [Export("bitArray")] ZXIntArray BitArray { get; } // -(void)reverse; [Export("reverse")] void Reverse(); } // @interface ZXBitMatrix : NSObject <NSCopying> [BaseType(typeof(NSObject))] interface ZXBitMatrix : INSCopying { // @property (readonly, assign, nonatomic) int width; [Export("width")] int Width { get; } // @property (readonly, assign, nonatomic) int height; [Export("height")] int Height { get; } //// @property (readonly, assign, nonatomic) int32_t * bits; //[Export("bits", ArgumentSemantic.Assign)] //unsafe int* Bits { get; } // @property (readonly, assign, nonatomic) int rowSize; [Export("rowSize")] int RowSize { get; } // -(id)initWithDimension:(int)dimension; [Export("initWithDimension:")] IntPtr Constructor(int dimension); // -(id)initWithWidth:(int)width height:(int)height; [Export("initWithWidth:height:")] IntPtr Constructor(int width, int height); // +(ZXBitMatrix *)parse:(NSString *)stringRepresentation setString:(NSString *)setString unsetString:(NSString *)unsetString; [Static] [Export("parse:setString:unsetString:")] ZXBitMatrix Parse(string stringRepresentation, string setString, string unsetString); // -(BOOL)getX:(int)x y:(int)y; [Export("getX:y:")] bool GetX(int x, int y); // -(void)setX:(int)x y:(int)y; [Export("setX:y:")] void SetX(int x, int y); // -(void)unsetX:(int)x y:(int)y; [Export("unsetX:y:")] void UnsetX(int x, int y); // -(void)flipX:(int)x y:(int)y; [Export("flipX:y:")] void FlipX(int x, int y); // -(void)xor:(ZXBitMatrix *)mask; [Export("xor:")] void Xor(ZXBitMatrix mask); // -(void)clear; [Export("clear")] void Clear(); // -(void)setRegionAtLeft:(int)left top:(int)top width:(int)width height:(int)height; [Export("setRegionAtLeft:top:width:height:")] void SetRegionAtLeft(int left, int top, int width, int height); // -(ZXBitArray *)rowAtY:(int)y row:(ZXBitArray *)row; [Export("rowAtY:row:")] ZXBitArray RowAtY(int y, ZXBitArray row); // -(void)setRowAtY:(int)y row:(ZXBitArray *)row; [Export("setRowAtY:row:")] void SetRowAtY(int y, ZXBitArray row); // -(void)rotate180; [Export("rotate180")] void Rotate180(); // -(ZXIntArray *)enclosingRectangle; [Export("enclosingRectangle")] ZXIntArray EnclosingRectangle { get; } // -(ZXIntArray *)topLeftOnBit; [Export("topLeftOnBit")] ZXIntArray TopLeftOnBit { get; } // -(ZXIntArray *)bottomRightOnBit; [Export("bottomRightOnBit")] ZXIntArray BottomRightOnBit { get; } // -(NSString *)descriptionWithSetString:(NSString *)setString unsetString:(NSString *)unsetString; [Export("descriptionWithSetString:unsetString:")] string DescriptionWithSetString(string setString, string unsetString); // -(NSString *)descriptionWithSetString:(NSString *)setString unsetString:(NSString *)unsetString lineSeparator:(NSString *)lineSeparator __attribute__((deprecated(""))); [Export("descriptionWithSetString:unsetString:lineSeparator:")] string DescriptionWithSetString(string setString, string unsetString, string lineSeparator); } // @interface ZXBitSource : NSObject [BaseType(typeof(NSObject))] interface ZXBitSource { // @property (readonly, assign, nonatomic) int bitOffset; [Export("bitOffset")] int BitOffset { get; } // @property (readonly, assign, nonatomic) int byteOffset; [Export("byteOffset")] int ByteOffset { get; } // -(id)initWithBytes:(ZXByteArray *)bytes; [Export("initWithBytes:")] IntPtr Constructor(ZXByteArray bytes); // -(int)readBits:(int)numBits; [Export("readBits:")] int ReadBits(int numBits); // -(int)available; [Export("available")] int Available { get; } } // @interface ZXBoolArray : NSObject [BaseType(typeof(NSObject))] interface ZXBoolArray { //// @property (readonly, assign, nonatomic) BOOL * array; //[Export("array", ArgumentSemantic.Assign)] //unsafe bool* Array { get; } // @property (readonly, assign, nonatomic) unsigned int length; [Export("length")] uint Length { get; } // -(id)initWithLength:(unsigned int)length; [Export("initWithLength:")] IntPtr Constructor(uint length); } // @interface ZXByteArray : NSObject [BaseType(typeof(NSObject))] interface ZXByteArray { //// @property (readonly, assign, nonatomic) int8_t * array; //[Export("array", ArgumentSemantic.Assign)] //unsafe sbyte* Array { get; } // @property (readonly, assign, nonatomic) unsigned int length; [Export("length")] uint Length { get; } // -(id)initWithLength:(unsigned int)length; [Export("initWithLength:")] IntPtr Constructor(uint length); // -(id)initWithBytes:(int)byte1, ...; [Internal] [Export("initWithBytes:", IsVariadic = true)] IntPtr Constructor(int byte1, IntPtr varArgs); } // @interface ZXCharacterSetECI : NSObject [BaseType(typeof(NSObject))] interface ZXCharacterSetECI { // @property (readonly, assign, nonatomic) NSStringEncoding encoding; [Export("encoding")] nuint Encoding { get; } // @property (readonly, assign, nonatomic) int value; [Export("value")] int Value { get; } // +(ZXCharacterSetECI *)characterSetECIByValue:(int)value; [Static] [Export("characterSetECIByValue:")] ZXCharacterSetECI CharacterSetECIByValue(int value); // +(ZXCharacterSetECI *)characterSetECIByEncoding:(NSStringEncoding)encoding; [Static] [Export("characterSetECIByEncoding:")] ZXCharacterSetECI CharacterSetECIByEncoding(nuint encoding); } // @interface ZXDecoderResult : NSObject [BaseType(typeof(NSObject))] interface ZXDecoderResult { // @property (readonly, nonatomic, strong) ZXByteArray * rawBytes; [Export("rawBytes", ArgumentSemantic.Strong)] ZXByteArray RawBytes { get; } // @property (readonly, copy, nonatomic) NSString * text; [Export("text")] string Text { get; } // @property (readonly, nonatomic, strong) NSMutableArray * byteSegments; [Export("byteSegments", ArgumentSemantic.Strong)] NSMutableArray ByteSegments { get; } // @property (readonly, copy, nonatomic) NSString * ecLevel; [Export("ecLevel")] string EcLevel { get; } // @property (copy, nonatomic) NSNumber * errorsCorrected; [Export("errorsCorrected", ArgumentSemantic.Copy)] NSNumber ErrorsCorrected { get; set; } // @property (copy, nonatomic) NSNumber * erasures; [Export("erasures", ArgumentSemantic.Copy)] NSNumber Erasures { get; set; } // @property (nonatomic, strong) id other; [Export("other", ArgumentSemantic.Strong)] NSObject Other { get; set; } // @property (readonly, assign, nonatomic) int structuredAppendParity; [Export("structuredAppendParity")] int StructuredAppendParity { get; } // @property (readonly, assign, nonatomic) int structuredAppendSequenceNumber; [Export("structuredAppendSequenceNumber")] int StructuredAppendSequenceNumber { get; } // -(id)initWithRawBytes:(ZXByteArray *)rawBytes text:(NSString *)text byteSegments:(NSMutableArray *)byteSegments ecLevel:(NSString *)ecLevel; [Export("initWithRawBytes:text:byteSegments:ecLevel:")] IntPtr Constructor(ZXByteArray rawBytes, string text, NSMutableArray byteSegments, string ecLevel); // -(id)initWithRawBytes:(ZXByteArray *)rawBytes text:(NSString *)text byteSegments:(NSMutableArray *)byteSegments ecLevel:(NSString *)ecLevel saSequence:(int)saSequence saParity:(int)saParity; [Export("initWithRawBytes:text:byteSegments:ecLevel:saSequence:saParity:")] IntPtr Constructor(ZXByteArray rawBytes, string text, NSMutableArray byteSegments, string ecLevel, int saSequence, int saParity); // -(BOOL)hasStructuredAppend; [Export("hasStructuredAppend")] bool HasStructuredAppend { get; } } // @interface ZXGridSampler : NSObject [BaseType(typeof(NSObject))] interface ZXGridSampler { // +(void)setGridSampler:(ZXGridSampler *)newGridSampler; [Static] [Export("setGridSampler:")] void SetGridSampler(ZXGridSampler newGridSampler); // +(ZXGridSampler *)instance; [Static] [Export("instance")] ZXGridSampler Instance { get; } // -(ZXBitMatrix *)sampleGrid:(ZXBitMatrix *)image dimensionX:(int)dimensionX dimensionY:(int)dimensionY p1ToX:(float)p1ToX p1ToY:(float)p1ToY p2ToX:(float)p2ToX p2ToY:(float)p2ToY p3ToX:(float)p3ToX p3ToY:(float)p3ToY p4ToX:(float)p4ToX p4ToY:(float)p4ToY p1FromX:(float)p1FromX p1FromY:(float)p1FromY p2FromX:(float)p2FromX p2FromY:(float)p2FromY p3FromX:(float)p3FromX p3FromY:(float)p3FromY p4FromX:(float)p4FromX p4FromY:(float)p4FromY error:(NSError **)error; [Export("sampleGrid:dimensionX:dimensionY:p1ToX:p1ToY:p2ToX:p2ToY:p3ToX:p3ToY:p4ToX:p4ToY:p1FromX:p1FromY:p2FromX:p2FromY:p3FromX:p3FromY:p4FromX:p4FromY:error:")] ZXBitMatrix SampleGrid(ZXBitMatrix image, int dimensionX, int dimensionY, float p1ToX, float p1ToY, float p2ToX, float p2ToY, float p3ToX, float p3ToY, float p4ToX, float p4ToY, float p1FromX, float p1FromY, float p2FromX, float p2FromY, float p3FromX, float p3FromY, float p4FromX, float p4FromY, out NSError error); // -(ZXBitMatrix *)sampleGrid:(ZXBitMatrix *)image dimensionX:(int)dimensionX dimensionY:(int)dimensionY transform:(ZXPerspectiveTransform *)transform error:(NSError **)error; [Export("sampleGrid:dimensionX:dimensionY:transform:error:")] ZXBitMatrix SampleGrid(ZXBitMatrix image, int dimensionX, int dimensionY, ZXPerspectiveTransform transform, out NSError error); //// +(BOOL)checkAndNudgePoints:(ZXBitMatrix *)image points:(float *)points pointsLen:(int)pointsLen error:(NSError **)error; //[Static] //[Export("checkAndNudgePoints:points:pointsLen:error:")] //unsafe bool CheckAndNudgePoints(ZXBitMatrix image, float* points, int pointsLen, out NSError error); } // @interface ZXDefaultGridSampler : ZXGridSampler [BaseType(typeof(ZXGridSampler))] interface ZXDefaultGridSampler { } // @interface ZXDetectorResult : NSObject [BaseType(typeof(NSObject))] interface ZXDetectorResult { // @property (readonly, nonatomic, strong) ZXBitMatrix * bits; [Export("bits", ArgumentSemantic.Strong)] ZXBitMatrix Bits { get; } // @property (readonly, nonatomic, strong) NSArray * points; [Export("points", ArgumentSemantic.Strong)] ZXQRCodeFinderPattern[] Points { get; } // -(id)initWithBits:(ZXBitMatrix *)bits points:(NSArray *)points; [Export("initWithBits:points:")] IntPtr Constructor(ZXBitMatrix bits, NSObject[] points); } // @interface ZXGenericGFPoly : NSObject [BaseType(typeof(NSObject))] interface ZXGenericGFPoly { // - (id)initWithField:(ZXGenericGF *)field coefficients:(ZXIntArray *)coefficients; [Export("initWithField:coefficients:")] IntPtr Constructor(ZXGenericGF field, ZXIntArray coefficients); [Export("degree")] int Degree { get; } [Export("zero")] bool Zero { get; } [Export("coefficient:")] int Coefficient(int degree); [Export("evaluateAt:")] int EvaluateAt(int a); } // @interface ZXGenericGF : NSObject [BaseType(typeof(NSObject))] interface ZXGenericGF { // @property (readonly, nonatomic, strong) ZXGenericGFPoly * zero; [Export("zero", ArgumentSemantic.Strong)] ZXGenericGFPoly Zero { get; } // @property (readonly, nonatomic, strong) ZXGenericGFPoly * one; [Export("one", ArgumentSemantic.Strong)] ZXGenericGFPoly One { get; } // @property (readonly, assign, nonatomic) int32_t size; [Export("size")] int Size { get; } // @property (readonly, assign, nonatomic) int32_t generatorBase; [Export("generatorBase")] int GeneratorBase { get; } // +(ZXGenericGF *)AztecData12; [Static] [Export("AztecData12")] ZXGenericGF AztecData12 { get; } // +(ZXGenericGF *)AztecData10; [Static] [Export("AztecData10")] ZXGenericGF AztecData10 { get; } // +(ZXGenericGF *)AztecData6; [Static] [Export("AztecData6")] ZXGenericGF AztecData6 { get; } // +(ZXGenericGF *)AztecParam; [Static] [Export("AztecParam")] ZXGenericGF AztecParam { get; } // +(ZXGenericGF *)QrCodeField256; [Static] [Export("QrCodeField256")] ZXGenericGF QrCodeField256 { get; } // +(ZXGenericGF *)DataMatrixField256; [Static] [Export("DataMatrixField256")] ZXGenericGF DataMatrixField256 { get; } // +(ZXGenericGF *)AztecData8; [Static] [Export("AztecData8")] ZXGenericGF AztecData8 { get; } // +(ZXGenericGF *)MaxiCodeField64; [Static] [Export("MaxiCodeField64")] ZXGenericGF MaxiCodeField64 { get; } // -(id)initWithPrimitive:(int)primitive size:(int)size b:(int)b; [Export("initWithPrimitive:size:b:")] IntPtr Constructor(int primitive, int size, int b); // -(ZXGenericGFPoly *)buildMonomial:(int)degree coefficient:(int)coefficient; [Export("buildMonomial:coefficient:")] ZXGenericGFPoly BuildMonomial(int degree, int coefficient); // +(int32_t)addOrSubtract:(int32_t)a b:(int32_t)b; [Static] [Export("addOrSubtract:b:")] int AddOrSubtract(int a, int b); // -(int32_t)exp:(int)a; [Export("exp:")] int Exp(int a); // -(int32_t)log:(int)a; [Export("log:")] int Log(int a); // -(int32_t)inverse:(int)a; [Export("inverse:")] int Inverse(int a); // -(int32_t)multiply:(int)a b:(int)b; [Export("multiply:b:")] int Multiply(int a, int b); } // @interface ZXBinarizer : NSObject [BaseType(typeof(NSObject))] interface ZXBinarizer { // @property (readonly, nonatomic, strong) ZXLuminanceSource * luminanceSource; [Export("luminanceSource", ArgumentSemantic.Strong)] ZXLuminanceSource LuminanceSource { get; } // @property (readonly, assign, nonatomic) int width; [Export("width")] int Width { get; } // @property (readonly, assign, nonatomic) int height; [Export("height")] int Height { get; } // -(id)initWithSource:(ZXLuminanceSource *)source; [Export("initWithSource:")] IntPtr Constructor(ZXLuminanceSource source); // +(id)binarizerWithSource:(ZXLuminanceSource *)source; [Static] [Export("binarizerWithSource:")] ZXBinarizer BinarizerWithSource(ZXLuminanceSource source); // -(ZXBitArray *)blackRow:(int)y row:(ZXBitArray *)row error:(NSError **)error; [Export("blackRow:row:error:")] ZXBitArray BlackRow(int y, ZXBitArray row, out NSError error); // -(ZXBitMatrix *)blackMatrixWithError:(NSError **)error; [Export("blackMatrixWithError:")] ZXBitMatrix BlackMatrixWithError(out NSError error); // -(ZXBinarizer *)createBinarizer:(ZXLuminanceSource *)source; [Export("createBinarizer:")] ZXBinarizer CreateBinarizer(ZXLuminanceSource source); // -(CGImageRef)createImage __attribute__((cf_returns_retained)); [Export("createImage")] unsafe CGImage CreateImage { get; } } // @interface ZXGlobalHistogramBinarizer : ZXBinarizer [BaseType(typeof(ZXBinarizer))] interface ZXGlobalHistogramBinarizer { [Static] [Export("binarizerWithSource:")] ZXGlobalHistogramBinarizer BinarizerWithSource(ZXLuminanceSource source); // -(ZXBitArray *)blackRow:(int)y row:(ZXBitArray *)row error:(NSError **)error; [Export("blackRow:row:error:")] ZXBitArray BlackRow(int y, ZXBitArray row, out NSError error); // -(ZXBinarizer *)createBinarizer:(ZXLuminanceSource *)source; [Export("createBinarizer:")] ZXGlobalHistogramBinarizer CreateBinarizer(ZXLuminanceSource source); } // @interface ZXHybridBinarizer : ZXGlobalHistogramBinarizer [BaseType(typeof(ZXGlobalHistogramBinarizer))] interface ZXHybridBinarizer { [Static] [Export("binarizerWithSource:")] ZXHybridBinarizer BinarizerWithSource(ZXLuminanceSource source); [Export("createBinarizer:")] ZXHybridBinarizer CreateBinarizer(ZXLuminanceSource source); } // @interface ZXIntArray : NSObject <NSCopying> [BaseType(typeof(NSObject))] interface ZXIntArray : INSCopying { //// @property (readonly, assign, nonatomic) int32_t * array; //[Export("array", ArgumentSemantic.Assign)] //unsafe int* Array { get; } // @property (readonly, assign, nonatomic) unsigned int length; [Export("length")] uint Length { get; } // -(id)initWithLength:(unsigned int)length; [Export("initWithLength:")] IntPtr Constructor(uint length); // -(id)initWithInts:(int32_t)int1, ...; [Internal] [Export("initWithInts:", IsVariadic = true)] IntPtr Constructor(int int1, IntPtr varArgs); // -(void)clear; [Export("clear")] void Clear(); // -(int)sum; [Export("sum")] int Sum { get; } } // @interface ZXMathUtils : NSObject [BaseType(typeof(NSObject))] interface ZXMathUtils { // +(int)round:(float)d; [Static] [Export("round:")] int Round(float d); // +(float)distance:(float)aX aY:(float)aY bX:(float)bX bY:(float)bY; [Static] [Export("distance:aY:bX:bY:")] float Distance(float aX, float aY, float bX, float bY); // +(float)distanceInt:(int)aX aY:(int)aY bX:(int)bX bY:(int)bY; [Static] [Export("distanceInt:aY:bX:bY:")] float DistanceInt(int aX, int aY, int bX, int bY); } // @interface ZXMonochromeRectangleDetector : NSObject [BaseType(typeof(NSObject))] interface ZXMonochromeRectangleDetector { // -(id)initWithImage:(ZXBitMatrix *)image; [Export("initWithImage:")] IntPtr Constructor(ZXBitMatrix image); // -(NSArray *)detectWithError:(NSError **)error; [Export("detectWithError:")] NSObject[] DetectWithError(out NSError error); } // @interface ZXPerspectiveTransform : NSObject [BaseType(typeof(NSObject))] interface ZXPerspectiveTransform { // +(ZXPerspectiveTransform *)quadrilateralToQuadrilateral:(float)x0 y0:(float)y0 x1:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 x3:(float)x3 y3:(float)y3 x0p:(float)x0p y0p:(float)y0p x1p:(float)x1p y1p:(float)y1p x2p:(float)x2p y2p:(float)y2p x3p:(float)x3p y3p:(float)y3p; [Static] [Export("quadrilateralToQuadrilateral:y0:x1:y1:x2:y2:x3:y3:x0p:y0p:x1p:y1p:x2p:y2p:x3p:y3p:")] ZXPerspectiveTransform QuadrilateralToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float x0p, float y0p, float x1p, float y1p, float x2p, float y2p, float x3p, float y3p); //// -(void)transformPoints:(float *)points pointsLen:(int)pointsLen; //[Export("transformPoints:pointsLen:")] //unsafe void TransformPoints(float* points, int pointsLen); //// -(void)transformPoints:(float *)xValues yValues:(float *)yValues pointsLen:(int)pointsLen; //[Export("transformPoints:yValues:pointsLen:")] //unsafe void TransformPoints(float* xValues, float* yValues, int pointsLen); // +(ZXPerspectiveTransform *)squareToQuadrilateral:(float)x0 y0:(float)y0 x1:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 x3:(float)x3 y3:(float)y3; [Static] [Export("squareToQuadrilateral:y0:x1:y1:x2:y2:x3:y3:")] ZXPerspectiveTransform SquareToQuadrilateral(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3); // +(ZXPerspectiveTransform *)quadrilateralToSquare:(float)x0 y0:(float)y0 x1:(float)x1 y1:(float)y1 x2:(float)x2 y2:(float)y2 x3:(float)x3 y3:(float)y3; [Static] [Export("quadrilateralToSquare:y0:x1:y1:x2:y2:x3:y3:")] ZXPerspectiveTransform QuadrilateralToSquare(float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3); // -(ZXPerspectiveTransform *)buildAdjoint; [Export("buildAdjoint")] ZXPerspectiveTransform BuildAdjoint { get; } // -(ZXPerspectiveTransform *)times:(ZXPerspectiveTransform *)other; [Export("times:")] ZXPerspectiveTransform Times(ZXPerspectiveTransform other); } // @interface ZXReedSolomonDecoder : NSObject [BaseType(typeof(NSObject))] interface ZXReedSolomonDecoder { // -(id)initWithField:(ZXGenericGF *)field; [Export("initWithField:")] IntPtr Constructor(ZXGenericGF field); // -(BOOL)decode:(ZXIntArray *)received twoS:(int)twoS error:(NSError **)error; [Export("decode:twoS:error:")] bool Decode(ZXIntArray received, int twoS, out NSError error); } // @interface ZXReedSolomonEncoder : NSObject [BaseType(typeof(NSObject))] interface ZXReedSolomonEncoder { // -(id)initWithField:(ZXGenericGF *)field; [Export("initWithField:")] IntPtr Constructor(ZXGenericGF field); // -(void)encode:(ZXIntArray *)toEncode ecBytes:(int)ecBytes; [Export("encode:ecBytes:")] void Encode(ZXIntArray toEncode, int ecBytes); } // @interface ZXStringUtils : NSObject [BaseType(typeof(NSObject))] interface ZXStringUtils { // +(NSStringEncoding)guessEncoding:(ZXByteArray *)bytes hints:(ZXDecodeHints *)hints; [Static] [Export("guessEncoding:hints:")] nuint GuessEncoding(ZXByteArray bytes, ZXDecodeHints hints); } // @interface ZXResultPoint : NSObject <NSCopying> [BaseType(typeof(NSObject))] interface ZXResultPoint : INSCopying { // @property (readonly, assign, nonatomic) float x; [Export("x")] float X { get; } // @property (readonly, assign, nonatomic) float y; [Export("y")] float Y { get; } // -(id)initWithX:(float)x y:(float)y; [Export("initWithX:y:")] IntPtr Constructor(float x, float y); // +(id)resultPointWithX:(float)x y:(float)y; [Static] [Export("resultPointWithX:y:")] NSObject ResultPointWithX(float x, float y); // +(void)orderBestPatterns:(NSMutableArray *)patterns; [Static] [Export("orderBestPatterns:")] void OrderBestPatterns(NSMutableArray patterns); // +(float)distance:(ZXResultPoint *)pattern1 pattern2:(ZXResultPoint *)pattern2; [Static] [Export("distance:pattern2:")] float Distance(ZXResultPoint pattern1, ZXResultPoint pattern2); } // @interface ZXWhiteRectangleDetector : NSObject [BaseType(typeof(NSObject))] interface ZXWhiteRectangleDetector { // -(id)initWithImage:(ZXBitMatrix *)image error:(NSError **)error; [Export("initWithImage:error:")] IntPtr Constructor(ZXBitMatrix image, out NSError error); // -(id)initWithImage:(ZXBitMatrix *)image initSize:(int)initSize x:(int)x y:(int)y error:(NSError **)error; [Export("initWithImage:initSize:x:y:error:")] IntPtr Constructor(ZXBitMatrix image, int initSize, int x, int y, out NSError error); // -(NSArray *)detectWithError:(NSError **)error; [Export("detectWithError:")] NSObject[] DetectWithError(out NSError error); } // @interface ZXBinaryBitmap : NSObject [BaseType(typeof(NSObject))] interface ZXBinaryBitmap { // @property (readonly, nonatomic) int width; [Export("width")] int Width { get; } // @property (readonly, nonatomic) int height; [Export("height")] int Height { get; } // @property (readonly, nonatomic) BOOL cropSupported; [Export("cropSupported")] bool CropSupported { get; } // @property (readonly, nonatomic) BOOL rotateSupported; [Export("rotateSupported")] bool RotateSupported { get; } // -(id)initWithBinarizer:(ZXBinarizer *)binarizer; [Export("initWithBinarizer:")] IntPtr Constructor(ZXBinarizer binarizer); // +(id)binaryBitmapWithBinarizer:(ZXBinarizer *)binarizer; [Static] [Export("binaryBitmapWithBinarizer:")] ZXBinaryBitmap BinaryBitmapWithBinarizer(ZXBinarizer binarizer); // -(ZXBitArray *)blackRow:(int)y row:(ZXBitArray *)row error:(NSError **)error; [Export("blackRow:row:error:")] ZXBitArray BlackRow(int y, ZXBitArray row, out NSError error); // -(ZXBitMatrix *)blackMatrixWithError:(NSError **)error; [Export("blackMatrixWithError:")] ZXBitMatrix BlackMatrixWithError(out NSError error); // -(ZXBinaryBitmap *)crop:(int)left top:(int)top width:(int)width height:(int)height; [Export("crop:top:width:height:")] ZXBinaryBitmap Crop(int left, int top, int width, int height); // -(ZXBinaryBitmap *)rotateCounterClockwise; [Export("rotateCounterClockwise")] ZXBinaryBitmap RotateCounterClockwise { get; } // -(ZXBinaryBitmap *)rotateCounterClockwise45; [Export("rotateCounterClockwise45")] ZXBinaryBitmap RotateCounterClockwise45 { get; } } // @interface ZXByteMatrix : NSObject [BaseType(typeof(NSObject))] interface ZXByteMatrix { //// @property (readonly, assign, nonatomic) int8_t ** array; //[Export("array", ArgumentSemantic.Assign)] //unsafe sbyte** Array { get; } // @property (readonly, assign, nonatomic) int height; [Export("height")] int Height { get; } // @property (readonly, assign, nonatomic) int width; [Export("width")] int Width { get; } // -(id)initWithWidth:(int)width height:(int)height; [Export("initWithWidth:height:")] IntPtr Constructor(int width, int height); // -(int8_t)getX:(int)x y:(int)y; [Export("getX:y:")] sbyte GetX(int x, int y); // -(void)setX:(int)x y:(int)y byteValue:(int8_t)value; [Export("setX:y:byteValue:")] void SetX(int x, int y, sbyte value); // -(void)setX:(int)x y:(int)y intValue:(int32_t)value; [Export("setX:y:intValue:")] void SetX(int x, int y, int value); // -(void)setX:(int)x y:(int)y boolValue:(BOOL)value; [Export("setX:y:boolValue:")] void SetX(int x, int y, bool value); // -(void)clear:(int8_t)value; [Export("clear:")] void Clear(sbyte value); } // @interface ZXDecodeHints : NSObject <NSCopying> [BaseType(typeof(NSObject))] interface ZXDecodeHints : INSCopying { // +(id)hints; [Static] [Export("hints")] NSObject Hints { get; } // @property (assign, nonatomic) BOOL assumeCode39CheckDigit; [Export("assumeCode39CheckDigit")] bool AssumeCode39CheckDigit { get; set; } // @property (assign, nonatomic) BOOL assumeGS1; [Export("assumeGS1")] bool AssumeGS1 { get; set; } // @property (nonatomic, strong) NSArray * allowedLengths; [Export("allowedLengths", ArgumentSemantic.Strong)] NSObject[] AllowedLengths { get; set; } // @property (assign, nonatomic) NSStringEncoding encoding; [Export("encoding")] nuint Encoding { get; set; } // @property (nonatomic, strong) id other; [Export("other", ArgumentSemantic.Strong)] NSObject Other { get; set; } // @property (assign, nonatomic) BOOL pureBarcode; [Export("pureBarcode")] bool PureBarcode { get; set; } // @property (assign, nonatomic) BOOL returnCodaBarStartEnd; [Export("returnCodaBarStartEnd")] bool ReturnCodaBarStartEnd { get; set; } // @property (nonatomic, strong) id<ZXResultPointCallback> resultPointCallback; [Export("resultPointCallback", ArgumentSemantic.Strong)] ZXResultPointCallback ResultPointCallback { get; set; } // @property (assign, nonatomic) BOOL tryHarder; [Export("tryHarder")] bool TryHarder { get; set; } // @property (nonatomic, strong) ZXIntArray * allowedEANExtensions; [Export("allowedEANExtensions", ArgumentSemantic.Strong)] ZXIntArray AllowedEANExtensions { get; set; } // -(void)addPossibleFormat:(ZXBarcodeFormat)format; [Export("addPossibleFormat:")] void AddPossibleFormat(ZXBarcodeFormat format); // -(BOOL)containsFormat:(ZXBarcodeFormat)format; [Export("containsFormat:")] bool ContainsFormat(ZXBarcodeFormat format); // -(int)numberOfPossibleFormats; [Export("numberOfPossibleFormats")] int NumberOfPossibleFormats { get; } // -(void)removePossibleFormat:(ZXBarcodeFormat)format; [Export("removePossibleFormat:")] void RemovePossibleFormat(ZXBarcodeFormat format); } // @interface ZXDimension : NSObject [BaseType(typeof(NSObject))] interface ZXDimension { // @property (readonly, assign, nonatomic) int height; [Export("height")] int Height { get; } // @property (readonly, assign, nonatomic) int width; [Export("width")] int Width { get; } // -(id)initWithWidth:(int)width height:(int)height; [Export("initWithWidth:height:")] IntPtr Constructor(int width, int height); } // @interface ZXEncodeHints : NSObject [BaseType(typeof(NSObject))] interface ZXEncodeHints { // +(id)hints; [Static] [Export("hints")] NSObject Hints { get; } // @property (assign, nonatomic) NSStringEncoding encoding; [Export("encoding")] nuint Encoding { get; set; } // @property (assign, nonatomic) ZXDataMatrixSymbolShapeHint dataMatrixShape; [Export("dataMatrixShape", ArgumentSemantic.Assign)] ZXDataMatrixSymbolShapeHint DataMatrixShape { get; set; } // @property (nonatomic, strong) ZXDimension * minSize __attribute__((deprecated(""))); [Export("minSize", ArgumentSemantic.Strong)] ZXDimension MinSize { get; set; } // @property (nonatomic, strong) ZXDimension * maxSize __attribute__((deprecated(""))); [Export("maxSize", ArgumentSemantic.Strong)] ZXDimension MaxSize { get; set; } // @property (nonatomic, strong) ZXQRCodeErrorCorrectionLevel * errorCorrectionLevel; [Export("errorCorrectionLevel", ArgumentSemantic.Strong)] ZXQRCodeErrorCorrectionLevel ErrorCorrectionLevel { get; set; } // @property (nonatomic, strong) NSNumber * errorCorrectionPercent; [Export("errorCorrectionPercent", ArgumentSemantic.Strong)] NSNumber ErrorCorrectionPercent { get; set; } // @property (nonatomic, strong) NSNumber * margin; [Export("margin", ArgumentSemantic.Strong)] NSNumber Margin { get; set; } // @property (assign, nonatomic) BOOL pdf417Compact; [Export("pdf417Compact")] bool Pdf417Compact { get; set; } // @property (assign, nonatomic) ZXPDF417Compaction pdf417Compaction; [Export("pdf417Compaction", ArgumentSemantic.Assign)] ZXPDF417Compaction Pdf417Compaction { get; set; } // @property (nonatomic, strong) ZXPDF417Dimensions * pdf417Dimensions; [Export("pdf417Dimensions", ArgumentSemantic.Strong)] ZXPDF417Dimensions Pdf417Dimensions { get; set; } // @property (nonatomic, strong) NSNumber * aztecLayers; [Export("aztecLayers", ArgumentSemantic.Strong)] NSNumber AztecLayers { get; set; } } // @interface ZXInvertedLuminanceSource : ZXLuminanceSource [BaseType(typeof(ZXLuminanceSource))] interface ZXInvertedLuminanceSource { // -(id)initWithDelegate:(ZXLuminanceSource *)delegate; [Export("initWithDelegate:")] IntPtr Constructor(ZXLuminanceSource @delegate); } // @interface ZXPlanarYUVLuminanceSource : ZXLuminanceSource [BaseType(typeof(ZXLuminanceSource))] interface ZXPlanarYUVLuminanceSource { // @property (readonly, assign, nonatomic) int thumbnailWidth; [Export("thumbnailWidth")] int ThumbnailWidth { get; } // @property (readonly, assign, nonatomic) int thumbnailHeight; [Export("thumbnailHeight")] int ThumbnailHeight { get; } //// -(id)initWithYuvData:(int8_t *)yuvData yuvDataLen:(int)yuvDataLen dataWidth:(int)dataWidth dataHeight:(int)dataHeight left:(int)left top:(int)top width:(int)width height:(int)height reverseHorizontal:(BOOL)reverseHorizontal; //[Export("initWithYuvData:yuvDataLen:dataWidth:dataHeight:left:top:width:height:reverseHorizontal:")] //unsafe IntPtr Constructor(sbyte* yuvData, int yuvDataLen, int dataWidth, int dataHeight, int left, int top, int width, int height, bool reverseHorizontal); //// -(int32_t *)renderThumbnail; //[Export("renderThumbnail")] //unsafe int* RenderThumbnail { get; } } public interface IZXReader { } // @protocol ZXReader <NSObject> [Protocol] [BaseType(typeof(NSObject))] interface ZXReader { // @required -(ZXResult *)decode:(ZXBinaryBitmap *)image error:(NSError **)error; [Abstract] [Export("decode:error:")] ZXResult Decode(ZXBinaryBitmap image, out NSError error); // @required -(ZXResult *)decode:(ZXBinaryBitmap *)image hints:(ZXDecodeHints *)hints error:(NSError **)error; [Abstract] [Export("decode:hints:error:")] ZXResult Decode(ZXBinaryBitmap image, ZXDecodeHints hints, out NSError error); // @required -(void)reset; [Abstract] [Export("reset")] void Reset(); } // @interface ZXResult : NSObject [BaseType(typeof(NSObject))] interface ZXResult { // @property (readonly, copy, nonatomic) NSString * text; [Export("text")] string Text { get; } // @property (readonly, nonatomic, strong) ZXByteArray * rawBytes; [Export("rawBytes", ArgumentSemantic.Strong)] ZXByteArray RawBytes { get; } // @property (readonly, nonatomic, strong) NSMutableArray * resultPoints; [Export("resultPoints", ArgumentSemantic.Strong)] NSMutableArray ResultPoints { get; } // @property (readonly, assign, nonatomic) ZXBarcodeFormat barcodeFormat; [Export("barcodeFormat", ArgumentSemantic.Assign)] ZXBarcodeFormat BarcodeFormat { get; } // @property (readonly, nonatomic, strong) NSMutableDictionary * resultMetadata; [Export("resultMetadata", ArgumentSemantic.Strong)] NSMutableDictionary ResultMetadata { get; } // @property (readonly, assign, nonatomic) long timestamp; [Export("timestamp")] nint Timestamp { get; } // -(id)initWithText:(NSString *)text rawBytes:(ZXByteArray *)rawBytes resultPoints:(NSArray *)resultPoints format:(ZXBarcodeFormat)format; [Export("initWithText:rawBytes:resultPoints:format:")] IntPtr Constructor(string text, ZXByteArray rawBytes, NSObject[] resultPoints, ZXBarcodeFormat format); // -(id)initWithText:(NSString *)text rawBytes:(ZXByteArray *)rawBytes resultPoints:(NSArray *)resultPoints format:(ZXBarcodeFormat)format timestamp:(long)timestamp; [Export("initWithText:rawBytes:resultPoints:format:timestamp:")] IntPtr Constructor(string text, ZXByteArray rawBytes, NSObject[] resultPoints, ZXBarcodeFormat format, nint timestamp); // +(id)resultWithText:(NSString *)text rawBytes:(ZXByteArray *)rawBytes resultPoints:(NSArray *)resultPoints format:(ZXBarcodeFormat)format; [Static] [Export("resultWithText:rawBytes:resultPoints:format:")] NSObject ResultWithText(string text, ZXByteArray rawBytes, NSObject[] resultPoints, ZXBarcodeFormat format); // +(id)resultWithText:(NSString *)text rawBytes:(ZXByteArray *)rawBytes resultPoints:(NSArray *)resultPoints format:(ZXBarcodeFormat)format timestamp:(long)timestamp; [Static] [Export("resultWithText:rawBytes:resultPoints:format:timestamp:")] NSObject ResultWithText(string text, ZXByteArray rawBytes, NSObject[] resultPoints, ZXBarcodeFormat format, nint timestamp); // -(void)putMetadata:(ZXResultMetadataType)type value:(id)value; [Export("putMetadata:value:")] void PutMetadata(ZXResultMetadataType type, NSObject value); // -(void)putAllMetadata:(NSMutableDictionary *)metadata; [Export("putAllMetadata:")] void PutAllMetadata(NSMutableDictionary metadata); // -(void)addResultPoints:(NSArray *)newPoints; [Export("addResultPoints:")] void AddResultPoints(NSObject[] newPoints); } public interface IZXResultPointCallback { } // @protocol ZXResultPointCallback <NSObject> [Protocol, Model] [BaseType(typeof(NSObject))] interface ZXResultPointCallback { // @required -(void)foundPossibleResultPoint:(ZXResultPoint *)point; [Abstract] [Export("foundPossibleResultPoint:")] void FoundPossibleResultPoint(ZXResultPoint point); } // @interface ZXRGBLuminanceSource : ZXLuminanceSource [BaseType(typeof(ZXLuminanceSource))] interface ZXRGBLuminanceSource { //// -(id)initWithWidth:(int)width height:(int)height pixels:(int32_t *)pixels pixelsLen:(int)pixelsLen; //[Export("initWithWidth:height:pixels:pixelsLen:")] //unsafe IntPtr Constructor(int width, int height, int* pixels, int pixelsLen); } public interface IZXWriter { } // @protocol ZXWriter <NSObject> [Protocol] [BaseType(typeof(NSObject))] interface ZXWriter { // @required -(ZXBitMatrix *)encode:(NSString *)contents format:(ZXBarcodeFormat)format width:(int)width height:(int)height error:(NSError **)error; [Abstract] [Export("encode:format:width:height:error:")] ZXBitMatrix Format(string contents, ZXBarcodeFormat format, int width, int height, out NSError error); // @required -(ZXBitMatrix *)encode:(NSString *)contents format:(ZXBarcodeFormat)format width:(int)width height:(int)height hints:(ZXEncodeHints *)hints error:(NSError **)error; [Abstract] [Export("encode:format:width:height:hints:error:")] ZXBitMatrix Format(string contents, ZXBarcodeFormat format, int width, int height, ZXEncodeHints hints, out NSError error); } // @interface ZXByQuadrantReader : NSObject <ZXReader> [BaseType(typeof(NSObject))] interface ZXByQuadrantReader : ZXReader { // -(id)initWithDelegate:(id<ZXReader>)delegate; [Export("initWithDelegate:")] IntPtr Constructor(ZXReader @delegate); } public interface IZXMultipleBarcodeReader {} // @protocol ZXMultipleBarcodeReader <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface ZXMultipleBarcodeReader { // @required -(NSArray *)decodeMultiple:(ZXBinaryBitmap *)image error:(NSError **)error; [Abstract] [Export ("decodeMultiple:error:")] NSObject[] Error (ZXBinaryBitmap image, out NSError error); // @required -(NSArray *)decodeMultiple:(ZXBinaryBitmap *)image hints:(ZXDecodeHints *)hints error:(NSError **)error; [Abstract] [Export ("decodeMultiple:hints:error:")] NSObject[] Hints (ZXBinaryBitmap image, ZXDecodeHints hints, out NSError error); } // @interface ZXGenericMultipleBarcodeReader : NSObject <ZXMultipleBarcodeReader> [BaseType (typeof(NSObject))] interface ZXGenericMultipleBarcodeReader : IZXMultipleBarcodeReader { // -(id)initWithDelegate:(id<ZXReader>)delegate; [Export ("initWithDelegate:")] IntPtr Constructor (ZXReader @delegate); } // @interface ZXAztecCode : NSObject [BaseType (typeof(NSObject))] interface ZXAztecCode { // @property (assign, nonatomic) int codeWords; [Export ("codeWords")] int CodeWords { get; set; } // @property (getter = isCompact, assign, nonatomic) BOOL compact; [Export ("compact")] bool Compact { [Bind ("isCompact")] get; set; } // @property (assign, nonatomic) int layers; [Export ("layers")] int Layers { get; set; } // @property (nonatomic, strong) ZXBitMatrix * matrix; [Export ("matrix", ArgumentSemantic.Strong)] ZXBitMatrix Matrix { get; set; } // @property (assign, nonatomic) int size; [Export ("size")] int Size { get; set; } } // @interface ZXAztecDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXAztecDecoder { // -(ZXDecoderResult *)decode:(ZXAztecDetectorResult *)detectorResult error:(NSError **)error; [Export ("decode:error:")] ZXDecoderResult Decode (ZXAztecDetectorResult detectorResult, out NSError error); // +(NSString *)highLevelDecode:(ZXBoolArray *)correctedBits; [Static] [Export ("highLevelDecode:")] string HighLevelDecode (ZXBoolArray correctedBits); } // @interface ZXAztecPoint : NSObject [BaseType (typeof(NSObject))] interface ZXAztecPoint { // @property (readonly, assign, nonatomic) int x; [Export ("x")] int X { get; } // @property (readonly, assign, nonatomic) int y; [Export ("y")] int Y { get; } // -(id)initWithX:(int)x y:(int)y; [Export ("initWithX:y:")] IntPtr Constructor (int x, int y); } // @interface ZXAztecDetector : NSObject [BaseType (typeof(NSObject))] interface ZXAztecDetector { // -(id)initWithImage:(ZXBitMatrix *)image; [Export ("initWithImage:")] IntPtr Constructor (ZXBitMatrix image); // -(ZXAztecDetectorResult *)detectWithError:(NSError **)error; [Export ("detectWithError:")] ZXAztecDetectorResult DetectWithError (out NSError error); // -(ZXAztecDetectorResult *)detectWithMirror:(BOOL)isMirror error:(NSError **)error; [Export ("detectWithMirror:error:")] ZXAztecDetectorResult DetectWithMirror (bool isMirror, out NSError error); } // @interface ZXAztecDetectorResult : ZXDetectorResult [BaseType (typeof(ZXDetectorResult))] interface ZXAztecDetectorResult { // @property (readonly, getter = isCompact, assign, nonatomic) BOOL compact; [Export ("compact")] bool Compact { [Bind ("isCompact")] get; } // @property (readonly, assign, nonatomic) int nbDatablocks; [Export ("nbDatablocks")] int NbDatablocks { get; } // @property (readonly, assign, nonatomic) int nbLayers; [Export ("nbLayers")] int NbLayers { get; } // -(id)initWithBits:(ZXBitMatrix *)bits points:(NSArray *)points compact:(BOOL)compact nbDatablocks:(int)nbDatablocks nbLayers:(int)nbLayers; [Export ("initWithBits:points:compact:nbDatablocks:nbLayers:")] IntPtr Constructor (ZXBitMatrix bits, NSObject[] points, bool compact, int nbDatablocks, int nbLayers); } [Static] partial interface Constants { //// extern const int ZX_AZTEC_DEFAULT_EC_PERCENT; //[Field ("ZX_AZTEC_DEFAULT_EC_PERCENT")] //int ZX_AZTEC_DEFAULT_EC_PERCENT { get; } //// extern const int ZX_AZTEC_DEFAULT_LAYERS; //[Field ("ZX_AZTEC_DEFAULT_LAYERS")] //int ZX_AZTEC_DEFAULT_LAYERS { get; } //// extern NSArray * ZX_AZTEC_MODE_NAMES; //[Field("ZX_AZTEC_MODE_NAMES")] //NSObject[] ZX_AZTEC_MODE_NAMES { get; } //// extern const int ZX_AZTEC_MODE_UPPER; //[Field("ZX_AZTEC_MODE_UPPER")] //int ZX_AZTEC_MODE_UPPER { get; } //// extern const int ZX_AZTEC_MODE_LOWER; //[Field("ZX_AZTEC_MODE_LOWER")] //int ZX_AZTEC_MODE_LOWER { get; } //// extern const int ZX_AZTEC_MODE_DIGIT; //[Field("ZX_AZTEC_MODE_DIGIT")] //int ZX_AZTEC_MODE_DIGIT { get; } //// extern const int ZX_AZTEC_MODE_MIXED; //[Field("ZX_AZTEC_MODE_MIXED")] //int ZX_AZTEC_MODE_MIXED { get; } //// extern const int ZX_AZTEC_MODE_PUNCT; //[Field("ZX_AZTEC_MODE_PUNCT")] //int ZX_AZTEC_MODE_PUNCT { get; } //// extern const int [][5] ZX_AZTEC_LATCH_TABLE; //[Field("ZX_AZTEC_LATCH_TABLE")] //int[][] ZX_AZTEC_LATCH_TABLE { get; } //// extern int [6][6] ZX_AZTEC_SHIFT_TABLE; //[Field("ZX_AZTEC_SHIFT_TABLE")] //int[][] ZX_AZTEC_SHIFT_TABLE { get; } //// extern const int [][7] ZX_CODE128_CODE_PATTERNS; //[Field("ZX_CODE128_CODE_PATTERNS")] //int[][] ZX_CODE128_CODE_PATTERNS { get; } //// extern const int ZX_CODE128_CODE_START_B; //[Field("ZX_CODE128_CODE_START_B")] //int ZX_CODE128_CODE_START_B { get; } //// extern const int ZX_CODE128_CODE_START_C; //[Field("ZX_CODE128_CODE_START_C")] //int ZX_CODE128_CODE_START_C { get; } //// extern const int ZX_CODE128_CODE_CODE_B; //[Field("ZX_CODE128_CODE_CODE_B")] //int ZX_CODE128_CODE_CODE_B { get; } //// extern const int ZX_CODE128_CODE_CODE_C; //[Field("ZX_CODE128_CODE_CODE_C")] //int ZX_CODE128_CODE_CODE_C { get; } //// extern const int ZX_CODE128_CODE_STOP; //[Field("ZX_CODE128_CODE_STOP")] //int ZX_CODE128_CODE_STOP { get; } //// extern const int ZX_CODE128_CODE_FNC_1; //[Field("ZX_CODE128_CODE_FNC_1")] //int ZX_CODE128_CODE_FNC_1 { get; } //// extern const int ZX_CODE128_CODE_FNC_2; //[Field("ZX_CODE128_CODE_FNC_2")] //int ZX_CODE128_CODE_FNC_2 { get; } //// extern const int ZX_CODE128_CODE_FNC_3; //[Field("ZX_CODE128_CODE_FNC_3")] //int ZX_CODE128_CODE_FNC_3 { get; } //// extern const int ZX_CODE128_CODE_FNC_4_A; //[Field("ZX_CODE128_CODE_FNC_4_A")] //int ZX_CODE128_CODE_FNC_4_A { get; } //// extern const int ZX_CODE128_CODE_FNC_4_B; //[Field("ZX_CODE128_CODE_FNC_4_B")] //int ZX_CODE128_CODE_FNC_4_B { get; } //// extern unichar [] ZX_CODE39_ALPHABET; //[Field("ZX_CODE39_ALPHABET")] //ushort[] ZX_CODE39_ALPHABET { get; } //// extern NSString * ZX_CODE39_ALPHABET_STRING; //[Field("ZX_CODE39_ALPHABET_STRING")] //NSString ZX_CODE39_ALPHABET_STRING { get; } //// extern const int [] ZX_CODE39_CHARACTER_ENCODINGS; //[Field("ZX_CODE39_CHARACTER_ENCODINGS")] //int[] ZX_CODE39_CHARACTER_ENCODINGS { get; } //// extern const int ZX_UPC_EAN_START_END_PATTERN_LEN; //[Field("ZX_UPC_EAN_START_END_PATTERN_LEN")] //int ZX_UPC_EAN_START_END_PATTERN_LEN { get; } //// extern const int [] ZX_UPC_EAN_START_END_PATTERN; //[Field("ZX_UPC_EAN_START_END_PATTERN")] //int[] ZX_UPC_EAN_START_END_PATTERN { get; } //// extern const int ZX_UPC_EAN_MIDDLE_PATTERN_LEN; //[Field("ZX_UPC_EAN_MIDDLE_PATTERN_LEN")] //int ZX_UPC_EAN_MIDDLE_PATTERN_LEN { get; } //// extern const int [] ZX_UPC_EAN_MIDDLE_PATTERN; //[Field("ZX_UPC_EAN_MIDDLE_PATTERN")] //int[] ZX_UPC_EAN_MIDDLE_PATTERN { get; } //// extern const int ZX_UPC_EAN_L_PATTERNS_LEN; //[Field("ZX_UPC_EAN_L_PATTERNS_LEN")] //int ZX_UPC_EAN_L_PATTERNS_LEN { get; } //// extern const int ZX_UPC_EAN_L_PATTERNS_SUB_LEN; //[Field("ZX_UPC_EAN_L_PATTERNS_SUB_LEN")] //int ZX_UPC_EAN_L_PATTERNS_SUB_LEN { get; } //// extern const int [][4] ZX_UPC_EAN_L_PATTERNS; //[Field("ZX_UPC_EAN_L_PATTERNS")] //int[][] ZX_UPC_EAN_L_PATTERNS { get; } //// extern const int ZX_UPC_EAN_L_AND_G_PATTERNS_LEN; //[Field("ZX_UPC_EAN_L_AND_G_PATTERNS_LEN")] //int ZX_UPC_EAN_L_AND_G_PATTERNS_LEN { get; } //// extern const int ZX_UPC_EAN_L_AND_G_PATTERNS_SUB_LEN; //[Field("ZX_UPC_EAN_L_AND_G_PATTERNS_SUB_LEN")] //int ZX_UPC_EAN_L_AND_G_PATTERNS_SUB_LEN { get; } //// extern const int [][4] ZX_UPC_EAN_L_AND_G_PATTERNS; //[Field("ZX_UPC_EAN_L_AND_G_PATTERNS")] //int[][] ZX_UPC_EAN_L_AND_G_PATTERNS { get; } //// extern const int [] ZX_EAN13_FIRST_DIGIT_ENCODINGS; //[Field("ZX_EAN13_FIRST_DIGIT_ENCODINGS")] //int[] ZX_EAN13_FIRST_DIGIT_ENCODINGS { get; } //// extern const int [][5] ZX_ITF_PATTERNS; //[Field("ZX_ITF_PATTERNS")] //int[][] ZX_ITF_PATTERNS { get; } //// extern const int [] CHECK_DIGIT_ENCODINGS; //[Field("CHECK_DIGIT_ENCODINGS")] //int[] CHECK_DIGIT_ENCODINGS { get; } //// extern const int ZX_UPCE_MIDDLE_END_PATTERN_LEN; //[Field("ZX_UPCE_MIDDLE_END_PATTERN_LEN")] //int ZX_UPCE_MIDDLE_END_PATTERN_LEN { get; } //// extern const int [] ZX_UPCE_MIDDLE_END_PATTERN; //[Field("ZX_UPCE_MIDDLE_END_PATTERN")] //int[] ZX_UPCE_MIDDLE_END_PATTERN { get; } //// extern NSString *const ZX_KILOGRAM; //[Field("ZX_KILOGRAM")] //NSString ZX_KILOGRAM { get; } //// extern NSString *const ZX_POUND; //[Field("ZX_POUND")] //NSString ZX_POUND { get; } //// extern const int [] ZX_PDF417_SYMBOL_TABLE; //[Field("ZX_PDF417_SYMBOL_TABLE")] //int[] ZX_PDF417_SYMBOL_TABLE { get; } //// extern const int ZX_PDF417_NUMBER_OF_CODEWORDS; //[Field("ZX_PDF417_NUMBER_OF_CODEWORDS")] //int ZX_PDF417_NUMBER_OF_CODEWORDS { get; } //// extern const int ZX_PDF417_MIN_ROWS_IN_BARCODE; //[Field("ZX_PDF417_MIN_ROWS_IN_BARCODE")] //int ZX_PDF417_MIN_ROWS_IN_BARCODE { get; } //// extern const int ZX_PDF417_MAX_ROWS_IN_BARCODE; //[Field("ZX_PDF417_MAX_ROWS_IN_BARCODE")] //int ZX_PDF417_MAX_ROWS_IN_BARCODE { get; } //// extern const int ZX_PDF417_MAX_CODEWORDS_IN_BARCODE; //[Field("ZX_PDF417_MAX_CODEWORDS_IN_BARCODE")] //int ZX_PDF417_MAX_CODEWORDS_IN_BARCODE { get; } //// extern const int ZX_PDF417_MODULES_IN_CODEWORD; //[Field("ZX_PDF417_MODULES_IN_CODEWORD")] //int ZX_PDF417_MODULES_IN_CODEWORD { get; } //// extern const int ZX_PDF417_MODULES_IN_STOP_PATTERN; //[Field("ZX_PDF417_MODULES_IN_STOP_PATTERN")] //int ZX_PDF417_MODULES_IN_STOP_PATTERN { get; } //// extern const int ZX_NUM_MASK_PATTERNS; //[Field("ZX_NUM_MASK_PATTERNS")] //int ZX_NUM_MASK_PATTERNS { get; } //// extern const NSStringEncoding ZX_DEFAULT_BYTE_MODE_ENCODING; //[Field("ZX_DEFAULT_BYTE_MODE_ENCODING")] //nuint ZX_DEFAULT_BYTE_MODE_ENCODING { get; } //// extern const int ZX_FINDER_PATTERN_MIN_SKIP; //[Field("ZX_FINDER_PATTERN_MIN_SKIP")] //int ZX_FINDER_PATTERN_MIN_SKIP { get; } //// extern const int ZX_FINDER_PATTERN_MAX_MODULES; //[Field("ZX_FINDER_PATTERN_MAX_MODULES")] //int ZX_FINDER_PATTERN_MAX_MODULES { get; } //// extern const int ZX_CODA_ALPHABET_LEN; //[Field("ZX_CODA_ALPHABET_LEN")] //int ZX_CODA_ALPHABET_LEN { get; } //// extern const unichar [] ZX_CODA_ALPHABET; //[Field("ZX_CODA_ALPHABET")] //ushort[] ZX_CODA_ALPHABET { get; } //// extern const int [] ZX_CODA_CHARACTER_ENCODINGS; //[Field("ZX_CODA_CHARACTER_ENCODINGS")] //int[] ZX_CODA_CHARACTER_ENCODINGS { get; } } // @interface ZXAztecEncoder : NSObject [BaseType (typeof(NSObject))] interface ZXAztecEncoder { // +(ZXAztecCode *)encode:(ZXByteArray *)data; [Static] [Export ("encode:")] ZXAztecCode Encode (ZXByteArray data); // +(ZXAztecCode *)encode:(ZXByteArray *)data minECCPercent:(int)minECCPercent userSpecifiedLayers:(int)userSpecifiedLayers; [Static] [Export ("encode:minECCPercent:userSpecifiedLayers:")] ZXAztecCode Encode (ZXByteArray data, int minECCPercent, int userSpecifiedLayers); } // @interface ZXAztecHighLevelEncoder : NSObject [BaseType (typeof(NSObject))] interface ZXAztecHighLevelEncoder { // -(id)initWithText:(ZXByteArray *)text; [Export ("initWithText:")] IntPtr Constructor (ZXByteArray text); // -(ZXBitArray *)encode; [Export ("encode")] ZXBitArray Encode { get; } } // @interface ZXAztecReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXAztecReader : ZXReader { } // @interface ZXAztecWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXAztecWriter : ZXWriter { } // @interface ZXDataMatrixDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixDecoder { // -(ZXDecoderResult *)decode:(NSArray *)image error:(NSError **)error; [Export ("decode:error:")] ZXDecoderResult Decode (NSObject[] image, out NSError error); // -(ZXDecoderResult *)decodeMatrix:(ZXBitMatrix *)bits error:(NSError **)error; [Export ("decodeMatrix:error:")] ZXDecoderResult DecodeMatrix (ZXBitMatrix bits, out NSError error); } // @interface ZXDataMatrixDefaultPlacement : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixDefaultPlacement { // @property (readonly, copy, nonatomic) NSString * codewords; [Export ("codewords")] string Codewords { get; } // @property (readonly, assign, nonatomic) int numrows; [Export ("numrows")] int Numrows { get; } // @property (readonly, assign, nonatomic) int numcols; [Export ("numcols")] int Numcols { get; } //// @property (readonly, assign, nonatomic) int8_t * bits; //[Export ("bits", ArgumentSemantic.Assign)] //unsafe sbyte* Bits { get; } // @property (readonly, assign, nonatomic) int bitsLen; [Export ("bitsLen")] int BitsLen { get; } // -(id)initWithCodewords:(NSString *)codewords numcols:(int)numcols numrows:(int)numrows; [Export ("initWithCodewords:numcols:numrows:")] IntPtr Constructor (string codewords, int numcols, int numrows); // -(BOOL)bitAtCol:(int)col row:(int)row; [Export ("bitAtCol:row:")] bool BitAtCol (int col, int row); // -(void)setBitAtCol:(int)col row:(int)row bit:(BOOL)bit; [Export ("setBitAtCol:row:bit:")] void SetBitAtCol (int col, int row, bool bit); // -(BOOL)hasBitAtCol:(int)col row:(int)row; [Export ("hasBitAtCol:row:")] bool HasBitAtCol (int col, int row); // -(void)place; [Export ("place")] void Place (); } // @interface ZXDataMatrixDetector : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixDetector { // -(id)initWithImage:(ZXBitMatrix *)image error:(NSError **)error; [Export ("initWithImage:error:")] IntPtr Constructor (ZXBitMatrix image, out NSError error); // -(ZXDetectorResult *)detectWithError:(NSError **)error; [Export ("detectWithError:")] ZXDetectorResult DetectWithError (out NSError error); } public interface IZXDataMatrixEncoder {} // @protocol ZXDataMatrixEncoder <NSObject> [Protocol, Model] [BaseType (typeof(NSObject))] interface ZXDataMatrixEncoder { // @required -(int)encodingMode; [Abstract] [Export ("encodingMode")] int EncodingMode { get; } // @required -(void)encode:(ZXDataMatrixEncoderContext *)context; [Abstract] [Export ("encode:")] void Encode (ZXDataMatrixEncoderContext context); } // @interface ZXDataMatrixEdifactEncoder : NSObject <ZXDataMatrixEncoder> [BaseType (typeof(NSObject))] interface ZXDataMatrixEdifactEncoder : ZXDataMatrixEncoder { } // @interface ZXDataMatrixEncoderContext : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixEncoderContext { // @property (readonly, copy, nonatomic) NSMutableString * codewords; [Export ("codewords", ArgumentSemantic.Copy)] NSMutableString Codewords { get; } // @property (readonly, copy, nonatomic) NSString * message; [Export ("message")] string Message { get; } // @property (assign, nonatomic) int newEncoding; [Export ("newEncoding")] int NewEncoding { get; set; } // @property (assign, nonatomic) int pos; [Export ("pos")] int Pos { get; set; } // @property (assign, nonatomic) int skipAtEnd; [Export ("skipAtEnd")] int SkipAtEnd { get; set; } // @property (assign, nonatomic) ZXDataMatrixSymbolShapeHint symbolShape; [Export ("symbolShape", ArgumentSemantic.Assign)] ZXDataMatrixSymbolShapeHint SymbolShape { get; set; } // @property (nonatomic, strong) ZXDataMatrixSymbolInfo * symbolInfo; [Export ("symbolInfo", ArgumentSemantic.Strong)] ZXDataMatrixSymbolInfo SymbolInfo { get; set; } // -(id)initWithMessage:(NSString *)msg; [Export ("initWithMessage:")] IntPtr Constructor (string msg); // -(void)setSizeConstraints:(ZXDimension *)minSize maxSize:(ZXDimension *)maxSize; [Export ("setSizeConstraints:maxSize:")] void SetSizeConstraints (ZXDimension minSize, ZXDimension maxSize); // -(unichar)currentChar; [Export ("currentChar")] ushort CurrentChar { get; } // -(unichar)current; [Export ("current")] ushort Current { get; } // -(void)writeCodewords:(NSString *)codewords; [Export ("writeCodewords:")] void WriteCodewords (string codewords); // -(void)writeCodeword:(unichar)codeword; [Export ("writeCodeword:")] void WriteCodeword (ushort codeword); // -(int)codewordCount; [Export ("codewordCount")] int CodewordCount { get; } // -(void)signalEncoderChange:(int)encoding; [Export ("signalEncoderChange:")] void SignalEncoderChange (int encoding); // -(void)resetEncoderSignal; [Export ("resetEncoderSignal")] void ResetEncoderSignal (); // -(BOOL)hasMoreCharacters; [Export ("hasMoreCharacters")] bool HasMoreCharacters { get; } // -(int)totalMessageCharCount; [Export ("totalMessageCharCount")] int TotalMessageCharCount { get; } // -(int)remainingCharacters; [Export ("remainingCharacters")] int RemainingCharacters { get; } // -(void)updateSymbolInfo; [Export ("updateSymbolInfo")] void UpdateSymbolInfo (); // -(void)updateSymbolInfoWithLength:(int)len; [Export ("updateSymbolInfoWithLength:")] void UpdateSymbolInfoWithLength (int len); // -(void)resetSymbolInfo; [Export ("resetSymbolInfo")] void ResetSymbolInfo (); } // @interface ZXDataMatrixErrorCorrection : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixErrorCorrection { // +(NSString *)encodeECC200:(NSString *)codewords symbolInfo:(ZXDataMatrixSymbolInfo *)symbolInfo; [Static] [Export ("encodeECC200:symbolInfo:")] string EncodeECC200 (string codewords, ZXDataMatrixSymbolInfo symbolInfo); } // @interface ZXDataMatrixHighLevelEncoder : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixHighLevelEncoder { // +(unichar)latchToC40; [Static] [Export ("latchToC40")] ushort LatchToC40 { get; } // +(unichar)latchToBase256; [Static] [Export ("latchToBase256")] ushort LatchToBase256 { get; } // +(unichar)upperShift; [Static] [Export ("upperShift")] ushort UpperShift { get; } // +(unichar)macro05; [Static] [Export ("macro05")] ushort Macro05 { get; } // +(unichar)macro06; [Static] [Export ("macro06")] ushort Macro06 { get; } // +(unichar)latchToAnsiX12; [Static] [Export ("latchToAnsiX12")] ushort LatchToAnsiX12 { get; } // +(unichar)latchToText; [Static] [Export ("latchToText")] ushort LatchToText { get; } // +(unichar)latchToEdifact; [Static] [Export ("latchToEdifact")] ushort LatchToEdifact { get; } // +(unichar)c40Unlatch; [Static] [Export ("c40Unlatch")] ushort C40Unlatch { get; } // +(unichar)x12Unlatch; [Static] [Export ("x12Unlatch")] ushort X12Unlatch { get; } // +(int)asciiEncodation; [Static] [Export ("asciiEncodation")] int AsciiEncodation { get; } // +(int)c40Encodation; [Static] [Export ("c40Encodation")] int C40Encodation { get; } // +(int)textEncodation; [Static] [Export ("textEncodation")] int TextEncodation { get; } // +(int)x12Encodation; [Static] [Export ("x12Encodation")] int X12Encodation { get; } // +(int)edifactEncodation; [Static] [Export ("edifactEncodation")] int EdifactEncodation { get; } // +(int)base256Encodation; [Static] [Export ("base256Encodation")] int Base256Encodation { get; } // +(NSString *)encodeHighLevel:(NSString *)msg; [Static] [Export ("encodeHighLevel:")] string EncodeHighLevel (string msg); // +(NSString *)encodeHighLevel:(NSString *)msg shape:(ZXDataMatrixSymbolShapeHint)shape minSize:(ZXDimension *)minSize maxSize:(ZXDimension *)maxSize; [Static] [Export ("encodeHighLevel:shape:minSize:maxSize:")] string EncodeHighLevel (string msg, ZXDataMatrixSymbolShapeHint shape, ZXDimension minSize, ZXDimension maxSize); // +(int)lookAheadTest:(NSString *)msg startpos:(int)startpos currentMode:(int)currentMode; [Static] [Export ("lookAheadTest:startpos:currentMode:")] int LookAheadTest (string msg, int startpos, int currentMode); // +(int)determineConsecutiveDigitCount:(NSString *)msg startpos:(int)startpos; [Static] [Export ("determineConsecutiveDigitCount:startpos:")] int DetermineConsecutiveDigitCount (string msg, int startpos); // +(BOOL)isDigit:(unichar)ch; [Static] [Export ("isDigit:")] bool IsDigit (ushort ch); // +(BOOL)isExtendedASCII:(unichar)ch; [Static] [Export ("isExtendedASCII:")] bool IsExtendedASCII (ushort ch); // +(void)illegalCharacter:(unichar)c; [Static] [Export ("illegalCharacter:")] void IllegalCharacter (ushort c); } // @interface ZXDataMatrixReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXDataMatrixReader : ZXReader { } // @interface ZXDataMatrixSymbolInfo : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixSymbolInfo { // @property (readonly, assign, nonatomic) BOOL rectangular; [Export ("rectangular")] bool Rectangular { get; } // @property (readonly, assign, nonatomic) int errorCodewords; [Export ("errorCodewords")] int ErrorCodewords { get; } // @property (readonly, assign, nonatomic) int dataCapacity; [Export ("dataCapacity")] int DataCapacity { get; } // @property (readonly, assign, nonatomic) int dataRegions; [Export ("dataRegions")] int DataRegions { get; } // @property (readonly, assign, nonatomic) int matrixWidth; [Export ("matrixWidth")] int MatrixWidth { get; } // @property (readonly, assign, nonatomic) int matrixHeight; [Export ("matrixHeight")] int MatrixHeight { get; } // @property (readonly, assign, nonatomic) int rsBlockData; [Export ("rsBlockData")] int RsBlockData { get; } // @property (readonly, assign, nonatomic) int rsBlockError; [Export ("rsBlockError")] int RsBlockError { get; } // +(void)overrideSymbolSet:(NSArray *)override; [Static] [Export ("overrideSymbolSet:")] void OverrideSymbolSet (NSObject[] @override); // +(NSArray *)prodSymbols; [Static] [Export ("prodSymbols")] NSObject[] ProdSymbols { get; } // -(id)initWithRectangular:(BOOL)rectangular dataCapacity:(int)dataCapacity errorCodewords:(int)errorCodewords matrixWidth:(int)matrixWidth matrixHeight:(int)matrixHeight dataRegions:(int)dataRegions; [Export ("initWithRectangular:dataCapacity:errorCodewords:matrixWidth:matrixHeight:dataRegions:")] IntPtr Constructor (bool rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions); // -(id)initWithRectangular:(BOOL)rectangular dataCapacity:(int)dataCapacity errorCodewords:(int)errorCodewords matrixWidth:(int)matrixWidth matrixHeight:(int)matrixHeight dataRegions:(int)dataRegions rsBlockData:(int)rsBlockData rsBlockError:(int)rsBlockError; [Export ("initWithRectangular:dataCapacity:errorCodewords:matrixWidth:matrixHeight:dataRegions:rsBlockData:rsBlockError:")] IntPtr Constructor (bool rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions, int rsBlockData, int rsBlockError); // +(ZXDataMatrixSymbolInfo *)lookup:(int)dataCodewords; [Static] [Export ("lookup:")] ZXDataMatrixSymbolInfo Lookup (int dataCodewords); // +(ZXDataMatrixSymbolInfo *)lookup:(int)dataCodewords shape:(ZXDataMatrixSymbolShapeHint)shape; [Static] [Export ("lookup:shape:")] ZXDataMatrixSymbolInfo Lookup (int dataCodewords, ZXDataMatrixSymbolShapeHint shape); // +(ZXDataMatrixSymbolInfo *)lookup:(int)dataCodewords allowRectangular:(BOOL)allowRectangular fail:(BOOL)fail; [Static] [Export ("lookup:allowRectangular:fail:")] ZXDataMatrixSymbolInfo Lookup (int dataCodewords, bool allowRectangular, bool fail); // +(ZXDataMatrixSymbolInfo *)lookup:(int)dataCodewords shape:(ZXDataMatrixSymbolShapeHint)shape fail:(BOOL)fail; [Static] [Export ("lookup:shape:fail:")] ZXDataMatrixSymbolInfo Lookup (int dataCodewords, ZXDataMatrixSymbolShapeHint shape, bool fail); // +(ZXDataMatrixSymbolInfo *)lookup:(int)dataCodewords shape:(ZXDataMatrixSymbolShapeHint)shape minSize:(ZXDimension *)minSize maxSize:(ZXDimension *)maxSize fail:(BOOL)fail; [Static] [Export ("lookup:shape:minSize:maxSize:fail:")] ZXDataMatrixSymbolInfo Lookup (int dataCodewords, ZXDataMatrixSymbolShapeHint shape, ZXDimension minSize, ZXDimension maxSize, bool fail); // -(int)horizontalDataRegions; [Export ("horizontalDataRegions")] int HorizontalDataRegions { get; } // -(int)verticalDataRegions; [Export ("verticalDataRegions")] int VerticalDataRegions { get; } // -(int)symbolDataWidth; [Export ("symbolDataWidth")] int SymbolDataWidth { get; } // -(int)symbolDataHeight; [Export ("symbolDataHeight")] int SymbolDataHeight { get; } // -(int)symbolWidth; [Export ("symbolWidth")] int SymbolWidth { get; } // -(int)symbolHeight; [Export ("symbolHeight")] int SymbolHeight { get; } // -(int)codewordCount; [Export ("codewordCount")] int CodewordCount { get; } // -(int)interleavedBlockCount; [Export ("interleavedBlockCount")] int InterleavedBlockCount { get; } // -(int)dataLengthForInterleavedBlock:(int)index; [Export ("dataLengthForInterleavedBlock:")] int DataLengthForInterleavedBlock (int index); // -(int)errorLengthForInterleavedBlock:(int)index; [Export ("errorLengthForInterleavedBlock:")] int ErrorLengthForInterleavedBlock (int index); } // @interface ZXDataMatrixECBlocks : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixECBlocks { // @property (readonly, nonatomic, strong) NSArray * ecBlocks; [Export ("ecBlocks", ArgumentSemantic.Strong)] NSObject[] EcBlocks { get; } // @property (readonly, assign, nonatomic) int ecCodewords; [Export ("ecCodewords")] int EcCodewords { get; } } // @interface ZXDataMatrixECB : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixECB { // @property (readonly, assign, nonatomic) int count; [Export ("count")] int Count { get; } // @property (readonly, assign, nonatomic) int dataCodewords; [Export ("dataCodewords")] int DataCodewords { get; } } // @interface ZXDataMatrixVersion : NSObject [BaseType (typeof(NSObject))] interface ZXDataMatrixVersion { // @property (readonly, nonatomic, strong) ZXDataMatrixECBlocks * ecBlocks; [Export ("ecBlocks", ArgumentSemantic.Strong)] ZXDataMatrixECBlocks EcBlocks { get; } // @property (readonly, assign, nonatomic) int dataRegionSizeColumns; [Export ("dataRegionSizeColumns")] int DataRegionSizeColumns { get; } // @property (readonly, assign, nonatomic) int dataRegionSizeRows; [Export ("dataRegionSizeRows")] int DataRegionSizeRows { get; } // @property (readonly, assign, nonatomic) int symbolSizeColumns; [Export ("symbolSizeColumns")] int SymbolSizeColumns { get; } // @property (readonly, assign, nonatomic) int symbolSizeRows; [Export ("symbolSizeRows")] int SymbolSizeRows { get; } // @property (readonly, assign, nonatomic) int totalCodewords; [Export ("totalCodewords")] int TotalCodewords { get; } // @property (readonly, assign, nonatomic) int versionNumber; [Export ("versionNumber")] int VersionNumber { get; } // +(ZXDataMatrixVersion *)versionForDimensions:(int)numRows numColumns:(int)numColumns; [Static] [Export ("versionForDimensions:numColumns:")] ZXDataMatrixVersion VersionForDimensions (int numRows, int numColumns); } // @interface ZXDataMatrixWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXDataMatrixWriter : ZXWriter { } // @interface ZXMaxiCodeDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXMaxiCodeDecoder { // -(ZXDecoderResult *)decode:(ZXBitMatrix *)bits error:(NSError **)error; [Export ("decode:error:")] ZXDecoderResult Decode (ZXBitMatrix bits, out NSError error); // -(ZXDecoderResult *)decode:(ZXBitMatrix *)bits hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decode:hints:error:")] ZXDecoderResult Decode (ZXBitMatrix bits, ZXDecodeHints hints, out NSError error); } // @interface ZXMaxiCodeReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXMaxiCodeReader : ZXReader { } [BaseType (typeof(NSObject))] interface ZXRSSExpandedGeneralAppIdDecoder { } // @interface ZXAbstractExpandedDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXAbstractExpandedDecoder { // @property (readonly, nonatomic, strong) ZXRSSExpandedGeneralAppIdDecoder * generalDecoder; [Export ("generalDecoder", ArgumentSemantic.Strong)] ZXRSSExpandedGeneralAppIdDecoder GeneralDecoder { get; } // @property (readonly, nonatomic, strong) ZXBitArray * information; [Export ("information", ArgumentSemantic.Strong)] ZXBitArray Information { get; } // -(id)initWithInformation:(ZXBitArray *)information; [Export ("initWithInformation:")] IntPtr Constructor (ZXBitArray information); // -(NSString *)parseInformationWithError:(NSError **)error; [Export ("parseInformationWithError:")] string ParseInformationWithError (out NSError error); // +(ZXAbstractExpandedDecoder *)createDecoder:(ZXBitArray *)information; [Static] [Export ("createDecoder:")] ZXAbstractExpandedDecoder CreateDecoder (ZXBitArray information); } // @interface ZXOneDReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXOneDReader : ZXReader { // +(BOOL)recordPattern:(ZXBitArray *)row start:(int)start counters:(ZXIntArray *)counters; [Static] [Export ("recordPattern:start:counters:")] bool RecordPattern (ZXBitArray row, int start, ZXIntArray counters); // +(BOOL)recordPatternInReverse:(ZXBitArray *)row start:(int)start counters:(ZXIntArray *)counters; [Static] [Export ("recordPatternInReverse:start:counters:")] bool RecordPatternInReverse (ZXBitArray row, int start, ZXIntArray counters); //// +(float)patternMatchVariance:(ZXIntArray *)counters pattern:(const int *)pattern maxIndividualVariance:(float)maxIndividualVariance; //[Static] //[Export ("patternMatchVariance:pattern:maxIndividualVariance:")] //float PatternMatchVariance (ZXIntArray counters, int[] pattern, float maxIndividualVariance); // -(ZXResult *)decodeRow:(int)rowNumber row:(ZXBitArray *)row hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decodeRow:row:hints:error:")] ZXResult DecodeRow (int rowNumber, ZXBitArray row, ZXDecodeHints hints, out NSError error); } // @interface ZXAbstractRSSReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXAbstractRSSReader { // @property (readonly, nonatomic, strong) ZXIntArray * decodeFinderCounters; [Export ("decodeFinderCounters", ArgumentSemantic.Strong)] ZXIntArray DecodeFinderCounters { get; } // @property (readonly, nonatomic, strong) ZXIntArray * dataCharacterCounters; [Export ("dataCharacterCounters", ArgumentSemantic.Strong)] ZXIntArray DataCharacterCounters { get; } //// @property (readonly, assign, nonatomic) float * oddRoundingErrors; //[Export ("oddRoundingErrors", ArgumentSemantic.Assign)] //unsafe float* OddRoundingErrors { get; } // @property (readonly, assign, nonatomic) unsigned int oddRoundingErrorsLen; [Export ("oddRoundingErrorsLen")] uint OddRoundingErrorsLen { get; } //// @property (readonly, assign, nonatomic) float * evenRoundingErrors; //[Export ("evenRoundingErrors", ArgumentSemantic.Assign)] //unsafe float* EvenRoundingErrors { get; } // @property (readonly, assign, nonatomic) unsigned int evenRoundingErrorsLen; [Export ("evenRoundingErrorsLen")] uint EvenRoundingErrorsLen { get; } // @property (readonly, nonatomic, strong) ZXIntArray * oddCounts; [Export ("oddCounts", ArgumentSemantic.Strong)] ZXIntArray OddCounts { get; } // @property (readonly, nonatomic, strong) ZXIntArray * evenCounts; [Export ("evenCounts", ArgumentSemantic.Strong)] ZXIntArray EvenCounts { get; } // +(int)parseFinderValue:(ZXIntArray *)counters finderPatternType:(ZX_RSS_PATTERNS)finderPatternType; [Static] [Export ("parseFinderValue:finderPatternType:")] int ParseFinderValue (ZXIntArray counters, ZxRssPatterns finderPatternType); // +(int)count:(ZXIntArray *)array; [Static] [Export ("count:")] int Count (ZXIntArray array); //// +(void)increment:(ZXIntArray *)array errors:(float *)errors; //[Static] //[Export ("increment:errors:")] //unsafe void Increment (ZXIntArray array, float* errors); //// +(void)decrement:(ZXIntArray *)array errors:(float *)errors; //[Static] //[Export ("decrement:errors:")] //unsafe void Decrement (ZXIntArray array, float* errors); // +(BOOL)isFinderPattern:(ZXIntArray *)counters; [Static] [Export ("isFinderPattern:")] bool IsFinderPattern (ZXIntArray counters); } // @interface ZXCodaBarReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXCodaBarReader { //// +(BOOL)arrayContains:(const unichar *)array length:(unsigned int)length key:(unichar)key; //[Static] //[Export ("arrayContains:length:key:")] //unsafe bool ArrayContains (ushort* array, uint length, ushort key); } // @interface ZXOneDimensionalCodeWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXOneDimensionalCodeWriter : ZXWriter { // -(ZXBoolArray *)encode:(NSString *)contents; [Export ("encode:")] ZXBoolArray Encode (string contents); //// -(int)appendPattern:(ZXBoolArray *)target pos:(int)pos pattern:(const int *)pattern patternLen:(int)patternLen startColor:(BOOL)startColor; //[Export ("appendPattern:pos:pattern:patternLen:startColor:")] //int AppendPattern (ZXBoolArray target, int pos, int[] pattern, int patternLen, bool startColor); // -(int)defaultMargin; [Export ("defaultMargin")] int DefaultMargin { get; } } // @interface ZXCodaBarWriter : ZXOneDimensionalCodeWriter [BaseType (typeof(ZXOneDimensionalCodeWriter))] interface ZXCodaBarWriter { } // @interface ZXCode128Reader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXCode128Reader { } // @interface ZXCode128Writer : ZXOneDimensionalCodeWriter [BaseType (typeof(ZXOneDimensionalCodeWriter))] interface ZXCode128Writer { } // @interface ZXCode39Reader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXCode39Reader { // -(id)initUsingCheckDigit:(BOOL)usingCheckDigit; [Export ("initUsingCheckDigit:")] IntPtr Constructor (bool usingCheckDigit); // -(id)initUsingCheckDigit:(BOOL)usingCheckDigit extendedMode:(BOOL)extendedMode; [Export ("initUsingCheckDigit:extendedMode:")] IntPtr Constructor (bool usingCheckDigit, bool extendedMode); } // @interface ZXCode39Writer : ZXOneDimensionalCodeWriter [BaseType (typeof(ZXOneDimensionalCodeWriter))] interface ZXCode39Writer { } // @interface ZXCode93Reader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXCode93Reader { } // @interface ZXUPCEANReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXUPCEANReader { // +(NSRange)findStartGuardPattern:(ZXBitArray *)row error:(NSError **)error; [Static] [Export ("findStartGuardPattern:error:")] NSRange FindStartGuardPattern (ZXBitArray row, out NSError error); // -(ZXResult *)decodeRow:(int)rowNumber row:(ZXBitArray *)row startGuardRange:(NSRange)startGuardRange hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decodeRow:row:startGuardRange:hints:error:")] ZXResult DecodeRow (int rowNumber, ZXBitArray row, NSRange startGuardRange, ZXDecodeHints hints, out NSError error); // -(BOOL)checkChecksum:(NSString *)s error:(NSError **)error; [Export ("checkChecksum:error:")] bool CheckChecksum (string s, out NSError error); // +(BOOL)checkStandardUPCEANChecksum:(NSString *)s; [Static] [Export ("checkStandardUPCEANChecksum:")] bool CheckStandardUPCEANChecksum (string s); // -(NSRange)decodeEnd:(ZXBitArray *)row endStart:(int)endStart error:(NSError **)error; [Export ("decodeEnd:endStart:error:")] NSRange DecodeEnd (ZXBitArray row, int endStart, out NSError error); //// +(NSRange)findGuardPattern:(ZXBitArray *)row rowOffset:(int)rowOffset whiteFirst:(BOOL)whiteFirst pattern:(const int *)pattern patternLen:(int)patternLen error:(NSError **)error; //[Static] //[Export ("findGuardPattern:rowOffset:whiteFirst:pattern:patternLen:error:")] //NSRange FindGuardPattern (ZXBitArray row, int rowOffset, bool whiteFirst, int[] pattern, int patternLen, out NSError error); //// +(NSRange)findGuardPattern:(ZXBitArray *)row rowOffset:(int)rowOffset whiteFirst:(BOOL)whiteFirst pattern:(const int *)pattern patternLen:(int)patternLen counters:(ZXIntArray *)counters error:(NSError **)error; //[Static] //[Export ("findGuardPattern:rowOffset:whiteFirst:pattern:patternLen:counters:error:")] //NSRange FindGuardPattern (ZXBitArray row, int rowOffset, bool whiteFirst, int[] pattern, int patternLen, ZXIntArray counters, out NSError error); // +(int)decodeDigit:(ZXBitArray *)row counters:(ZXIntArray *)counters rowOffset:(int)rowOffset patternType:(ZX_UPC_EAN_PATTERNS)patternType error:(NSError **)error; [Static] [Export ("decodeDigit:counters:rowOffset:patternType:error:")] int DecodeDigit (ZXBitArray row, ZXIntArray counters, int rowOffset, ZxUpcEanPatterns patternType, out NSError error); // -(ZXBarcodeFormat)barcodeFormat; [Export ("barcodeFormat")] ZXBarcodeFormat BarcodeFormat { get; } // -(int)decodeMiddle:(ZXBitArray *)row startRange:(NSRange)startRange result:(NSMutableString *)result error:(NSError **)error; [Export ("decodeMiddle:startRange:result:error:")] int DecodeMiddle (ZXBitArray row, NSRange startRange, NSMutableString result, out NSError error); } // @interface ZXEAN13Reader : ZXUPCEANReader [BaseType (typeof(ZXUPCEANReader))] interface ZXEAN13Reader { } // @interface ZXUPCEANWriter : ZXOneDimensionalCodeWriter [BaseType (typeof(ZXOneDimensionalCodeWriter))] interface ZXUPCEANWriter { } // @interface ZXEAN13Writer : ZXUPCEANWriter [BaseType (typeof(ZXUPCEANWriter))] interface ZXEAN13Writer { } // @interface ZXEAN8Reader : ZXUPCEANReader [BaseType (typeof(ZXUPCEANReader))] interface ZXEAN8Reader { } // @interface ZXEAN8Writer : ZXUPCEANWriter [BaseType (typeof(ZXUPCEANWriter))] interface ZXEAN8Writer { } // @interface ZXITFReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXITFReader { // -(ZXIntArray *)decodeStart:(ZXBitArray *)row; [Export ("decodeStart:")] ZXIntArray DecodeStart (ZXBitArray row); // -(ZXIntArray *)decodeEnd:(ZXBitArray *)row; [Export ("decodeEnd:")] ZXIntArray DecodeEnd (ZXBitArray row); } // @interface ZXITFWriter : ZXOneDimensionalCodeWriter [BaseType (typeof(ZXOneDimensionalCodeWriter))] interface ZXITFWriter { } // @interface ZXMultiFormatOneDReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXMultiFormatOneDReader { // -(id)initWithHints:(ZXDecodeHints *)hints; [Export ("initWithHints:")] IntPtr Constructor (ZXDecodeHints hints); } // @interface ZXMultiFormatUPCEANReader : ZXOneDReader [BaseType (typeof(ZXOneDReader))] interface ZXMultiFormatUPCEANReader { // -(id)initWithHints:(ZXDecodeHints *)hints; [Export ("initWithHints:")] IntPtr Constructor (ZXDecodeHints hints); } // @interface ZXRSS14Reader : ZXAbstractRSSReader [BaseType (typeof(ZXAbstractRSSReader))] interface ZXRSS14Reader { } // @interface ZXRSSDataCharacter : NSObject [BaseType (typeof(NSObject))] interface ZXRSSDataCharacter { // @property (readonly, assign, nonatomic) int value; [Export ("value")] int Value { get; } // @property (readonly, assign, nonatomic) int checksumPortion; [Export ("checksumPortion")] int ChecksumPortion { get; } // -(id)initWithValue:(int)value checksumPortion:(int)checksumPortion; [Export ("initWithValue:checksumPortion:")] IntPtr Constructor (int value, int checksumPortion); } // @interface ZXRSSExpandedReader : ZXAbstractRSSReader [BaseType (typeof(ZXAbstractRSSReader))] interface ZXRSSExpandedReader { // @property (readonly, nonatomic, strong) NSMutableArray * rows; [Export ("rows", ArgumentSemantic.Strong)] NSMutableArray Rows { get; } // -(ZXRSSDataCharacter *)decodeDataCharacter:(ZXBitArray *)row pattern:(ZXRSSFinderPattern *)pattern isOddPattern:(BOOL)isOddPattern leftChar:(BOOL)leftChar; [Export ("decodeDataCharacter:pattern:isOddPattern:leftChar:")] ZXRSSDataCharacter DecodeDataCharacter (ZXBitArray row, ZXRSSFinderPattern pattern, bool isOddPattern, bool leftChar); } // @interface ZXRSSFinderPattern : NSObject [BaseType (typeof(NSObject))] interface ZXRSSFinderPattern { // @property (readonly, assign, nonatomic) int value; [Export ("value")] int Value { get; } // @property (readonly, nonatomic, strong) ZXIntArray * startEnd; [Export ("startEnd", ArgumentSemantic.Strong)] ZXIntArray StartEnd { get; } // @property (readonly, nonatomic, strong) NSMutableArray * resultPoints; [Export ("resultPoints", ArgumentSemantic.Strong)] NSMutableArray ResultPoints { get; } // -(id)initWithValue:(int)value startEnd:(ZXIntArray *)startEnd start:(int)start end:(int)end rowNumber:(int)rowNumber; [Export ("initWithValue:startEnd:start:end:rowNumber:")] IntPtr Constructor (int value, ZXIntArray startEnd, int start, int end, int rowNumber); } // @interface ZXRSSUtils : NSObject [BaseType (typeof(NSObject))] interface ZXRSSUtils { // +(int)rssValue:(ZXIntArray *)widths maxWidth:(int)maxWidth noNarrow:(BOOL)noNarrow; [Static] [Export ("rssValue:maxWidth:noNarrow:")] int RssValue (ZXIntArray widths, int maxWidth, bool noNarrow); } // @interface ZXUPCAReader : ZXUPCEANReader [BaseType (typeof(ZXUPCEANReader))] interface ZXUPCAReader { } // @interface ZXUPCAWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXUPCAWriter : ZXWriter { } // @interface ZXUPCEReader : ZXUPCEANReader [BaseType (typeof(ZXUPCEANReader))] interface ZXUPCEReader { // +(NSString *)convertUPCEtoUPCA:(NSString *)upce; [Static] [Export ("convertUPCEtoUPCA:")] string ConvertUPCEtoUPCA (string upce); } // @interface ZXUPCEWriter : ZXUPCEANWriter [BaseType (typeof(ZXUPCEANWriter))] interface ZXUPCEWriter { } // @interface ZXResultParser : NSObject [BaseType (typeof(NSObject))] interface ZXResultParser { // -(ZXParsedResult *)parse:(ZXResult *)result; [Export ("parse:")] ZXParsedResult Parse (ZXResult result); // +(NSString *)massagedText:(ZXResult *)result; [Static] [Export ("massagedText:")] string MassagedText (ZXResult result); // +(ZXParsedResult *)parseResult:(ZXResult *)theResult; [Static] [Export ("parseResult:")] ZXParsedResult ParseResult (ZXResult theResult); // -(void)maybeAppend:(NSString *)value result:(NSMutableString *)result; [Export ("maybeAppend:result:")] void MaybeAppend (string value, NSMutableString result); // -(void)maybeAppendArray:(NSArray *)value result:(NSMutableString *)result; [Export ("maybeAppendArray:result:")] void MaybeAppendArray (NSObject[] value, NSMutableString result); // -(NSArray *)maybeWrap:(NSString *)value; [Export ("maybeWrap:")] NSObject[] MaybeWrap (string value); // +(BOOL)isStringOfDigits:(NSString *)value length:(unsigned int)length; [Static] [Export ("isStringOfDigits:length:")] bool IsStringOfDigits (string value, uint length); // +(BOOL)isSubstringOfDigits:(NSString *)value offset:(int)offset length:(int)length; [Static] [Export ("isSubstringOfDigits:offset:length:")] bool IsSubstringOfDigits (string value, int offset, int length); // +(int)parseHexDigit:(unichar)c; [Static] [Export ("parseHexDigit:")] int ParseHexDigit (ushort c); // -(NSMutableDictionary *)parseNameValuePairs:(NSString *)uri; [Export ("parseNameValuePairs:")] NSMutableDictionary ParseNameValuePairs (string uri); // +(NSString *)urlDecode:(NSString *)encoded; [Static] [Export ("urlDecode:")] string UrlDecode (string encoded); // +(NSArray *)matchPrefixedField:(NSString *)prefix rawText:(NSString *)rawText endChar:(unichar)endChar trim:(BOOL)trim; [Static] [Export ("matchPrefixedField:rawText:endChar:trim:")] NSObject[] MatchPrefixedField (string prefix, string rawText, ushort endChar, bool trim); // +(NSString *)matchSinglePrefixedField:(NSString *)prefix rawText:(NSString *)rawText endChar:(unichar)endChar trim:(BOOL)trim; [Static] [Export ("matchSinglePrefixedField:rawText:endChar:trim:")] string MatchSinglePrefixedField (string prefix, string rawText, ushort endChar, bool trim); } // @interface ZXAddressBookAUResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXAddressBookAUResultParser { } // @interface ZXAbstractDoCoMoResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXAbstractDoCoMoResultParser { // +(NSArray *)matchDoCoMoPrefixedField:(NSString *)prefix rawText:(NSString *)rawText trim:(BOOL)trim; [Static] [Export ("matchDoCoMoPrefixedField:rawText:trim:")] NSObject[] MatchDoCoMoPrefixedField (string prefix, string rawText, bool trim); // +(NSString *)matchSingleDoCoMoPrefixedField:(NSString *)prefix rawText:(NSString *)rawText trim:(BOOL)trim; [Static] [Export ("matchSingleDoCoMoPrefixedField:rawText:trim:")] string MatchSingleDoCoMoPrefixedField (string prefix, string rawText, bool trim); } // @interface ZXAddressBookDoCoMoResultParser : ZXAbstractDoCoMoResultParser [BaseType (typeof(ZXAbstractDoCoMoResultParser))] interface ZXAddressBookDoCoMoResultParser { } // @interface ZXParsedResult : NSObject [BaseType (typeof(NSObject))] interface ZXParsedResult { // @property (readonly, assign, nonatomic) ZXParsedResultType type; [Export ("type", ArgumentSemantic.Assign)] ZXParsedResultType Type { get; } // -(id)initWithType:(ZXParsedResultType)type; [Export ("initWithType:")] IntPtr Constructor (ZXParsedResultType type); // +(id)parsedResultWithType:(ZXParsedResultType)type; [Static] [Export ("parsedResultWithType:")] NSObject ParsedResultWithType (ZXParsedResultType type); // -(NSString *)displayResult; [Export ("displayResult")] string DisplayResult { get; } // +(void)maybeAppend:(NSString *)value result:(NSMutableString *)result; [Static] [Export ("maybeAppend:result:")] void MaybeAppend (string value, NSMutableString result); // +(void)maybeAppendArray:(NSArray *)value result:(NSMutableString *)result; [Static] [Export ("maybeAppendArray:result:")] void MaybeAppendArray (NSObject[] value, NSMutableString result); } // @interface ZXAddressBookParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXAddressBookParsedResult { // @property (readonly, nonatomic, strong) NSArray * names; [Export ("names", ArgumentSemantic.Strong)] NSObject[] Names { get; } // @property (readonly, nonatomic, strong) NSArray * nicknames; [Export ("nicknames", ArgumentSemantic.Strong)] NSObject[] Nicknames { get; } // @property (readonly, copy, nonatomic) NSString * pronunciation; [Export ("pronunciation")] string Pronunciation { get; } // @property (readonly, nonatomic, strong) NSArray * phoneNumbers; [Export ("phoneNumbers", ArgumentSemantic.Strong)] NSObject[] PhoneNumbers { get; } // @property (readonly, nonatomic, strong) NSArray * phoneTypes; [Export ("phoneTypes", ArgumentSemantic.Strong)] NSObject[] PhoneTypes { get; } // @property (readonly, nonatomic, strong) NSArray * emails; [Export ("emails", ArgumentSemantic.Strong)] NSObject[] Emails { get; } // @property (readonly, nonatomic, strong) NSArray * emailTypes; [Export ("emailTypes", ArgumentSemantic.Strong)] NSObject[] EmailTypes { get; } // @property (readonly, copy, nonatomic) NSString * instantMessenger; [Export ("instantMessenger")] string InstantMessenger { get; } // @property (readonly, copy, nonatomic) NSString * note; [Export ("note")] string Note { get; } // @property (readonly, nonatomic, strong) NSArray * addresses; [Export ("addresses", ArgumentSemantic.Strong)] NSObject[] Addresses { get; } // @property (readonly, nonatomic, strong) NSArray * addressTypes; [Export ("addressTypes", ArgumentSemantic.Strong)] NSObject[] AddressTypes { get; } // @property (readonly, copy, nonatomic) NSString * title; [Export ("title")] string Title { get; } // @property (readonly, copy, nonatomic) NSString * org; [Export ("org")] string Org { get; } // @property (readonly, nonatomic, strong) NSArray * urls; [Export ("urls", ArgumentSemantic.Strong)] NSObject[] Urls { get; } // @property (readonly, copy, nonatomic) NSString * birthday; [Export ("birthday")] string Birthday { get; } // @property (readonly, nonatomic, strong) NSArray * geo; [Export ("geo", ArgumentSemantic.Strong)] NSObject[] Geo { get; } // -(id)initWithNames:(NSArray *)names phoneNumbers:(NSArray *)phoneNumbers phoneTypes:(NSArray *)phoneTypes emails:(NSArray *)emails emailTypes:(NSArray *)emailTypes addresses:(NSArray *)addresses addressTypes:(NSArray *)addressTypes; [Export ("initWithNames:phoneNumbers:phoneTypes:emails:emailTypes:addresses:addressTypes:")] IntPtr Constructor (NSObject[] names, NSObject[] phoneNumbers, NSObject[] phoneTypes, NSObject[] emails, NSObject[] emailTypes, NSObject[] addresses, NSObject[] addressTypes); // -(id)initWithNames:(NSArray *)names nicknames:(NSArray *)nicknames pronunciation:(NSString *)pronunciation phoneNumbers:(NSArray *)phoneNumbers phoneTypes:(NSArray *)phoneTypes emails:(NSArray *)emails emailTypes:(NSArray *)emailTypes instantMessenger:(NSString *)instantMessenger note:(NSString *)note addresses:(NSArray *)addresses addressTypes:(NSArray *)addressTypes org:(NSString *)org birthday:(NSString *)birthday title:(NSString *)title urls:(NSArray *)urls geo:(NSArray *)geo; [Export ("initWithNames:nicknames:pronunciation:phoneNumbers:phoneTypes:emails:emailTypes:instantMessenger:note:addresses:addressTypes:org:birthday:title:urls:geo:")] IntPtr Constructor (NSObject[] names, NSObject[] nicknames, string pronunciation, NSObject[] phoneNumbers, NSObject[] phoneTypes, NSObject[] emails, NSObject[] emailTypes, string instantMessenger, string note, NSObject[] addresses, NSObject[] addressTypes, string org, string birthday, string title, NSObject[] urls, NSObject[] geo); // +(id)addressBookParsedResultWithNames:(NSArray *)names phoneNumbers:(NSArray *)phoneNumbers phoneTypes:(NSArray *)phoneTypes emails:(NSArray *)emails emailTypes:(NSArray *)emailTypes addresses:(NSArray *)addresses addressTypes:(NSArray *)addressTypes; [Static] [Export ("addressBookParsedResultWithNames:phoneNumbers:phoneTypes:emails:emailTypes:addresses:addressTypes:")] NSObject AddressBookParsedResultWithNames (NSObject[] names, NSObject[] phoneNumbers, NSObject[] phoneTypes, NSObject[] emails, NSObject[] emailTypes, NSObject[] addresses, NSObject[] addressTypes); // +(id)addressBookParsedResultWithNames:(NSArray *)names nicknames:(NSArray *)nicknames pronunciation:(NSString *)pronunciation phoneNumbers:(NSArray *)phoneNumbers phoneTypes:(NSArray *)phoneTypes emails:(NSArray *)emails emailTypes:(NSArray *)emailTypes instantMessenger:(NSString *)instantMessenger note:(NSString *)note addresses:(NSArray *)addresses addressTypes:(NSArray *)addressTypes org:(NSString *)org birthday:(NSString *)birthday title:(NSString *)title urls:(NSArray *)urls geo:(NSArray *)geo; [Static] [Export ("addressBookParsedResultWithNames:nicknames:pronunciation:phoneNumbers:phoneTypes:emails:emailTypes:instantMessenger:note:addresses:addressTypes:org:birthday:title:urls:geo:")] NSObject AddressBookParsedResultWithNames (NSObject[] names, NSObject[] nicknames, string pronunciation, NSObject[] phoneNumbers, NSObject[] phoneTypes, NSObject[] emails, NSObject[] emailTypes, string instantMessenger, string note, NSObject[] addresses, NSObject[] addressTypes, string org, string birthday, string title, NSObject[] urls, NSObject[] geo); } // @interface ZXBizcardResultParser : ZXAbstractDoCoMoResultParser [BaseType (typeof(ZXAbstractDoCoMoResultParser))] interface ZXBizcardResultParser { } // @interface ZXBookmarkDoCoMoResultParser : ZXAbstractDoCoMoResultParser [BaseType (typeof(ZXAbstractDoCoMoResultParser))] interface ZXBookmarkDoCoMoResultParser { } // @interface ZXCalendarParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXCalendarParsedResult { // @property (readonly, copy, nonatomic) NSString * summary; [Export ("summary")] string Summary { get; } // @property (readonly, nonatomic, strong) NSDate * start; [Export ("start", ArgumentSemantic.Strong)] NSDate Start { get; } // @property (readonly, assign, nonatomic) BOOL startAllDay; [Export ("startAllDay")] bool StartAllDay { get; } // @property (readonly, nonatomic, strong) NSDate * end; [Export ("end", ArgumentSemantic.Strong)] NSDate End { get; } // @property (readonly, assign, nonatomic) BOOL endAllDay; [Export ("endAllDay")] bool EndAllDay { get; } // @property (readonly, copy, nonatomic) NSString * location; [Export ("location")] string Location { get; } // @property (readonly, copy, nonatomic) NSString * organizer; [Export ("organizer")] string Organizer { get; } // @property (readonly, nonatomic, strong) NSArray * attendees; [Export ("attendees", ArgumentSemantic.Strong)] NSObject[] Attendees { get; } // @property (readonly, copy, nonatomic) NSString * resultDescription; [Export ("resultDescription")] string ResultDescription { get; } // @property (readonly, assign, nonatomic) double latitude; [Export ("latitude")] double Latitude { get; } // @property (readonly, assign, nonatomic) double longitude; [Export ("longitude")] double Longitude { get; } // -(id)initWithSummary:(NSString *)summary startString:(NSString *)startString endString:(NSString *)endString durationString:(NSString *)durationString location:(NSString *)location organizer:(NSString *)organizer attendees:(NSArray *)attendees description:(NSString *)description latitude:(double)latitude longitude:(double)longitude; [Export ("initWithSummary:startString:endString:durationString:location:organizer:attendees:description:latitude:longitude:")] IntPtr Constructor (string summary, string startString, string endString, string durationString, string location, string organizer, NSObject[] attendees, string description, double latitude, double longitude); // +(id)calendarParsedResultWithSummary:(NSString *)summary startString:(NSString *)startString endString:(NSString *)endString durationString:(NSString *)durationString location:(NSString *)location organizer:(NSString *)organizer attendees:(NSArray *)attendees description:(NSString *)description latitude:(double)latitude longitude:(double)longitude; [Static] [Export ("calendarParsedResultWithSummary:startString:endString:durationString:location:organizer:attendees:description:latitude:longitude:")] NSObject CalendarParsedResultWithSummary (string summary, string startString, string endString, string durationString, string location, string organizer, NSObject[] attendees, string description, double latitude, double longitude); } // @interface ZXEmailAddressParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXEmailAddressParsedResult { // @property (readonly, copy, nonatomic) NSArray * tos; [Export ("tos", ArgumentSemantic.Copy)] NSObject[] Tos { get; } // @property (readonly, copy, nonatomic) NSArray * ccs; [Export ("ccs", ArgumentSemantic.Copy)] NSObject[] Ccs { get; } // @property (readonly, copy, nonatomic) NSArray * bccs; [Export ("bccs", ArgumentSemantic.Copy)] NSObject[] Bccs { get; } // @property (readonly, copy, nonatomic) NSString * subject; [Export ("subject")] string Subject { get; } // @property (readonly, copy, nonatomic) NSString * body; [Export ("body")] string Body { get; } // @property (readonly, copy, nonatomic) NSString * emailAddress __attribute__((deprecated(""))); [Export ("emailAddress")] string EmailAddress { get; } // @property (readonly, copy, nonatomic) NSString * mailtoURI __attribute__((deprecated(""))); [Export ("mailtoURI")] string MailtoURI { get; } // -(id)initWithTo:(NSString *)to; [Export ("initWithTo:")] IntPtr Constructor (string to); // -(id)initWithTos:(NSArray *)tos ccs:(NSArray *)ccs bccs:(NSArray *)bccs subject:(NSString *)subject body:(NSString *)body; [Export ("initWithTos:ccs:bccs:subject:body:")] IntPtr Constructor (NSObject[] tos, NSObject[] ccs, NSObject[] bccs, string subject, string body); } // @interface ZXEmailAddressResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXEmailAddressResultParser { } // @interface ZXEmailDoCoMoResultParser : ZXAbstractDoCoMoResultParser [BaseType (typeof(ZXAbstractDoCoMoResultParser))] interface ZXEmailDoCoMoResultParser { // +(BOOL)isBasicallyValidEmailAddress:(NSString *)email; [Static] [Export ("isBasicallyValidEmailAddress:")] bool IsBasicallyValidEmailAddress (string email); } // @interface ZXExpandedProductParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXExpandedProductParsedResult { // @property (readonly, copy, nonatomic) NSString * rawText; [Export ("rawText")] string RawText { get; } // @property (readonly, copy, nonatomic) NSString * productID; [Export ("productID")] string ProductID { get; } // @property (readonly, copy, nonatomic) NSString * sscc; [Export ("sscc")] string Sscc { get; } // @property (readonly, copy, nonatomic) NSString * lotNumber; [Export ("lotNumber")] string LotNumber { get; } // @property (readonly, copy, nonatomic) NSString * productionDate; [Export ("productionDate")] string ProductionDate { get; } // @property (readonly, copy, nonatomic) NSString * packagingDate; [Export ("packagingDate")] string PackagingDate { get; } // @property (readonly, copy, nonatomic) NSString * bestBeforeDate; [Export ("bestBeforeDate")] string BestBeforeDate { get; } // @property (readonly, copy, nonatomic) NSString * expirationDate; [Export ("expirationDate")] string ExpirationDate { get; } // @property (readonly, copy, nonatomic) NSString * weight; [Export ("weight")] string Weight { get; } // @property (readonly, copy, nonatomic) NSString * weightType; [Export ("weightType")] string WeightType { get; } // @property (readonly, copy, nonatomic) NSString * weightIncrement; [Export ("weightIncrement")] string WeightIncrement { get; } // @property (readonly, copy, nonatomic) NSString * price; [Export ("price")] string Price { get; } // @property (readonly, copy, nonatomic) NSString * priceIncrement; [Export ("priceIncrement")] string PriceIncrement { get; } // @property (readonly, copy, nonatomic) NSString * priceCurrency; [Export ("priceCurrency")] string PriceCurrency { get; } // @property (readonly, nonatomic, strong) NSMutableDictionary * uncommonAIs; [Export ("uncommonAIs", ArgumentSemantic.Strong)] NSMutableDictionary UncommonAIs { get; } // -(id)initWithRawText:(NSString *)rawText productID:(NSString *)productID sscc:(NSString *)sscc lotNumber:(NSString *)lotNumber productionDate:(NSString *)productionDate packagingDate:(NSString *)packagingDate bestBeforeDate:(NSString *)bestBeforeDate expirationDate:(NSString *)expirationDate weight:(NSString *)weight weightType:(NSString *)weightType weightIncrement:(NSString *)weightIncrement price:(NSString *)price priceIncrement:(NSString *)priceIncrement priceCurrency:(NSString *)priceCurrency uncommonAIs:(NSMutableDictionary *)uncommonAIs; [Export ("initWithRawText:productID:sscc:lotNumber:productionDate:packagingDate:bestBeforeDate:expirationDate:weight:weightType:weightIncrement:price:priceIncrement:priceCurrency:uncommonAIs:")] IntPtr Constructor (string rawText, string productID, string sscc, string lotNumber, string productionDate, string packagingDate, string bestBeforeDate, string expirationDate, string weight, string weightType, string weightIncrement, string price, string priceIncrement, string priceCurrency, NSMutableDictionary uncommonAIs); // +(id)expandedProductParsedResultWithRawText:(NSString *)rawText productID:(NSString *)productID sscc:(NSString *)sscc lotNumber:(NSString *)lotNumber productionDate:(NSString *)productionDate packagingDate:(NSString *)packagingDate bestBeforeDate:(NSString *)bestBeforeDate expirationDate:(NSString *)expirationDate weight:(NSString *)weight weightType:(NSString *)weightType weightIncrement:(NSString *)weightIncrement price:(NSString *)price priceIncrement:(NSString *)priceIncrement priceCurrency:(NSString *)priceCurrency uncommonAIs:(NSMutableDictionary *)uncommonAIs; [Static] [Export ("expandedProductParsedResultWithRawText:productID:sscc:lotNumber:productionDate:packagingDate:bestBeforeDate:expirationDate:weight:weightType:weightIncrement:price:priceIncrement:priceCurrency:uncommonAIs:")] NSObject ExpandedProductParsedResultWithRawText (string rawText, string productID, string sscc, string lotNumber, string productionDate, string packagingDate, string bestBeforeDate, string expirationDate, string weight, string weightType, string weightIncrement, string price, string priceIncrement, string priceCurrency, NSMutableDictionary uncommonAIs); } // @interface ZXExpandedProductResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXExpandedProductResultParser { } // @interface ZXGeoParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXGeoParsedResult { // @property (readonly, assign, nonatomic) double latitude; [Export ("latitude")] double Latitude { get; } // @property (readonly, assign, nonatomic) double longitude; [Export ("longitude")] double Longitude { get; } // @property (readonly, assign, nonatomic) double altitude; [Export ("altitude")] double Altitude { get; } // @property (readonly, copy, nonatomic) NSString * query; [Export ("query")] string Query { get; } // -(id)initWithLatitude:(double)latitude longitude:(double)longitude altitude:(double)altitude query:(NSString *)query; [Export ("initWithLatitude:longitude:altitude:query:")] IntPtr Constructor (double latitude, double longitude, double altitude, string query); // +(id)geoParsedResultWithLatitude:(double)latitude longitude:(double)longitude altitude:(double)altitude query:(NSString *)query; [Static] [Export ("geoParsedResultWithLatitude:longitude:altitude:query:")] NSObject GeoParsedResultWithLatitude (double latitude, double longitude, double altitude, string query); // -(NSString *)geoURI; [Export ("geoURI")] string GeoURI { get; } } // @interface ZXGeoResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXGeoResultParser { } // @interface ZXISBNParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXISBNParsedResult { // @property (readonly, copy, nonatomic) NSString * isbn; [Export ("isbn")] string Isbn { get; } // -(id)initWithIsbn:(NSString *)isbn; [Export ("initWithIsbn:")] IntPtr Constructor (string isbn); // +(id)isbnParsedResultWithIsbn:(NSString *)isbn; [Static] [Export ("isbnParsedResultWithIsbn:")] NSObject IsbnParsedResultWithIsbn (string isbn); } // @interface ZXISBNResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXISBNResultParser { } // @interface ZXProductParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXProductParsedResult { // @property (readonly, copy, nonatomic) NSString * normalizedProductID; [Export ("normalizedProductID")] string NormalizedProductID { get; } // @property (readonly, copy, nonatomic) NSString * productID; [Export ("productID")] string ProductID { get; } // -(id)initWithProductID:(NSString *)productID; [Export ("initWithProductID:")] IntPtr Constructor (string productID); // -(id)initWithProductID:(NSString *)productID normalizedProductID:(NSString *)normalizedProductID; [Export ("initWithProductID:normalizedProductID:")] IntPtr Constructor (string productID, string normalizedProductID); // +(id)productParsedResultWithProductID:(NSString *)productID; [Static] [Export ("productParsedResultWithProductID:")] NSObject ProductParsedResultWithProductID (string productID); // +(id)productParsedResultWithProductID:(NSString *)productID normalizedProductID:(NSString *)normalizedProductID; [Static] [Export ("productParsedResultWithProductID:normalizedProductID:")] NSObject ProductParsedResultWithProductID (string productID, string normalizedProductID); } // @interface ZXProductResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXProductResultParser { } // @interface ZXSMSMMSResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXSMSMMSResultParser { } // @interface ZXSMSParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXSMSParsedResult { // @property (readonly, nonatomic, strong) NSArray * numbers; [Export ("numbers", ArgumentSemantic.Strong)] NSObject[] Numbers { get; } // @property (readonly, nonatomic, strong) NSArray * vias; [Export ("vias", ArgumentSemantic.Strong)] NSObject[] Vias { get; } // @property (readonly, copy, nonatomic) NSString * subject; [Export ("subject")] string Subject { get; } // @property (readonly, copy, nonatomic) NSString * body; [Export ("body")] string Body { get; } // -(id)initWithNumber:(NSString *)number via:(NSString *)via subject:(NSString *)subject body:(NSString *)body; [Export ("initWithNumber:via:subject:body:")] IntPtr Constructor (string number, string via, string subject, string body); // -(id)initWithNumbers:(NSArray *)numbers vias:(NSArray *)vias subject:(NSString *)subject body:(NSString *)body; [Export ("initWithNumbers:vias:subject:body:")] IntPtr Constructor (NSObject[] numbers, NSObject[] vias, string subject, string body); // +(id)smsParsedResultWithNumber:(NSString *)number via:(NSString *)via subject:(NSString *)subject body:(NSString *)body; [Static] [Export ("smsParsedResultWithNumber:via:subject:body:")] NSObject SmsParsedResultWithNumber (string number, string via, string subject, string body); // +(id)smsParsedResultWithNumbers:(NSArray *)numbers vias:(NSArray *)vias subject:(NSString *)subject body:(NSString *)body; [Static] [Export ("smsParsedResultWithNumbers:vias:subject:body:")] NSObject SmsParsedResultWithNumbers (NSObject[] numbers, NSObject[] vias, string subject, string body); // -(NSString *)sMSURI; [Export ("sMSURI")] string SMSURI { get; } } // @interface ZXSMSTOMMSTOResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXSMSTOMMSTOResultParser { } // @interface ZXSMTPResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXSMTPResultParser { } // @interface ZXTelParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXTelParsedResult { // @property (readonly, copy, nonatomic) NSString * number; [Export ("number")] string Number { get; } // @property (readonly, copy, nonatomic) NSString * telURI; [Export ("telURI")] string TelURI { get; } // @property (readonly, copy, nonatomic) NSString * title; [Export ("title")] string Title { get; } // -(id)initWithNumber:(NSString *)number telURI:(NSString *)telURI title:(NSString *)title; [Export ("initWithNumber:telURI:title:")] IntPtr Constructor (string number, string telURI, string title); // +(id)telParsedResultWithNumber:(NSString *)number telURI:(NSString *)telURI title:(NSString *)title; [Static] [Export ("telParsedResultWithNumber:telURI:title:")] NSObject TelParsedResultWithNumber (string number, string telURI, string title); } // @interface ZXTelResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXTelResultParser { } // @interface ZXTextParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXTextParsedResult { // @property (readonly, copy, nonatomic) NSString * text; [Export ("text")] string Text { get; } // @property (readonly, copy, nonatomic) NSString * language; [Export ("language")] string Language { get; } // -(id)initWithText:(NSString *)text language:(NSString *)language; [Export ("initWithText:language:")] IntPtr Constructor (string text, string language); // +(id)textParsedResultWithText:(NSString *)text language:(NSString *)language; [Static] [Export ("textParsedResultWithText:language:")] NSObject TextParsedResultWithText (string text, string language); } // @interface ZXURIParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXURIParsedResult { // @property (readonly, copy, nonatomic) NSString * uri; [Export ("uri")] string Uri { get; } // @property (readonly, copy, nonatomic) NSString * title; [Export ("title")] string Title { get; } // -(id)initWithUri:(NSString *)uri title:(NSString *)title; [Export ("initWithUri:title:")] IntPtr Constructor (string uri, string title); // +(id)uriParsedResultWithUri:(NSString *)uri title:(NSString *)title; [Static] [Export ("uriParsedResultWithUri:title:")] NSObject UriParsedResultWithUri (string uri, string title); // -(BOOL)possiblyMaliciousURI; [Export ("possiblyMaliciousURI")] bool PossiblyMaliciousURI { get; } } // @interface ZXURIResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXURIResultParser { // +(BOOL)isBasicallyValidURI:(NSString *)uri; [Static] [Export ("isBasicallyValidURI:")] bool IsBasicallyValidURI (string uri); } // @interface ZXURLTOResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXURLTOResultParser { } // @interface ZXVCardResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXVCardResultParser { // +(NSArray *)matchSingleVCardPrefixedField:(NSString *)prefix rawText:(NSString *)rawText trim:(BOOL)trim parseFieldDivider:(BOOL)parseFieldDivider; [Static] [Export ("matchSingleVCardPrefixedField:rawText:trim:parseFieldDivider:")] NSObject[] MatchSingleVCardPrefixedField (string prefix, string rawText, bool trim, bool parseFieldDivider); // +(NSMutableArray *)matchVCardPrefixedField:(NSString *)prefix rawText:(NSString *)rawText trim:(BOOL)trim parseFieldDivider:(BOOL)parseFieldDivider; [Static] [Export ("matchVCardPrefixedField:rawText:trim:parseFieldDivider:")] NSMutableArray MatchVCardPrefixedField (string prefix, string rawText, bool trim, bool parseFieldDivider); } // @interface ZXVEventResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXVEventResultParser { } // @interface ZXVINParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXVINParsedResult { // @property (readonly, copy, nonatomic) NSString * vin; [Export ("vin")] string Vin { get; } // @property (readonly, copy, nonatomic) NSString * worldManufacturerID; [Export ("worldManufacturerID")] string WorldManufacturerID { get; } // @property (readonly, copy, nonatomic) NSString * vehicleDescriptorSection; [Export ("vehicleDescriptorSection")] string VehicleDescriptorSection { get; } // @property (readonly, copy, nonatomic) NSString * vehicleIdentifierSection; [Export ("vehicleIdentifierSection")] string VehicleIdentifierSection { get; } // @property (readonly, copy, nonatomic) NSString * countryCode; [Export ("countryCode")] string CountryCode { get; } // @property (readonly, copy, nonatomic) NSString * vehicleAttributes; [Export ("vehicleAttributes")] string VehicleAttributes { get; } // @property (readonly, assign, nonatomic) int modelYear; [Export ("modelYear")] int ModelYear { get; } // @property (readonly, assign, nonatomic) unichar plantCode; [Export ("plantCode")] ushort PlantCode { get; } // @property (readonly, copy, nonatomic) NSString * sequentialNumber; [Export ("sequentialNumber")] string SequentialNumber { get; } // -(id)initWithVIN:(NSString *)vin worldManufacturerID:(NSString *)worldManufacturerID vehicleDescriptorSection:(NSString *)vehicleDescriptorSection vehicleIdentifierSection:(NSString *)vehicleIdentifierSection countryCode:(NSString *)countryCode vehicleAttributes:(NSString *)vehicleAttributes modelYear:(int)modelYear plantCode:(unichar)plantCode sequentialNumber:(NSString *)sequentialNumber; [Export ("initWithVIN:worldManufacturerID:vehicleDescriptorSection:vehicleIdentifierSection:countryCode:vehicleAttributes:modelYear:plantCode:sequentialNumber:")] IntPtr Constructor (string vin, string worldManufacturerID, string vehicleDescriptorSection, string vehicleIdentifierSection, string countryCode, string vehicleAttributes, int modelYear, ushort plantCode, string sequentialNumber); } // @interface ZXVINResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXVINResultParser { } // @interface ZXWifiParsedResult : ZXParsedResult [BaseType (typeof(ZXParsedResult))] interface ZXWifiParsedResult { // @property (readonly, copy, nonatomic) NSString * ssid; [Export ("ssid")] string Ssid { get; } // @property (readonly, copy, nonatomic) NSString * networkEncryption; [Export ("networkEncryption")] string NetworkEncryption { get; } // @property (readonly, copy, nonatomic) NSString * password; [Export ("password")] string Password { get; } // @property (readonly, assign, nonatomic) BOOL hidden; [Export ("hidden")] bool Hidden { get; } // -(id)initWithNetworkEncryption:(NSString *)networkEncryption ssid:(NSString *)ssid password:(NSString *)password; [Export ("initWithNetworkEncryption:ssid:password:")] IntPtr Constructor (string networkEncryption, string ssid, string password); // -(id)initWithNetworkEncryption:(NSString *)networkEncryption ssid:(NSString *)ssid password:(NSString *)password hidden:(BOOL)hidden; [Export ("initWithNetworkEncryption:ssid:password:hidden:")] IntPtr Constructor (string networkEncryption, string ssid, string password, bool hidden); // +(id)wifiParsedResultWithNetworkEncryption:(NSString *)networkEncryption ssid:(NSString *)ssid password:(NSString *)password; [Static] [Export ("wifiParsedResultWithNetworkEncryption:ssid:password:")] NSObject WifiParsedResultWithNetworkEncryption (string networkEncryption, string ssid, string password); // +(id)wifiParsedResultWithNetworkEncryption:(NSString *)networkEncryption ssid:(NSString *)ssid password:(NSString *)password hidden:(BOOL)hidden; [Static] [Export ("wifiParsedResultWithNetworkEncryption:ssid:password:hidden:")] NSObject WifiParsedResultWithNetworkEncryption (string networkEncryption, string ssid, string password, bool hidden); } // @interface ZXWifiResultParser : ZXResultParser [BaseType (typeof(ZXResultParser))] interface ZXWifiResultParser { } [BaseType(typeof(NSObject))] interface ZXModulusPoly { } // @interface ZXModulusGF : NSObject [BaseType (typeof(NSObject))] interface ZXModulusGF { // @property (readonly, nonatomic, strong) ZXModulusPoly * one; [Export ("one", ArgumentSemantic.Strong)] ZXModulusPoly One { get; } // @property (readonly, nonatomic, strong) ZXModulusPoly * zero; [Export ("zero", ArgumentSemantic.Strong)] ZXModulusPoly Zero { get; } // +(ZXModulusGF *)PDF417_GF; [Static] [Export ("PDF417_GF")] ZXModulusGF PDF417_GF { get; } // -(id)initWithModulus:(int)modulus generator:(int)generator; [Export ("initWithModulus:generator:")] IntPtr Constructor (int modulus, int generator); // -(ZXModulusPoly *)buildMonomial:(int)degree coefficient:(int)coefficient; [Export ("buildMonomial:coefficient:")] ZXModulusPoly BuildMonomial (int degree, int coefficient); // -(int)add:(int)a b:(int)b; [Export ("add:b:")] int Add (int a, int b); // -(int)subtract:(int)a b:(int)b; [Export ("subtract:b:")] int Subtract (int a, int b); // -(int)exp:(int)a; [Export ("exp:")] int Exp (int a); // -(int)log:(int)a; [Export ("log:")] int Log (int a); // -(int)inverse:(int)a; [Export ("inverse:")] int Inverse (int a); // -(int)multiply:(int)a b:(int)b; [Export ("multiply:b:")] int Multiply (int a, int b); // -(int)size; [Export ("size")] int Size { get; } } // @interface ZXPDF417 : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417 { // @property (readonly, nonatomic, strong) ZXPDF417BarcodeMatrix * barcodeMatrix; [Export ("barcodeMatrix", ArgumentSemantic.Strong)] ZXPDF417BarcodeMatrix BarcodeMatrix { get; } // @property (assign, nonatomic) BOOL compact; [Export ("compact")] bool Compact { get; set; } // @property (assign, nonatomic) ZXPDF417Compaction compaction; [Export ("compaction", ArgumentSemantic.Assign)] ZXPDF417Compaction Compaction { get; set; } // @property (assign, nonatomic) NSStringEncoding encoding; [Export ("encoding")] nuint Encoding { get; set; } // -(id)initWithCompact:(BOOL)compact; [Export ("initWithCompact:")] IntPtr Constructor (bool compact); // -(BOOL)generateBarcodeLogic:(NSString *)msg errorCorrectionLevel:(int)errorCorrectionLevel error:(NSError **)error; [Export ("generateBarcodeLogic:errorCorrectionLevel:error:")] bool GenerateBarcodeLogic (string msg, int errorCorrectionLevel, out NSError error); // -(ZXIntArray *)determineDimensions:(int)sourceCodeWords errorCorrectionCodeWords:(int)errorCorrectionCodeWords error:(NSError **)error; [Export ("determineDimensions:errorCorrectionCodeWords:error:")] ZXIntArray DetermineDimensions (int sourceCodeWords, int errorCorrectionCodeWords, out NSError error); // -(void)setDimensionsWithMaxCols:(int)maxCols minCols:(int)minCols maxRows:(int)maxRows minRows:(int)minRows; [Export ("setDimensionsWithMaxCols:minCols:maxRows:minRows:")] void SetDimensionsWithMaxCols (int maxCols, int minCols, int maxRows, int minRows); } [BaseType(typeof(NSObject))] interface ZXPDF417BarcodeRow { } // @interface ZXPDF417BarcodeMatrix : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417BarcodeMatrix { // @property (readonly, assign, nonatomic) int height; [Export ("height")] int Height { get; } // @property (readonly, assign, nonatomic) int width; [Export ("width")] int Width { get; } // -(id)initWithHeight:(int)height width:(int)width; [Export ("initWithHeight:width:")] IntPtr Constructor (int height, int width); // -(void)startRow; [Export ("startRow")] void StartRow (); // -(ZXPDF417BarcodeRow *)currentRow; [Export ("currentRow")] ZXPDF417BarcodeRow CurrentRow { get; } // -(NSArray *)matrix; [Export ("matrix")] NSObject[] Matrix { get; } // -(NSArray *)scaledMatrixWithXScale:(int)xScale yScale:(int)yScale; [Export ("scaledMatrixWithXScale:yScale:")] NSObject[] ScaledMatrixWithXScale (int xScale, int yScale); } // @interface ZXPDF417Common : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417Common { // +(int)bitCountSum:(NSArray *)moduleBitCount; [Static] [Export ("bitCountSum:")] int BitCountSum (NSObject[] moduleBitCount); // +(ZXIntArray *)toIntArray:(NSArray *)list; [Static] [Export ("toIntArray:")] ZXIntArray ToIntArray (NSObject[] list); // +(int)codeword:(int)symbol; [Static] [Export ("codeword:")] int Codeword (int symbol); } // @interface ZXPDF417Detector : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417Detector { // +(ZXPDF417DetectorResult *)detect:(ZXBinaryBitmap *)image hints:(ZXDecodeHints *)hints multiple:(BOOL)multiple error:(NSError **)error; [Static] [Export ("detect:hints:multiple:error:")] ZXPDF417DetectorResult Detect (ZXBinaryBitmap image, ZXDecodeHints hints, bool multiple, out NSError error); } // @interface ZXPDF417DetectorResult : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417DetectorResult { // @property (readonly, nonatomic, strong) ZXBitMatrix * bits; [Export ("bits", ArgumentSemantic.Strong)] ZXBitMatrix Bits { get; } // @property (readonly, nonatomic, strong) NSArray * points; [Export ("points", ArgumentSemantic.Strong)] NSObject[] Points { get; } // -(id)initWithBits:(ZXBitMatrix *)bits points:(NSArray *)points; [Export ("initWithBits:points:")] IntPtr Constructor (ZXBitMatrix bits, NSObject[] points); } // @interface ZXPDF417Dimensions : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417Dimensions { // @property (readonly, assign, nonatomic) int minCols; [Export ("minCols")] int MinCols { get; } // @property (readonly, assign, nonatomic) int maxCols; [Export ("maxCols")] int MaxCols { get; } // @property (readonly, assign, nonatomic) int minRows; [Export ("minRows")] int MinRows { get; } // @property (readonly, assign, nonatomic) int maxRows; [Export ("maxRows")] int MaxRows { get; } // -(id)initWithMinCols:(int)minCols maxCols:(int)maxCols minRows:(int)minRows maxRows:(int)maxRows; [Export ("initWithMinCols:maxCols:minRows:maxRows:")] IntPtr Constructor (int minCols, int maxCols, int minRows, int maxRows); } // @interface ZXPDF417ECErrorCorrection : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417ECErrorCorrection { // -(int)decode:(ZXIntArray *)received numECCodewords:(int)numECCodewords erasures:(ZXIntArray *)erasures; [Export ("decode:numECCodewords:erasures:")] int Decode (ZXIntArray received, int numECCodewords, ZXIntArray erasures); } // @interface ZXPDF417Reader : NSObject <ZXReader, ZXMultipleBarcodeReader> [BaseType (typeof(NSObject))] interface ZXPDF417Reader : ZXReader, IZXMultipleBarcodeReader { // -(NSArray *)decodeMultiple:(ZXBinaryBitmap *)image error:(NSError **)error; [Export ("decodeMultiple:error:")] NSObject[] DecodeMultiple (ZXBinaryBitmap image, out NSError error); // -(NSArray *)decodeMultiple:(ZXBinaryBitmap *)image hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decodeMultiple:hints:error:")] NSObject[] DecodeMultiple (ZXBinaryBitmap image, ZXDecodeHints hints, out NSError error); } // @interface ZXPDF417ResultMetadata : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417ResultMetadata { // @property (assign, nonatomic) int segmentIndex; [Export ("segmentIndex")] int SegmentIndex { get; set; } // @property (copy, nonatomic) NSString * fileId; [Export ("fileId")] string FileId { get; set; } // @property (nonatomic, strong) NSArray * optionalData; [Export ("optionalData", ArgumentSemantic.Strong)] NSObject[] OptionalData { get; set; } // @property (assign, nonatomic) BOOL lastSegment; [Export ("lastSegment")] bool LastSegment { get; set; } } // @interface ZXPDF417ScanningDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXPDF417ScanningDecoder { // +(ZXDecoderResult *)decode:(ZXBitMatrix *)image imageTopLeft:(ZXResultPoint *)imageTopLeft imageBottomLeft:(ZXResultPoint *)imageBottomLeft imageTopRight:(ZXResultPoint *)imageTopRight imageBottomRight:(ZXResultPoint *)imageBottomRight minCodewordWidth:(int)minCodewordWidth maxCodewordWidth:(int)maxCodewordWidth error:(NSError **)error; [Static] [Export ("decode:imageTopLeft:imageBottomLeft:imageTopRight:imageBottomRight:minCodewordWidth:maxCodewordWidth:error:")] ZXDecoderResult Decode (ZXBitMatrix image, ZXResultPoint imageTopLeft, ZXResultPoint imageBottomLeft, ZXResultPoint imageTopRight, ZXResultPoint imageBottomRight, int minCodewordWidth, int maxCodewordWidth, out NSError error); // -(NSString *)description:(NSArray *)barcodeMatrix; [Export ("description:")] string Description (NSObject[] barcodeMatrix); } // @interface ZXPDF417Writer : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXPDF417Writer : ZXWriter { } // @interface ZXQRCodeDetector : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeDetector { // @property (readonly, nonatomic, strong) ZXBitMatrix * image; [Export ("image", ArgumentSemantic.Strong)] ZXBitMatrix Image { get; } // @property (readonly, nonatomic, weak) id<ZXResultPointCallback> resultPointCallback; [Export ("resultPointCallback", ArgumentSemantic.Weak)] ZXResultPointCallback ResultPointCallback { get; } // -(id)initWithImage:(ZXBitMatrix *)image; [Export ("initWithImage:")] IntPtr Constructor (ZXBitMatrix image); // -(ZXDetectorResult *)detectWithError:(NSError **)error; [Export ("detectWithError:")] ZXDetectorResult DetectWithError (out NSError error); // -(ZXDetectorResult *)detect:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("detect:error:")] ZXDetectorResult Detect ([NullAllowed] ZXDecodeHints hints, out NSError error); // -(ZXDetectorResult *)processFinderPatternInfo:(ZXQRCodeFinderPatternInfo *)info error:(NSError **)error; [Export ("processFinderPatternInfo:error:")] ZXDetectorResult ProcessFinderPatternInfo (ZXQRCodeFinderPatternInfo info, out NSError error); // -(float)calculateModuleSize:(ZXResultPoint *)topLeft topRight:(ZXResultPoint *)topRight bottomLeft:(ZXResultPoint *)bottomLeft; [Export ("calculateModuleSize:topRight:bottomLeft:")] float CalculateModuleSize (ZXResultPoint topLeft, ZXResultPoint topRight, ZXResultPoint bottomLeft); // -(ZXQRCodeAlignmentPattern *)findAlignmentInRegion:(float)overallEstModuleSize estAlignmentX:(int)estAlignmentX estAlignmentY:(int)estAlignmentY allowanceFactor:(float)allowanceFactor error:(NSError **)error; [Export ("findAlignmentInRegion:estAlignmentX:estAlignmentY:allowanceFactor:error:")] ZXQRCodeAlignmentPattern FindAlignmentInRegion (float overallEstModuleSize, int estAlignmentX, int estAlignmentY, float allowanceFactor, out NSError error); } // @interface ZXMultiDetector : ZXQRCodeDetector [BaseType (typeof(ZXQRCodeDetector))] [DisableDefaultCtor] interface ZXMultiDetector { [Export("initWithImage:")] IntPtr Constructor(ZXBitMatrix image); // -(NSArray *)detectMulti:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("detectMulti:error:")] ZXDetectorResult[] DetectMulti ([NullAllowed] ZXDecodeHints hints, out NSError error); } // @interface ZXQRCode : NSObject [BaseType (typeof(NSObject))] interface ZXQRCode { // @property (nonatomic, strong) ZXQRCodeMode * mode; [Export ("mode", ArgumentSemantic.Strong)] ZXQRCodeMode Mode { get; set; } // @property (nonatomic, strong) ZXQRCodeErrorCorrectionLevel * ecLevel; [Export ("ecLevel", ArgumentSemantic.Strong)] ZXQRCodeErrorCorrectionLevel EcLevel { get; set; } // @property (nonatomic, strong) ZXQRCodeVersion * version; [Export ("version", ArgumentSemantic.Strong)] ZXQRCodeVersion Version { get; set; } // @property (assign, nonatomic) int maskPattern; [Export ("maskPattern")] int MaskPattern { get; set; } // @property (nonatomic, strong) ZXByteMatrix * matrix; [Export ("matrix", ArgumentSemantic.Strong)] ZXByteMatrix Matrix { get; set; } // +(BOOL)isValidMaskPattern:(int)maskPattern; [Static] [Export ("isValidMaskPattern:")] bool IsValidMaskPattern (int maskPattern); } // @interface ZXQRCodeAlignmentPattern : ZXResultPoint [BaseType (typeof(ZXResultPoint))] interface ZXQRCodeAlignmentPattern { // -(id)initWithPosX:(float)posX posY:(float)posY estimatedModuleSize:(float)estimatedModuleSize; [Export ("initWithPosX:posY:estimatedModuleSize:")] IntPtr Constructor (float posX, float posY, float estimatedModuleSize); // -(BOOL)aboutEquals:(float)moduleSize i:(float)i j:(float)j; [Export ("aboutEquals:i:j:")] bool AboutEquals (float moduleSize, float i, float j); // -(ZXQRCodeAlignmentPattern *)combineEstimateI:(float)i j:(float)j newModuleSize:(float)newModuleSize; [Export ("combineEstimateI:j:newModuleSize:")] ZXQRCodeAlignmentPattern CombineEstimateI (float i, float j, float newModuleSize); } // @interface ZXQRCodeDecoder : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeDecoder { // -(ZXDecoderResult *)decode:(NSArray *)image error:(NSError **)error; [Export ("decode:error:")] ZXDecoderResult Decode (NSObject[] image, out NSError error); // -(ZXDecoderResult *)decode:(NSArray *)image hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decode:hints:error:")] ZXDecoderResult Decode (NSObject[] image, ZXDecodeHints hints, out NSError error); // -(ZXDecoderResult *)decodeMatrix:(ZXBitMatrix *)bits error:(NSError **)error; [Export ("decodeMatrix:error:")] ZXDecoderResult DecodeMatrix (ZXBitMatrix bits, out NSError error); // -(ZXDecoderResult *)decodeMatrix:(ZXBitMatrix *)bits hints:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("decodeMatrix:hints:error:")] ZXDecoderResult DecodeMatrix (ZXBitMatrix bits, ZXDecodeHints hints, out NSError error); } // @interface ZXQRCodeDecoderMetaData : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeDecoderMetaData { // @property (readonly, assign, nonatomic) BOOL mirrored; [Export ("mirrored")] bool Mirrored { get; } // -(id)initWithMirrored:(BOOL)mirrored; [Export ("initWithMirrored:")] IntPtr Constructor (bool mirrored); // -(void)applyMirroredCorrection:(NSMutableArray *)points; [Export ("applyMirroredCorrection:")] void ApplyMirroredCorrection (NSMutableArray points); } // @interface ZXQRCodeEncoder : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeEncoder { // +(ZXQRCode *)encode:(NSString *)content ecLevel:(ZXQRCodeErrorCorrectionLevel *)ecLevel error:(NSError **)error; [Static] [Export ("encode:ecLevel:error:")] ZXQRCode Encode (string content, ZXQRCodeErrorCorrectionLevel ecLevel, out NSError error); // +(ZXQRCode *)encode:(NSString *)content ecLevel:(ZXQRCodeErrorCorrectionLevel *)ecLevel hints:(ZXEncodeHints *)hints error:(NSError **)error; [Static] [Export ("encode:ecLevel:hints:error:")] ZXQRCode Encode (string content, ZXQRCodeErrorCorrectionLevel ecLevel, ZXEncodeHints hints, out NSError error); // +(int)alphanumericCode:(int)code; [Static] [Export ("alphanumericCode:")] int AlphanumericCode (int code); // +(BOOL)terminateBits:(int)numDataBytes bits:(ZXBitArray *)bits error:(NSError **)error; [Static] [Export ("terminateBits:bits:error:")] bool TerminateBits (int numDataBytes, ZXBitArray bits, out NSError error); //// +(BOOL)numDataBytesAndNumECBytesForBlockID:(int)numTotalBytes numDataBytes:(int)numDataBytes numRSBlocks:(int)numRSBlocks blockID:(int)blockID numDataBytesInBlock:(int *)numDataBytesInBlock numECBytesInBlock:(int *)numECBytesInBlock error:(NSError **)error; //[Static] //[Export ("numDataBytesAndNumECBytesForBlockID:numDataBytes:numRSBlocks:blockID:numDataBytesInBlock:numECBytesInBlock:error:")] //bool NumDataBytesAndNumECBytesForBlockID (int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock, out NSError error); // +(ZXBitArray *)interleaveWithECBytes:(ZXBitArray *)bits numTotalBytes:(int)numTotalBytes numDataBytes:(int)numDataBytes numRSBlocks:(int)numRSBlocks error:(NSError **)error; [Static] [Export ("interleaveWithECBytes:numTotalBytes:numDataBytes:numRSBlocks:error:")] ZXBitArray InterleaveWithECBytes (ZXBitArray bits, int numTotalBytes, int numDataBytes, int numRSBlocks, out NSError error); // +(ZXByteArray *)generateECBytes:(ZXByteArray *)dataBytes numEcBytesInBlock:(int)numEcBytesInBlock; [Static] [Export ("generateECBytes:numEcBytesInBlock:")] ZXByteArray GenerateECBytes (ZXByteArray dataBytes, int numEcBytesInBlock); // +(void)appendModeInfo:(ZXQRCodeMode *)mode bits:(ZXBitArray *)bits; [Static] [Export ("appendModeInfo:bits:")] void AppendModeInfo (ZXQRCodeMode mode, ZXBitArray bits); // +(BOOL)appendLengthInfo:(int)numLetters version:(ZXQRCodeVersion *)version mode:(ZXQRCodeMode *)mode bits:(ZXBitArray *)bits error:(NSError **)error; [Static] [Export ("appendLengthInfo:version:mode:bits:error:")] bool AppendLengthInfo (int numLetters, ZXQRCodeVersion version, ZXQRCodeMode mode, ZXBitArray bits, out NSError error); // +(BOOL)appendBytes:(NSString *)content mode:(ZXQRCodeMode *)mode bits:(ZXBitArray *)bits encoding:(NSStringEncoding)encoding error:(NSError **)error; [Static] [Export ("appendBytes:mode:bits:encoding:error:")] bool AppendBytes (string content, ZXQRCodeMode mode, ZXBitArray bits, nuint encoding, out NSError error); // +(void)appendNumericBytes:(NSString *)content bits:(ZXBitArray *)bits; [Static] [Export ("appendNumericBytes:bits:")] void AppendNumericBytes (string content, ZXBitArray bits); // +(BOOL)appendAlphanumericBytes:(NSString *)content bits:(ZXBitArray *)bits error:(NSError **)error; [Static] [Export ("appendAlphanumericBytes:bits:error:")] bool AppendAlphanumericBytes (string content, ZXBitArray bits, out NSError error); // +(void)append8BitBytes:(NSString *)content bits:(ZXBitArray *)bits encoding:(NSStringEncoding)encoding; [Static] [Export ("append8BitBytes:bits:encoding:")] void Append8BitBytes (string content, ZXBitArray bits, nuint encoding); // +(BOOL)appendKanjiBytes:(NSString *)content bits:(ZXBitArray *)bits error:(NSError **)error; [Static] [Export ("appendKanjiBytes:bits:error:")] bool AppendKanjiBytes (string content, ZXBitArray bits, out NSError error); } // @interface ZXQRCodeErrorCorrectionLevel : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeErrorCorrectionLevel { // @property (readonly, assign, nonatomic) int bits; [Export ("bits")] int Bits { get; } // @property (readonly, copy, nonatomic) NSString * name; [Export ("name")] string Name { get; } // @property (readonly, assign, nonatomic) int ordinal; [Export ("ordinal")] int Ordinal { get; } // -(id)initWithOrdinal:(int)anOrdinal bits:(int)bits name:(NSString *)name; [Export ("initWithOrdinal:bits:name:")] IntPtr Constructor (int anOrdinal, int bits, string name); // +(ZXQRCodeErrorCorrectionLevel *)forBits:(int)bits; [Static] [Export ("forBits:")] ZXQRCodeErrorCorrectionLevel ForBits (int bits); // +(ZXQRCodeErrorCorrectionLevel *)errorCorrectionLevelL; [Static] [Export ("errorCorrectionLevelL")] ZXQRCodeErrorCorrectionLevel ErrorCorrectionLevelL { get; } // +(ZXQRCodeErrorCorrectionLevel *)errorCorrectionLevelM; [Static] [Export ("errorCorrectionLevelM")] ZXQRCodeErrorCorrectionLevel ErrorCorrectionLevelM { get; } // +(ZXQRCodeErrorCorrectionLevel *)errorCorrectionLevelQ; [Static] [Export ("errorCorrectionLevelQ")] ZXQRCodeErrorCorrectionLevel ErrorCorrectionLevelQ { get; } // +(ZXQRCodeErrorCorrectionLevel *)errorCorrectionLevelH; [Static] [Export ("errorCorrectionLevelH")] ZXQRCodeErrorCorrectionLevel ErrorCorrectionLevelH { get; } } // @interface ZXQRCodeFinderPatternInfo : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeFinderPatternInfo { // @property (readonly, nonatomic, strong) ZXQRCodeFinderPattern * bottomLeft; [Export ("bottomLeft", ArgumentSemantic.Strong)] ZXQRCodeFinderPattern BottomLeft { get; } // @property (readonly, nonatomic, strong) ZXQRCodeFinderPattern * topLeft; [Export ("topLeft", ArgumentSemantic.Strong)] ZXQRCodeFinderPattern TopLeft { get; } // @property (readonly, nonatomic, strong) ZXQRCodeFinderPattern * topRight; [Export ("topRight", ArgumentSemantic.Strong)] ZXQRCodeFinderPattern TopRight { get; } // -(id)initWithPatternCenters:(NSArray *)patternCenters; [Export ("initWithPatternCenters:")] IntPtr Constructor (NSObject[] patternCenters); } // @interface ZXQRCodeFinderPattern : ZXResultPoint [BaseType (typeof(ZXResultPoint))] interface ZXQRCodeFinderPattern { // @property (readonly, assign, nonatomic) int count; [Export ("count")] int Count { get; } // @property (readonly, assign, nonatomic) float estimatedModuleSize; [Export ("estimatedModuleSize")] float EstimatedModuleSize { get; } // -(id)initWithPosX:(float)posX posY:(float)posY estimatedModuleSize:(float)estimatedModuleSize; [Export ("initWithPosX:posY:estimatedModuleSize:")] IntPtr Constructor (float posX, float posY, float estimatedModuleSize); // -(id)initWithPosX:(float)posX posY:(float)posY estimatedModuleSize:(float)estimatedModuleSize count:(int)count; [Export ("initWithPosX:posY:estimatedModuleSize:count:")] IntPtr Constructor (float posX, float posY, float estimatedModuleSize, int count); // -(BOOL)aboutEquals:(float)moduleSize i:(float)i j:(float)j; [Export ("aboutEquals:i:j:")] bool AboutEquals (float moduleSize, float i, float j); // -(ZXQRCodeFinderPattern *)combineEstimateI:(float)i j:(float)j newModuleSize:(float)newModuleSize; [Export ("combineEstimateI:j:newModuleSize:")] ZXQRCodeFinderPattern CombineEstimateI (float i, float j, float newModuleSize); } // @interface ZXQRCodeFinderPatternFinder : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeFinderPatternFinder { // @property (readonly, nonatomic, strong) ZXBitMatrix * image; [Export ("image", ArgumentSemantic.Strong)] ZXBitMatrix Image { get; } // @property (readonly, nonatomic, strong) NSMutableArray * possibleCenters; [Export ("possibleCenters", ArgumentSemantic.Strong)] NSMutableArray PossibleCenters { get; } // -(id)initWithImage:(ZXBitMatrix *)image; [Export ("initWithImage:")] IntPtr Constructor (ZXBitMatrix image); // -(id)initWithImage:(ZXBitMatrix *)image resultPointCallback:(id<ZXResultPointCallback>)resultPointCallback; [Export ("initWithImage:resultPointCallback:")] IntPtr Constructor (ZXBitMatrix image, ZXResultPointCallback resultPointCallback); // -(ZXQRCodeFinderPatternInfo *)find:(ZXDecodeHints *)hints error:(NSError **)error; [Export ("find:error:")] ZXQRCodeFinderPatternInfo Find (ZXDecodeHints hints, out NSError error); //// +(BOOL)foundPatternCross:(const int *)stateCount; //[Static] //[Export ("foundPatternCross:")] //bool FoundPatternCross (int[] stateCount); //// -(BOOL)handlePossibleCenter:(const int *)stateCount i:(int)i j:(int)j pureBarcode:(BOOL)pureBarcode; //[Export ("handlePossibleCenter:i:j:pureBarcode:")] //bool HandlePossibleCenter (int[] stateCount, int i, int j, bool pureBarcode); } // @interface ZXQRCodeMode : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeMode { // @property (readonly, assign, nonatomic) int bits; [Export ("bits")] int Bits { get; } // @property (readonly, copy, nonatomic) NSString * name; [Export ("name")] string Name { get; } // -(id)initWithCharacterCountBitsForVersions:(NSArray *)characterCountBitsForVersions bits:(int)bits name:(NSString *)name; [Export ("initWithCharacterCountBitsForVersions:bits:name:")] IntPtr Constructor (NSObject[] characterCountBitsForVersions, int bits, string name); // +(ZXQRCodeMode *)forBits:(int)bits; [Static] [Export ("forBits:")] ZXQRCodeMode ForBits (int bits); // -(int)characterCountBits:(ZXQRCodeVersion *)version; [Export ("characterCountBits:")] int CharacterCountBits (ZXQRCodeVersion version); // +(ZXQRCodeMode *)terminatorMode; [Static] [Export ("terminatorMode")] ZXQRCodeMode TerminatorMode { get; } // +(ZXQRCodeMode *)numericMode; [Static] [Export ("numericMode")] ZXQRCodeMode NumericMode { get; } // +(ZXQRCodeMode *)alphanumericMode; [Static] [Export ("alphanumericMode")] ZXQRCodeMode AlphanumericMode { get; } // +(ZXQRCodeMode *)structuredAppendMode; [Static] [Export ("structuredAppendMode")] ZXQRCodeMode StructuredAppendMode { get; } // +(ZXQRCodeMode *)byteMode; [Static] [Export ("byteMode")] ZXQRCodeMode ByteMode { get; } // +(ZXQRCodeMode *)eciMode; [Static] [Export ("eciMode")] ZXQRCodeMode EciMode { get; } // +(ZXQRCodeMode *)kanjiMode; [Static] [Export ("kanjiMode")] ZXQRCodeMode KanjiMode { get; } // +(ZXQRCodeMode *)fnc1FirstPositionMode; [Static] [Export ("fnc1FirstPositionMode")] ZXQRCodeMode Fnc1FirstPositionMode { get; } // +(ZXQRCodeMode *)fnc1SecondPositionMode; [Static] [Export ("fnc1SecondPositionMode")] ZXQRCodeMode Fnc1SecondPositionMode { get; } // +(ZXQRCodeMode *)hanziMode; [Static] [Export ("hanziMode")] ZXQRCodeMode HanziMode { get; } } // @interface ZXQRCodeReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXQRCodeReader : ZXReader { // @property (readonly, nonatomic, strong) ZXQRCodeDecoder * decoder; [Export ("decoder", ArgumentSemantic.Strong)] ZXQRCodeDecoder Decoder { get; } } // @interface ZXQRCodeMultiReader : ZXQRCodeReader <ZXMultipleBarcodeReader> [BaseType (typeof(ZXQRCodeReader))] interface ZXQRCodeMultiReader : IZXMultipleBarcodeReader { } // @interface ZXQRCodeVersion : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeVersion { // @property (readonly, assign, nonatomic) int versionNumber; [Export ("versionNumber")] int VersionNumber { get; } // @property (readonly, nonatomic, strong) ZXIntArray * alignmentPatternCenters; [Export ("alignmentPatternCenters", ArgumentSemantic.Strong)] ZXIntArray AlignmentPatternCenters { get; } // @property (readonly, nonatomic, strong) NSArray * ecBlocks; [Export ("ecBlocks", ArgumentSemantic.Strong)] NSObject[] EcBlocks { get; } // @property (readonly, assign, nonatomic) int totalCodewords; [Export ("totalCodewords")] int TotalCodewords { get; } // @property (readonly, assign, nonatomic) int dimensionForVersion; [Export ("dimensionForVersion")] int DimensionForVersion { get; } // -(ZXQRCodeECBlocks *)ecBlocksForLevel:(ZXQRCodeErrorCorrectionLevel *)ecLevel; [Export ("ecBlocksForLevel:")] ZXQRCodeECBlocks EcBlocksForLevel (ZXQRCodeErrorCorrectionLevel ecLevel); // +(ZXQRCodeVersion *)provisionalVersionForDimension:(int)dimension; [Static] [Export ("provisionalVersionForDimension:")] ZXQRCodeVersion ProvisionalVersionForDimension (int dimension); // +(ZXQRCodeVersion *)versionForNumber:(int)versionNumber; [Static] [Export ("versionForNumber:")] ZXQRCodeVersion VersionForNumber (int versionNumber); // +(ZXQRCodeVersion *)decodeVersionInformation:(int)versionBits; [Static] [Export ("decodeVersionInformation:")] ZXQRCodeVersion DecodeVersionInformation (int versionBits); // -(ZXBitMatrix *)buildFunctionPattern; [Export ("buildFunctionPattern")] ZXBitMatrix BuildFunctionPattern { get; } } // @interface ZXQRCodeECBlocks : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeECBlocks { // @property (readonly, assign, nonatomic) int ecCodewordsPerBlock; [Export ("ecCodewordsPerBlock")] int EcCodewordsPerBlock { get; } // @property (readonly, assign, nonatomic) int numBlocks; [Export ("numBlocks")] int NumBlocks { get; } // @property (readonly, assign, nonatomic) int totalECCodewords; [Export ("totalECCodewords")] int TotalECCodewords { get; } // @property (readonly, nonatomic, strong) NSArray * ecBlocks; [Export ("ecBlocks", ArgumentSemantic.Strong)] NSObject[] EcBlocks { get; } // -(id)initWithEcCodewordsPerBlock:(int)ecCodewordsPerBlock ecBlocks:(ZXQRCodeECB *)ecBlocks; [Export ("initWithEcCodewordsPerBlock:ecBlocks:")] IntPtr Constructor (int ecCodewordsPerBlock, ZXQRCodeECB ecBlocks); // -(id)initWithEcCodewordsPerBlock:(int)ecCodewordsPerBlock ecBlocks1:(ZXQRCodeECB *)ecBlocks1 ecBlocks2:(ZXQRCodeECB *)ecBlocks2; [Export ("initWithEcCodewordsPerBlock:ecBlocks1:ecBlocks2:")] IntPtr Constructor (int ecCodewordsPerBlock, ZXQRCodeECB ecBlocks1, ZXQRCodeECB ecBlocks2); // +(ZXQRCodeECBlocks *)ecBlocksWithEcCodewordsPerBlock:(int)ecCodewordsPerBlock ecBlocks:(ZXQRCodeECB *)ecBlocks; [Static] [Export ("ecBlocksWithEcCodewordsPerBlock:ecBlocks:")] ZXQRCodeECBlocks EcBlocksWithEcCodewordsPerBlock (int ecCodewordsPerBlock, ZXQRCodeECB ecBlocks); // +(ZXQRCodeECBlocks *)ecBlocksWithEcCodewordsPerBlock:(int)ecCodewordsPerBlock ecBlocks1:(ZXQRCodeECB *)ecBlocks1 ecBlocks2:(ZXQRCodeECB *)ecBlocks2; [Static] [Export ("ecBlocksWithEcCodewordsPerBlock:ecBlocks1:ecBlocks2:")] ZXQRCodeECBlocks EcBlocksWithEcCodewordsPerBlock (int ecCodewordsPerBlock, ZXQRCodeECB ecBlocks1, ZXQRCodeECB ecBlocks2); } // @interface ZXQRCodeECB : NSObject [BaseType (typeof(NSObject))] interface ZXQRCodeECB { // @property (readonly, assign, nonatomic) int count; [Export ("count")] int Count { get; } // @property (readonly, assign, nonatomic) int dataCodewords; [Export ("dataCodewords")] int DataCodewords { get; } // -(id)initWithCount:(int)count dataCodewords:(int)dataCodewords; [Export ("initWithCount:dataCodewords:")] IntPtr Constructor (int count, int dataCodewords); // +(ZXQRCodeECB *)ecbWithCount:(int)count dataCodewords:(int)dataCodewords; [Static] [Export ("ecbWithCount:dataCodewords:")] ZXQRCodeECB EcbWithCount (int count, int dataCodewords); } // @interface ZXQRCodeWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXQRCodeWriter : ZXWriter { } // @interface ZXMultiFormatReader : NSObject <ZXReader> [BaseType (typeof(NSObject))] interface ZXMultiFormatReader : ZXReader { // @property (nonatomic, strong) ZXDecodeHints * hints; [Export ("hints", ArgumentSemantic.Strong)] ZXDecodeHints Hints { get; set; } // +(id)reader; [Static] [Export ("reader")] NSObject Reader { get; } // -(ZXResult *)decodeWithState:(ZXBinaryBitmap *)image error:(NSError **)error; [Export ("decodeWithState:error:")] ZXResult DecodeWithState (ZXBinaryBitmap image, out NSError error); } // @interface ZXMultiFormatWriter : NSObject <ZXWriter> [BaseType (typeof(NSObject))] interface ZXMultiFormatWriter : ZXWriter { // +(id)writer; [Static] [Export ("writer")] NSObject Writer { get; } } }
36.762394
578
0.697997
[ "Apache-2.0" ]
msioen/ZXingObjC.Binding
ZXingObjC.OSX.Binding/ApiDefinitions.cs
160,909
C#
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using System; using System.Linq; using System.Web.UI; using WebChat.Data; using WebChat.Models; namespace WebChat { public partial class _Default : Page { protected void Page_Init(object sender, EventArgs e) { if (!Page.IsPostBack) { this.Redirect(); } } protected void Page_Load(object sender, EventArgs e) { using (var context = new ApplicationDbContext()) { this.RepeaterMessages.DataSource = context.Messages.ToList(); this.RepeaterMessages.DataBind(); } } protected void ButtonSendMessage_Click(object sender, EventArgs e) { string contents = this.TextBoxMessage.Text.Trim(); if (string.IsNullOrWhiteSpace(contents)) { this.LabelErrorMessage.Text = "No message to send."; return; } using (var context = new ApplicationDbContext()) { var user = context.Users.Find(User.Identity.GetUserId()); if (user == null) { this.LabelErrorMessage.Text = "User not logged in."; return; } var newMessage = new Message { Author = user, Contents = contents, Timestamp = DateTime.Now }; context.Messages.Add(newMessage); context.SaveChanges(); Response.Redirect(Request.RawUrl); } } private async void Redirect() { AuthenticationIdentityManager manager = new AuthenticationIdentityManager(new IdentityStore(new ApplicationDbContext())); var userId = User.Identity.GetUserId(); var roles = await manager.Roles.GetRolesForUserAsync(userId); if (roles.Any(r => r.Name == "Administrator")) { Response.Redirect("~/Administrator/AdministratorDefault.aspx"); } else if (roles.Any(r => r.Name == "Moderator")) { Response.Redirect("~/Moderator/ModeratorDefault.aspx"); } } } }
31.115385
133
0.529872
[ "MIT" ]
vic-alexiev/TelerikAcademy
ASP.NET Web Forms/Homework Assignments/7. ASP.NET Identity/WebChat/Default.aspx.cs
2,429
C#
using System; namespace MadWorld.Business.Messages { public static class StandardErrorMessages { public const string GeneralError = "Something went wrong"; } }
18.2
66
0.708791
[ "Apache-2.0" ]
oveldman/AzureMadWorld
MadWorld/MadWorld.Business/Messages/StandardErrorMessages.cs
184
C#
namespace Archimedes.Logic { internal interface IClauseNode : ILogicNode { } }
21
51
0.738095
[ "MIT" ]
webrokeit/DTU
02180 - Introduction to Artificial Intelligence/Heureka Project/Archimedes/Logic/IClauseNode.cs
86
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AlarmLight : BasicDistractionDevice { [Ordinal(0)] [RED("isGlitching")] public CBool IsGlitching { get; set; } public AlarmLight(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
24.125
97
0.707254
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/AlarmLight.cs
371
C#
/* * 6. Write a program that prints from given array of integers * all numbers that are divisible by 7 and 3. Use the built-in * extension methods and lambda expressions. * Rewrite the same with LINQ. */ using System; using System.Linq; class Program { static readonly Random rnd = new Random(); static void Main() { int[] numbers = new int[100]; for (int i = 0; i < numbers.Length; i++) numbers[i] = rnd.Next(200); Console.WriteLine("All numbers: {0}", string.Join(", ", numbers)); Console.WriteLine("\nNumbers divisible by 7 and 3: "); Console.WriteLine("\n#1: Using built-in extension method:"); // Built-in extension method var divisibleBy21 = numbers.Where(number => number % 21 == 0); Console.WriteLine(string.Join(" ", divisibleBy21)); Console.WriteLine("\n#2: Using LINQ query:"); // Linq query divisibleBy21 = from number in numbers where number % 21 == 0 select number; Console.WriteLine(string.Join(" ", divisibleBy21)); } }
27.804878
74
0.585088
[ "MIT" ]
NinoSimeonov/Telerik-Academy
Programming with C#/3. C# Object-Oriented Programming/03. Extension Methods, Lambda Expressions and LINQ/06. Numbers divisible by 21/Program.cs
1,142
C#
using System; using System.Collections.Generic; using System.Linq; namespace EFSaving.Basics { public class Sample { public static void Run() { using (var db = new BloggingContext()) { db.Database.EnsureDeleted(); db.Database.EnsureCreated(); } using (var db = new BloggingContext()) { var blog = new Blog { Url = "http://sample.com" }; db.Blogs.Add(blog); db.SaveChanges(); Console.WriteLine(blog.BlogId + ": " + blog.Url); } using (var db = new BloggingContext()) { var blog = db.Blogs.First(); blog.Url = "http://sample.com/blog"; db.SaveChanges(); } using (var db = new BloggingContext()) { var blog = db.Blogs.First(); db.Blogs.Remove(blog); db.SaveChanges(); } // Insert some seed data for the final example using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://sample.com/blog" }); db.Blogs.Add(new Blog { Url = "http://sample.com/another_blog" }); db.SaveChanges(); } using (var db = new BloggingContext()) { db.Blogs.Add(new Blog { Url = "http://sample.com/blog_one" }); db.Blogs.Add(new Blog { Url = "http://sample.com/blog_two" }); var firstBlog = db.Blogs.First(); firstBlog.Url = ""; var lastBlog = db.Blogs.Last(); db.Blogs.Remove(lastBlog); db.SaveChanges(); } } } }
28.671875
82
0.451226
[ "Apache-2.0" ]
Ashrafnet/EntityFramework.Docs
samples/core/Saving/Saving/Basics/Sample.cs
1,837
C#
using System; using System.IO; using System.Runtime.InteropServices; namespace Vildmark.Serialization { public class Reader : IReader { public Stream BaseStream { get; } public Reader(Stream stream) { BaseStream = stream ?? throw new ArgumentNullException(nameof(stream)); } public unsafe T ReadValue<T>() where T : unmanaged { T result = new(); ReadRaw(new Span<T>(&result, 1)); return result; } public T[] ReadValues<T>() where T : unmanaged { if (ReadIsDefault()) { return default; } T[] result = new T[ReadValue<int>()]; ReadRaw(result.AsSpan()); return result; } public T ReadObject<T>() where T : ISerializable, new() { if (ReadIsDefault()) { return default; } T result = new(); result.Deserialize(this); return result; } public T[] ReadObjects<T>() where T : ISerializable, new() { if (ReadIsDefault()) { return default; } T[] result = new T[ReadValue<int>()]; for (int i = 0; i < result.Length; i++) { result[i] = ReadObject<T>(); } return result; } public string ReadString() { char[] chars = ReadValues<char>(); return chars != null ? new string(chars) : null; } public string[] ReadStrings() { if (ReadIsDefault()) { return default; } string[] result = new string[ReadValue<int>()]; for (int i = 0; i < result.Length; i++) { result[i] = ReadString(); } return result; } public bool ReadIsDefault() { return ReadValue<bool>(); } private unsafe void ReadRaw<T>(Span<T> span) where T : unmanaged { byte[] buffer = new byte[span.Length * sizeof(T)]; BaseStream.Read(buffer); MemoryMarshal.Cast<byte, T>(buffer).CopyTo(span); } } }
21.777778
83
0.452806
[ "MIT" ]
Phyyl/Vildmark
Vildmark.Core/Serialization/Reader.cs
2,352
C#
using Dexter.Configurations; using Dexter.Databases.Games; using Dexter.Extensions; using Discord; using Discord.WebSocket; using System.Drawing; using System.Text; using System.Text.RegularExpressions; namespace Dexter.Helpers.Games { /// <summary> /// Represents a game of Chess. /// </summary> public class GameChess : IGameTemplate { private const string EmptyData = StartingPos + ", -, 0, 0, 0, 0, NN, standard, 0"; private const string StartingPos = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; private string BoardRaw { get { return game.Data.Split(", ")[0]; } set { string[] newValue = game.Data.Split(", "); newValue[0] = value; game.Data = string.Join(", ", newValue); } } private string LastMove { get { return game.Data.Split(", ")[1]; } set { string[] newValue = game.Data.Split(", "); newValue[1] = value; game.Data = string.Join(", ", newValue); } } private ulong BoardID { get { return ulong.Parse(game.Data.Split(", ")[2]); } set { string[] newValue = game.Data.Split(", "); newValue[2] = value.ToString(); game.Data = string.Join(", ", newValue); } } private ulong DumpID { get { return ulong.Parse(game.Data.Split(", ")[3]); } set { string[] newValue = game.Data.Split(", "); newValue[3] = value.ToString(); game.Data = string.Join(", ", newValue); } } private ulong PlayerWhite { get { return ulong.Parse(game.Data.Split(", ")[4]); } set { string[] newValue = game.Data.Split(", "); newValue[4] = value.ToString(); game.Data = string.Join(", ", newValue); } } private ulong PlayerBlack { get { return ulong.Parse(game.Data.Split(", ")[5]); } set { string[] newValue = game.Data.Split(", "); newValue[5] = value.ToString(); game.Data = string.Join(", ", newValue); } } private string Agreements { get { return game.Data.Split(", ")[6]; } set { string[] newValue = game.Data.Split(", "); newValue[6] = value; game.Data = string.Join(", ", newValue); } } private string Theme { get { return game.Data.Split(", ")[7]; } set { string[] newValue = game.Data.Split(", "); newValue[7] = value; game.Data = string.Join(", ", newValue); } } private enum ViewMode { Flip, White, Black } private ViewMode View { get { return (ViewMode)int.Parse(game.Data.Split(", ")[8]); } set { string[] newValue = game.Data.Split(", "); newValue[8] = ((int)value).ToString(); game.Data = string.Join(", ", newValue); } } private bool IsWhitesTurn { get { return BoardRaw.Split(" ")[1] == "w"; } } private GameInstance game; /// <summary> /// Creates a new instance of a chess game given a generic GameInstance <paramref name="game"/> /// </summary> /// <param name="game">The generic GameInstance from which to generate the chess game.</param> public GameChess(GameInstance game) { this.game = game; if (string.IsNullOrEmpty(game.Data)) game.Data = EmptyData; } /// <summary> /// Represents the general status and data of a Chess Game. /// </summary> /// <param name="client">SocketClient used to parse UserIDs.</param> /// <returns>An Embed detailing the various aspects of the game in its current instance.</returns> public EmbedBuilder GetStatus(DiscordSocketClient client) { return new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle($"{game.Title} (Game {game.GameID})") .WithDescription($"{game.Description}") .AddField("White", $"<@{PlayerWhite}>", true) .AddField("Black", $"<@{PlayerBlack}>", true) .AddField("Turn", $"{(IsWhitesTurn ? "White" : "Black")}", true) .AddField("FEN Expression", BoardRaw) .AddField("Master", client.GetUser(game.Master)?.GetUserInformation() ?? "<N/A>") .AddField(game.Banned.Length > 0, "Banned Players", game.BannedMentions.TruncateTo(500)); } /// <summary> /// Prints information about how to play Chess. /// </summary> /// <param name="funConfiguration">The configuration file holding relevant information for the game.</param> /// <returns>An <see cref="EmbedBuilder"/> object holding the stylized information.</returns> public EmbedBuilder Info(FunConfiguration funConfiguration) { return new EmbedBuilder() .WithColor(Discord.Color.Magenta) .WithTitle("How to Play: Chess") .WithDescription("**Step 1.** Create a board by typing `board` in chat.\n" + "**Step 2.** Claim your colors! Type `claim <black|white>` to claim the pieces of a given color.\n" + "**Step 3.** White starts! Take turns moving pieces by typing moves in chat until an outcome is decided.\n" + "**[MORE INFO]**, for information on specific mechanics, type `info` followed by any of the following categories:\n" + $"{AuxiliaryInfo}\n" + "You can import a position from FEN notation using the `game set board [FEN]` command.\n" + "Standard rules of chess apply, you can resign with `resign` or offer a draw by typing `draw` in chat.\n" + "Once the game is complete, you can type `swap` to swap colors, or `pass [color] [player]` to give control of your pieces to someone else."); } const string AuxiliaryInfo = "> *moves* => Information about phrasing moves that can be understood by the engine.\n" + "> *view* => Information about changing the way the game is viewed graphically.\n" + "> *chess* => Information about how to play chess and useful resources for learning the game.\n" + "> *positions* => Information about additional custom starting positions that can be set using the `game set board [position]` command."; /// <summary> /// Resets all data, except player color control, if given a <paramref name="gamesDB"/>, it will also reset their score and lives. /// </summary> /// <param name="funConfiguration">The configuration file holding all relevant parameters for Games.</param> /// <param name="gamesDB">The games database where relevant data concerning games and players is stored.</param> public void Reset(FunConfiguration funConfiguration, GamesDB gamesDB) { ulong white = PlayerWhite; ulong black = PlayerBlack; ulong dumpID = DumpID; game.Data = EmptyData; PlayerWhite = white; PlayerBlack = black; DumpID = dumpID; if (gamesDB is not null) { foreach (Player p in gamesDB.GetPlayersFromInstance(game.GameID)) { p.Score = 0; p.Lives = 0; } } } /// <summary> /// Sets an internal game field <paramref name="field"/> to a given <paramref name="value"/>. /// </summary> /// <param name="field">The field to modify</param> /// <param name="value">The value to set <paramref name="field"/> to</param> /// <param name="funConfiguration">The configuration file holding relevant information about games settings.</param> /// <param name="feedback">The result of the operation, explained in a humanized way.</param> /// <returns><see langword="true"/> if the change was successful, otherwise <see langword="false"/>.</returns> public bool Set(string field, string value, FunConfiguration funConfiguration, out string feedback) { switch (field.ToLower()) { case "fen": case "pos": case "position": case "state": case "board": if (funConfiguration.ChessPositions.ContainsKey(value.ToLower())) { BoardRaw = funConfiguration.ChessPositions[value.ToLower()]; feedback = $"Successfully reset the board to custom position: `{value}`."; return true; } if (!Board.TryParseBoard(value, out Board board, out feedback)) return false; BoardRaw = board.ToString(); LastMove = "-"; feedback = "Successfully set the value of board to the given value, type `board` to see the updated position."; return true; case "theme": case "style": if (!funConfiguration.ChessThemes.Contains(value.ToLower())) { feedback = $"Unable to find theme \"{value}\", valid themes are: {string.Join(", ", funConfiguration.ChessThemes)}."; return false; } Theme = value.ToLower(); feedback = $"Successfully set theme to {value}"; return true; case "view": switch (value.ToLower()) { case "white": View = ViewMode.White; feedback = "View mode set to white! The game will be seen from white's perspective."; return true; case "black": View = ViewMode.Black; feedback = "View mode set to black! The game will be seen from black's perspective."; return true; case "flip": View = ViewMode.Flip; feedback = "View mode set to flip! The board will rotate for whoever's turn it is to play"; return true; default: feedback = "Invalid view mode! Choose `white`, `black`, or `flip`."; return false; } } feedback = $"Invalid field: \"{field}\" is not a default field nor \"board\", \"theme\", or \"view\"."; return false; } /// <summary> /// Handles a message sent in a games channel by a player currently playing in this game instance. /// </summary> /// <param name="message">The message sent by the player to be handled.</param> /// <param name="gamesDB">The database holding relevant information about games and players.</param> /// <param name="client">The Discord client used to send messages and parse users.</param> /// <param name="funConfiguration">The configuration settings attached to the Fun Commands module.</param> /// <returns>A <c>Task</c> object, which can be awaited until the method completes successfully.</returns> public async Task HandleMessage(IMessage message, GamesDB gamesDB, DiscordSocketClient client, FunConfiguration funConfiguration) { if (message.Channel is IDMChannel) return; Player player = gamesDB.GetOrCreatePlayer(message.Author.Id); string msgRaw = message.Content.Replace("@", "@-"); string msg = msgRaw.ToLower(); IUserMessage boardMsg = null; if (BoardID != 0) boardMsg = await message.Channel.GetMessageAsync(BoardID) as IUserMessage; if (!Board.TryParseBoard(BoardRaw, out Board board, out string boardCorruptedError)) { await new EmbedBuilder() .WithColor(Discord.Color.Red) .WithTitle("Corrupted Board State") .WithDescription($"Your current board state can't be parsed to a valid board, it has the following error:\n" + $"{boardCorruptedError}\n" + $"Feel free to reset the game using the `game reset` command or by setting a new board state in FEN notation with the `game set board [FEN]` command.") .SendEmbed(message.Channel); return; } if (msg == "board") { bool lastMoveValid = Move.TryParseMock(LastMove, board, out Move lastMove, out string lastMoveError); if (!lastMoveValid) lastMove = null; Outcome checkCalc = board.GetOutcome(); if (checkCalc is Outcome.Check) lastMove.isCheck = true; if (checkCalc is Outcome.Checkmate) lastMove.isCheckMate = true; if (boardMsg is not null) await boardMsg.DeleteAsync(); IUserMessage newBoard = await message.Channel.SendMessageAsync(await CreateBoardDisplay(board, lastMove, client, funConfiguration)); BoardID = newBoard.Id; return; } string[] args = msg.Split(' '); if (args.Length > 0 && args[0] == "info") { if (args.Length == 1) { await new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle("Auxiliary Information: Chess") .WithDescription($"Please specify one of the following categories when requesting information:\n{AuxiliaryInfo}") .SendEmbed(message.Channel); return; } switch (args[1]) { case "moves": await new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle("Auxiliary Information: Chess Moves") .WithDescription("Moves in chess can be expressed in one of two ways:\n" + "`[origin](x)[target]` - This represents a move from [origin] to [target], the piece is not specified.\n" + "Examples: Rook moves from a1 to d1: `a1d1`. Knight in b3 captures a piece on d4: `b3xd4`.\n" + "`(piece)(disambiguation)(x)[target]` - This represents the movement of a specific piece to a target square.\n" + "If no piece is provided, it's assumed you mean a pawn; disambiguation is required if multiple pieces of the same type could be moved to the same square.\n" + "Examples: Knight moves from a2 to c3: `Nc3`. Rook moves from a1 do d1, another rook is in e1: `Rad1`. Pawn on the e file captures in d3: `exd3`. Opening the game with pawn to d4: `d4`.\n" + "Castling is always notated as `O-O` for kingside castling and `O-O-O` for queenside castling.\n" + "Promotion to a non-queen can be specified by adding `=[Piece]` at the end of your pawn move: e.g. `e8=N`, `dxc1=R`." + "Note: The capture indicator is completely optional and ignored by the parser, it's not required or enforced.") .SendEmbed(message.Channel); return; case "view": await new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle("Auxiliary Information: Chess Views") .WithDescription("There are two ways a game master can modify the way the game is viewed.\n" + "**View Mode**: If you don't like the board rotating every time it's the next player's turn, you can fix it to a specific side with the `game set view <flip|black|white>` command.\n" + "**Theme**: Getting bored of the way the pieces look? Change up their look a bit, explore our various themes for chess with the `game set theme [theme]` command.\n" + $"Currently supported themes are: {string.Join(", ", funConfiguration.ChessThemes)}.") .SendEmbed(message.Channel); return; case "chess": case "rules": await new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle("Auxiliary Information: Chess Rules") .WithDescription("We heavily recommend you check out [this article on chess.com](https://www.chess.com/learn-how-to-play-chess) for an in-depth tutorial; but if you just want to read, here's a quick rundown.\n" + "The goal of the game is to put the enemy king in checkmate, meaning that it can't avoid capture in the next turn.\n" + "The **king** (K) moves one space in any direction, but can't move into a space that would put it in check!\n" + "The **queen** (Q) is the most powerful piece, it can move as many spaces as she wants in any direction.\n" + "The **rook** (R) moves orthogonally (horizontally or vertically) as many squares as it wants.\n" + "The **bishop** (B) moves diagonally as many squares as it wants, a bishop will always remain in the same square color.\n" + "The **knight** (N) moves in an L-shape, two squares in one direction, one in another. The knight is the only piece which can jump over other pieces\n" + "The **pawn** (P) is weird! It generally moves forward one square (except in the first move where it can move two), but it can ONLY capture diagonally. This means a pawn can't move if a piece is in front of it, unless it can capture a piece next to it.\n" + "Chess has a couple special moves, such as **castling** and **en passant**, these moves are a bit complicated, here are guides on [castling](https://www.youtube.com/watch?v=FcLYgXCkucc) and [en passant](https://www.youtube.com/watch?v=c_KRIH0wnhE).") .SendEmbed(message.Channel); return; case "positions": await new EmbedBuilder() .WithColor(Discord.Color.Blue) .WithTitle("Auxiliary Information: Chess Positions") .WithDescription("Here are a couple predefined custom chess positions you can play.\n" + "To set your game to these positions, use the `game set board [position name]` command!\n" + $"Custom positions: **{string.Join("**, **", funConfiguration.ChessPositions.Keys)}**.") .SendEmbed(message.Channel); return; default: await new EmbedBuilder() .WithColor(Discord.Color.Red) .WithTitle("Invalid Auxiliary Information Provided") .WithDescription("Please make sure to use the following categories: `moves`, `view`, or `chess`.") .SendEmbed(message.Channel); return; } } if (msg.StartsWith("claim")) { if (args.Length > 1) { Player prevPlayer = null; bool skip = false; switch (args[1]) { case "white": case "w": if (PlayerWhite == 0) skip = true; else prevPlayer = gamesDB.Players.Find(PlayerWhite); break; case "black": case "b": if (PlayerBlack == 0) skip = true; else prevPlayer = gamesDB.Players.Find(PlayerBlack); break; default: await message.Channel.SendMessageAsync($"\"{args[1]}\" is not a valid color! Use 'B' or 'W'."); return; } if (!skip && prevPlayer is not null && prevPlayer.Playing == game.GameID) { await message.Channel.SendMessageAsync($"Can't claim color since player <@{prevPlayer.UserID}> is actively controlling it."); return; } if (args[1].StartsWith("w")) PlayerWhite = message.Author.Id; else PlayerBlack = message.Author.Id; await message.Channel.SendMessageAsync($"<@{message.Author.Id}> will play with {(args[1].StartsWith("w") ? "white" : "black")}!"); return; } await message.Channel.SendMessageAsync("You need to specify what color you'd like to claim!"); return; } if (msg == "resign") { if (BoardRaw == StartingPos) return; bool resign = false; bool isWhite = false; if (message.Author.Id == PlayerWhite) { resign = true; isWhite = true; gamesDB.GetOrCreatePlayer(PlayerBlack).Score++; } else if (message.Author.Id == PlayerBlack) { resign = true; isWhite = false; gamesDB.GetOrCreatePlayer(PlayerWhite).Score++; } if (resign) { await new EmbedBuilder() .WithColor(Discord.Color.Gold) .WithTitle($"{(isWhite ? "White" : "Black")} resigns!") .WithDescription($"The victory goes for {(isWhite ? "Black" : "White")}! The board has been reset, you can play again by typing `board`. The game master can swap colors by typing `swap`.") .SendEmbed(message.Channel); Reset(funConfiguration, gamesDB); gamesDB.SaveChanges(); } } if (msg == "draw") { if (BoardRaw == StartingPos) return; bool draw = false; bool isWhite = false; bool retracted = false; if (message.Author.Id == PlayerWhite) { draw = true; isWhite = true; if (Agreements[0] == 'D') { Agreements = $"N{Agreements[1]}"; retracted = true; } else Agreements = $"D{Agreements[1]}"; } else if (message.Author.Id == PlayerBlack) { draw = true; isWhite = false; if (Agreements[1] == 'D') { Agreements = $"{Agreements[0]}N"; retracted = true; } else Agreements = $"{Agreements[0]}D"; } if (draw) { if (Agreements == "DD") { await new EmbedBuilder() .WithColor(Discord.Color.Orange) .WithTitle($"Draw!") .WithDescription($"No winners this game, but also no losers! The board has been reset, you can play again by typing `board`. The game master can swap colors by typing `swap`.") .SendEmbed(message.Channel); Reset(funConfiguration, gamesDB); gamesDB.SaveChanges(); } else { if (retracted) { await message.Channel.SendMessageAsync($"{(isWhite ? "White" : "Black")} retracts their offer to draw the game!"); } else { await message.Channel.SendMessageAsync($"{(isWhite ? "White" : "Black")} is offering a draw, to accept it; type \"draw\"!"); } } } } if (Move.TryParse(msgRaw, board, out Move move, out string error)) { if (boardMsg is null) { await message.Channel.SendMessageAsync($"You must create a board first! Type `board`."); return; } if (!string.IsNullOrEmpty(error)) { await message.Channel.SendMessageAsync(error); return; } if ((board.isWhitesTurn && message.Author.Id != PlayerWhite) || (!board.isWhitesTurn && message.Author.Id != PlayerBlack)) { await message.Channel.SendMessageAsync($"You don't control the {(board.isWhitesTurn ? "white" : "black")} pieces!"); return; } if (!move.IsLegal(board, out string legalerror)) { await message.Channel.SendMessageAsync(legalerror); return; } board.ExecuteMove(move); Outcome outcome = board.GetOutcome(); if (outcome is Outcome.Check) move.isCheck = true; if (outcome is Outcome.Checkmate) move.isCheckMate = true; BoardRaw = board.ToString(); LastMove = move.ToString(); await message.DeleteAsync(); string link = await CreateBoardDisplay(board, move, client, funConfiguration); await boardMsg.ModifyAsync(m => m.Content = link); if (outcome == Outcome.Checkmate) { BoardID = 0; player.Score += 1; await new EmbedBuilder() .WithColor(Discord.Color.Green) .WithTitle($"{(!board.isWhitesTurn ? "White" : "Black")} wins!") .WithDescription("Create a new board if you wish to play again, or pass your color control to a different player.") .SendEmbed(message.Channel); Reset(funConfiguration, null); return; } if (outcome == Outcome.Draw) { await new EmbedBuilder() .WithColor(Discord.Color.LightOrange) .WithTitle("Draw!") .WithDescription($"Stalemate reached {(board.isWhitesTurn ? "White" : "Black")} has no legal moves but isn't in check. Create a new board if you wish to play again, or pass your color control to a different player.") .SendEmbed(message.Channel); Reset(funConfiguration, null); return; } if (outcome == Outcome.FiftyMoveRule) { await new EmbedBuilder() .WithColor(Discord.Color.LightOrange) .WithTitle("Draw!") .WithDescription("50 moves went by without advancing a pawn or capturing a piece, the game is declared a draw. \nCreate a new board if you wish to play again, or pass your color control to a different player.") .SendEmbed(message.Channel); Reset(funConfiguration, null); } if (outcome == Outcome.InsufficientMaterial) { await new EmbedBuilder() .WithColor(Discord.Color.LightOrange) .WithTitle("Draw!") .WithDescription("Neither player has sufficient material to deliver checkmate, the game is declared a draw. \nCreate a new board if you wish to play again, or pass your color control to a different player.") .SendEmbed(message.Channel); Reset(funConfiguration, null); } return; } if (args.Length > 2 && args[0] == "pass") { ulong otherID = message.MentionedUserIds.FirstOrDefault(); if (otherID == default && !ulong.TryParse(args[2], out otherID) || otherID == 0) { await message.Channel.SendMessageAsync($"Could not parse \"{args[2]}\" into a valid user."); return; } IUser otherUser = client.GetUser(otherID); if (otherUser is null) { await message.Channel.SendMessageAsync($"I wasn't able to find this user!"); return; } Player otherPlayer = gamesDB.GetOrCreatePlayer(otherUser.Id); if (otherPlayer.Playing != game.GameID) { await message.Channel.SendMessageAsync("That user isn't playing in this game session!"); return; } switch (args[1]) { case "w": case "white": if (message.Author.Id != game.Master && message.Author.Id != PlayerWhite) { await message.Channel.SendMessageAsync($"You aren't the master nor controlling the white pieces!"); return; } PlayerWhite = otherPlayer.UserID; break; case "b": case "black": if (message.Author.Id != game.Master && message.Author.Id != PlayerBlack) { await message.Channel.SendMessageAsync($"You aren't the master nor controlling the black pieces!"); return; } PlayerBlack = otherPlayer.UserID; break; default: await message.Channel.SendMessageAsync($"Unable to parse \"{args[1]}\" into a valid color!"); return; } await message.Channel.SendMessageAsync($"{otherUser.Mention} now controls the {(args[1][0] == 'w' ? "white" : "black")} pieces!"); return; } if (args[0] == "swap") { if (message.Author.Id != game.Master) { await message.Channel.SendMessageAsync("Only the game master can swap the colors!"); return; } ulong temp = PlayerWhite; PlayerWhite = PlayerBlack; PlayerBlack = temp; await message.Channel.SendMessageAsync($"Colors have been swapped!\n" + $"WHITE: <@{PlayerWhite}>\n" + $"BLACK: <@{PlayerBlack}>"); return; } } private async Task<string> CreateBoardDisplay(Board board, Move lastMove, DiscordSocketClient client, FunConfiguration funConfiguration) { string imageChacheDir = Path.Combine(Directory.GetCurrentDirectory(), "ImageCache"); string filepath = Path.Join(imageChacheDir, $"Chess{game.Master}.png"); System.Drawing.Image image = RenderBoard(board, lastMove); image.Save(filepath); if (DumpID != 0) { IMessage prevDump = await (client.GetChannel(funConfiguration.GamesImageDumpsChannel) as ITextChannel).GetMessageAsync(DumpID); if (prevDump is not null) await prevDump.DeleteAsync(); } IUserMessage cacheMessage = await (client.GetChannel(funConfiguration.GamesImageDumpsChannel) as ITextChannel).SendFileAsync(filepath); DumpID = cacheMessage.Id; return cacheMessage.Attachments.First().ProxyUrl; } private System.Drawing.Image RenderBoard(Board board, Move lastMove) { Bitmap img = new(2 * Offset + 8 * CellSize, 2 * Offset + 8 * CellSize); Dictionary<char, System.Drawing.Image> pieceImages = new(); foreach (Piece p in Piece.pieces) { for (int c = 0; c < 2; c++) { pieceImages.Add(c == 0 ? p.representation : char.ToLower(p.representation), System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{PiecePrefixes[c]}{p.representation}.png"))); } } bool whiteside = (View) switch { ViewMode.White => true, ViewMode.Black => false, _ => board.isWhitesTurn }; using (Graphics g = Graphics.FromImage(img)) { using (System.Drawing.Image boardImg = System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{BoardImgName}.png"))) { if (!whiteside) boardImg.RotateFlip(RotateFlipType.Rotate180FlipNone); g.DrawImage(boardImg, 0, 0, 2 * Offset + 8 * CellSize, 2 * Offset + 8 * CellSize); } if (lastMove != null) { using (System.Drawing.Image highlight = System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{HighlightImage}.png"))) { foreach (int n in lastMove.ToHighlight()) { if (whiteside) g.DrawImage(highlight, Offset + (n % 8) * CellSize, Offset + (n / 8) * CellSize, CellSize, CellSize); else g.DrawImage(highlight, Offset + (7 - n % 8) * CellSize, Offset + (7 - n / 8) * CellSize, CellSize, CellSize); } } if (lastMove.isCapture) { if (lastMove.isEnPassant) { using (System.Drawing.Image captureMark = System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{CaptureImage}.png"))) { foreach (int n in lastMove.ToEnPassant()) { if (whiteside) g.DrawImage(captureMark, (n % 8) * CellSize, (n / 8) * CellSize, CellSize + 2 * Offset, CellSize + 2 * Offset); else g.DrawImage(captureMark, (7 - n % 8) * CellSize, (7 - n / 8) * CellSize, CellSize + 2 * Offset, CellSize + 2 * Offset); } } } else { using (System.Drawing.Image captureMark = System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{CaptureImage}.png"))) { if (whiteside) g.DrawImage(captureMark, (lastMove.target % 8) * CellSize, (lastMove.target / 8) * CellSize, CellSize + 2 * Offset, CellSize + 2 * Offset); else g.DrawImage(captureMark, (7 - lastMove.target % 8) * CellSize, (7 - lastMove.target / 8) * CellSize, CellSize + 2 * Offset, CellSize + 2 * Offset); } } } using (System.Drawing.Image danger = System.Drawing.Image.FromFile(Path.Join(ChessPath, Theme, $"{DangerImage}.png"))) { foreach (int n in lastMove.ToDanger(board)) { if (whiteside) g.DrawImage(danger, Offset + (n % 8) * CellSize, Offset + (n / 8) * CellSize, CellSize, CellSize); else g.DrawImage(danger, Offset + (7 - n % 8) * CellSize, Offset + (7 - n / 8) * CellSize, CellSize, CellSize); } } } for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { if (board.squares[x, y] != '-') { if (whiteside) g.DrawImage(pieceImages[board.squares[x, y]], Offset + CellSize * x, Offset + CellSize * y, CellSize, CellSize); else g.DrawImage(pieceImages[board.squares[x, y]], Offset + (7 - x) * CellSize, Offset + (7 - y) * CellSize, CellSize, CellSize); } } } } return img; } const int CellSize = 64; const int Offset = 32; private const string ChessPath = "Images/Games/Chess"; private const string BoardImgName = "Board"; private const string HighlightImage = "SquareHighlight"; private const string CaptureImage = "CaptureMarker"; private const string DangerImage = "SquareDanger"; private readonly string[] PiecePrefixes = new string[] { "W", "B" }; private static Tuple<int, int> ToMatrixCoords(int pos) { return new Tuple<int, int>(pos % 8, pos / 8); } private static string ToSquareName(Tuple<int, int> coord) { return $"{(char)('a' + coord.Item1)}{(char)('8' - coord.Item2)}"; } private static bool TryParseSquare(string input, out int pos) { pos = -1; if (input.Length < 2) return false; if (input[0] < 'a' || input[0] > 'h') return false; pos = input[0] - 'a'; if (input[1] < '1' || input[1] > '8') return false; pos += ('8' - input[1]) * 8; return true; } [Flags] private enum MoveType { None = 0, Orthogonal = 1, Diagonal = 2, Direct = 4, Pawn = 8 } private class Piece { public char representation; public string name; public bool canPin; public Func<int, int, Board, bool, bool> isValid; public Func<int, Board, bool, bool> hasValidMoves; public static readonly Piece Rook = new() { representation = 'R', name = "Rook", canPin = true, isValid = (origin, target, board, flip) => { if (!BasicValidate(Rook, origin, target, board, flip)) return false; return OrthogonalValidate(origin, target, board); }, hasValidMoves = (origin, board, flip) => HasOrthogonalValidMoves(origin, board, flip) }; public static readonly Piece Knight = new() { representation = 'N', name = "Knight", canPin = false, isValid = (origin, target, board, flip) => { if (!BasicValidate(Knight, origin, target, board, flip)) return false; int xdiff = Math.Abs(target % 8 - origin % 8); int ydiff = Math.Abs(target / 8 - origin / 8); if (xdiff == 0 || ydiff == 0) return false; return xdiff + ydiff == 3; }, hasValidMoves = (origin, board, flip) => { int x0 = origin % 8; int y0 = origin / 8; for (int dx = 1; dx <= 2; dx++) { for (int xsign = -1; xsign <= 1; xsign += 2) { int x = x0 + dx * xsign; if (x < 0 || x >= 8) continue; for (int ysign = -1; ysign <= 1; ysign += 2) { int y = y0 + (3 - dx) * ysign; if (y < 0 || y >= 8) continue; if (board.squares[x, y] == '-' || (char.IsUpper(board.squares[x, y]) ^ board.isWhitesTurn ^ flip)) return true; } } } return false; } }; public static readonly Piece Bishop = new() { representation = 'B', name = "Bishop", canPin = true, isValid = (origin, target, board, flip) => { if (!BasicValidate(Bishop, origin, target, board, flip)) return false; return DiagonalValidate(origin, target, board); }, hasValidMoves = (origin, board, flip) => HasDiagonalValidMoves(origin, board, flip) }; public static readonly Piece King = new() { representation = 'K', name = "King", canPin = false, isValid = (origin, target, board, flip) => { if (!BasicValidate(King, origin, target, board, flip)) return false; int xdiff = Math.Abs(target % 8 - origin % 8); int ydiff = Math.Abs(target / 8 - origin / 8); return xdiff <= 1 && ydiff <= 1; }, hasValidMoves = (origin, board, flip) => HasDiagonalValidMoves(origin, board, flip, true) || HasOrthogonalValidMoves(origin, board, flip, true) }; public static readonly Piece Queen = new() { representation = 'Q', name = "Queen", canPin = true, isValid = (origin, target, board, flip) => { if (!BasicValidate(Queen, origin, target, board, flip)) return false; return OrthogonalValidate(origin, target, board) || DiagonalValidate(origin, target, board); }, hasValidMoves = (origin, board, flip) => HasDiagonalValidMoves(origin, board, flip) || HasOrthogonalValidMoves(origin, board, flip) }; public static readonly Piece Pawn = new() { representation = 'P', name = "Pawn", canPin = false, isValid = (origin, target, board, flip) => { if (!BasicValidate(Pawn, origin, target, board, flip)) return false; int yAdv = (board.isWhitesTurn ^ flip) ? -1 : 1; int x0 = origin % 8; int y0 = origin / 8; int xf = target % 8; int yf = target / 8; if (board.GetSquare(target) != '-' || (target == board.enPassant && x0 != xf)) { return Math.Abs(x0 - xf) == 1 && yf == y0 + yAdv; } else { if (xf != x0) return false; if (yf == y0 + yAdv) return true; int initialRank = (board.isWhitesTurn ^ flip) ? 6 : 1; return y0 == initialRank && yf == y0 + 2 * yAdv && board.squares[x0, y0 + yAdv] == '-'; } }, hasValidMoves = (origin, board, flip) => { int yAdv = (board.isWhitesTurn ^ flip) ? -1 : 1; int x0 = origin % 8; int y0 = origin / 8; if (y0 + yAdv < 0 || y0 + yAdv >= 8) return false; if (board.squares[x0, y0 + yAdv] == '-') return true; for (int x = x0 - 1; x <= x0 + 1; x += 2) { if (x < 0 || x >= 8) continue; if (board.enPassant == x + (y0 + yAdv) * 8) return true; if (board.squares[x, y0 + yAdv] == '-') continue; if (char.IsUpper(board.squares[x, y0 + yAdv]) ^ board.isWhitesTurn ^ flip) return true; } return false; } }; private static bool BasicValidate(Piece p, int origin, int target, Board board, bool flip) { if (origin == target) return false; if (char.ToUpper(board.GetSquare(origin)) != p.representation) return false; char piecef = board.GetSquare(target); if (piecef != '-' && (char.IsLower(piecef) ^ board.isWhitesTurn ^ flip)) return false; return true; } private static bool OrthogonalValidate(int origin, int target, Board board) { int x0 = origin % 8; int y0 = origin / 8; int xf = target % 8; int yf = target / 8; if (y0 == yf) { int direction = target - origin > 0 ? 1 : -1; int x = x0 + direction; while (x != xf) { if (board.squares[x, y0] != '-') return false; x += direction; } return true; } else if (x0 == xf) { int direction = target - origin > 0 ? 1 : -1; int y = y0 + direction; while (y != yf) { if (board.squares[x0, y] != '-') return false; y += direction; } return true; } return false; } private static bool DiagonalValidate(int origin, int target, Board board) { int x0 = origin % 8; int y0 = origin / 8; int xf = target % 8; int yf = target / 8; int ydir = target - origin > 0 ? 1 : -1; int xdir; if (x0 + y0 == xf + yf) { xdir = -ydir; } else if (x0 - y0 == xf - yf) { xdir = ydir; } else return false; int x = x0 + xdir; int y = y0 + ydir; while (x != xf) { if (board.squares[x, y] != '-') return false; x += xdir; y += ydir; } return true; } private static bool HasOrthogonalValidMoves(int origin, Board board, bool flip, bool mustBeSafe = false) { int x0 = origin % 8; int y0 = origin / 8; char p; char thisPiece = board.squares[x0, y0]; for (int x = x0 - 1; x <= x0 + 1; x += 2) { if (x < 0 || x >= 8) continue; p = board.squares[x, y0]; if (p != '-' && !(char.IsUpper(p) ^ board.isWhitesTurn ^ flip)) continue; if (!mustBeSafe) return true; board.squares[x0, y0] = '-'; if (!board.IsControlled(x + y0 * 8, !flip)) { board.squares[x0, y0] = thisPiece; return true; } board.squares[x0, y0] = thisPiece; } for (int y = y0 - 1; y <= y0 + 1; y += 2) { if (y < 0 || y >= 8) continue; p = board.squares[x0, y]; if (p != '-' && !(char.IsUpper(p) ^ board.isWhitesTurn ^ flip)) continue; if (!mustBeSafe) return true; board.squares[x0, y0] = '-'; if (!board.IsControlled(x0 + y * 8, !flip)) { board.squares[x0, y0] = thisPiece; return true; } board.squares[x0, y0] = thisPiece; } return false; } private static bool HasDiagonalValidMoves(int origin, Board board, bool flip, bool mustBeSafe = false) { int x0 = origin % 8; int y0 = origin / 8; char p; char thisPiece = board.squares[x0, y0]; for (int x = x0 - 1; x <= x0 + 1; x += 2) { if (x < 0 || x >= 8) continue; for (int y = y0 - 1; y <= y0 + 1; y += 2) { if (y < 0 || y >= 8) continue; p = board.squares[x, y]; if (p != '-' && !(char.IsUpper(p) ^ board.isWhitesTurn ^ flip)) continue; if (!mustBeSafe) return true; board.squares[x0, y0] = '-'; if (!board.IsControlled(x + y * 8, !flip)) { board.squares[x0, y0] = thisPiece; return true; } board.squares[x0, y0] = thisPiece; } } return false; } public static readonly Piece[] pieces = new Piece[] { Rook, Knight, Bishop, King, Queen, Pawn }; public static char[] PieceCharacters { get { char[] result = new char[pieces.Length]; for (int i = 0; i < result.Length; i++) { result[i] = pieces[i].representation; } return result; } } public static Piece FromRepresentation(char c) { foreach (Piece p in pieces) { if (p.representation == char.ToUpper(c)) return p; } return null; } } /// <summary> /// Represents a move in chess /// </summary> private class Move { public int origin; public int target; public bool isCastle; public bool isCapture; public bool isEnPassant; public bool isCheck; public bool isCheckMate; public char promote; public bool IsLegal(Board boardOriginal, out string error) { Board board = (Board)boardOriginal.Clone(); board.ExecuteMove(this); if (!isCastle) { error = "King will be under attack - invalid move!"; int kingPosition = board.isWhitesTurn ? board.blackKing : board.whiteKing; if (board.IsThreatened(kingPosition)) return false; } else { error = "King or rook will be under attack - invalid castle!"; bool targetReached = false; for (int moveSquare = origin; !targetReached; moveSquare += (target - origin) > 0 ? 1 : -1) { if (board.IsThreatened(moveSquare)) return false; if (moveSquare == target) targetReached = true; } } error = ""; return true; } public static bool TryParseMock(string input, Board board, out Move move, out string error) { move = new Move(-1, -1); error = ""; if (Regex.IsMatch(input.ToUpper(), @"^[O0]\-[O0]([+#!?.\s]|$)")) { move.origin = !board.isWhitesTurn ? 60 : 4; move.target = !board.isWhitesTurn ? 62 : 6; move.isCastle = true; return true; } else if (Regex.IsMatch(input.ToUpper(), @"^[O0]\-[O0]\-[O0]([+#!?.\s]|$)")) { move.origin = !board.isWhitesTurn ? 60 : 4; move.target = !board.isWhitesTurn ? 58 : 2; move.isCastle = true; return true; } else if (input.Length != 4 && (input.Length != 5 || input[^1] != 'x') && (input.Length != 6 || input[^2..] != "xp")) { error = "wrong format"; return false; } if (!TryParseSquare(input[..2], out move.origin)) { error = "wrong format on origin"; return false; } if (!TryParseSquare(input[2..4], out move.target)) { error = "wrong format on target"; return false; } if (input[^1] == 'x') move.isCapture = true; if (input[^2..] == "xp") { move.isCapture = true; move.isEnPassant = true; } return true; } public static bool TryParse(string input, Board board, out Move move, out string error) { move = new(-1, -1); error = ""; Match promotionSegment = Regex.Match(input, @"=[A-Z]([+#!?.]|$)"); if (promotionSegment.Success) { move.promote = promotionSegment.Value[1]; if (!Piece.PieceCharacters.Contains(move.promote)) { error = $"\"{move.promote}\" cannot be parsed to a valid piece!"; return true; } if (move.promote == Piece.King.representation || move.promote == Piece.Pawn.representation) { error = $"You can't promote a piece to a King or a Pawn."; return true; } } if (Regex.IsMatch(input.ToUpper(), @"^[O0]\-[O0]([+#!?.\s]|$)")) { if (!board.castling[board.isWhitesTurn ? 0 : 2]) { error = "Short castling is currently unavailable!"; return true; } move.origin = board.isWhitesTurn ? 60 : 4; move.target = board.isWhitesTurn ? 62 : 6; move.isCastle = true; int dir = move.target - move.origin > 0 ? 1 : -1; int rook = board.isWhitesTurn ? 63 : 7; for (int pos = move.origin + dir; pos != rook; pos += dir) { if (board.GetSquare(pos) != '-') { error = $"Can't castle king-side! A piece is obstructing the castle in {ToSquareName(ToMatrixCoords(pos))}."; return true; } } return true; } else if (Regex.IsMatch(input.ToUpper(), @"^[O0]\-[O0]\-[O0]([+#!?.\s]|$)")) { if (!board.castling[board.isWhitesTurn ? 1 : 3]) { error = "Long castling is currently unavailable!"; return true; } move.origin = board.isWhitesTurn ? 60 : 4; move.target = board.isWhitesTurn ? 58 : 2; move.isCastle = true; int dir = move.target - move.origin > 0 ? 1 : -1; int rook = board.isWhitesTurn ? 56 : 0; for (int pos = move.origin + dir; pos != rook; pos += dir) { if (board.GetSquare(pos) != '-') { error = $"Can't castle queen-side! A piece is obstructing the castle in {ToSquareName(ToMatrixCoords(pos))}."; return true; } } return true; } List<int> potentialOrigins = new(); int rankFilter = -1; int fileFilter = -1; Piece toMove; Match explicitFormMatch = Regex.Match(input, @"^[a-h][1-8][x\s]*[a-hA-H][1-8]"); if (explicitFormMatch.Success) { if (!TryParseSquare(explicitFormMatch.Value[..2], out move.origin)) { error = $"The specified origin square ({explicitFormMatch.Value[..2]}) is invalid!"; return true; } potentialOrigins.Add(move.origin); if (!Piece.PieceCharacters.Contains(char.ToUpper(board.GetSquare(move.origin)))) { error = $"The specified origin square ({explicitFormMatch.Value[..2]}) doesn't contain a valid piece"; return true; } toMove = Piece.FromRepresentation(board.GetSquare(move.origin)); if (!TryParseSquare(explicitFormMatch.Value[^2..].ToLower(), out move.target)) { error = $"The specified target square ({explicitFormMatch.Value[^2..]}) is invalid!"; return true; } if (!toMove.isValid(move.origin, move.target, board, false)) { error = "The targeted piece cannot move to the desired square!"; return true; } } else { Match basicFormMatch = Regex.Match(input, @"^[A-Z]?[a-h1-8]?x?[a-hA-H][1-8]"); if (basicFormMatch.Success) { string basicForm = basicFormMatch.Value; if (!TryParseSquare(basicForm[^2..].ToLower(), out move.target)) { error = $"The specified target square ({basicForm[^2..]}) is invalid!"; return true; } if (char.IsLower(basicForm[0])) toMove = Piece.Pawn; else if (!Piece.PieceCharacters.Contains(input[0])) { error = $"\"{input[0]}\" cannot be parsed to a valid piece!"; return true; } else toMove = Piece.FromRepresentation(input[0]); if (Regex.IsMatch(basicForm, @"^[A-Z]?[a-h]x?[a-hA-H][1-8]")) { fileFilter = (char.IsLower(basicForm[0]) ? basicForm[0] : basicForm[1]) - 'a'; } else if (Regex.IsMatch(basicForm, @"^[A-Z][1-8]x?[a-hA-H][1-8]")) { rankFilter = '8' - basicForm[1]; } char targetPiece = board.isWhitesTurn ? toMove.representation : char.ToLower(toMove.representation); for (int x = 0; x < 8; x++) { if (fileFilter != -1 && fileFilter != x) continue; for (int y = 0; y < 8; y++) { if (rankFilter != -1 && rankFilter != y) continue; if (board.squares[x, y] == targetPiece) potentialOrigins.Add(x + y * 8); } } List<int> validOrigins = new(); foreach (int origin in potentialOrigins) { if (toMove.isValid(origin, move.target, board, false)) { validOrigins.Add(origin); } } if (validOrigins.Count == 0) { error = $"Invalid move! Unable to find any {toMove.name}" + $"{(fileFilter == -1 ? "" : $" in file {(char)('a' + fileFilter)}")}" + $"{(rankFilter == -1 ? "" : $" in rank {(char)('8' - rankFilter)}")}" + $" which can move to {ToSquareName(ToMatrixCoords(move.target))}"; return true; } else if (validOrigins.Count > 1) { string[] ambiguousSquares = new string[validOrigins.Count]; for (int i = 0; i < ambiguousSquares.Length; i++) { ambiguousSquares[i] = ToSquareName(ToMatrixCoords(validOrigins[i])); } error = $"Ambiguous move! A {toMove.name} can move to that position from: {string.Join(", ", ambiguousSquares)}"; return true; } move.origin = validOrigins[0]; } else return false; } if (move.origin >= 0 && move.target >= 0) { if (((move.target / 8 == 0 && board.isWhitesTurn) || (move.target / 8 == 7 && !board.isWhitesTurn)) && (toMove == Piece.Pawn)) { if (move.promote == ' ') move.promote = Piece.Queen.representation; } else move.promote = ' '; } if (move.target == board.enPassant && toMove == Piece.Pawn && board.GetSquare(move.target) == '-' && (move.target - move.origin) % 8 != 0) { move.isEnPassant = true; move.isCapture = true; } if (board.GetSquare(move.target) != '-') move.isCapture = true; return true; } public Move(int origin, int target, bool isCastle = false, bool isCapture = false, bool isEnPassant = false, bool isCheck = false, bool isCheckMate = false, char promote = ' ') { this.origin = origin; this.target = target; this.isCastle = isCastle; this.isCapture = isCapture; this.isEnPassant = isEnPassant; this.isCheck = isCheck; this.isCheckMate = isCheckMate; this.promote = promote; } public List<int> ToHighlight() { List<int> result = new(); result.Add(origin); result.Add(target); if (isCastle) { if (target % 8 < 4) { result.Add(target + 1); result.Add(target - 2); } else { result.Add(target - 1); result.Add(target + 1); } } return result; } public List<int> ToEnPassant() { List<int> result = new(); result.Add((origin / 8) * 8 + target % 8); return result; } public List<int> ToDanger(Board board) { List<int> result = new(); if (isCheck || isCheckMate) { result.Add(board.isWhitesTurn ? board.whiteKing : board.blackKing); } return result; } /// <summary> /// Stringifies the move. /// </summary> /// <returns>A string representing the origin and endpoint of the move.</returns> public override string ToString() { if (isCastle) { return target > origin ? "O-O" : "O-O-O"; } Tuple<int, int> originpos = ToMatrixCoords(origin); Tuple<int, int> finalpos = ToMatrixCoords(target); return $"{ToSquareName(originpos)}{ToSquareName(finalpos)}{(isCapture ? "x" : "")}{(isEnPassant ? "p" : "")}"; } } private enum Outcome { Playing, Draw, FiftyMoveRule, InsufficientMaterial, Checkmate, Check } private class Board { public char[,] squares; public bool isWhitesTurn; public bool[] castling; public int enPassant; public int halfmoves; public int fullmoves; public int whiteKing = -1; public int blackKing = -1; public static bool TryParseBoard(string fen, out Board board, out string error) { error = ""; board = new Board(); string[] components = fen.Split(" "); if (components.Length < 6) { error = "Missing components! The syntax must be `positions turn castling enpassant halfmoves fullmoves`"; return false; } string[] ranks = components[0].Split('/'); if (ranks.Length != 8) { error = "Positions expression doesn't have the correct number of ranks separated by '/'"; return false; } char[] pieceChars = Piece.PieceCharacters; board.squares = new char[8, 8]; for (int i = 0; i < 8; i++) { int counter = 0; foreach (char c in ranks[i]) { if (counter >= 8) { error = $"Rank {8 - i} contains more than 8 positions."; return false; } if (!int.TryParse(c.ToString(), out int n)) { if (!pieceChars.Contains(char.ToUpper(c))) { error = $"Rank {8 - i} contains an invalid piece: \"{c}\""; return false; } if (c == 'K') { if (board.whiteKing >= 0) { error = $"This board contains more than one white king!"; return false; } board.whiteKing = i * 8 + counter; } else if (c == 'k') { if (board.blackKing >= 0) { error = $"This board contains more than one black king!"; return false; } board.blackKing = i * 8 + counter; } board.squares[counter++, i] = c; continue; } if (counter + n > 8) { error = $"Rank {8 - i} contains more than 8 positions."; return false; } for (int j = 0; j < n; j++) { board.squares[counter++, i] = '-'; } } } if (board.whiteKing < 0 || board.blackKing < 0) { error = $"Both colors must at least have a king!"; return false; } board.isWhitesTurn = components[1] == "w"; board.castling = new bool[] { components[2].Contains('K'), components[2].Contains('Q'), components[2].Contains('k'), components[2].Contains('q') }; if (board.squares[0, 0] != 'r') board.castling[3] = false; if (board.squares[4, 0] != 'k') { board.castling[2] = false; board.castling[3] = false; } if (board.squares[7, 0] != 'r') board.castling[2] = false; if (board.squares[0, 7] != 'R') board.castling[1] = false; if (board.squares[4, 7] != 'K') { board.castling[0] = false; board.castling[1] = false; } if (board.squares[7, 7] != 'R') board.castling[0] = false; if (components[3] == "-") board.enPassant = -1; else if (!TryParseSquare(components[3], out board.enPassant)) { error = "Unable to parse en-passant square into a valid square (a1-h8)"; return false; } if (!int.TryParse(components[4], out board.halfmoves)) { error = "Unable to parse halfmoves into an integer."; return false; } if (!int.TryParse(components[5], out board.fullmoves)) { error = "Unable to parse fullmoves into an integer."; return false; } return true; } public void ExecuteMove(Move move) { int x0 = move.origin % 8; int y0 = move.origin / 8; int xf = move.target % 8; int yf = move.target / 8; char representation = squares[x0, y0]; squares[x0, y0] = '-'; squares[xf, yf] = representation; if (move.isEnPassant) squares[xf, y0] = '-'; if (move.isCastle) { squares[xf < 4 ? 0 : 7, yf] = '-'; squares[(x0 + xf) / 2, yf] = 'r'.MatchCase(representation); } bool isPawn = char.ToUpper(representation) == Piece.Pawn.representation; if (isPawn && Math.Abs(yf - y0) == 2) enPassant = (move.target + move.origin) / 2; else enPassant = -1; if (isPawn && move.promote != ' ') squares[xf, yf] = move.promote.MatchCase(representation); if (char.ToUpper(representation) == Piece.King.representation) { if (char.IsUpper(representation)) whiteKing = move.target; else blackKing = move.target; } isWhitesTurn = !isWhitesTurn; if (isWhitesTurn) fullmoves++; if (isPawn || move.isCapture) halfmoves = 0; else halfmoves++; } public Outcome GetOutcome() { if (halfmoves >= 100) return Outcome.FiftyMoveRule; if (InsufficientMaterial()) return Outcome.InsufficientMaterial; bool check = IsThreatenedVerbose(isWhitesTurn ? whiteKing : blackKing, true, out bool doubleAttack, out int attacker); bool noMove = !HasLegalMoves(check, doubleAttack, attacker); if (check && noMove) { return Outcome.Checkmate; } else if (check) { return Outcome.Check; } else if (noMove) { return Outcome.Draw; } return Outcome.Playing; } public bool InsufficientMaterial() { Dictionary<char, int> pieceCounts = new(); foreach (char p in Piece.PieceCharacters) { pieceCounts.Add(p, 0); pieceCounts.Add(char.ToLower(p), 0); } for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { char c = squares[x, y]; if (c == '-') continue; else pieceCounts[c]++; } } for (int i = 0; i <= 1; i++) { char color = i == 0 ? 'a' : 'A'; if (pieceCounts[Piece.Queen.representation.MatchCase(color)] > 0) return false; if (pieceCounts[Piece.Rook.representation.MatchCase(color)] > 0) return false; if (pieceCounts[Piece.Pawn.representation.MatchCase(color)] > 0) return false; if (pieceCounts[Piece.Bishop.representation.MatchCase(color)] + pieceCounts[Piece.Knight.representation.MatchCase(color)] > 1) return false; } return true; } public bool HasLegalMoves(bool inCheck, bool doubleAttack, int attackerPos) { HashSet<int> pinned = new(); int kingPos = isWhitesTurn ? whiteKing : blackKing; if (!inCheck) { for (int pos = 0; pos < 64; pos++) { if (pos == kingPos) continue; char piecechar = GetSquare(pos); if (piecechar == '-' || char.IsLower(piecechar) == isWhitesTurn) continue; if (IsPiecePinned(pos, kingPos)) { pinned.Add(pos); } else { Piece piece = Piece.FromRepresentation(piecechar); if (piece.hasValidMoves(pos, this, false)) { return true; } } } int kx = kingPos % 8; int ky = kingPos / 8; foreach (int pos in pinned) { char piecechar = GetSquare(pos); Piece piece = Piece.FromRepresentation(piecechar); int x0 = pos % 8; int y0 = pos / 8; int dx = Math.Sign(kx - x0); int dy = Math.Sign(ky - y0); for (int sign = -1; sign <= 1; sign += 2) { if (piece.isValid(pos, pos + dx * sign + dy * sign * 8, this, false)) return true; } } if (Piece.King.hasValidMoves(kingPos, this, false)) { return true; } } else { Piece attacker = Piece.FromRepresentation(GetSquare(attackerPos)); HashSet<int> blockSquares = new(); if (attacker.canPin && !doubleAttack) { int px = attackerPos % 8; int py = attackerPos / 8; int kx = kingPos % 8; int ky = kingPos / 8; int dx = px - kx; int dy = py - ky; int adv = Math.Sign(dx) + Math.Sign(dy) * 8; int newPos = kingPos + adv; while (newPos != attackerPos) { blockSquares.Add(newPos); newPos += adv; } } for (int pos = 0; pos < 64; pos++) { if (pos == kingPos) continue; char piecechar = GetSquare(pos); if (piecechar == '-' || char.IsLower(piecechar) == isWhitesTurn) continue; if (IsPiecePinned(pos, kingPos)) { pinned.Add(pos); } else if (!doubleAttack) { //If it is not pinned AND can capture only attacker, legal. Piece piece = Piece.FromRepresentation(piecechar); if (piece.isValid(pos, attackerPos, this, false)) return true; foreach (int sq in blockSquares) { //If a piece can block the attack, legal. if (piece.isValid(pos, sq, this, false)) return true; } } } //If the king can move, legal. if (Piece.King.hasValidMoves(kingPos, this, false)) return true; } return false; } public char GetSquare(int value) { return squares[value % 8, value / 8]; } public override string ToString() { StringBuilder builder = new(80); for (int y = 0; y < 8; y++) { if (y != 0) builder.Append('/'); int spaces = 0; for (int x = 0; x < 8; x++) { if (squares[x, y] == '-') { spaces++; continue; } if (spaces > 0) { builder.Append(spaces); spaces = 0; } builder.Append(squares[x, y]); } if (spaces > 0) builder.Append(spaces); } builder.Append($" {(isWhitesTurn ? 'w' : 'b')} "); if (!castling[0] && !castling[1] && !castling[2] && !castling[3]) builder.Append('-'); else { if (castling[0]) builder.Append('K'); if (castling[1]) builder.Append('Q'); if (castling[2]) builder.Append('k'); if (castling[3]) builder.Append('q'); } builder.Append(' '); string enPassantExpression = "-"; if (enPassant >= 0) { enPassantExpression = ToSquareName(ToMatrixCoords(enPassant)); } builder.Append($"{enPassantExpression} {halfmoves} {fullmoves}"); return builder.ToString(); } public object Clone() { Board output = new(); output.squares = new char[8, 8]; for (int i = 0; i < 64; i++) { output.squares.SetValue((Char)squares[i / 8, i % 8], new int[] { i / 8, i % 8 }); } output.isWhitesTurn = (bool)isWhitesTurn; output.castling = new bool[4]; for (int i = 0; i < 4; i++) { output.castling.SetValue((bool)castling[i], i); } output.enPassant = (int)enPassant; output.halfmoves = (int)halfmoves; output.fullmoves = (int)fullmoves; output.whiteKing = (int)whiteKing; output.blackKing = (int)blackKing; return output; } public bool IsThreatened(int square, bool flipThreat = false) { for (int position = 0; position < 64; position++) { char pieceName = squares[position % 8, position / 8]; if (!char.IsLetter(pieceName)) continue; if ((char.IsUpper(pieceName) == isWhitesTurn) ^ flipThreat) { Piece attacker = Piece.FromRepresentation(pieceName); if (attacker.isValid(position, square, this, flipThreat)) return true; } } return false; } public bool IsControlled(int square, bool flipThreat = false) { for (int position = 0; position < 64; position++) { char pieceName = squares[position % 8, position / 8]; if (!char.IsLetter(pieceName)) continue; if ((char.IsUpper(pieceName) == isWhitesTurn) ^ flipThreat) { Piece attacker = Piece.FromRepresentation(pieceName); char temp = squares[square % 8, square / 8]; char enemyPiece = isWhitesTurn ^ flipThreat ? char.ToLower(Piece.Pawn.representation) : char.ToUpper(Piece.Pawn.representation); squares[square % 8, square / 8] = enemyPiece; if (attacker.isValid(position, square, this, flipThreat)) { squares[square % 8, square / 8] = temp; return true; } else { squares[square % 8, square / 8] = temp; } } } return false; } public bool IsThreatenedVerbose(int square, bool flipThreat, out bool multipleAttackers, out int firstAttacker) { multipleAttackers = false; firstAttacker = -1; for (int position = 0; position < 64; position++) { char pieceName = squares[position % 8, position / 8]; if (!char.IsLetter(pieceName)) continue; if ((char.IsUpper(pieceName) == isWhitesTurn) ^ flipThreat) { Piece attacker = Piece.FromRepresentation(pieceName); if (attacker.isValid(position, square, this, flipThreat)) { if (firstAttacker >= 0) { multipleAttackers = true; return true; } else { firstAttacker = position; } } } } return firstAttacker >= 0; } public bool IsPiecePinned(int piecePosition, int kingLocation) { if (piecePosition == kingLocation) return false; int px = piecePosition % 8; int py = piecePosition / 8; int kx = kingLocation % 8; int ky = kingLocation / 8; int dx = px - kx; int dy = py - ky; if (dx != 0 && dy != 0 && dx != dy && dx != -dy) return false; int xAdv = Math.Sign(dx); int yAdv = Math.Sign(dy); int x = kx + xAdv; int y = ky + yAdv; bool beforePiece = true; while (x >= 0 && x < 8 && y >= 0 && y < 8) { if (x == px && y == py) { beforePiece = false; x += xAdv; y += yAdv; continue; } if (squares[x, y] != '-') { if (beforePiece) return false; Piece p = Piece.FromRepresentation(squares[x, y]); return p.canPin && p.isValid(x + y * 8, piecePosition, this, true); } x += xAdv; y += yAdv; } return false; } } } }
44.041033
289
0.434602
[ "MIT" ]
IndigoManedWolf/Dexter
Dexter/Helpers/Games/GameChess.cs
86,939
C#
//----------------------------------------------------------------------- // <copyright file="IJournalBehaviorSetter.cs" company="Akka.NET Project"> // Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- namespace Akka.Persistence.TestKit { using System.Threading.Tasks; public interface IJournalBehaviorSetter { Task SetInterceptorAsync(IJournalInterceptor interceptor); } }
37.3125
87
0.542714
[ "Apache-2.0" ]
Legacy07/akka.net
src/core/Akka.Persistence.TestKit/Journal/IJournalBehaviorSetter.cs
597
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Utilities { [ComImport] [Guid("9AD7EC03-4157-45B4-A999-403D6DB94578")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IVsEnumDebugName { [PreserveSig] int Next(uint celt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.Interface)] IVsDebugName[] rgelt, [Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] uint[] pceltFetched); [PreserveSig] int Skip(uint celt); [PreserveSig] int Reset(); [PreserveSig] int Clone(out IVsEnumDebugName ppEnum); [PreserveSig] int GetCount(out uint pceltCount); } }
31.939394
113
0.702087
[ "MIT" ]
06needhamt/roslyn
src/VisualStudio/Core/Def/Implementation/Utilities/IVsEnumDebugName.cs
1,056
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Compute.V20181001.Outputs { [OutputType] public sealed class ManagedDiskParametersResponse { /// <summary> /// Resource Id /// </summary> public readonly string? Id; /// <summary> /// Specifies the storage account type for the managed disk. NOTE: UltraSSD_LRS can only be used with data disks, it cannot be used with OS Disk. /// </summary> public readonly string? StorageAccountType; [OutputConstructor] private ManagedDiskParametersResponse( string? id, string? storageAccountType) { Id = id; StorageAccountType = storageAccountType; } } }
28.722222
153
0.645068
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Compute/V20181001/Outputs/ManagedDiskParametersResponse.cs
1,034
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Kentico.Kontent.Delivery; using KenticoKontentModels; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace kontent_sample_app_conference_net.Controllers { public class LandingPageController : BaseController { public LandingPageController(IDeliveryClient deliveryClient, IConfiguration configuration) : base(deliveryClient, configuration) { } public async Task<ActionResult> Index() { DeliveryItemListingResponse<Home> response = await DeliveryClient.GetItemsAsync<Home>( new EqualsFilter("system.type", "home") ); if (response.Items.Count > 1) { return View(response.Items); } else { var loc = response.Items.First().Location.First().Name; return RedirectToAction("Index", "Home", new { location = loc }); } } } }
28.837838
136
0.636364
[ "MIT" ]
kentico-michaelb/kontent-sample-app-conference-net
kontent-sample-app-conference-net/Controllers/LandingPageController.cs
1,069
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WaterSimDCDC; namespace WaterSimDCDC { public static class WaterSimManagerInfo { //public static string GetCurrentDirectory = Environment.CurrentDirectory; public static string GetCurrentDirectory { get { return Environment.CurrentDirectory; } } } ///------------------------------------------------------------------------------------------------- /// <summary> Water simulation manager sio. </summary> /// /// <remarks> Ray Quay, 1/7/2014. /// Runs extended watersim but only uses system Input and Output data types </remarks> ///------------------------------------------------------------------------------------------------- public class WaterSimManager_SIO : WaterSimManager { protected SimulationResults FAnnualResults = null; internal bool FIncludeAggregates = false; //int FSimulationYears = 0; ///------------------------------------------------------------------------------------------------- /// <summary> Constructor. </summary> /// /// <param name="DataDirectoryName"> Pathname of the data directory. </param> /// <param name="TempDirectoryName"> Pathname of the temporary directory. </param> ///------------------------------------------------------------------------------------------------- public WaterSimManager_SIO(string DataDirectoryName, string TempDirectoryName) : base (DataDirectoryName,TempDirectoryName) { } ///------------------------------------------------------------------------------------------------- /// <summary> Gets or sets a value indicating whether the aggregates should be included in the Simulation results for Provider Outputs. </summary> /// /// <value> true if include aggregates, false if not. </value> ///------------------------------------------------------------------------------------------------- public bool IncludeAggregates { get { return FIncludeAggregates; } set { FIncludeAggregates = value; } } /// <summary> Simulation initialize. </summary> public override void Simulation_Initialize() { base.Simulation_Initialize(); FAnnualResults = null; } ///------------------------------------------------------------------------------------------------- /// <summary> Executes the year operation. </summary> /// /// <param name="year"> The year. </param> ///------------------------------------------------------------------------------------------------- protected override bool runYear(int year) { bool testrun = base.runYear(year); if (testrun) { fetchData(year, ref FAnnualResults); } return testrun; } ///------------------------------------------------------------------------------------------------- /// <summary> Gets the simulation next year. </summary> /// /// <returns> . </returns> ///------------------------------------------------------------------------------------------------- public override int Simulation_NextYear() { if (Sim_CurrentYear == 0) { int NumberOfYears = (Simulation_End_Year - Simulation_Start_Year) + 1; initializeData(NumberOfYears, Sim_StartYear, ref FAnnualResults, FIncludeAggregates); } return base.Simulation_NextYear(); } /// <summary> Simulation all years. </summary> public override void Simulation_AllYears() { int NumberOfYears = (Simulation_End_Year - Simulation_Start_Year) + 1; initializeData(NumberOfYears, Sim_StartYear, ref FAnnualResults, FIncludeAggregates); base.Simulation_AllYears(); } ///------------------------------------------------------------------------------------------------- /// <summary> Gets the simulation results. </summary> /// /// <value> The simulation results. </value> ///------------------------------------------------------------------------------------------------- public SimulationResults SimulationRunResults { get { return FAnnualResults; } } ///------------------------------------------------------------------------------------------------- /// <summary> Initializes the data. </summary> /// /// <remarks> Ray Quay, 1/27/2014. </remarks> /// /// <param name="Years"> The years. </param> /// <param name="StartYear"> the AnnualSimulationResults . </param> /// <param name="SimResults"> [in,out] The simulation results. </param> ///------------------------------------------------------------------------------------------------- internal void initializeData(int Years, int StartYear, ref SimulationResults SimResults) { initializeData(Years, StartYear, ref SimResults, false); } ///------------------------------------------------------------------------------------------------- /// <summary> Initializes the data. </summary> /// <param name="Years"> The years. </param> /// <param name="StartYear"> the AnnualSimulationResults . </param> /// <param name="SimResults"> The simulation results. </param> /// <param name="IncludeAggregates"> true to include, false to exclude the aggregates. </param> ///------------------------------------------------------------------------------------------------- internal void initializeData(int Years, int StartYear, ref SimulationResults SimResults, bool IncludeAggregates) { if ((SimResults != null)&&(Years == (SimResults.LastYear-SimResults.StartYear)+1)) // if not new then zero it out from last use Added 5 22 12 { // Only supporting Aggregates in Output right now ProviderIntArray OutBlank = new ProviderIntArray(0,IncludeAggregates); ProviderIntArray InBlank = new ProviderIntArray(0, false); for (int yr = 0; yr < Years; yr++) { AnnualSimulationResults TheASR = SimResults[yr]; int cnt = 0; cnt = ParamManager.NumberOfParameters(modelParamtype.mptOutputBase); for (int parmi = 0; parmi < cnt; parmi++) { TheASR.Outputs.BaseOutput[parmi] = 0; TheASR.Outputs.BaseOutputModelParam[parmi] = -1; } cnt = 0; cnt = ParamManager.NumberOfParameters(modelParamtype.mptOutputProvider); for (int parmi = 0; parmi < cnt; parmi++) { TheASR.Outputs.ProviderOutput[parmi] = OutBlank; TheASR.Outputs.ProviderOutputModelParam[parmi] = -1; } cnt = 0; cnt = ParamManager.NumberOfParameters(modelParamtype.mptInputBase); for (int parmi = 0; parmi < cnt; parmi++) { TheASR.Inputs.BaseInput[parmi] = 0; TheASR.Inputs.BaseInputModelParam[parmi] = -1; } cnt = 0; cnt = ParamManager.NumberOfParameters(modelParamtype.mptInputProvider); for (int parmi = 0; parmi < cnt; parmi++) { TheASR.Inputs.ProviderInput[parmi] = InBlank; TheASR.Inputs.ProviderInputModelParam[parmi] = -1; } } } else { SimResults = new SimulationResults(Years, StartYear, ParamManager.NumberOfParameters(modelParamtype.mptOutputBase), ParamManager.NumberOfParameters(modelParamtype.mptOutputProvider), ParamManager.NumberOfParameters(modelParamtype.mptInputBase), ParamManager.NumberOfParameters(modelParamtype.mptInputProvider) , IncludeAggregates); } } ///------------------------------------------------------------------------------------------------- /// <summary> Fetches a data. </summary> /// /// <param name="year"> The year. </param> /// <param name="TheASR"> [in,out] the AnnualSimulationResults </param> ///------------------------------------------------------------------------------------------------- internal void fetchData(int year, ref SimulationResults SimResults) { int datai = 0; int index = year - Sim_StartYear; // changed 7 26 11 _SimulationDB_Start_Year; if ((index >= 0) & (index < SimResults.Length)) { int BaseOutputSize = ParamManager.NumberOfParameters(modelParamtype.mptOutputBase); int ProviderOutputSize = ParamManager.NumberOfParameters(modelParamtype.mptOutputProvider); int BaseInputSize = ParamManager.NumberOfParameters(modelParamtype.mptInputBase); int ProviderInputSize = ParamManager.NumberOfParameters(modelParamtype.mptInputProvider); datai = 0; AnnualSimulationResults TheASR = new AnnualSimulationResults(BaseOutputSize,ProviderOutputSize,BaseInputSize,ProviderInputSize, FIncludeAggregates); try { foreach (ModelParameterClass MP in ParamManager.BaseOutputs()) { TheASR.Outputs.BaseOutput[datai] = MP.Value; TheASR.Outputs.BaseOutputModelParam[datai] = MP.ModelParam; datai++; } } catch (Exception ex) { bool check = true; } datai = 0; foreach (ModelParameterClass MP in ParamManager.BaseInputs()) { TheASR.Inputs.BaseInput[datai] = MP.Value; TheASR.Inputs.BaseInputModelParam[datai] = MP.ModelParam; datai++; } datai = 0; foreach (ModelParameterClass MP in ParamManager.ProviderOutputs()) { // OK this is a bit complicated becuase of Aggregates if ((!TheASR.Outputs.AggregatesIncluded)||(MP.ProviderProperty.AggregateMode==eProviderAggregateMode.agNone)) { TheASR.Outputs.ProviderOutput[datai] = MP.ProviderProperty.getvalues(); } else { for (int i = 0; i < TheASR.Outputs.ProviderOutput[datai].Length; i++) { int tempVal = MP.ProviderProperty[i]; TheASR.Outputs.ProviderOutput[datai].Values[i] = tempVal; } } TheASR.Outputs.ProviderOutputModelParam[datai] = MP.ModelParam; datai++; } datai = 0; foreach (ModelParameterClass MP in ParamManager.ProviderInputs()) { // OK this is a bit complicated becuase of Aggregates if ((!TheASR.Inputs.AggregatesIncluded) || (MP.ProviderProperty.AggregateMode == eProviderAggregateMode.agNone)) { TheASR.Inputs.ProviderInput[datai] = MP.ProviderProperty.getvalues(); } else { TheASR.Inputs.ProviderInput.Values[datai] = MP.ProviderProperty.getvalues(); //for (int i = 0; i < TheASR.Inputs.ProviderInput[datai].Length; i++) //{ // int tempVal = MP.ProviderProperty[i]; // TheASR.Inputs.ProviderInput[datai].Values[i] = tempVal; //} } //TheASR.Inputs.ProviderInput[datai] = MP.ProviderProperty.getvalues(); TheASR.Inputs.ProviderInputModelParam[datai] = MP.ModelParam; datai++; } TheASR.year = year; SimResults[index] = TheASR; } } } }
45.56701
164
0.445701
[ "MIT" ]
DCDCWaterSim/API_SOURCE_FILES
WaterSimDCDC_API_SIO_v_9_01.cs
13,262
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: grafeas/v1/intoto_provenance.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Grafeas.V1 { /// <summary>Holder for reflection information generated from grafeas/v1/intoto_provenance.proto</summary> public static partial class IntotoProvenanceReflection { #region Descriptor /// <summary>File descriptor for grafeas/v1/intoto_provenance.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static IntotoProvenanceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJncmFmZWFzL3YxL2ludG90b19wcm92ZW5hbmNlLnByb3RvEgpncmFmZWFz", "LnYxGhlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGh9nb29nbGUvcHJvdG9i", "dWYvdGltZXN0YW1wLnByb3RvIpwBCgZSZWNpcGUSDAoEdHlwZRgBIAEoCRIb", "ChNkZWZpbmVkX2luX21hdGVyaWFsGAIgASgDEhMKC2VudHJ5X3BvaW50GAMg", "ASgJEicKCWFyZ3VtZW50cxgEIAMoCzIULmdvb2dsZS5wcm90b2J1Zi5BbnkS", "KQoLZW52aXJvbm1lbnQYBSADKAsyFC5nb29nbGUucHJvdG9idWYuQW55IkkK", "DENvbXBsZXRlbmVzcxIRCglhcmd1bWVudHMYASABKAgSEwoLZW52aXJvbm1l", "bnQYAiABKAgSEQoJbWF0ZXJpYWxzGAMgASgIItoBCghNZXRhZGF0YRIbChNi", "dWlsZF9pbnZvY2F0aW9uX2lkGAEgASgJEjQKEGJ1aWxkX3N0YXJ0ZWRfb24Y", "AiABKAsyGi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wEjUKEWJ1aWxkX2Zp", "bmlzaGVkX29uGAMgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIu", "Cgxjb21wbGV0ZW5lc3MYBCABKAsyGC5ncmFmZWFzLnYxLkNvbXBsZXRlbmVz", "cxIUCgxyZXByb2R1Y2libGUYBSABKAgiGwoNQnVpbGRlckNvbmZpZxIKCgJp", "ZBgBIAEoCSKkAQoQSW5Ub3RvUHJvdmVuYW5jZRIxCg5idWlsZGVyX2NvbmZp", "ZxgBIAEoCzIZLmdyYWZlYXMudjEuQnVpbGRlckNvbmZpZxIiCgZyZWNpcGUY", "AiABKAsyEi5ncmFmZWFzLnYxLlJlY2lwZRImCghtZXRhZGF0YRgDIAEoCzIU", "LmdyYWZlYXMudjEuTWV0YWRhdGESEQoJbWF0ZXJpYWxzGAQgAygJQlEKDWlv", "LmdyYWZlYXMudjFQAVo4Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29v", "Z2xlYXBpcy9ncmFmZWFzL3YxO2dyYWZlYXOiAgNHUkFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Grafeas.V1.Recipe), global::Grafeas.V1.Recipe.Parser, new[]{ "Type", "DefinedInMaterial", "EntryPoint", "Arguments", "Environment" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grafeas.V1.Completeness), global::Grafeas.V1.Completeness.Parser, new[]{ "Arguments", "Environment", "Materials" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grafeas.V1.Metadata), global::Grafeas.V1.Metadata.Parser, new[]{ "BuildInvocationId", "BuildStartedOn", "BuildFinishedOn", "Completeness", "Reproducible" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grafeas.V1.BuilderConfig), global::Grafeas.V1.BuilderConfig.Parser, new[]{ "Id" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Grafeas.V1.InTotoProvenance), global::Grafeas.V1.InTotoProvenance.Parser, new[]{ "BuilderConfig", "Recipe", "Metadata", "Materials" }, null, null, null, null) })); } #endregion } #region Messages /// <summary> /// Steps taken to build the artifact. /// For a TaskRun, typically each container corresponds to one step in the /// recipe. /// </summary> public sealed partial class Recipe : pb::IMessage<Recipe> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Recipe> _parser = new pb::MessageParser<Recipe>(() => new Recipe()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Recipe> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Grafeas.V1.IntotoProvenanceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Recipe() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Recipe(Recipe other) : this() { type_ = other.type_; definedInMaterial_ = other.definedInMaterial_; entryPoint_ = other.entryPoint_; arguments_ = other.arguments_.Clone(); environment_ = other.environment_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Recipe Clone() { return new Recipe(this); } /// <summary>Field number for the "type" field.</summary> public const int TypeFieldNumber = 1; private string type_ = ""; /// <summary> /// URI indicating what type of recipe was performed. It determines the meaning /// of recipe.entryPoint, recipe.arguments, recipe.environment, and materials. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Type { get { return type_; } set { type_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "defined_in_material" field.</summary> public const int DefinedInMaterialFieldNumber = 2; private long definedInMaterial_; /// <summary> /// Index in materials containing the recipe steps that are not implied by /// recipe.type. For example, if the recipe type were "make", then this would /// point to the source containing the Makefile, not the make program itself. /// Set to -1 if the recipe doesn't come from a material, as zero is default /// unset value for int64. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long DefinedInMaterial { get { return definedInMaterial_; } set { definedInMaterial_ = value; } } /// <summary>Field number for the "entry_point" field.</summary> public const int EntryPointFieldNumber = 3; private string entryPoint_ = ""; /// <summary> /// String identifying the entry point into the build. /// This is often a path to a configuration file and/or a target label within /// that file. The syntax and meaning are defined by recipe.type. For example, /// if the recipe type were "make", then this would reference the directory in /// which to run make as well as which target to use. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string EntryPoint { get { return entryPoint_; } set { entryPoint_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "arguments" field.</summary> public const int ArgumentsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Any> _repeated_arguments_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.WellKnownTypes.Any.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> arguments_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any>(); /// <summary> /// Collection of all external inputs that influenced the build on top of /// recipe.definedInMaterial and recipe.entryPoint. For example, if the recipe /// type were "make", then this might be the flags passed to make aside from /// the target, which is captured in recipe.entryPoint. Since the arguments /// field can greatly vary in structure, depending on the builder and recipe /// type, this is of form "Any". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> Arguments { get { return arguments_; } } /// <summary>Field number for the "environment" field.</summary> public const int EnvironmentFieldNumber = 5; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Any> _repeated_environment_codec = pb::FieldCodec.ForMessage(42, global::Google.Protobuf.WellKnownTypes.Any.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> environment_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any>(); /// <summary> /// Any other builder-controlled inputs necessary for correctly evaluating the /// recipe. Usually only needed for reproducing the build but not evaluated as /// part of policy. Since the environment field can greatly vary in structure, /// depending on the builder and recipe type, this is of form "Any". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> Environment { get { return environment_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Recipe); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Recipe other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Type != other.Type) return false; if (DefinedInMaterial != other.DefinedInMaterial) return false; if (EntryPoint != other.EntryPoint) return false; if(!arguments_.Equals(other.arguments_)) return false; if(!environment_.Equals(other.environment_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Type.Length != 0) hash ^= Type.GetHashCode(); if (DefinedInMaterial != 0L) hash ^= DefinedInMaterial.GetHashCode(); if (EntryPoint.Length != 0) hash ^= EntryPoint.GetHashCode(); hash ^= arguments_.GetHashCode(); hash ^= environment_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (DefinedInMaterial != 0L) { output.WriteRawTag(16); output.WriteInt64(DefinedInMaterial); } if (EntryPoint.Length != 0) { output.WriteRawTag(26); output.WriteString(EntryPoint); } arguments_.WriteTo(output, _repeated_arguments_codec); environment_.WriteTo(output, _repeated_environment_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Type.Length != 0) { output.WriteRawTag(10); output.WriteString(Type); } if (DefinedInMaterial != 0L) { output.WriteRawTag(16); output.WriteInt64(DefinedInMaterial); } if (EntryPoint.Length != 0) { output.WriteRawTag(26); output.WriteString(EntryPoint); } arguments_.WriteTo(ref output, _repeated_arguments_codec); environment_.WriteTo(ref output, _repeated_environment_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Type.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Type); } if (DefinedInMaterial != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(DefinedInMaterial); } if (EntryPoint.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(EntryPoint); } size += arguments_.CalculateSize(_repeated_arguments_codec); size += environment_.CalculateSize(_repeated_environment_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Recipe other) { if (other == null) { return; } if (other.Type.Length != 0) { Type = other.Type; } if (other.DefinedInMaterial != 0L) { DefinedInMaterial = other.DefinedInMaterial; } if (other.EntryPoint.Length != 0) { EntryPoint = other.EntryPoint; } arguments_.Add(other.arguments_); environment_.Add(other.environment_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Type = input.ReadString(); break; } case 16: { DefinedInMaterial = input.ReadInt64(); break; } case 26: { EntryPoint = input.ReadString(); break; } case 34: { arguments_.AddEntriesFrom(input, _repeated_arguments_codec); break; } case 42: { environment_.AddEntriesFrom(input, _repeated_environment_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Type = input.ReadString(); break; } case 16: { DefinedInMaterial = input.ReadInt64(); break; } case 26: { EntryPoint = input.ReadString(); break; } case 34: { arguments_.AddEntriesFrom(ref input, _repeated_arguments_codec); break; } case 42: { environment_.AddEntriesFrom(ref input, _repeated_environment_codec); break; } } } } #endif } /// <summary> /// Indicates that the builder claims certain fields in this message to be /// complete. /// </summary> public sealed partial class Completeness : pb::IMessage<Completeness> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Completeness> _parser = new pb::MessageParser<Completeness>(() => new Completeness()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Completeness> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Grafeas.V1.IntotoProvenanceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Completeness() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Completeness(Completeness other) : this() { arguments_ = other.arguments_; environment_ = other.environment_; materials_ = other.materials_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Completeness Clone() { return new Completeness(this); } /// <summary>Field number for the "arguments" field.</summary> public const int ArgumentsFieldNumber = 1; private bool arguments_; /// <summary> /// If true, the builder claims that recipe.arguments is complete, meaning that /// all external inputs are properly captured in the recipe. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Arguments { get { return arguments_; } set { arguments_ = value; } } /// <summary>Field number for the "environment" field.</summary> public const int EnvironmentFieldNumber = 2; private bool environment_; /// <summary> /// If true, the builder claims that recipe.environment is claimed to be /// complete. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Environment { get { return environment_; } set { environment_ = value; } } /// <summary>Field number for the "materials" field.</summary> public const int MaterialsFieldNumber = 3; private bool materials_; /// <summary> /// If true, the builder claims that materials are complete, usually through /// some controls to prevent network access. Sometimes called "hermetic". /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Materials { get { return materials_; } set { materials_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Completeness); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Completeness other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Arguments != other.Arguments) return false; if (Environment != other.Environment) return false; if (Materials != other.Materials) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Arguments != false) hash ^= Arguments.GetHashCode(); if (Environment != false) hash ^= Environment.GetHashCode(); if (Materials != false) hash ^= Materials.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Arguments != false) { output.WriteRawTag(8); output.WriteBool(Arguments); } if (Environment != false) { output.WriteRawTag(16); output.WriteBool(Environment); } if (Materials != false) { output.WriteRawTag(24); output.WriteBool(Materials); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Arguments != false) { output.WriteRawTag(8); output.WriteBool(Arguments); } if (Environment != false) { output.WriteRawTag(16); output.WriteBool(Environment); } if (Materials != false) { output.WriteRawTag(24); output.WriteBool(Materials); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Arguments != false) { size += 1 + 1; } if (Environment != false) { size += 1 + 1; } if (Materials != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Completeness other) { if (other == null) { return; } if (other.Arguments != false) { Arguments = other.Arguments; } if (other.Environment != false) { Environment = other.Environment; } if (other.Materials != false) { Materials = other.Materials; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Arguments = input.ReadBool(); break; } case 16: { Environment = input.ReadBool(); break; } case 24: { Materials = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Arguments = input.ReadBool(); break; } case 16: { Environment = input.ReadBool(); break; } case 24: { Materials = input.ReadBool(); break; } } } } #endif } /// <summary> /// Other properties of the build. /// </summary> public sealed partial class Metadata : pb::IMessage<Metadata> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<Metadata> _parser = new pb::MessageParser<Metadata>(() => new Metadata()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<Metadata> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Grafeas.V1.IntotoProvenanceReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Metadata() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Metadata(Metadata other) : this() { buildInvocationId_ = other.buildInvocationId_; buildStartedOn_ = other.buildStartedOn_ != null ? other.buildStartedOn_.Clone() : null; buildFinishedOn_ = other.buildFinishedOn_ != null ? other.buildFinishedOn_.Clone() : null; completeness_ = other.completeness_ != null ? other.completeness_.Clone() : null; reproducible_ = other.reproducible_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public Metadata Clone() { return new Metadata(this); } /// <summary>Field number for the "build_invocation_id" field.</summary> public const int BuildInvocationIdFieldNumber = 1; private string buildInvocationId_ = ""; /// <summary> /// Identifies the particular build invocation, which can be useful for finding /// associated logs or other ad-hoc analysis. The value SHOULD be globally /// unique, per in-toto Provenance spec. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string BuildInvocationId { get { return buildInvocationId_; } set { buildInvocationId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "build_started_on" field.</summary> public const int BuildStartedOnFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp buildStartedOn_; /// <summary> /// The timestamp of when the build started. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Timestamp BuildStartedOn { get { return buildStartedOn_; } set { buildStartedOn_ = value; } } /// <summary>Field number for the "build_finished_on" field.</summary> public const int BuildFinishedOnFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Timestamp buildFinishedOn_; /// <summary> /// The timestamp of when the build completed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Timestamp BuildFinishedOn { get { return buildFinishedOn_; } set { buildFinishedOn_ = value; } } /// <summary>Field number for the "completeness" field.</summary> public const int CompletenessFieldNumber = 4; private global::Grafeas.V1.Completeness completeness_; /// <summary> /// Indicates that the builder claims certain fields in this message to be /// complete. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Grafeas.V1.Completeness Completeness { get { return completeness_; } set { completeness_ = value; } } /// <summary>Field number for the "reproducible" field.</summary> public const int ReproducibleFieldNumber = 5; private bool reproducible_; /// <summary> /// If true, the builder claims that running the recipe on materials will /// produce bit-for-bit identical output. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Reproducible { get { return reproducible_; } set { reproducible_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as Metadata); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(Metadata other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BuildInvocationId != other.BuildInvocationId) return false; if (!object.Equals(BuildStartedOn, other.BuildStartedOn)) return false; if (!object.Equals(BuildFinishedOn, other.BuildFinishedOn)) return false; if (!object.Equals(Completeness, other.Completeness)) return false; if (Reproducible != other.Reproducible) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (BuildInvocationId.Length != 0) hash ^= BuildInvocationId.GetHashCode(); if (buildStartedOn_ != null) hash ^= BuildStartedOn.GetHashCode(); if (buildFinishedOn_ != null) hash ^= BuildFinishedOn.GetHashCode(); if (completeness_ != null) hash ^= Completeness.GetHashCode(); if (Reproducible != false) hash ^= Reproducible.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (BuildInvocationId.Length != 0) { output.WriteRawTag(10); output.WriteString(BuildInvocationId); } if (buildStartedOn_ != null) { output.WriteRawTag(18); output.WriteMessage(BuildStartedOn); } if (buildFinishedOn_ != null) { output.WriteRawTag(26); output.WriteMessage(BuildFinishedOn); } if (completeness_ != null) { output.WriteRawTag(34); output.WriteMessage(Completeness); } if (Reproducible != false) { output.WriteRawTag(40); output.WriteBool(Reproducible); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (BuildInvocationId.Length != 0) { output.WriteRawTag(10); output.WriteString(BuildInvocationId); } if (buildStartedOn_ != null) { output.WriteRawTag(18); output.WriteMessage(BuildStartedOn); } if (buildFinishedOn_ != null) { output.WriteRawTag(26); output.WriteMessage(BuildFinishedOn); } if (completeness_ != null) { output.WriteRawTag(34); output.WriteMessage(Completeness); } if (Reproducible != false) { output.WriteRawTag(40); output.WriteBool(Reproducible); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (BuildInvocationId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BuildInvocationId); } if (buildStartedOn_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BuildStartedOn); } if (buildFinishedOn_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BuildFinishedOn); } if (completeness_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Completeness); } if (Reproducible != false) { size += 1 + 1; } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(Metadata other) { if (other == null) { return; } if (other.BuildInvocationId.Length != 0) { BuildInvocationId = other.BuildInvocationId; } if (other.buildStartedOn_ != null) { if (buildStartedOn_ == null) { BuildStartedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } BuildStartedOn.MergeFrom(other.BuildStartedOn); } if (other.buildFinishedOn_ != null) { if (buildFinishedOn_ == null) { BuildFinishedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } BuildFinishedOn.MergeFrom(other.BuildFinishedOn); } if (other.completeness_ != null) { if (completeness_ == null) { Completeness = new global::Grafeas.V1.Completeness(); } Completeness.MergeFrom(other.Completeness); } if (other.Reproducible != false) { Reproducible = other.Reproducible; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { BuildInvocationId = input.ReadString(); break; } case 18: { if (buildStartedOn_ == null) { BuildStartedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(BuildStartedOn); break; } case 26: { if (buildFinishedOn_ == null) { BuildFinishedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(BuildFinishedOn); break; } case 34: { if (completeness_ == null) { Completeness = new global::Grafeas.V1.Completeness(); } input.ReadMessage(Completeness); break; } case 40: { Reproducible = input.ReadBool(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { BuildInvocationId = input.ReadString(); break; } case 18: { if (buildStartedOn_ == null) { BuildStartedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(BuildStartedOn); break; } case 26: { if (buildFinishedOn_ == null) { BuildFinishedOn = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(BuildFinishedOn); break; } case 34: { if (completeness_ == null) { Completeness = new global::Grafeas.V1.Completeness(); } input.ReadMessage(Completeness); break; } case 40: { Reproducible = input.ReadBool(); break; } } } } #endif } public sealed partial class BuilderConfig : pb::IMessage<BuilderConfig> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<BuilderConfig> _parser = new pb::MessageParser<BuilderConfig>(() => new BuilderConfig()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<BuilderConfig> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Grafeas.V1.IntotoProvenanceReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public BuilderConfig() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public BuilderConfig(BuilderConfig other) : this() { id_ = other.id_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public BuilderConfig Clone() { return new BuilderConfig(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private string id_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as BuilderConfig); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(BuilderConfig other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Id != other.Id) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Id.Length != 0) hash ^= Id.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Id.Length != 0) { output.WriteRawTag(10); output.WriteString(Id); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(BuilderConfig other) { if (other == null) { return; } if (other.Id.Length != 0) { Id = other.Id; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Id = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Id = input.ReadString(); break; } } } } #endif } public sealed partial class InTotoProvenance : pb::IMessage<InTotoProvenance> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<InTotoProvenance> _parser = new pb::MessageParser<InTotoProvenance>(() => new InTotoProvenance()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<InTotoProvenance> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Grafeas.V1.IntotoProvenanceReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InTotoProvenance() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InTotoProvenance(InTotoProvenance other) : this() { builderConfig_ = other.builderConfig_ != null ? other.builderConfig_.Clone() : null; recipe_ = other.recipe_ != null ? other.recipe_.Clone() : null; metadata_ = other.metadata_ != null ? other.metadata_.Clone() : null; materials_ = other.materials_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public InTotoProvenance Clone() { return new InTotoProvenance(this); } /// <summary>Field number for the "builder_config" field.</summary> public const int BuilderConfigFieldNumber = 1; private global::Grafeas.V1.BuilderConfig builderConfig_; /// <summary> /// required /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Grafeas.V1.BuilderConfig BuilderConfig { get { return builderConfig_; } set { builderConfig_ = value; } } /// <summary>Field number for the "recipe" field.</summary> public const int RecipeFieldNumber = 2; private global::Grafeas.V1.Recipe recipe_; /// <summary> /// Identifies the configuration used for the build. /// When combined with materials, this SHOULD fully describe the build, /// such that re-running this recipe results in bit-for-bit identical output /// (if the build is reproducible). /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Grafeas.V1.Recipe Recipe { get { return recipe_; } set { recipe_ = value; } } /// <summary>Field number for the "metadata" field.</summary> public const int MetadataFieldNumber = 3; private global::Grafeas.V1.Metadata metadata_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Grafeas.V1.Metadata Metadata { get { return metadata_; } set { metadata_ = value; } } /// <summary>Field number for the "materials" field.</summary> public const int MaterialsFieldNumber = 4; private static readonly pb::FieldCodec<string> _repeated_materials_codec = pb::FieldCodec.ForString(34); private readonly pbc::RepeatedField<string> materials_ = new pbc::RepeatedField<string>(); /// <summary> /// The collection of artifacts that influenced the build including sources, /// dependencies, build tools, base images, and so on. This is considered to be /// incomplete unless metadata.completeness.materials is true. Unset or null is /// equivalent to empty. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<string> Materials { get { return materials_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as InTotoProvenance); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(InTotoProvenance other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(BuilderConfig, other.BuilderConfig)) return false; if (!object.Equals(Recipe, other.Recipe)) return false; if (!object.Equals(Metadata, other.Metadata)) return false; if(!materials_.Equals(other.materials_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (builderConfig_ != null) hash ^= BuilderConfig.GetHashCode(); if (recipe_ != null) hash ^= Recipe.GetHashCode(); if (metadata_ != null) hash ^= Metadata.GetHashCode(); hash ^= materials_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (builderConfig_ != null) { output.WriteRawTag(10); output.WriteMessage(BuilderConfig); } if (recipe_ != null) { output.WriteRawTag(18); output.WriteMessage(Recipe); } if (metadata_ != null) { output.WriteRawTag(26); output.WriteMessage(Metadata); } materials_.WriteTo(output, _repeated_materials_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (builderConfig_ != null) { output.WriteRawTag(10); output.WriteMessage(BuilderConfig); } if (recipe_ != null) { output.WriteRawTag(18); output.WriteMessage(Recipe); } if (metadata_ != null) { output.WriteRawTag(26); output.WriteMessage(Metadata); } materials_.WriteTo(ref output, _repeated_materials_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (builderConfig_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(BuilderConfig); } if (recipe_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Recipe); } if (metadata_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Metadata); } size += materials_.CalculateSize(_repeated_materials_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(InTotoProvenance other) { if (other == null) { return; } if (other.builderConfig_ != null) { if (builderConfig_ == null) { BuilderConfig = new global::Grafeas.V1.BuilderConfig(); } BuilderConfig.MergeFrom(other.BuilderConfig); } if (other.recipe_ != null) { if (recipe_ == null) { Recipe = new global::Grafeas.V1.Recipe(); } Recipe.MergeFrom(other.Recipe); } if (other.metadata_ != null) { if (metadata_ == null) { Metadata = new global::Grafeas.V1.Metadata(); } Metadata.MergeFrom(other.Metadata); } materials_.Add(other.materials_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { if (builderConfig_ == null) { BuilderConfig = new global::Grafeas.V1.BuilderConfig(); } input.ReadMessage(BuilderConfig); break; } case 18: { if (recipe_ == null) { Recipe = new global::Grafeas.V1.Recipe(); } input.ReadMessage(Recipe); break; } case 26: { if (metadata_ == null) { Metadata = new global::Grafeas.V1.Metadata(); } input.ReadMessage(Metadata); break; } case 34: { materials_.AddEntriesFrom(input, _repeated_materials_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { if (builderConfig_ == null) { BuilderConfig = new global::Grafeas.V1.BuilderConfig(); } input.ReadMessage(BuilderConfig); break; } case 18: { if (recipe_ == null) { Recipe = new global::Grafeas.V1.Recipe(); } input.ReadMessage(Recipe); break; } case 26: { if (metadata_ == null) { Metadata = new global::Grafeas.V1.Metadata(); } input.ReadMessage(Metadata); break; } case 34: { materials_.AddEntriesFrom(ref input, _repeated_materials_codec); break; } } } } #endif } #endregion } #endregion Designer generated code
37.112984
238
0.657506
[ "Apache-2.0" ]
amanda-tarafa/google-cloud-dotnet
apis/Grafeas.V1/Grafeas.V1/IntotoProvenance.g.cs
59,455
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Microsoft.SharePoint.Client; using Microsoft.Phone.Tasks; using System.Device.Location; using Microsoft.Phone.Shell; using Microsoft.SharePoint.Phone.Application; namespace SPListAppLocalStorage { /// <summary> /// ListItem Edit Form /// </summary> public partial class EditForm : PhoneApplicationPage { EditItemViewModel viewModel; /// <summary> /// Constructor for Edit Form /// </summary> public EditForm() { InitializeComponent(); viewModel = App.MainViewModel.SelectedItemEditViewModelInstance; if (!viewModel.IsInitialized) { viewModel.InitializationCompleted += new EventHandler<InitializationCompletedEventArgs>(OnViewModelInitialization); viewModel.Initialize(); } else { this.DataContext = viewModel; } } /// <summary> /// Code to execute when app navigates to Edit Form /// </summary> /// <param name="e" /> protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); viewModel.ItemUpdated += new EventHandler<ItemUpdatedEventArgs>(OnItemUpdated); } /// <summary> /// Code to execute when app navigates away from Edit Form /// </summary> /// <param name="e" /> protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedFrom(e); viewModel.ItemUpdated -= new EventHandler<ItemUpdatedEventArgs>(OnItemUpdated); } /// <summary> /// Code to execute when ViewModel initialization completes /// </summary> /// <param name="sender" /> /// <param name="e" /> private void OnViewModelInitialization(object sender, InitializationCompletedEventArgs e) { this.Dispatcher.BeginInvoke(() => { //If initialization has failed show error message and return if (e.Error != null) { MessageBox.Show(e.Error.Message, e.Error.GetType().Name, MessageBoxButton.OK); return; } //Set Page's DataContext to current ViewModel instance this.DataContext = (sender as EditItemViewModel); }); } /// <summary> /// Code to execute when user clicks on cancel button on the Application /// </summary> private void OnCancelButtonClick(object sender, EventArgs e) { NavigationService.Navigate(new Uri("/Views/List.xaml", UriKind.Relative)); } /// <summary> /// Code to execute when user clicks on Submit button on the ListEdit Form to update SharePoint ListItem /// </summary> private void OnBtnSubmitClick(object sender, EventArgs e) { viewModel.UpdateItem(); } private void OnItemUpdated(object sender, ItemUpdatedEventArgs e) { this.Dispatcher.BeginInvoke(() => { if (e.Error != null) { MessageBox.Show(e.Error.Message, e.Error.GetType().Name, MessageBoxButton.OK); return; } this.NavigationService.Navigate(new Uri("/Views/List.xaml", UriKind.Relative)); }); } private void OnSaveDraftButtonClick(object sender, EventArgs e) { viewModel.SaveAsDraft(); } } }
31.669291
131
0.588016
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Microsoft Office Developer Documentation Team/Apps for SharePoint sample pack/79084-Apps for SharePoint sample pack/SharePoint 2013 Store and retrieve SharePoint list items on a Windows Phone/C#/SPListAppLocalStorage/Views/EditForm.xaml.cs
4,024
C#
namespace Sudoku.App.Factories { using System; using System.Linq; using System.Reflection; using Sudoku.App.Interfaces; using Sudoku.App.Utilities; public class CommandFactory { private readonly ModulesManager modulesManager; public CommandFactory() { this.modulesManager = Modules.Instance; } public ICommand GetCommand(string cmdName) { string commandFullName = cmdName + "Command"; Type cmdType = Assembly.GetExecutingAssembly() .GetTypes() .SingleOrDefault(t => t.Name == commandFullName); if (cmdType == null) { throw new ArgumentNullException($"{cmdName} does not exist!"); } ConstructorInfo constructor = cmdType.GetConstructors().Single(); Type[] constructorParameters = constructor .GetParameters() .Select(pi => pi.ParameterType) .ToArray(); object[] dependencies = new object[constructorParameters.Length]; int counter = 0; foreach (Type param in constructorParameters) { object instance = this.modulesManager.GetType() .GetMethod("GetService") .MakeGenericMethod(new[] { param }) .Invoke(this.modulesManager, null); dependencies[counter] = instance; counter++; } ICommand command = (ICommand)constructor.Invoke(dependencies); return command; } } }
28.896552
78
0.539976
[ "MIT" ]
HristoSpasov/Simple-Sudoku
Sudoku.App/Factories/CommandFactory.cs
1,678
C#
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using SerrisTabsServer.Items; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Windows.Storage; namespace SerrisTabsServer.Manager { public static class TabsAccessManager { public static List<InfosTab> GetTabs(int id) { TabsDataCache.LoadTabsData(); try { if (TabsDataCache.TabsListDeserialized != null) { return TabsDataCache.TabsListDeserialized.Where(m => m.ID == id).FirstOrDefault().tabs.Where(n => n.TabInvisibleByDefault == false).ToList(); } else { return null; } } catch { return null; } } public static List<int> GetTabsListID() { TabsDataCache.LoadTabsData(); try { var list_ids = new List<int>(); if (TabsDataCache.TabsListDeserialized != null) { foreach (TabsList list_tabs in TabsDataCache.TabsListDeserialized) { list_ids.Add(list_tabs.ID); } return list_ids; } else { return list_ids; } } catch { return null; } } public static List<int> GetTabsID(int id_list) { TabsDataCache.LoadTabsData(); try { var list_ids = new List<int>(); if (TabsDataCache.TabsListDeserialized != null) { if (TabsDataCache.TabsListDeserialized.Where(m => m.ID == id_list).FirstOrDefault().tabs != null) { foreach (InfosTab tab in TabsDataCache.TabsListDeserialized.Where(m => m.ID == id_list).FirstOrDefault().tabs) { if (!tab.TabInvisibleByDefault) { list_ids.Add(tab.ID); } } } return list_ids; } else { return list_ids; } } catch { return null; } } public static InfosTab GetTabViaID(TabID id) { TabsDataCache.LoadTabsData(); try { if (TabsDataCache.TabsListDeserialized != null) { List<InfosTab> InfosTabList = TabsDataCache.TabsListDeserialized.Where(m => m.ID == id.ID_TabsList).FirstOrDefault().tabs; if (InfosTabList != null) { return InfosTabList.Where(m => m.ID == id.ID_Tab).FirstOrDefault(); } } } catch { return null; } return null; } public static TabsList GetTabsListViaID(int id) { TabsDataCache.LoadTabsData(); try { if (TabsDataCache.TabsListDeserialized != null) { TabsList List = TabsDataCache.TabsListDeserialized.Where(m => m.ID == id).FirstOrDefault(); if (List.tabs != null) { return List; } } } catch { return null; } return null; } public static async Task<string> GetTabContentViaIDAsync(TabID id) { try { StorageFile file_content = await TabsDataCache.TabsListFolder.GetFileAsync(id.ID_TabsList + "_" + id.ID_Tab + ".json"); using (var reader = new StreamReader(await file_content.OpenStreamForReadAsync())) using (JsonReader JsonReader = new JsonTextReader(reader)) { try { ContentTab content = new JsonSerializer().Deserialize<ContentTab>(JsonReader); if (content != null) { return content.Content; } } catch { return null; } } return null; } catch { return null; } } public static string GetTabContentViaID(TabID id) { try { StorageFile file_content = Task.Run(async () => { return await TabsDataCache.TabsListFolder.GetFileAsync(id.ID_TabsList + "_" + id.ID_Tab + ".json"); }).Result; using (var reader = new StreamReader(Task.Run(async () => { return await file_content.OpenStreamForReadAsync(); }).Result)) using (JsonReader JsonReader = new JsonTextReader(reader)) { try { ContentTab content = new JsonSerializer().Deserialize<ContentTab>(JsonReader); if (content != null) { return content.Content; } } catch { return null; } } return null; } catch { return null; } } public static void UpdateTabRef(ref InfosTab tab, int id_list) { TabsDataCache.LoadTabsData(); using (var reader = new StreamReader(Task.Run(async() => { return await TabsDataCache.TabsListFile.OpenStreamForReadAsync(); }).Result)) { try { int id = tab.ID; JObject tabs = JObject.Parse(reader.ReadToEnd()).Values<JObject>().Where(m => m["ID"].Value<int>() == id_list).FirstOrDefault(), tab_search = tabs.Values<JObject>().Where(m => m["ID"].Value<int>() == id).FirstOrDefault(); if (tab != null) { tab = tab_search.Value<InfosTab>(); } } catch { } } } } }
29.012658
176
0.416958
[ "MIT" ]
AdminVIKO/SerrisCodeEditor
SerrisCodeEditor/SerrisTabsServer/Manager/TabsAccessManager.cs
6,878
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.Cpdp.V20190820.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DeleteAgentTaxPaymentInfosRequest : AbstractModel { /// <summary> /// 批次号 /// </summary> [JsonProperty("BatchNum")] public long? BatchNum{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "BatchNum", this.BatchNum); } } }
29.5
81
0.658706
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cpdp/V20190820/Models/DeleteAgentTaxPaymentInfosRequest.cs
1,304
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2020 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: LypyL, Hazelnut // // Notes: // #define SHOW_LAYOUT_TIMES //#define SHOW_LAYOUT_TIMES_NATURE using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallConnect.Utility; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Utility; using DaggerfallWorkshop.Game.Utility; using DaggerfallWorkshop.Game.Serialization; using Unity.Jobs; namespace DaggerfallWorkshop { /// <summary> /// Manages terrains for streaming world at runtime. /// At runtime only coordinates from LocalPlayerGPS will be used. Be sure to apply desired preview to PlayerGPS. /// Terrain tiles are spread outwards from a centre tile up to TerrainDistance around player. /// Terrains will be marked inactive once they pass beyond TerrainDistance. /// Inactive terrains greater than TerrainDistance+1 from player will be recycled. /// Locations and other loose objects greater than TerrainDistance+1 from player will be destroyed. /// </summary> public class StreamingWorld : MonoBehaviour { #region Fields const HideFlags defaultHideFlags = HideFlags.None; const int maxTerrainArray = 256; // Maximum terrains in memory at any time // Local player GPS for tracking player virtual position public PlayerGPS LocalPlayerGPS; // Number of terrains tiles to load around central terrain tile // Each terrain is equivalent to one full city area of 8x8 RMB blocks // 1 : ( 2 * 1 + 1 ) * ( 2 * 1 + 1 ) = 9 tiles // 2 : ( 2 * 2 + 1 ) * ( 2 * 2 + 1 ) = 25 tiles // 3 : ( 2 * 3 + 1 ) * ( 2 * 3 + 1 ) = 49 tiles // 4 : ( 2 * 4 + 1 ) * ( 2 * 4 + 1 ) = 81 tiles [Range(1, 4)] public int TerrainDistance = 3; // This controls central map pixel for streaming world // Synced to PlayerGPS at runtime [Range(TerrainHelper.minMapPixelX, TerrainHelper.maxMapPixelX)] public int MapPixelX = TerrainHelper.defaultMapPixelX; [Range(TerrainHelper.minMapPixelY, TerrainHelper.maxMapPixelY)] public int MapPixelY = TerrainHelper.defaultMapPixelY; // Increasing scale will amplify height of small details // This scale is replicated to every managed terrain // Not recommended to use greater than default value [Range(TerrainHelper.minTerrainScale, TerrainHelper.maxTerrainScale)] public float TerrainScale = TerrainHelper.defaultTerrainScale; [HideInInspector] public string EditorFindLocationString = "Daggerfall/Privateer's Hold"; //public bool AddLocationBeacon = false; public GameObject streamingTarget = null; public bool suppressWorld = false; public bool ShowDebugString = false; // List of terrain objects // Terrains all have the same format and will be endlessly recycled TerrainDesc[] terrainArray = new TerrainDesc[maxTerrainArray]; Dictionary<int, int> terrainIndexDict = new Dictionary<int, int>(); // List of loose objects, such as locations or loot containers // These objects are not recycled and will created/destroyed as needed List<LooseObjectDesc> looseObjectsList = new List<LooseObjectDesc>(); // Compensation for floating origin Vector3 worldCompensation = Vector3.zero; Vector3 playerStartPos; Vector3 lastPlayerPos; DaggerfallUnity dfUnity; DFPosition mapOrigin; double worldX, worldZ; readonly TerrainTexturing terrainTexturing = new TerrainTexturing(); bool isReady = false; Vector3 autoRepositionOffset = Vector3.zero; RepositionMethods autoRepositionMethod = RepositionMethods.RandomStartMarker; bool init; bool terrainUpdateRunning; bool updateLocatations; DaggerfallLocation currentPlayerLocationObject; int playerTilemapIndex = -1; DFPosition prevMapPixel; private int? travelStartX = null; private int? travelStartZ = null; #endregion #region Properties /// <summary> /// True if component is ready. /// </summary> public bool IsReady { get { return ReadyCheck(); } } /// <summary> /// True if world is currently initialising. /// </summary> public bool IsInit { get { return init; } } /// <summary> /// Gets the scene name for the current map pixel. /// </summary> public string SceneName { get { return GetSceneName(MapPixelX, MapPixelY); } } /// <summary>Gets the scene name for the given map pixel.</summary> public static string GetSceneName(int MapPixelX, int MapPixelY) { return string.Format("DaggerfallWorld [mapX={0}, mapY={1}]", MapPixelX, MapPixelY); } /// <summary> /// Gets Transform of central terrain player is standing on. /// </summary> public Transform PlayerTerrainTransform { get { return GetPlayerTerrainTransform(); } } /// <summary> /// Offset position of world for floating origin logic. /// </summary> public Vector3 WorldCompensation { get { return worldCompensation; } } /// <summary> /// This value is the amount of scene player movement equivalent to 1 native world map unit. /// </summary> public static float SceneMapRatio { get { return 1f / MeshReader.GlobalScale; } } // Streaming world objects are ultimately parented to this object // If left null, world objects will be parented to this transform // This allows for decoupling of GPS logic and streaming functions public Transform StreamingTarget { get { return (streamingTarget != null) ? streamingTarget.transform : this.transform; } } public TerrainTexturing TerrainTexturing { get { return terrainTexturing; } } /// <summary> /// Gets current DaggerfallLocation (if any) for player's current map pixel. /// Will return null for any map pixel in wilderness or if world still being built on init. /// </summary> public DaggerfallLocation CurrentPlayerLocationObject { get { return currentPlayerLocationObject; } } /// <summary> /// Gets index of tile under player at their current world position. /// There are many different tiles a player can stand on, including corner tiles for roads, etc. /// The main tile types in nature are: /// -1 = Nothing/Error /// 0 = Water /// 1 = Dirt (snow in winter set) /// 2 = Grass (snow in winter set) /// 3 = Stone (snow in winter set) /// </summary> public int PlayerTileMapIndex { get { return playerTilemapIndex; } } public bool IsRepositioningPlayer { get; private set; } #endregion #region Structs/Enums public struct TerrainDesc { public bool active; public bool updateData; public bool updateNature; public bool updateLocation; public bool hasLocation; public GameObject terrainObject; public GameObject billboardBatchObject; public int mapPixelX; public int mapPixelY; } struct LooseObjectDesc { public GameObject gameObject; public int mapPixelX; public int mapPixelY; public bool statefulObj; } /// <summary> /// Methods for auto-reposition logic. /// </summary> public enum RepositionMethods { None, Origin, Offset, DungeonEntrance, RandomStartMarker, DirectionFromStartMarker, } #endregion #region Unity private void Awake() { SaveLoadManager.OnStartLoad += SaveLoadManager_OnStartLoad; StartGameBehaviour.OnNewGame += StartGameBehaviour_OnNewGame; } void Update() { // Cannot proceed until ready and player is set if (!ReadyCheck()) return; // Handle moving to new map pixel or first-time init DFPosition curMapPixel = LocalPlayerGPS.CurrentMapPixel; if (curMapPixel.X != MapPixelX || curMapPixel.Y != MapPixelY || init) { Debug.Log(string.Format("Entering new map pixel X={0}, Y={1}", curMapPixel.X, curMapPixel.Y)); prevMapPixel = new DFPosition(MapPixelX, MapPixelY); MapPixelX = curMapPixel.X; MapPixelY = curMapPixel.Y; UpdateWorld(); InitPlayerTerrain(); StartCoroutine(UpdateTerrains()); updateLocatations = true; init = false; } // Exit if terrain data still updating // Raise location update flag any time terrain updates if (terrainUpdateRunning) { updateLocatations = true; return; } // Update locations when terrain data finished // This flag is raised during terrain update if (updateLocatations) { UpdateLocations(); updateLocatations = false; } // Reposition player if (autoRepositionMethod != RepositionMethods.None) { switch (autoRepositionMethod) { case RepositionMethods.DirectionFromStartMarker: case RepositionMethods.RandomStartMarker: PositionPlayerToLocation(); break; case RepositionMethods.Offset: RepositionPlayer(MapPixelX, MapPixelY, autoRepositionOffset); break; case RepositionMethods.DungeonEntrance: PositionPlayerToDungeonExit(); break; default: case RepositionMethods.Origin: RepositionPlayer(MapPixelX, MapPixelY, Vector3.zero); break; } autoRepositionMethod = RepositionMethods.None; } // Do not update world position if player is inside dungeon // This can cause player to become desynced from world as dungeon can // actually extend beyond the current map pixel area if (GameManager.Instance.PlayerEnterExit.IsPlayerInsideDungeon) return; // Get distance player has moved in world map units and apply to world position Vector3 playerPos = LocalPlayerGPS.transform.position; worldX += (playerPos.x - lastPlayerPos.x) * SceneMapRatio; worldZ += (playerPos.z - lastPlayerPos.z) * SceneMapRatio; // Sync PlayerGPS to new world position LocalPlayerGPS.WorldX = (int)worldX; LocalPlayerGPS.WorldZ = (int)worldZ; // Update last player position lastPlayerPos = playerPos; // Update index of terrain tile beneath player in world UpdatePlayerTerrainTileIndex(); } void UpdatePlayerTerrainTileIndex() { playerTilemapIndex = -1; // Player must be above a known terrain object DaggerfallTerrain playerTerrain = GetPlayerTerrain(); if (!playerTerrain) return; // The terrain must have a valid tilemap array if (playerTerrain.TileMap == null || playerTerrain.TileMap.Length == 0) return; // Get player relative position from terrain origin Vector3 relativePos = lastPlayerPos - playerTerrain.transform.position; // Convert X, Z position into 0-1 domain float dim = MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale; float u = relativePos.x / dim; float v = relativePos.z / dim; // Get clamped offset into tilemap array int x = Mathf.Clamp((int)(MapsFile.WorldMapTileDim * u), 0, MapsFile.WorldMapTileDim - 1); int y = Mathf.Clamp((int)(MapsFile.WorldMapTileDim * v), 0, MapsFile.WorldMapTileDim - 1); // Update index - divide by 4 to find actual tile base as each tile has 4x variants (flip, rotate, etc.) playerTilemapIndex = playerTerrain.TileMap[y * MapsFile.WorldMapTileDim + x].r / 4; //Debug.LogFormat("X={0}, Z={1}, Index={2}", x, y, playerTilemapIndex); } void OnGUI() { if (Event.current.type.Equals(EventType.Repaint) && ShowDebugString) { GUIStyle style = new GUIStyle(); style.normal.textColor = Color.black; string text = GetDebugString(); GUI.Label(new Rect(10, 30, 800, 24), text, style); GUI.Label(new Rect(8, 28, 800, 24), text); } } #endregion #region Public Methods /// <summary> /// Teleport to specific map pixel with an optional automatic reposition. /// </summary> public void TeleportToCoordinates(int mapPixelX, int mapPixelY, RepositionMethods autoReposition = RepositionMethods.Origin) { TeleportToMapPixel(mapPixelX, mapPixelY, Vector3.zero, autoReposition); } /// <summary> /// Teleport to specific map pixel and apply a specific reposition. /// </summary> public void TeleportToCoordinates(int mapPixelX, int mapPixelY, Vector3 repositionOffset) { TeleportToMapPixel(mapPixelX, mapPixelY, repositionOffset, RepositionMethods.None); } /// <summary> /// Teleport to specific world coordinates. /// </summary> public void TeleportToWorldCoordinates(int worldPosX, int worldPosZ) { // Convert world coordinates to map pixel and find origin world position of tile DFPosition mapPixel = MapsFile.WorldCoordToMapPixel(worldPosX, worldPosZ); DFPosition originWorldPos = MapsFile.MapPixelToWorldCoord(mapPixel.X, mapPixel.Y); // Find reposition offset based on difference between tile origin and desired absolute position Vector3 offset = new Vector3( (worldPosX - originWorldPos.X) / SceneMapRatio, 0, (worldPosZ - originWorldPos.Y) / SceneMapRatio); // Teleport to coordinates with reposition TeleportToMapPixel(mapPixel.X, mapPixel.Y, offset, RepositionMethods.Offset); } // Offset world compensation for floating origin world /// <summary> /// Offset world compensation for floating origin. /// </summary> /// <param name="change">Amount to offset world compensation.</param> /// <param name="offsetLastPlayerPos">Optionally update last known player position so GPS does not change.</param> public void OffsetWorldCompensation(Vector3 offset, bool offsetLastPlayerPos = true) { worldCompensation += offset; if (offsetLastPlayerPos) lastPlayerPos += offset; RaiseOnFloatingOriginChangeEvent(); } /// <summary> /// Returns terrain GameObject from mapPixel, or null if /// no terrain objects are mapped to that pixel /// </summary> public GameObject GetTerrainFromPixel(DFPosition mapPixel) { return GetTerrainFromPixel(mapPixel.X, mapPixel.Y); } /// <summary> /// Returns terrain GameObject from mapPixel, or null if /// no terrain objects are mapped to that pixel /// </summary> public GameObject GetTerrainFromPixel(int mapPixelX, int mapPixelY)//##Lypyl { //Get Key for terrain lookup int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY); if (terrainIndexDict.ContainsKey(key)) return terrainArray[terrainIndexDict[key]].terrainObject; else return null; } public void SetAutoReposition(RepositionMethods method, Vector3 offset) { autoRepositionOffset = offset; autoRepositionMethod = method; } /// <summary> /// Track an exterior object in streaming world. /// Tracked object will be automatically destroyed when outside of range. /// </summary> /// <param name="gameObject">Game object to track.</param> /// <param name="statefulObj">True to mark as a stateful game object which is managed by SerializedStateManager.</param> /// <param name="mapPixelX">Map pixel X to store gameobject. -1 for player location.</param> /// <param name="mapPixelY">Map pixel Y to store gameobject. -1 for player location.</param> /// <param name="setParent">True to set parent as StreamingTarget.</param> public void TrackLooseObject(GameObject gameObject, bool statefulObj = false, int mapPixelX = -1, int mapPixelY = -1, bool setParent = false) { // Create loose object description LooseObjectDesc desc = new LooseObjectDesc(); desc.gameObject = gameObject; if (mapPixelX == -1) desc.mapPixelX = MapPixelX; if (mapPixelY == -1) desc.mapPixelY = MapPixelY; desc.statefulObj = statefulObj; looseObjectsList.Add(desc); // Change object parent if (setParent) gameObject.transform.parent = StreamingTarget.transform; } public void ClearStatefulLooseObjects() { looseObjectsList.RemoveAll(x => { if (x.statefulObj) Destroy(x.gameObject); return x.statefulObj; }); } /// <summary> /// Gets the building directory for current player position. /// </summary> /// <returns>BuildingDirectory or null if player not inside a location map pixel.</returns> public BuildingDirectory GetCurrentBuildingDirectory() { if (!currentPlayerLocationObject) return null; return currentPlayerLocationObject.GetComponent<BuildingDirectory>(); } /// <summary> /// Gets the city navigation component for current player position. /// </summary> /// <returns>CityNavigation or null if player not inside a location map pixel.</returns> public CityNavigation GetCurrentCityNavigation() { if (!currentPlayerLocationObject) return null; return currentPlayerLocationObject.GetComponent<CityNavigation>(); } /// <summary> /// Gets terrain transform at mapPixelX, mapPixelY. /// </summary> /// <returns>DaggerfallTerrain Transform if found, or null if not currently in world.</returns> public Transform GetTerrainTransform(int mapPixelX, int mapPixelY) { int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY); if (!terrainIndexDict.ContainsKey(key)) return null; return terrainArray[terrainIndexDict[key]].terrainObject.transform; } /// <summary> /// Gets the DaggerfallLocation component for current player position. /// </summary> /// <returns>DaggerfallLocation component if player inside location map pixel, otherwise null.</returns> private DaggerfallLocation GetPlayerLocationObject() { // Look for location at current map pixel coords inside loose object list for (int i = 0; i < looseObjectsList.Count; i++) { LooseObjectDesc desc = looseObjectsList[i]; if (!desc.statefulObj && desc.gameObject && desc.mapPixelX == MapPixelX && desc.mapPixelY == MapPixelY) { DaggerfallLocation location = desc.gameObject.GetComponent<DaggerfallLocation>(); if (location) return location; } } return null; } #endregion #region World Setup Methods // Init world at startup or when player teleports private void InitWorld() { // Cannot init world without a player, as world positions around player // Also do nothing if world is on hold at start if (LocalPlayerGPS == null || suppressWorld) return; // Player must be at origin on init for proper world sync // Starting position will be assigned when terrain ready based on respositionMethod LocalPlayerGPS.transform.position = Vector3.zero; // Raise OnPreInitWorld event RaiseOnPreInitWorldEvent(); // Init streaming world ClearStreamingWorld(); worldCompensation = Vector3.zero; mapOrigin = LocalPlayerGPS.CurrentMapPixel; MapPixelX = mapOrigin.X; MapPixelY = mapOrigin.Y; playerStartPos = new Vector3(LocalPlayerGPS.transform.position.x, 0, LocalPlayerGPS.transform.position.z); lastPlayerPos = playerStartPos; // Set player world position to match PlayerGPS // StreamingWorld will then sync player to world worldX = LocalPlayerGPS.WorldX; worldZ = LocalPlayerGPS.WorldZ; init = true; RaiseOnInitWorldEvent(); } // Place terrain tiles when player changes map pixels private void UpdateWorld() { int dim = TerrainDistance * 2 + 1; int xs = MapPixelX - TerrainDistance; int ys = MapPixelY - TerrainDistance; for (int y = ys; y < ys + dim; y++) { for (int x = xs; x < xs + dim; x++) { PlaceTerrain(x, y); } } } // Fully init central terrain so player can be dropped into world as soon as possible private void InitPlayerTerrain() { if (!init) return; #if SHOW_LAYOUT_TIMES System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif CollectLooseObjects(); int playerTerrainIndex = terrainIndexDict[TerrainHelper.MakeTerrainKey(MapPixelX, MapPixelY)]; UpdateTerrainData(terrainArray[playerTerrainIndex]); terrainArray[playerTerrainIndex].updateData = false; UpdateTerrainNature(terrainArray[playerTerrainIndex]); terrainArray[playerTerrainIndex].updateNature = false; #if SHOW_LAYOUT_TIMES stopwatch.Stop(); DaggerfallUnity.LogMessage(string.Format("Time to init player terrain: {0}ms", stopwatch.ElapsedMilliseconds), true); #endif StartCoroutine(UpdateLocation(playerTerrainIndex, false)); terrainArray[playerTerrainIndex].updateLocation = false; } private IEnumerator UpdateTerrains() { RaiseOnUpdateTerrainsStartEvent(); terrainUpdateRunning = true; #if SHOW_LAYOUT_TIMES System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Update terrain heights and nature billboards CollectTerrains(); for (int i = 0; i < terrainArray.Length; i++) { if (terrainArray[i].active) { if (terrainArray[i].updateData) { if (init) UpdateTerrainData(terrainArray[i]); else yield return StartCoroutine(UpdateTerrainDataCoroutine(terrainArray[i])); terrainArray[i].updateData = false; } if (terrainArray[i].updateNature) { UpdateTerrainNature(terrainArray[i]); terrainArray[i].updateNature = false; if (!init) yield return new WaitForEndOfFrame(); } } } // If this is an init we can use the load time to unload unused assets // Keeps memory usage much lower over time if (init) { DaggerfallUnity.Instance.MaterialReader.PruneCache(); Resources.UnloadUnusedAssets(); } // Set terrain neighbours UpdateNeighbours(); #if SHOW_LAYOUT_TIMES stopwatch.Stop(); DaggerfallUnity.LogMessage(string.Format("Time to update terrains: {0}ms", stopwatch.ElapsedMilliseconds), true); #endif terrainUpdateRunning = false; RaiseOnUpdateTerrainsEndEvent(); } private void UpdateLocations() { CollectLooseObjects(); for (int i = 0; i < terrainArray.Length; i++) { if (terrainArray[i].active && terrainArray[i].hasLocation) StartCoroutine(UpdateLocation(i, true)); } // Update current player location object once location update complete currentPlayerLocationObject = GetPlayerLocationObject(); // Raise event RaiseOnAvailableLocationGameObjectEvent(); } private IEnumerator UpdateLocation(int index, bool allowYield) { if (terrainArray[index].active && terrainArray[index].hasLocation && terrainArray[index].updateLocation) { #if SHOW_LAYOUT_TIMES System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Disable update flag terrainArray[index].updateLocation = false; // Create location object DFLocation location; GameObject locationObject = CreateLocationGameObject(index, out location); if (locationObject) { // Add building directory to location game object BuildingDirectory buildingDirectory = locationObject.AddComponent<BuildingDirectory>(); buildingDirectory.SetLocation(location); // Add location to loose object list LooseObjectDesc looseObject = new LooseObjectDesc(); looseObject.gameObject = locationObject; looseObject.mapPixelX = terrainArray[index].mapPixelX; looseObject.mapPixelY = terrainArray[index].mapPixelY; looseObject.statefulObj = false; looseObjectsList.Add(looseObject); // Create billboard batch game objects for this location // Streaming world always batches for performance, regardless of options int natureArchive = ClimateSwaps.GetNatureArchive(LocalPlayerGPS.ClimateSettings.NatureSet, dfUnity.WorldTime.Now.SeasonValue); //TextureAtlasBuilder miscBillboardAtlas = dfUnity.MaterialReader.MiscBillboardAtlas; DaggerfallBillboardBatch natureBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(natureArchive, locationObject.transform); DaggerfallBillboardBatch lightsBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.LightsTextureArchive, locationObject.transform); DaggerfallBillboardBatch animalsBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(TextureReader.AnimalsTextureArchive, locationObject.transform); //DaggerfallBillboardBatch miscBillboardBatch = GameObjectHelper.CreateBillboardBatchGameObject(miscBillboardAtlas.AtlasMaterial, locationObject.transform); // Set hide flags natureBillboardBatch.hideFlags = defaultHideFlags; lightsBillboardBatch.hideFlags = defaultHideFlags; animalsBillboardBatch.hideFlags = defaultHideFlags; //miscBillboardBatch.hideFlags = defaultHideFlags; // Position RMB blocks inside terrain area int width = location.Exterior.ExteriorData.Width; int height = location.Exterior.ExteriorData.Height; DFPosition tilePos = TerrainHelper.GetLocationTerrainTileOrigin(location); Vector3 origin = new Vector3(tilePos.X * RMBLayout.RMBTileSide, 2.0f * MeshReader.GlobalScale, tilePos.Y * RMBLayout.RMBTileSide); // Get location component DaggerfallLocation dfLocation = locationObject.GetComponent<DaggerfallLocation>(); // Create CityNavigation component CityNavigation cityNavigation = dfLocation.gameObject.AddComponent<CityNavigation>(); cityNavigation.FormatNavigation(location.RegionName, location.Name, width, height); // Create PopulationManager component for locations with wandering NPCs if (location.MapTableData.LocationType == DFRegion.LocationTypes.TownCity || location.MapTableData.LocationType == DFRegion.LocationTypes.TownHamlet || location.MapTableData.LocationType == DFRegion.LocationTypes.TownVillage || location.MapTableData.LocationType == DFRegion.LocationTypes.HomeFarms || location.MapTableData.LocationType == DFRegion.LocationTypes.HomeWealthy || location.MapTableData.LocationType == DFRegion.LocationTypes.ReligionTemple || location.MapTableData.LocationType == DFRegion.LocationTypes.Tavern) { dfLocation.gameObject.AddComponent<PopulationManager>(); } // Perform layout and yield after each block is placed ContentReader contentReader = DaggerfallUnity.Instance.ContentReader; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { // Set block origin for billboard batches // This causes next additions to be offset by this position Vector3 blockOrigin = origin + new Vector3((x * RMBLayout.RMBSide), 0, (y * RMBLayout.RMBSide)); natureBillboardBatch.BlockOrigin = blockOrigin; lightsBillboardBatch.BlockOrigin = blockOrigin; animalsBillboardBatch.BlockOrigin = blockOrigin; //miscBillboardBatch.BlockOrigin = blockOrigin; // Get block name and data DFBlock blockData; string blockName = contentReader.BlockFileReader.CheckName(contentReader.MapFileReader.GetRmbBlockName(ref location, x, y)); RMBLayout.GetBlockData(blockName, out blockData); // Add block GameObject go = GameObjectHelper.CreateRMBBlockGameObject( blockData, x, y, false, dfUnity.Option_CityBlockPrefab, natureBillboardBatch, lightsBillboardBatch, animalsBillboardBatch, null, null, dfLocation.Summary.Nature, dfUnity.WorldTime.Now.SeasonValue == DaggerfallDateTime.Seasons.Winter ? ClimateSeason.Winter : ClimateSeason.Summer); // Set game object properties go.hideFlags = defaultHideFlags; go.transform.parent = locationObject.transform; go.transform.localPosition = blockOrigin; if (allowYield) dfLocation.ApplyClimateSettings(); // Set navigation info for this block cityNavigation.SetRMBData(ref blockData, x, y); // Optionally yield after placing block if (allowYield) yield return new WaitForEndOfFrame(); } } // Only apply climate settings after entire location updated if not spanning multiple frames. if (!allowYield) dfLocation.ApplyClimateSettings(); // Apply billboard batches natureBillboardBatch.Apply(); lightsBillboardBatch.Apply(); animalsBillboardBatch.Apply(); //miscBillboardBatch.Apply(); RaiseOnUpdateLocationGameObjectEvent(locationObject, allowYield); //// TEST: Store a RAW image of navgrid //string filename = string.Format("{0} [{1}x{2}].raw", location.Name, cityNavigation.CityWidth * 64, cityNavigation.CityHeight * 64); //cityNavigation.SaveTestRawImage(Path.Combine(@"d:\test\navgrids\", filename)); } #if SHOW_LAYOUT_TIMES stopwatch.Stop(); DaggerfallUnity.LogMessage(string.Format("Time to update location {1}: {0}ms", stopwatch.ElapsedMilliseconds, index), true); #endif } } // Place a single terrain and mark it for update private void PlaceTerrain(int mapPixelX, int mapPixelY) { // Do nothing if out of range if (mapPixelX < MapsFile.MinMapPixelX || mapPixelX >= MapsFile.MaxMapPixelX || mapPixelY < MapsFile.MinMapPixelY || mapPixelY >= MapsFile.MaxMapPixelY) { return; } // Get terrain key int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY); // If terrain is available if (terrainIndexDict.ContainsKey(key)) { // Terrain exists, check if active int index = terrainIndexDict[key]; if (terrainArray[index].active) { // Terrain already active in scene, nothing to do } else { // Terrain inactive but available, re-activate terrain terrainArray[index].active = true; terrainArray[index].terrainObject.SetActive(true); terrainArray[index].billboardBatchObject.SetActive(true); } // If any nature model replacements are used then do extra nature updates for any terrains moving into or out of distance 1 or less. if (TerrainHelper.NatureMeshUsed) { int prevDist = GetTerrainDist(prevMapPixel, terrainArray[index].mapPixelX, terrainArray[index].mapPixelY); int currDist = GetTerrainDist(LocalPlayerGPS.CurrentMapPixel, terrainArray[index].mapPixelX, terrainArray[index].mapPixelY); if ((prevDist == 1 && currDist > 1) || (currDist == 1 && prevDist > 1)) terrainArray[index].updateNature = true; } return; } // Need to place a new terrain, find next available terrain // This will either find a fresh terrain or recycle an old one int nextTerrain = FindNextAvailableTerrain(); if (nextTerrain == -1) return; // Setup new terrain terrainArray[nextTerrain].active = true; terrainArray[nextTerrain].updateData = true; terrainArray[nextTerrain].updateNature = true; terrainArray[nextTerrain].mapPixelX = mapPixelX; terrainArray[nextTerrain].mapPixelY = mapPixelY; if (!terrainArray[nextTerrain].terrainObject) { // Create game objects for new terrain // This is only done once then recycled CreateTerrainGameObjects( mapPixelX, mapPixelY, out terrainArray[nextTerrain].terrainObject, out terrainArray[nextTerrain].billboardBatchObject); } // Apply local transform float scale = MapsFile.WorldMapTerrainDim * MeshReader.GlobalScale; int xdif = mapPixelX - mapOrigin.X; int ydif = mapPixelY - mapOrigin.Y; Vector3 localPosition = new Vector3(xdif * scale, 0, -ydif * scale) + WorldCompensation; terrainArray[nextTerrain].terrainObject.transform.localPosition = localPosition; // Add new terrain index to dictionary terrainIndexDict.Add(key, nextTerrain); // Check if terrain has a location, if so it will be added on next update ContentReader.MapSummary mapSummary; terrainArray[nextTerrain].hasLocation = dfUnity.ContentReader.HasLocation(mapPixelX, mapPixelY, out mapSummary); terrainArray[nextTerrain].updateLocation = terrainArray[nextTerrain].hasLocation; } // Finds next available terrain in array private int FindNextAvailableTerrain() { // Evaluate terrain array int found = -1; for (int i = 0; i < terrainArray.Length; i++) { // A null terrain has never been instantiated and is free if (terrainArray[i].terrainObject == null) { found = i; break; } // Inactive terrain object can be evaluated for recycling based // on distance from current map pixel if (!terrainArray[i].active) { // If terrain out of range then recycle if (!IsInRange(terrainArray[i].mapPixelX, terrainArray[i].mapPixelY)) { found = i; break; } } } // Was a terrain found? if (found != -1) { // If we are recycling an inactive terrain, remove it from dictionary first int key = TerrainHelper.MakeTerrainKey(terrainArray[found].mapPixelX, terrainArray[found].mapPixelY); if (terrainIndexDict.ContainsKey(key)) { terrainIndexDict.Remove(key); } return found; } else { // Unable to find an available terrain // This should never happen unless TerrainDistance too high or maxTerrainArray too low DaggerfallUnity.LogMessage("StreamingWorld: Unable to find free terrain. Check maxTerrainArray is sized appropriately and you are collecting terrains. This can also happen when player movement speed too high.", true); if (Application.isEditor) Debug.Break(); else Application.Quit(); return -1; } } #endregion #region World Cleanup Methods // Remove managed child objects private void ClearStreamingWorld() { // Collect everything CollectTerrains(true); CollectLooseObjects(true); // Clear lists terrainIndexDict.Clear(); // Raise event RaiseOnClearStreamingWorldEvent(); } // Mark inactive any terrains outside of range private void CollectTerrains(bool collectAll = false) { for (int i = 0; i < terrainArray.Length; i++) { // Ignore uninitialised and inactive terrains if (terrainArray[i].terrainObject == null || !terrainArray[i].active) { continue; } // If terrain out of range then mark inactive for recycling if (!IsInRange(terrainArray[i].mapPixelX, terrainArray[i].mapPixelY) || collectAll) { // Mark terrain inactive terrainArray[i].terrainObject.name = "Pooled"; terrainArray[i].active = false; terrainArray[i].terrainObject.SetActive(false); terrainArray[i].billboardBatchObject.SetActive(false); // If collecting all then ensure terrain is out of range // This fixes a bug where continuously loading same location overflows terrain buffer if (collectAll) { terrainArray[i].mapPixelX = int.MinValue; terrainArray[i].mapPixelY = int.MinValue; terrainArray[i].updateLocation = terrainArray[i].hasLocation; } } } } // Destroy any loose objects outside of range private void CollectLooseObjects(bool collectAll = false) { // Walk list backward to RemoveAt doesn't shift unprocessed items for (int i = looseObjectsList.Count; i-- > 0;) { if (!IsInRange(looseObjectsList[i].mapPixelX, looseObjectsList[i].mapPixelY) || collectAll) { if (looseObjectsList[i].gameObject != null) { looseObjectsList[i].gameObject.SetActive(false); StartCoroutine(DestroyGameObjectIterative(looseObjectsList[i].gameObject)); } looseObjectsList.RemoveAt(i); } } } // Iteratively destroys game object as unity seems bad at doing this when just destroying parent private IEnumerator DestroyGameObjectIterative(GameObject gameObject) { // Destroy all children iteratively foreach (Transform t in gameObject.transform) { DestroyGameObjectIterative(t.gameObject); yield return new WaitForEndOfFrame(); } // Now destroy this object GameObject.Destroy(gameObject.transform.gameObject); } #endregion #region World Utility Methods // Teleports to map pixel with an optional reset or autoreposition void TeleportToMapPixel(int mapPixelX, int mapPixelY, Vector3 repositionOffset, RepositionMethods autoReposition) { if (autoReposition == RepositionMethods.DirectionFromStartMarker) { // Save travel origin travelStartX = LocalPlayerGPS.WorldX; travelStartZ = LocalPlayerGPS.WorldZ; } DFPosition worldPos = MapsFile.MapPixelToWorldCoord(mapPixelX, mapPixelY); LocalPlayerGPS.WorldX = worldPos.X; LocalPlayerGPS.WorldZ = worldPos.Y; LocalPlayerGPS.UpdateWorldInfo(); autoRepositionOffset = repositionOffset; autoRepositionMethod = autoReposition; suppressWorld = false; InitWorld(); // Clear falling damage so player doesn't take damage if they were in the air before a transition GameManager.Instance.AcrobatMotor.ClearFallingDamage(); RaiseOnTeleportToCoordinatesEvent(worldPos); } // Sets terrain neighbours // Should only be done after terrain is placed and collected private void UpdateNeighbours() { for (int i = 0; i < terrainArray.Length; i++) { // Check object exists if (!terrainArray[i].terrainObject) continue; // Get DaggerfallTerrain DaggerfallTerrain dfTerrain = terrainArray[i].terrainObject.GetComponent<DaggerfallTerrain>(); if (!dfTerrain) continue; // Set or clear neighbours if (terrainArray[i].active) { dfTerrain.LeftNeighbour = GetTerrain(dfTerrain.MapPixelX - 1, dfTerrain.MapPixelY); dfTerrain.RightNeighbour = GetTerrain(dfTerrain.MapPixelX + 1, dfTerrain.MapPixelY); dfTerrain.TopNeighbour = GetTerrain(dfTerrain.MapPixelX, dfTerrain.MapPixelY - 1); dfTerrain.BottomNeighbour = GetTerrain(dfTerrain.MapPixelX, dfTerrain.MapPixelY + 1); } else { dfTerrain.LeftNeighbour = null; dfTerrain.RightNeighbour = null; dfTerrain.TopNeighbour = null; dfTerrain.BottomNeighbour = null; } // Update Unity Terrain dfTerrain.UpdateNeighbours(); } } // Anything greater than TerrainDistance+1 is out of range private bool IsInRange(int mapPixelX, int mapPixelY) { if (Math.Abs(mapPixelX - this.MapPixelX) > TerrainDistance || Math.Abs(mapPixelY - this.MapPixelY) > TerrainDistance) { return false; } return true; } // Create new terrain game objects public void CreateTerrainGameObjects(int mapPixelX, int mapPixelY, out GameObject terrainObject, out GameObject billboardBatchObject) { // Create new terrain object parented to streaming world terrainObject = GameObjectHelper.CreateDaggerfallTerrainGameObject(StreamingTarget); terrainObject.name = TerrainHelper.GetTerrainName(mapPixelX, mapPixelY); terrainObject.hideFlags = defaultHideFlags; // Create new billboard batch object parented to terrain billboardBatchObject = new GameObject(); billboardBatchObject.name = string.Format("DaggerfallBillboardBatch [{0},{1}]", mapPixelX, mapPixelY); billboardBatchObject.hideFlags = defaultHideFlags; billboardBatchObject.transform.parent = terrainObject.transform; billboardBatchObject.transform.localPosition = Vector3.zero; billboardBatchObject.AddComponent<DaggerfallBillboardBatch>(); } // Create new location game object private GameObject CreateLocationGameObject(int terrain, out DFLocation locationOut) { locationOut = new DFLocation(); // Terrain must have a location DaggerfallTerrain dfTerrain = terrainArray[terrain].terrainObject.GetComponent<DaggerfallTerrain>(); if (!dfTerrain.MapData.hasLocation) return null; // Get location data locationOut = dfUnity.ContentReader.MapFileReader.GetLocation(dfTerrain.MapData.mapRegionIndex, dfTerrain.MapData.mapLocationIndex); if (!locationOut.Loaded) return null; // Sample height of terrain at origin tile position, this is more accurate than scaled average - thanks Nystul! // TODO: Daggerfall does not always position locations at exact centre as assumed. // Working around this for now and will update this code later Terrain terrainInstance = dfTerrain.gameObject.GetComponent<Terrain>(); float scale = terrainInstance.terrainData.heightmapScale.x; float xSamplePos = dfUnity.TerrainSampler.HeightmapDimension * 0.55f; float ySamplePos = dfUnity.TerrainSampler.HeightmapDimension * 0.55f; Vector3 pos = new Vector3(xSamplePos * scale, 0, ySamplePos * scale); float height = terrainInstance.SampleHeight(pos + terrainArray[terrain].terrainObject.transform.position); // Spawn parent game object for new location //float height = dfTerrain.MapData.averageHeight * TerrainScale; GameObject locationObject = new GameObject(string.Format("DaggerfallLocation [Region={0}, Name={1}]", locationOut.RegionName, locationOut.Name)); locationObject.transform.parent = StreamingTarget; locationObject.hideFlags = defaultHideFlags; locationObject.transform.position = terrainArray[terrain].terrainObject.transform.position + new Vector3(0, height, 0); DaggerfallLocation dfLocation = locationObject.AddComponent<DaggerfallLocation>() as DaggerfallLocation; dfLocation.SetLocation(locationOut, false); // Raise event RaiseOnCreateLocationGameObjectEvent(dfLocation); return locationObject; } // Update terrain data. public void UpdateTerrainData(TerrainDesc terrainDesc) { // Instantiate Daggerfall terrain DaggerfallTerrain dfTerrain = terrainDesc.terrainObject.GetComponent<DaggerfallTerrain>(); if (dfTerrain) { dfTerrain.TerrainScale = TerrainScale; dfTerrain.MapPixelX = terrainDesc.mapPixelX; dfTerrain.MapPixelY = terrainDesc.mapPixelY; dfTerrain.InstantiateTerrain(); } // Update data for terrain JobHandle updateTerrainDataJobHandle = dfTerrain.BeginMapPixelDataUpdate(terrainTexturing); CompleteUpdateTerrainDataJobs(terrainDesc, dfTerrain, updateTerrainDataJobHandle); } private void CompleteUpdateTerrainDataJobs(TerrainDesc terrainDesc, DaggerfallTerrain dfTerrain, JobHandle updateTerrainDataJobHandle) { // Ensure jobs have completed. updateTerrainDataJobHandle.Complete(); dfTerrain.CompleteMapPixelDataUpdate(terrainTexturing); // Promote data to live terrain dfTerrain.UpdateClimateMaterial(init); dfTerrain.PromoteTerrainData(); // Only set active again once complete terrainDesc.terrainObject.SetActive(true); terrainDesc.terrainObject.name = TerrainHelper.GetTerrainName(dfTerrain.MapPixelX, dfTerrain.MapPixelY); } // Update terrain data using coroutine to decouple from main thread & FPS. private IEnumerator UpdateTerrainDataCoroutine(TerrainDesc terrainDesc) { // Instantiate Daggerfall terrain DaggerfallTerrain dfTerrain = terrainDesc.terrainObject.GetComponent<DaggerfallTerrain>(); if (dfTerrain) { dfTerrain.TerrainScale = TerrainScale; dfTerrain.MapPixelX = terrainDesc.mapPixelX; dfTerrain.MapPixelY = terrainDesc.mapPixelY; dfTerrain.InstantiateTerrain(); } JobHandle updateTerrainDataJobHandle = dfTerrain.BeginMapPixelDataUpdate(terrainTexturing); yield return new WaitUntil(() => updateTerrainDataJobHandle.IsCompleted); CompleteUpdateTerrainDataJobs(terrainDesc, dfTerrain, updateTerrainDataJobHandle); } // Update terrain nature public void UpdateTerrainNature(TerrainDesc terrainDesc) { #if SHOW_LAYOUT_TIMES_NATURE System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); #endif // Setup billboards DaggerfallTerrain dfTerrain = terrainDesc.terrainObject.GetComponent<DaggerfallTerrain>(); DaggerfallBillboardBatch dfBillboardBatch = terrainDesc.billboardBatchObject.GetComponent<DaggerfallBillboardBatch>(); if (dfTerrain && dfBillboardBatch) { // Get current climate and nature archive and terrain distance int natureArchive = ClimateSwaps.GetNatureArchive(LocalPlayerGPS.ClimateSettings.NatureSet, dfUnity.WorldTime.Now.SeasonValue); dfBillboardBatch.SetMaterial(natureArchive); int terrainDist = GetTerrainDist(LocalPlayerGPS.CurrentMapPixel, dfTerrain.MapPixelX, dfTerrain.MapPixelY); TerrainHelper.LayoutNatureBillboards(dfTerrain, dfBillboardBatch, TerrainScale, terrainDist); } // Only set active again once complete terrainDesc.billboardBatchObject.SetActive(true); #if SHOW_LAYOUT_TIMES_NATURE stopwatch.Stop(); DaggerfallUnity.LogMessage(string.Format("Time to update terrain natures for ({1},{2}): {0}ms", stopwatch.ElapsedMilliseconds, terrainDesc.mapPixelX, terrainDesc.mapPixelY), true); #endif } // Gets terrain at map pixel coordinates, or null if not found private Terrain GetTerrain(int mapPixelX, int mapPixelY) { int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY); if (terrainIndexDict.ContainsKey(key)) { return terrainArray[terrainIndexDict[key]].terrainObject.GetComponent<Terrain>(); } return null; } #endregion #region Player Utility Methods // Calculate the distance of terrain from given map position private int GetTerrainDist(DFPosition mapPosition, int terrainMapPixelX, int terrainMapPixelY) { DFPosition curMapPixel = LocalPlayerGPS.CurrentMapPixel; int dx = Mathf.Abs(terrainMapPixelX - mapPosition.X); int dy = Mathf.Abs(terrainMapPixelY - mapPosition.Y); return Mathf.Max(dx, dy); } private DaggerfallTerrain GetPlayerTerrain() { Transform terrainTransform = GetPlayerTerrainTransform(); if (terrainTransform) return terrainTransform.GetComponent<DaggerfallTerrain>(); return null; } // Gets transform of the terrain player is standing on private Transform GetPlayerTerrainTransform() { int key = TerrainHelper.MakeTerrainKey(MapPixelX, MapPixelY); if (!terrainIndexDict.ContainsKey(key)) return null; return terrainArray[terrainIndexDict[key]].terrainObject.transform; } // Repositions player in world after a teleport. // If position.y is less than terrain height then player will be raised to sit on terrain. // If grounded is true, position.y will be unconditionally set to terrain height. // Terrain data must already be loaded and LocalGPS must be attached to your player game object. private void RepositionPlayer(int mapPixelX, int mapPixelY, Vector3 position, bool grounded = false) { // Get terrain key int key = TerrainHelper.MakeTerrainKey(mapPixelX, mapPixelY); if (!terrainIndexDict.ContainsKey(key)) return; // Get terrain Terrain terrain = terrainArray[terrainIndexDict[key]].terrainObject.GetComponent<Terrain>(); // Sample height at this position CharacterController controller = LocalPlayerGPS.gameObject.GetComponent<CharacterController>(); if (controller) { // Get target position at terrain height + player standing height // This is our minimum height before player falls through world IsRepositioningPlayer = true; Vector3 targetPosition = new Vector3(position.x, 0, position.z); float height = terrain.SampleHeight(targetPosition + terrain.transform.position) + worldCompensation.y; targetPosition.y = height + controller.height / 2f + 0.15f; // If desired position is higher then minimum position then we can safely use that if (!grounded && position.y > targetPosition.y) targetPosition.y = position.y; // Move player object to new position LocalPlayerGPS.transform.position = targetPosition; // Clear falling damage so player doesn't take damage after reposition GameManager.Instance.AcrobatMotor.ClearFallingDamage(); // Perform another pass at collecting loose objects as sometimes they don't clean up properly after fast travel // This is more common the more loose objects are present in scene, such as with a greater TerrainDistance CollectLooseObjects(); ResyncWorldCoordinates(); IsRepositioningPlayer = false; } else { throw new Exception("StreamingWorld: Could not find CharacterController peered with LocalPlayerGPS."); } } // Position player outside first dungeon door of this location private void PositionPlayerToDungeonExit(DaggerfallLocation location = null) { // If location is null, try current player location and bail if not found if (!location) { location = GetPlayerLocationObject(); if (!location) return; } DaggerfallStaticDoors[] doors = location.StaticDoorCollections; // If no doors found then just position to origin if (doors == null || doors.Length == 0) { RepositionPlayer(MapPixelX, MapPixelY, Vector3.zero); return; } // Find vertically lowest dungeon door, this should be the ground-level door int foundIndex = -1; float lowestHeight = float.MaxValue; DaggerfallStaticDoors foundCollection = null; Vector3 foundDoorNormal = Vector3.zero; foreach (var collection in doors) { for (int i = 0; i < collection.Doors.Length; i++) { if (collection.Doors[i].doorType == DoorTypes.DungeonEntrance) { Vector3 pos = collection.GetDoorPosition(i); if (pos.y < lowestHeight) { lowestHeight = pos.y; foundCollection = collection; foundDoorNormal = collection.GetDoorNormal(i); foundIndex = i; } } } } // Position player outside door position if (foundCollection) { Vector3 startPosition = foundCollection.GetDoorPosition(foundIndex); startPosition += foundDoorNormal * (GameManager.Instance.PlayerController.radius + 0.1f); RepositionPlayer(MapPixelX, MapPixelY, startPosition); } else { RepositionPlayer(MapPixelX, MapPixelY, Vector3.zero); } // Set player facing away from door PlayerMouseLook playerMouseLook = GameManager.Instance.PlayerMouseLook; if (playerMouseLook) { playerMouseLook.SetHorizontalFacing(foundDoorNormal); } } private void PositionPlayerToLocation() { // Find current location DaggerfallLocation currentLocation = GetPlayerLocationObject(); if (!currentLocation) { // No location found, fail back to terrain origin RepositionPlayer(MapPixelX, MapPixelY, Vector3.zero); return; } // Get location dimensions for positioning int width = currentLocation.Summary.BlockWidth; int height = currentLocation.Summary.BlockHeight; DFPosition tilePos = TerrainHelper.GetLocationTerrainTileOrigin(currentLocation.Summary.LegacyLocation); Vector3 origin = new Vector3(tilePos.X * RMBLayout.RMBTileSide, 2.0f * MeshReader.GlobalScale, tilePos.Y * RMBLayout.RMBTileSide); // Position player to random side of location PositionPlayerToLocation( MapPixelX, MapPixelY, currentLocation, origin, width, height, (currentLocation.Summary.LocationType == DFRegion.LocationTypes.TownCity || currentLocation.Summary.LocationType == DFRegion.LocationTypes.HomeYourShips), currentLocation.Summary.LocationType != DFRegion.LocationTypes.HomeYourShips); } // Sets player to ground level near a location // Will spawn at a random edge facing location // Can use start markers if present private void PositionPlayerToLocation( int mapPixelX, int mapPixelY, DaggerfallLocation dfLocation, Vector3 origin, int mapWidth, int mapHeight, bool useNearestStartMarker = false, bool grounded = true) { UnityEngine.Random.InitState(DateTime.Now.Millisecond); int side; if (travelStartX == null || travelStartZ == null) { // Randomly pick one side of location to spawn side = UnityEngine.Random.Range(0, 4); } else { // use travel origin as a facing hint int worldDeltaX = LocalPlayerGPS.WorldX - (int)travelStartX; int worldDeltaZ = LocalPlayerGPS.WorldZ - (int)travelStartZ; if (worldDeltaX == 0 && worldDeltaZ == 0) side = UnityEngine.Random.Range(0, 4); else { int px = Math.Abs(worldDeltaX); int pz = Math.Abs(worldDeltaZ); // if travel start is distant enough, chances of hitting square sides are // approximatively px/(px+pz) and pz/(px+pz) int random = UnityEngine.Random.Range(0, px + pz); if (px > pz) { // direction is mainly E-W, do we hit square front side? if (random < px) side = worldDeltaX > 0 ? 3 : 2; else side = worldDeltaZ > 0 ? 1 : 0; } else { // direction is mainly N-S, do we hit square front side? if (random < pz) side = worldDeltaZ > 0 ? 1 : 0; else side = worldDeltaX > 0 ? 3 : 2; } } // Debug.Log(String.Format("{0},{1} => {2},{3}: facing {4}", (int)travelStartX, (int)travelStartZ, LocalPlayerGPS.WorldX, LocalPlayerGPS.WorldZ, side)); travelStartX = null; travelStartZ = null; } // Get half width and height float halfWidth = (float)mapWidth * 0.5f * RMBLayout.RMBSide; float halfHeight = (float)mapHeight * 0.5f * RMBLayout.RMBSide; Vector3 centre = origin + new Vector3(halfWidth, 0, halfHeight); // Sometimes buildings are right up to edge of block // Extra distance places player a little bit outside location area float extraDistance = RMBLayout.RMBSide * 0.1f; // Start player in position Vector3 newPlayerPosition = centre; PlayerMouseLook mouseLook = LocalPlayerGPS.GetComponentInChildren<PlayerMouseLook>(); if (mouseLook) { switch (side) { case 0: // North newPlayerPosition += new Vector3(0, 0, (halfHeight + extraDistance)); mouseLook.SetFacing(180, 0); //LocalPlayerGPS.gameObject.SendMessage("SetFacing", Vector3.back, SendMessageOptions.DontRequireReceiver); //Debug.Log("Spawned player north."); break; case 1: // South newPlayerPosition += new Vector3(0, 0, -(halfHeight + extraDistance)); mouseLook.SetFacing(0, 0); //LocalPlayerGPS.gameObject.SendMessage("SetFacing", Vector3.forward, SendMessageOptions.DontRequireReceiver); //Debug.Log("Spawned player south."); break; case 2: // East newPlayerPosition += new Vector3((halfWidth + extraDistance), 0, 0); mouseLook.SetFacing(270, 0); //LocalPlayerGPS.gameObject.SendMessage("SetFacing", Vector3.left, SendMessageOptions.DontRequireReceiver); //Debug.Log("Spawned player east."); break; case 3: // West newPlayerPosition += new Vector3(-(halfWidth + extraDistance), 0, 0); mouseLook.SetFacing(90, 0); //LocalPlayerGPS.gameObject.SendMessage("SetFacing", Vector3.right, SendMessageOptions.DontRequireReceiver); //Debug.Log("Spawned player west."); break; } } // Adjust to nearest start marker if requested if (useNearestStartMarker) { float smallestDistance = float.MaxValue; int closestMarker = -1; GameObject[] startMarkers = dfLocation.StartMarkers; for (int i = 0; i < startMarkers.Length; i++) { float distance = Vector3.Distance(newPlayerPosition, startMarkers[i].transform.position); if (distance < smallestDistance) { smallestDistance = distance; closestMarker = i; } } if (closestMarker != -1) { //PositionPlayerToTerrain(mapPixelX, mapPixelY, startMarkers[closestMarker].transform.position); RepositionPlayer(mapPixelX, mapPixelY, startMarkers[closestMarker].transform.position, grounded); return; } } // Just position to outside location //PositionPlayerToTerrain(mapPixelX, mapPixelY, newPlayerPosition); RepositionPlayer(mapPixelX, mapPixelY, newPlayerPosition, grounded); } // Align player to ground private bool FixStanding(Transform playerTransform, float playerHeight, float extraHeight = 0, float extraDistance = 0) { RaycastHit hit; Ray ray = new Ray(playerTransform.position + (Vector3.up * extraHeight), Vector3.down); if (Physics.Raycast(ray, out hit, (playerHeight * 2) + extraHeight + extraDistance)) { // Position player at hit position plus just over half controller height up playerTransform.position = hit.point + Vector3.up * (playerHeight * 0.6f); return true; } return false; } // Resync world coordinates after changing player transform position void ResyncWorldCoordinates() { Vector3 playerPos = LocalPlayerGPS.transform.position; DFPosition mapPixelOrigin = MapsFile.MapPixelToWorldCoord(MapPixelX, MapPixelY); worldX = mapPixelOrigin.X + (playerPos.x * SceneMapRatio); worldZ = mapPixelOrigin.Y + (playerPos.z * SceneMapRatio); lastPlayerPos = playerPos; } // Destroy untracked objects parented to streaming target // This will remove loose enemies, missiles, etc. on load or new game // These dynamically spawned objects are fully untracked in wilderness void CleanupUntrackedObjects() { // Destroy loose enemies EnemyMotor[] enemies = StreamingTarget.GetComponentsInChildren<EnemyMotor>(); foreach(EnemyMotor enemy in enemies) GameObject.Destroy(enemy.gameObject); // Destroy loose missiles DaggerfallMissile[] missiles = StreamingTarget.GetComponentsInChildren<DaggerfallMissile>(); foreach (DaggerfallMissile missile in missiles) GameObject.Destroy(missile.gameObject); } private void StartGameBehaviour_OnNewGame() { CleanupUntrackedObjects(); } private void SaveLoadManager_OnStartLoad(SaveData_v1 saveData) { CleanupUntrackedObjects(); } #endregion #region Startup/Shutdown Methods private bool ReadyCheck() { if (suppressWorld) return false; if (isReady) return true; if (dfUnity == null) { dfUnity = DaggerfallUnity.Instance; } if (LocalPlayerGPS == null) return false; else InitWorld(); // Do nothing if DaggerfallUnity not ready if (!dfUnity.IsReady) { DaggerfallUnity.LogMessage("StreamingWorld: DaggerfallUnity component is not ready. Have you set your Arena2 path?"); return false; } // Perform initial runtime setup if (Application.isPlaying) { // Fix coastal climate data TerrainHelper.DilateCoastalClimate(dfUnity.ContentReader, 2); // Smooth steep location on steep gradients // TODO: What is this supposed to be doing? It doesn't seem to change any data that's used anywhere.. TerrainHelper.SmoothLocationNeighbourhood(dfUnity.ContentReader); } // Raise ready flag isReady = true; RaiseOnReadyEvent(); return true; } private string GetDebugString() { string final = string.Format("[{0},{1}] [{2},{3}] You are in the {4} region with a {5} climate.", MapPixelX, MapPixelY, LocalPlayerGPS.WorldX, LocalPlayerGPS.WorldZ, LocalPlayerGPS.CurrentRegionName, LocalPlayerGPS.ClimateSettings.ClimateType.ToString()); if (LocalPlayerGPS.CurrentLocation.Loaded) { final += string.Format(" {0} is nearby.", LocalPlayerGPS.CurrentLocation.Name); } return final; } #endregion #region Editor Support #if UNITY_EDITOR public void __EditorFindLocation() { DFLocation location; if (!GameObjectHelper.FindMultiNameLocation(EditorFindLocationString, out location)) { DaggerfallUnity.LogMessage(string.Format("Could not find location [Region={0}, Name={1}]", location.RegionName, location.Name), true); return; } int longitude = (int)location.MapTableData.Longitude; int latitude = (int)location.MapTableData.Latitude; DFPosition pos = MapsFile.LongitudeLatitudeToMapPixel(longitude, latitude); MapPixelX = pos.X; MapPixelY = pos.Y; } public void __EditorGetFromPlayerGPS() { if (LocalPlayerGPS != null) { DFPosition pos = MapsFile.WorldCoordToMapPixel(LocalPlayerGPS.WorldX, LocalPlayerGPS.WorldZ); MapPixelX = pos.X; MapPixelY = pos.Y; } } public void __EditorApplyToPlayerGPS() { if (LocalPlayerGPS != null) { DFPosition pos = MapsFile.MapPixelToWorldCoord(MapPixelX, MapPixelY); LocalPlayerGPS.WorldX = pos.X; LocalPlayerGPS.WorldZ = pos.Y; } } #endif #endregion #region Event Handlers // OnReady public delegate void OnReadyEventHandler(); public static event OnReadyEventHandler OnReady; protected virtual void RaiseOnReadyEvent() { if (OnReady != null) OnReady(); } // OnTeleportToCoordinates public delegate void OnTeleportToCoordinatesEventHandler(DFPosition worldPos); public static event OnTeleportToCoordinatesEventHandler OnTeleportToCoordinates; protected virtual void RaiseOnTeleportToCoordinatesEvent(DFPosition worldPos) { if (OnTeleportToCoordinates != null) OnTeleportToCoordinates(worldPos); } // OnPreInitWorld public delegate void OnPreInitWorldEventHandler(); public static event OnPreInitWorldEventHandler OnPreInitWorld; protected virtual void RaiseOnPreInitWorldEvent() { if (OnPreInitWorld != null) OnPreInitWorld(); } // OnInitWorld public delegate void OnInitWorldEventHandler(); public static event OnInitWorldEventHandler OnInitWorld; protected virtual void RaiseOnInitWorldEvent() { if (OnInitWorld != null) OnInitWorld(); } // OnUpdateTerrainsStart public delegate void OnUpdateTerrainsStartEventHandler(); public static event OnUpdateTerrainsStartEventHandler OnUpdateTerrainsStart; protected virtual void RaiseOnUpdateTerrainsStartEvent() { if (OnUpdateTerrainsStart != null) OnUpdateTerrainsStart(); } // OnUpdateTerrainsEnd public delegate void OnUpdateTerrainsEndEventHandler(); public static event OnUpdateTerrainsEndEventHandler OnUpdateTerrainsEnd; protected virtual void RaiseOnUpdateTerrainsEndEvent() { if (OnUpdateTerrainsEnd != null) OnUpdateTerrainsEnd(); } // OnClearStreamingWorld public delegate void OnClearStreamingWorldEventHandler(); public static event OnClearStreamingWorldEventHandler OnClearStreamingWorld; protected virtual void RaiseOnClearStreamingWorldEvent() { if (OnClearStreamingWorld != null) OnClearStreamingWorld(); } // OnCreateLocationGameObject public delegate void OnCreateLocationGameObjectEventHandler(DaggerfallLocation dfLocation); public static event OnCreateLocationGameObjectEventHandler OnCreateLocationGameObject; protected virtual void RaiseOnCreateLocationGameObjectEvent(DaggerfallLocation dfLocation) { if (OnCreateLocationGameObject != null) OnCreateLocationGameObject(dfLocation); } // OnUpdateLocationGameObject public delegate void OnUpdateLocationGameObjectEventHandler(GameObject locationObject, bool allowYeld); public static event OnUpdateLocationGameObjectEventHandler OnUpdateLocationGameObject; protected virtual void RaiseOnUpdateLocationGameObjectEvent(GameObject locationObject, bool allowYeld) { if (OnUpdateLocationGameObject != null) OnUpdateLocationGameObject(locationObject, allowYeld); } // OnAvailableLocationGameObject public delegate void OnAvailableLocationGameObjectHandler(); public static event OnAvailableLocationGameObjectHandler OnAvailableLocationGameObject; protected virtual void RaiseOnAvailableLocationGameObjectEvent() { if (OnAvailableLocationGameObject != null) OnAvailableLocationGameObject(); } // OnFloatingOriginChange public delegate void OnFloatingOriginChangeEventHandler(); public static event OnFloatingOriginChangeEventHandler OnFloatingOriginChange; protected virtual void RaiseOnFloatingOriginChangeEvent() { if (OnFloatingOriginChange != null) OnFloatingOriginChange(); } #endregion } }
42.534276
233
0.58606
[ "MIT" ]
UncannyValley21/daggerfall-unity
Assets/Scripts/Terrain/StreamingWorld.cs
78,178
C#
/* * Prime Developer Trial * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.StocksAPIforDigitalPortals.Client.OpenAPIDateConverter; namespace FactSet.SDK.StocksAPIforDigitalPortals.Model { /// <summary> /// Operating margin, which is the ratio of the operating income, divided by the sales revenue. /// </summary> [DataContract(Name = "inline_response_200_5_data_reportedKeyFigures_firstFiscalYear_operatingMargin")] public partial class InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin : IEquatable<InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin" /> class. /// </summary> /// <param name="minimum">Minimum value..</param> /// <param name="maximum">Maximum value..</param> public InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin(decimal minimum = default(decimal), decimal maximum = default(decimal)) { this.Minimum = minimum; this.Maximum = maximum; } /// <summary> /// Minimum value. /// </summary> /// <value>Minimum value.</value> [DataMember(Name = "minimum", EmitDefaultValue = false)] public decimal Minimum { get; set; } /// <summary> /// Maximum value. /// </summary> /// <value>Maximum value.</value> [DataMember(Name = "maximum", EmitDefaultValue = false)] public decimal Maximum { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin {\n"); sb.Append(" Minimum: ").Append(Minimum).Append("\n"); sb.Append(" Maximum: ").Append(Maximum).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin); } /// <summary> /// Returns true if InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin instances are equal /// </summary> /// <param name="input">Instance of InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin input) { if (input == null) { return false; } return ( this.Minimum == input.Minimum || this.Minimum.Equals(input.Minimum) ) && ( this.Maximum == input.Maximum || this.Maximum.Equals(input.Maximum) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; hashCode = (hashCode * 59) + this.Minimum.GetHashCode(); hashCode = (hashCode * 59) + this.Maximum.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
37.574468
200
0.624953
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/StocksAPIforDigitalPortals/v2/src/FactSet.SDK.StocksAPIforDigitalPortals/Model/InlineResponse2005DataReportedKeyFiguresFirstFiscalYearOperatingMargin.cs
5,298
C#
using DaAPI.Core.Packets.DHCPv4; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DaAPI.Infrastructure.StorageEngine.DHCPv4 { public interface IDHCPv4EventStore : IEventStore { Task<Boolean> LogInvalidDHCPv4Packet(DHCPv4Packet packet); Task<Boolean> LogFilteredDHCPv4Packet(DHCPv4Packet packet, string filterName); } }
26.625
86
0.776995
[ "MIT" ]
just-the-benno/DaAPI
src/DaAPI.Infrastructure/StorageEngine/DHCPv4/IDHCPv4EventStore.cs
428
C#
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Tencent is pleased to support the open source community by making behaviac available. // // Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed under the License is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Behaviac.Design.Attributes; using Behaviac.Design.Properties; namespace Behaviac.Design { internal partial class MetaPropertyPanel : UserControl { public delegate void MetaPropertyNameDelegate(); public event MetaPropertyNameDelegate MetaPropertyNameHandler; public delegate void MetaPropertyDelegate(); public event MetaPropertyDelegate MetaPropertyHandler; private bool _initialized = false; private bool _isNew = true; private bool _isArray = false; private AgentType _agent = null; StructType _structType = null; private PropertyDef _originalProperty = null; private PropertyDef _property = null; DesignerPropertyEditor _valueEditor; public MetaPropertyPanel() { InitializeComponent(); } private bool _shouldCheckMembersInWorkspace = false; public bool ShouldCheckMembersInWorkspace() { return _shouldCheckMembersInWorkspace; } public void Initialize(bool canBeEdit, AgentType agent, StructType structType, PropertyDef prop, bool canBePar) { Debug.Check(agent != null || structType != null); _initialized = false; _isModified = false; _shouldCheckMembersInWorkspace = false; _isNew = (prop == null); _agent = agent; _structType = structType; _originalProperty = prop; setTypes(); if (_isNew) { this.Text = canBeEdit ? Resources.AddProperty : Resources.ViewProperty; if (_structType == null) { if (agent != null) { _property = new PropertyDef(agent, null, agent.Name, "", "", ""); } } else { _property = new PropertyDef(null, null, _structType.Name, "", "", ""); } _property.IsPublic = false; resetProperty(_property, _property.IsPar); } else { this.Text = canBeEdit ? Resources.EditProperty : Resources.ViewProperty; resetProperty(prop, prop.IsPar); } //this.customizedCheckBox.Visible = canBeEdit && !_property.IsInherited && agent != null; this.customizedCheckBox.Visible = false; this.isLocalCheckBox.Checked = _structType == null && _property.IsPar; this.isLocalCheckBox.Visible = canBePar && _structType == null && !_property.IsMember; this.isLocalCheckBox.Enabled = canBeEdit; this.nameTextBox.Enabled = canBeEdit; this.arrayCheckBox.Enabled = canBeEdit || (_structType == null || _structType.IsCustomized) && _property.IsChangeableType; this.typeComboBox.Enabled = canBeEdit || (_structType == null || _structType.IsCustomized) && _property.IsChangeableType; this.isStaticCheckBox.Enabled = canBeEdit; this.isPublicCheckBox.Enabled = canBeEdit; this.isConstCheckBox.Enabled = canBeEdit; this.dispTextBox.Enabled = canBeEdit; this.descTextBox.Enabled = canBeEdit; this.nameTextBox.Focus(); if (this.nameTextBox.TextLength > 0) { this.nameTextBox.SelectionStart = this.nameTextBox.TextLength; } else { this.nameTextBox.Select(); } _initialized = true; } public PropertyDef GetProperty() { Debug.Check(_property != null && !string.IsNullOrEmpty(_property.BasicName)); if (_property != null) { if (string.IsNullOrEmpty(_property.DisplayName)) { _property.DisplayName = _property.BasicName; } if (string.IsNullOrEmpty(_property.BasicDescription)) { _property.BasicDescription = _property.BasicName; } return _property; } return null; } private bool _isModified = false; public bool IsModified { get { return _isModified; } set { _isModified = true; } } private void resetProperty(PropertyDef prop, bool isPar) { if (prop != null && (_property != prop || _property != null && _property.IsPar != isPar)) { if (isPar) { _property = new ParInfo(prop); } else { _property = new PropertyDef(prop); } } if (_property != null) { if (prop != null) { _property.OldName = prop.Name; } _isArray = Plugin.IsArrayType(_property.Type); Type type = _isArray ? _property.Type.GetGenericArguments()[0] : _property.Type; this.nameTextBox.Text = _property.BasicName; this.arrayCheckBox.Checked = _isArray; this.typeComboBox.Text = Plugin.GetMemberValueTypeName(type); this.isStaticCheckBox.Checked = _property.IsStatic; this.isPublicCheckBox.Checked = _property.IsPublic; this.isConstCheckBox.Checked = _property.IsReadonly; this.customizedCheckBox.Checked = _property.IsCustomized; this.dispTextBox.Text = _property.DisplayName; this.descTextBox.Text = _property.BasicDescription; resetType(type, false); } } private void createValueEditor(Type type) { Type editorType = Plugin.InvokeEditorType(type); Debug.Check(editorType != null); if (editorType != null) { ParInfo par = this._property as ParInfo; if (_property.Variable == null || _property.Variable.ValueType != type) { _property.Variable = new VariableDef(Plugin.DefaultValue(type)); } _valueEditor = (DesignerPropertyEditor)editorType.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, new object[0]); if (_valueEditor != null) { _valueEditor.Margin = new System.Windows.Forms.Padding(0); _valueEditor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; _valueEditor.Width = this.dispTextBox.Width; _valueEditor.Location = this.dispTextBox.Location; _valueEditor.Location = new Point(_valueEditor.Location.X, _valueEditor.Location.Y - _valueEditor.Height - 6); _valueEditor.ValueWasChanged += new DesignerPropertyEditor.ValueChanged(editor_ValueWasChanged); if (par != null) { _valueEditor.SetPar(par, null); } else { _valueEditor.SetVariable(this._property.Variable, null); } _valueEditor.ValueWasAssigned(); this.Controls.Add(_valueEditor); _valueEditor.BringToFront(); } } } private void editor_ValueWasChanged(object sender, DesignerPropertyInfo property) { if (_initialized) { DesignerPropertyEditor editor = sender as DesignerPropertyEditor; _property.Variable = editor.GetVariable(); this.IsModified = true; } } public bool Verify() { Debug.Check(_property != null); string propertyName = this.nameTextBox.Text; bool isValid = false; if (_property != null) { isValid = !string.IsNullOrEmpty(propertyName) && propertyName.Length >= 1 && char.IsLetter(propertyName[0]) && (_property.Type != null); } if (isValid && _agent != null) { PropertyDef prop = _agent.GetPropertyByName(propertyName); if (_isNew) { isValid = (prop == null); } else { isValid = (prop == null || prop == _originalProperty); } } return isValid; } private void setTypes() { this.typeComboBox.Items.Clear(); foreach (string typeName in Plugin.GetAllMemberValueTypeNames(false, true)) { this.typeComboBox.Items.Add(typeName); } } private void resetType(Type type, bool reset) { Debug.Check(_property != null); if (type == null) { if (this.typeComboBox.SelectedItem != null) { type = Plugin.GetMemberValueType(this.typeComboBox.SelectedItem.ToString()); Debug.Check(type != null); if (_isArray) { type = typeof(List<>).MakeGenericType(type); } } } else { if (_isArray) { type = typeof(List<>).MakeGenericType(type); } } if (type != null) { if (reset && _property != null) { _property.Type = type; _property.NativeType = Plugin.GetMemberValueTypeName(type); } if (_valueEditor != null) { this.Controls.Remove(_valueEditor); _valueEditor = null; } if (_agent != null) { createValueEditor(type); this.valueLabel.Visible = true; } else { this.valueLabel.Visible = false; } } } private bool _isNameModified = false; private void nameTextBox_TextChanged(object sender, EventArgs e) { if (_initialized) { _isNameModified = true; } } private void nameTextBox_Leave(object sender, EventArgs e) { ModifyName(); } private void nameTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { ModifyName(); } } private void ModifyName() { if (_initialized && _isNameModified) { _isNameModified = false; Debug.Check(_property != null); if (_property != null) { if (!_isNew && !this.Verify()) { MessageBox.Show(Resources.PropertyVerifyWarning, Resources.Warning, MessageBoxButtons.OK); this.nameTextBox.Text = _property.BasicName; } else if (_property.BasicName != this.nameTextBox.Text) { _property.Name = this.nameTextBox.Text; _property.DisplayName = _property.Name; this.dispTextBox.Text = _property.DisplayName; this.IsModified = true; _shouldCheckMembersInWorkspace = true; if (MetaPropertyNameHandler != null) { MetaPropertyNameHandler(); } } } } } private void arrayCheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { _isArray = this.arrayCheckBox.Checked; resetType(null, true); this.IsModified = true; } } private void typeComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (_initialized) { resetType(null, true); this.IsModified = true; _shouldCheckMembersInWorkspace = true; } } private void isStaticCheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { Debug.Check(_property != null); if (_property != null) { _property.IsStatic = this.isStaticCheckBox.Checked; } this.IsModified = true; } } private void isPublicCheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { Debug.Check(_property != null); if (_property != null) { _property.IsPublic = this.isPublicCheckBox.Checked; } this.IsModified = true; } } private void dispTextBox_TextChanged(object sender, EventArgs e) { if (_initialized && _property != null && _property.DisplayName != this.dispTextBox.Text) { _property.DisplayName = this.dispTextBox.Text; this.IsModified = true; } } private void descTextBox_TextChanged(object sender, EventArgs e) { if (_initialized && _property != null && _property.BasicDescription != this.descTextBox.Text) { _property.BasicDescription = this.descTextBox.Text; this.IsModified = true; } } private void isConstcheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { Debug.Check(_property != null); if (_property != null) { _property.IsReadonly = this.isConstCheckBox.Checked; } this.IsModified = true; } } private void customizedCheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { Debug.Check(_property != null); if (_property != null) { _property.IsCustomized = this.customizedCheckBox.Checked; } this.IsModified = true; if (MetaPropertyHandler != null) { MetaPropertyHandler(); } } } private void isLocalCheckBox_CheckedChanged(object sender, EventArgs e) { if (_initialized) { Debug.Check(_property != null); if (_property != null) { resetProperty(_property, this.isLocalCheckBox.Checked); } this.IsModified = true; if (MetaPropertyHandler != null) { MetaPropertyHandler(); } } } } }
32.548944
167
0.49599
[ "MIT" ]
3-Delta/Unity-UI
Tools/AI/Behaviac/BehaviacDesigner/MetaPropertyPanel.cs
16,958
C#
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using UHubApi.AspNetCore.Models; namespace UHubApi.AspNetCore.Middlewares { public class AddUserMiddleware : UHubApiMiddleware<AddUserModel> { public AddUserMiddleware(RequestDelegate next, IOptions<UHubApiOptions> optionsAccessor, IUHubApiApp uHubApiApp) : base(next, optionsAccessor, uHubApiApp) { } public override AppNoticeResponseModel ExecuteApi(AddUserModel model) { return _uHubApiApp.AddUser(model); } } }
29.454545
162
0.75
[ "Apache-2.0" ]
yiyungent/UHub
src/Sdk/UHubApi.AspNetCore/Middlewares/AddUserMiddleware.cs
650
C#
using System; using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; namespace _05_CableNetwork { public class Edge { public int First { get; set; } public int Second { get; set; } public int Weight { get; set; } } public class Program { private static List<Edge>[] graph; private static HashSet<int> spanningTree; public static void Main(string[] args) { var budget = int.Parse(Console.ReadLine()); var nodesCount = int.Parse(Console.ReadLine()); var edgesCount = int.Parse(Console.ReadLine()); spanningTree = new HashSet<int>(); graph = ReadGraph(nodesCount, edgesCount); var usedBudget = Prim(budget); Console.WriteLine($"Budget used: {usedBudget}"); } private static int Prim(int budget) { var usedBudget = 0; var queue = new OrderedBag<Edge>( Comparer<Edge>.Create((f, s) => f.Weight - s.Weight)); foreach (var node in spanningTree) { queue.AddMany(graph[node]); } while (queue.Count > 0) { var edge = queue.RemoveFirst(); var nonTreeNode = GetNonTreeNode(edge.First, edge.Second); if (nonTreeNode == -1) { continue; } if (edge.Weight > budget) { break; } usedBudget += edge.Weight; budget -= edge.Weight; spanningTree.Add(nonTreeNode); queue.AddMany(graph[nonTreeNode]); } return usedBudget; } private static int GetNonTreeNode(int first, int second) { var nonTreeNode = -1; if (spanningTree.Contains(first) && !spanningTree.Contains(second)) { nonTreeNode = second; } else if (spanningTree.Contains(second) && !spanningTree.Contains(first)) { nonTreeNode = first; } return nonTreeNode; } private static List<Edge>[] ReadGraph(int nodesCount, int edgesCount) { var result = new List<Edge>[nodesCount]; for (int node = 0; node < nodesCount; node++) { result[node] = new List<Edge>(); } for (int i = 0; i < edgesCount; i++) { var edgeData = Console.ReadLine() .Split() .ToArray(); var first = int.Parse(edgeData[0]); var second = int.Parse(edgeData[1]); var weight = int.Parse(edgeData[2]); if (edgeData.Length == 4) { spanningTree.Add(first); spanningTree.Add(second); } var edge = new Edge { First = first, Second = second, Weight = weight }; result[first].Add(edge); result[second].Add(edge); } return result; } } }
25.706767
77
0.454811
[ "MIT" ]
marinakolova/CSharp-Courses
Algorithms-Advanced-with-CSharp-January-2021/03-GraphsBellmanFordLongestPathInDAG-Exercise/05-CableNetwork/Program.cs
3,421
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; namespace ICSharpCode.SharpDevelop.Dom { /// <summary> /// The GetClassReturnType is used when the class should be resolved on demand, but the /// full name is already known. /// </summary> public sealed class GetClassReturnType : ProxyReturnType { IProjectContent content; string fullName; string shortName; int typeArgumentCount; GetClassOptions options; public GetClassReturnType(IProjectContent content, string fullName, int typeArgumentCount) : this(content, fullName, typeArgumentCount, GetClassOptions.Default) { } public GetClassReturnType(IProjectContent content, string fullName, int typeArgumentCount, GetClassOptions options) { this.content = content; this.typeArgumentCount = typeArgumentCount; SetFullyQualifiedName(fullName); this.options = options; } public override bool IsDefaultReturnType { get { return true; } } public override int TypeArgumentCount { get { return typeArgumentCount; } } public override IReturnType BaseType { get { IClass c = content.GetClass(fullName, typeArgumentCount, content.Language, options); return (c != null) ? c.DefaultReturnType : null; } } public override string FullyQualifiedName { get { return fullName; } } void SetFullyQualifiedName(string fullName) { if (fullName == null) throw new ArgumentNullException("fullName"); this.fullName = fullName; int pos = fullName.LastIndexOf('.'); if (pos < 0) shortName = fullName; else shortName = fullName.Substring(pos + 1); } public override string Name { get { return shortName; } } public override string Namespace { get { string tmp = base.Namespace; if (tmp == "?") { if (fullName.IndexOf('.') > 0) return fullName.Substring(0, fullName.LastIndexOf('.')); else return ""; } return tmp; } } public override string DotNetName { get { string tmp = base.DotNetName; if (tmp == "?") { return fullName; } return tmp; } } public override string ToString() { return String.Format("[GetClassReturnType: {0}]", fullName); } } }
22.847619
117
0.674865
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/Main/ICSharpCode.SharpDevelop.Dom/Project/Src/Implementations/GetClassReturnType.cs
2,401
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("OddOrEvenIntegers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OddOrEvenIntegers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bee4f430-e97e-48c4-a11c-65a4716ca3c9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.746979
[ "MIT" ]
GeorgiPetrovGH/TelerikAcademy
01.C# part 1/03.OperatorsAndExpressions/OddOrEvenIntegers/Properties/AssemblyInfo.cs
1,410
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("treeDiM.FileTransfer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("treeDiM.FileTransfer")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c5cb16dd-c621-4de0-8c1a-c7fdf848cb3d")] // 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.189189
84
0.746638
[ "MIT" ]
minrogi/PLMPack
Sources/treeDiM.FileTransfer/Properties/AssemblyInfo.cs
1,416
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Projects; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestWindow.Extensibility; using Microsoft.VisualStudioTools.TestAdapter; namespace Microsoft.PythonTools.TestAdapter { internal class ProjectInfo : IDisposable { private readonly PythonProject _pythonProject; private readonly IPythonWorkspaceContext _pythonWorkspace; private readonly string _projectHome; private readonly string _projectName; private readonly ConcurrentDictionary<string, TestContainer> _containers; public ProjectInfo(PythonProject project) { _pythonProject = project; _pythonWorkspace = null; _projectHome = _pythonProject.ProjectHome; _projectName = _pythonProject.ProjectName; _containers = new ConcurrentDictionary<string, TestContainer>(StringComparer.OrdinalIgnoreCase); } public ProjectInfo(IPythonWorkspaceContext workspace) { _pythonProject = null; _pythonWorkspace = workspace; _projectHome = workspace.Location; _projectName = workspace.WorkspaceName; _containers = new ConcurrentDictionary<string, TestContainer>(StringComparer.OrdinalIgnoreCase); } public void Dispose() { _containers.Clear(); } public bool IsWorkspace => _pythonWorkspace != null; public TestContainer[] GetAllContainers() { //ConcurrentDictionary.ToArray() locks before copying return _containers.Values.ToArray(); } public bool TryGetContainer(string path, out TestContainer container) { return _containers.TryGetValue(path, out container); } public LaunchConfiguration GetLaunchConfigurationOrThrow() { if (IsWorkspace) { if (!_pythonWorkspace.CurrentFactory.Configuration.IsAvailable()) { throw new Exception("MissingEnvironment"); } var config = new LaunchConfiguration(_pythonWorkspace.CurrentFactory.Configuration) { WorkingDirectory = _pythonWorkspace.Location, SearchPaths = _pythonWorkspace.GetAbsoluteSearchPaths().ToList(), Environment = PathUtils.ParseEnvironment(_pythonWorkspace.GetStringProperty(PythonConstants.EnvironmentSetting) ?? "") }; return config; } return _pythonProject.GetLaunchConfigurationOrThrow(); } public string GetProperty(string name) { if (IsWorkspace) { return _pythonWorkspace.GetStringProperty(name); } return _pythonProject.GetProperty(name); } public bool? GetBoolProperty(string name) { if (IsWorkspace) { return _pythonWorkspace.GetBoolProperty(name); } return _pythonProject.GetProperty(name).IsTrue(); } public void AddTestContainer(ITestContainerDiscoverer discoverer, string path) { if (!Path.GetExtension(path).Equals(PythonConstants.FileExtension, StringComparison.OrdinalIgnoreCase)) return; _containers[path] = new TestContainer( discoverer, path, _projectHome, ProjectName, Architecture, IsWorkspace ); } public bool RemoveTestContainer(string path) { return _containers.TryRemove(path, out _); } private Architecture Architecture => Architecture.Default; public string ProjectHome => _projectHome; public string ProjectName { get { if (IsWorkspace) { return _pythonWorkspace.WorkspaceName; } return _projectName; } } } }
36.962121
138
0.652388
[ "Apache-2.0" ]
Bhaskers-Blu-Org2/PTVS
Python/Product/TestAdapter/ProjectInfo.cs
4,881
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Arm.Expression.Configuration; using Arm.Expression.Expressions; using Bicep.Core.Emit; using Bicep.Core.SemanticModel; using Bicep.Core.Syntax; using Bicep.Core.UnitTests.Utils; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bicep.Core.UnitTests.Emit { [TestClass] public class ExpressionConverterTests { [DataTestMethod] [DataRow("null", "[json('null')]")] [DataRow("true","[json('true')]")] [DataRow("false", "[json('false')]")] [DataRow("32", "[32]")] [DataRow("'hello world'", "hello world")] [DataRow(@"'\rI\nlike\ttabs\tand\'single\'quotes'", "\rI\nlike\ttabs\tand'single'quotes")] [DataRow(@"'\rI\nlike\ttabs\tand\'single\'quotes' + 2", "[add('\rI\nlike\ttabs\tand''single''quotes', 2)]")] [DataRow(@"!'escaping single quotes \'is\' simple'", "[not('escaping single quotes ''is'' simple')]")] [DataRow("!true", "[not(json('true'))]")] [DataRow("-10", "[-10]")] [DataRow("-'foo'", "[sub(0, 'foo')]")] [DataRow("-(2+4)", "[sub(0, add(2, 4))]")] [DataRow("'fake' ? 12 : null", "[if('fake', 12, json('null'))]")] [DataRow("[\n]", "[json('[]')]")] [DataRow("{\n}", "[json('{}')]")] [DataRow("2+3*4-10", "[sub(add(2, mul(3, 4)), 10)]")] [DataRow("true == false != null == 4 != 'a'", "[not(equals(equals(not(equals(equals(json('true'), json('false')), json('null'))), 4), 'a'))]")] [DataRow("-2 && 3 && !4 && 5", "[and(and(and(-2, 3), not(4)), 5)]")] [DataRow("-2 +-3 + -4 -10", "[sub(add(add(-2, -3), -4), 10)]")] [DataRow("true || false && null", "[or(json('true'), and(json('false'), json('null')))]")] [DataRow("3 / 2 + 4 % 0", "[add(div(3, 2), mod(4, 0))]")] [DataRow("3 / (2 + 4) % 0", "[mod(div(3, add(2, 4)), 0)]")] [DataRow("true < false", "[less(json('true'), json('false'))]")] [DataRow("null > 1", "[greater(json('null'), 1)]")] [DataRow("'aa' >= 14", "[greaterOrEquals('aa', 14)]")] [DataRow("10 <= -11", "[lessOrEquals(10, -11)]")] [DataRow("{\nfoo: 12\nbar: true\n}", "[json('{\"foo\":12,\"bar\":true}')]")] [DataRow("[\ntrue\nfalse\n12\nnull\n]", "[createArray(json('true'), json('false'), 12, json('null'))]")] [DataRow("[]", "[json('[]')]")] [DataRow("'aaa' =~ 'bbb'", "[equals(toLower('aaa'), toLower('bbb'))]")] [DataRow("'aaa' !~ 'bbb'", "[not(equals(toLower('aaa'), toLower('bbb')))]")] [DataRow("resourceGroup().location", "[resourceGroup().location]")] [DataRow("resourceGroup()['location']", "[resourceGroup().location]")] [DataRow("[\n4\n][0]", "[createArray(4)[0]]")] [DataRow("[\n[]\n[\n12\n's'\n][1]\n\n]","[createArray(json('[]'), createArray(12, 's')[1])]")] [DataRow("42[33].foo","[int(42)[33].foo]")] [DataRow("'foo'[x()]","[string('foo')[x()]]")] public void ShouldConvertExpressionsCorrectly(string text, string expected) { var compilation = new Compilation(TestResourceTypeProvider.Create(), SyntaxFactory.CreateFromText(string.Empty)); var parsed = ParserHelper.ParseExpression(text); var converter = new ExpressionConverter(new EmitterContext(compilation.GetSemanticModel())); var converted = converter.ConvertExpression(parsed); var serializer = new ExpressionSerializer(new ExpressionSerializerSettings { IncludeOuterSquareBrackets = true, SingleStringHandling = ExpressionSerializerSingleStringHandling.SerializeAsString }); var actual = serializer.SerializeExpression(converted); actual.Should().Be(expected); } } }
51.36
151
0.555556
[ "MIT" ]
joncloud/bicep
src/Bicep.Core.UnitTests/Emit/ExpressionConverterTests.cs
3,852
C#
using TechTalk.SpecFlow.Assist.Attributes; namespace Molder.Service.Models { public class Header { [TableAliases("Name", "Имя")] public string Name { get; set; } [TableAliases("Value", "Значение")] public string Value { get; set; } [TableAliases("Style", "Тип")] public string Style { get; set; } } }
22.058824
43
0.570667
[ "MIT" ]
Fufelhmertz/AlfaBank.AFT.Core.Library
src/Molder.Service/Models/Header.cs
391
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("HelloCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("HelloCSharp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9cb9d157-af76-4532-a5c9-5def3d1928fd")] // 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.702703
84
0.744803
[ "MIT" ]
MapuH/Telerik-Academy
Intro-Programming-Homework/HelloCSharp/Properties/AssemblyInfo.cs
1,398
C#
using System; namespace _0543 { /** * Definition for a binary tree node. */ public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } public class Solution { public int DiameterOfBinaryTree(TreeNode root) { return DFS(root).maxDiameter; } private (int depth, int maxDiameter) DFS(TreeNode root) { if (root == null) { return (0, 0); } var leftResult = DFS(root.left); var rightResult = DFS(root.right); var depth = Math.Max(leftResult.depth, rightResult.depth) + 1; var maxDiameter = Math.Max(Math.Max(leftResult.maxDiameter, rightResult.maxDiameter), leftResult.depth + rightResult.depth); return (depth, maxDiameter); } } class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
22.270833
136
0.53508
[ "Apache-2.0" ]
twilightgod/PlayLeetcode
0543/Program.cs
1,071
C#
// // System.Web.UI.WebControls.TableRowCollection.cs // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.ComponentModel; using System.Collections; namespace System.Web.UI.WebControls { #if NET_2_0 [Editor ("System.Web.UI.Design.WebControls.TableRowsCollectionEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)] #else [Editor ("System.Web.UI.Design.WebControls.TableRowsCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))] #endif public sealed class TableRowCollection : IList, ICollection, IEnumerable { ControlCollection cc; #if NET_2_0 Table owner; #endif internal TableRowCollection (Table table) { if (table == null) throw new ArgumentNullException ("table"); cc = table.Controls; #if NET_2_0 owner = table; #endif } public int Count { get { return cc.Count; } } public bool IsReadOnly { get { return false; } // documented as always false } public bool IsSynchronized { get { return false; } // documented as always false } public TableRow this [int index] { get { return (TableRow) cc [index]; } } public object SyncRoot { get { return this; } // as documented } public int Add (TableRow row) { if (row == null) throw new NullReferenceException (); // .NET compatibility #if NET_2_0 if (row.TableRowSectionSet) owner.GenerateTableSections = true; row.Container = this; #endif int index = cc.IndexOf (row); if (index < 0) { cc.Add (row); index = cc.Count; } return index; } public void AddAt (int index, TableRow row) { if (row == null) throw new NullReferenceException (); // .NET compatibility if (cc.IndexOf (row) < 0) { #if NET_2_0 if (row.TableRowSectionSet) owner.GenerateTableSections = true; row.Container = this; #endif cc.AddAt (index, row); } } public void AddRange (TableRow[] rows) { foreach (TableRow tr in rows) { if (tr == null) throw new NullReferenceException (); // .NET compatibility if (cc.IndexOf (tr) < 0) { #if NET_2_0 if (tr.TableRowSectionSet) owner.GenerateTableSections = true; tr.Container = this; #endif cc.Add (tr); } } } public void Clear () { #if NET_2_0 owner.GenerateTableSections = false; #endif cc.Clear (); } public void CopyTo (Array array, int index) { cc.CopyTo (array, index); } public IEnumerator GetEnumerator () { return cc.GetEnumerator (); } public int GetRowIndex (TableRow row) { return cc.IndexOf (row); } #if NET_2_0 internal void RowTableSectionSet () { owner.GenerateTableSections = true; } #endif public void Remove (TableRow row) { #if NET_2_0 if (row != null) row.Container = null; #endif cc.Remove (row); } public void RemoveAt (int index) { #if NET_2_0 TableRow row = this [index] as TableRow; if (row != null) row.Container = null; #endif cc.RemoveAt (index); } // implements IList but doesn't make some members public bool IList.IsFixedSize { get { return false; } } object IList.this [int index] { get { return cc [index]; } set { cc.AddAt (index, (TableRow)value); cc.RemoveAt (index + 1); } } int IList.Add (object value) { return Add (value as TableRow); } bool IList.Contains (object value) { return cc.Contains (value as TableRow); } int IList.IndexOf (object value) { return cc.IndexOf (value as TableRow); } void IList.Insert (int index, object value) { AddAt (index, value as TableRow); } void IList.Remove (object value) { Remove (value as TableRow); } } }
22.5
177
0.676656
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web/System.Web.UI.WebControls/TableRowCollection.cs
4,905
C#
using System.Text.Json.Serialization; namespace MtgApiManager.Lib.Dto { internal class RootCardDto : IMtgResponse { [JsonPropertyName("card")] public CardDto Card { get; set; } } }
21
45
0.661905
[ "MIT" ]
MagicTheGathering/mtg-sdk-dotnet
src/MtgApiManager.Lib/Dto/Cards/RootCardDto.cs
212
C#
using System.Collections.Generic; using Elektronik.Renderers; using Elektronik.RosPlugin.Common.Containers; using Elektronik.RosPlugin.Ros2.Bag.Data; using RosSharp.RosBridgeClient.MessageTypes.Sensor; using SQLite; namespace Elektronik.RosPlugin.Ros2.Bag.Containers { public class ImageDBContainer : DBContainerToWindow<Image, ImageRenderer, ImageData> { public ImageDBContainer(string displayName, List<SQLiteConnection> dbModels, Topic topic, List<long> actualTimestamps) : base(displayName, dbModels, topic, actualTimestamps) { } public override bool IsVisible { get => Renderer is not null && Renderer.IsShowing; set { } } #region DBContainerToWindow protected override ImageData ToRenderType(Image message) { return ImageDataExt.FromImageMessage(message); } protected override void SetRendererCallback() { if (Renderer is not null) Renderer.FlipVertically = true; } #endregion } }
28.097561
97
0.62934
[ "MIT" ]
dioram/Elektronik
plugins/Ros/Ros2/Bag/Containers/ImageDBContainer.cs
1,154
C#
using System; using System.Text; using Certes.Crypto; using Certes.Json; using Certes.Pkcs; using Newtonsoft.Json; using Org.BouncyCastle.Security; namespace Certes.Jws { /// <summary> /// Represents a JSON Web Signature (JWS) key pair. /// </summary> public interface IAccountKey { /// <summary> /// Gets the signing algorithm. /// </summary> /// <value> /// The signing algorithm. /// </value> KeyAlgorithm Algorithm { get; } /// <summary> /// Signs the data. /// </summary> /// <param name="data">The data.</param> /// <returns>The signature.</returns> byte[] SignData(byte[] data); /// <summary> /// Computes the hash for given data. /// </summary> /// <param name="data">The data.</param> /// <returns>The hash.</returns> byte[] ComputeHash(byte[] data); /// <summary> /// Gets the JSON web key. /// </summary> /// <value> /// The JSON web key. /// </value> [Obsolete("Use JsonWebKey instead.")] object Jwk { get; } /// <summary> /// Gets the JSON web key. /// </summary> /// <value> /// The JSON web key. /// </value> JsonWebKey JsonWebKey { get; } /// <summary> /// Gets the signature key. /// </summary> /// <value> /// The signature key. /// </value> IKey SignatureKey { get; } /// <summary> /// Exports the key pair. /// </summary> /// <returns>The key pair.</returns> KeyInfo Export(); } /// <summary> /// Helper methods for <see cref="AccountKey"/>. /// </summary> public static class AccountKeyExtensions { private static readonly JsonSerializerSettings thumbprintSettings = JsonUtil.CreateSettings(); /// <summary> /// Generates the thumbprint for the given account <paramref name="key"/>. /// </summary> /// <param name="key">The account key.</param> /// <returns>The thumbprint.</returns> public static byte[] GenerateThumbprint(this IAccountKey key) => key.SignatureKey.GenerateThumbprint(); /// <summary> /// Generates the base64 encoded thumbprint for the given account <paramref name="key"/>. /// </summary> /// <param name="key">The account key.</param> /// <returns>The thumbprint.</returns> public static string Thumbprint(this IAccountKey key) => key.SignatureKey.Thumbprint(); /// <summary> /// Generates key authorization string. /// </summary> /// <param name="key">The key.</param> /// <param name="token">The challenge token.</param> /// <returns></returns> public static string KeyAuthorization(this IAccountKey key, string token) => $"{token}.{key.Thumbprint()}"; } }
29.87
115
0.540676
[ "MIT" ]
webprofusion/certes
src/Certes/Jws/IAccountKey.cs
2,989
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#GetInitializationScripts()", Justification = "It is analogous to the get pattern users are familiar with")] [assembly: SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#GetFacebookUserProfile()", Justification = "It is analogous to the get pattern users are familiar with")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.Analytics", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.Bing", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.Facebook", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.FileUpload", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.GamerCard", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.LinkShare", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.Maps", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.ReCaptcha", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1053:StaticHolderTypesShouldNotHaveConstructors", Scope = "type", Target = "Microsoft.Web.Helpers.Twitter", Justification = "This is the default format in which helpers are generated.")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "4#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#OpenGraphRequiredProperties(System.String,System.String,System.String,System.String,System.String,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#", Scope = "member", Target = "Microsoft.Web.Helpers.Bing.#SearchBox(System.String,System.String,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#OpenGraphRequiredProperties(System.String,System.String,System.String,System.String,System.String,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#TweetButton(System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.String)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LiveStream(System.Int32,System.Int32,System.String,System.String,System.Boolean)", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Scope = "member", Target = "Microsoft.Web.Helpers.Bing.#SiteUrl", Justification = "We prefer strings to URIs for helpers")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Web.Helpers.Twitter.RawJS(System.String)", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Faves(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Web.Helpers.Twitter.RawJS(System.String)", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#List(System.String,System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color code")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Web.Helpers.Twitter.RawJS(System.String)", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Profile(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color code")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Web.Helpers.Twitter.RawJS(System.String)", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Search(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color code")] [assembly: SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Scope = "type", Target = "Microsoft.Web.Helpers.Facebook+UserProfile", Justification = "The type is consumed but never instantiated by a user")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Maps.#GetBingHtml(System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.String,System.Boolean,System.String,System.Collections.Generic.IEnumerable`1<Microsoft.Web.Helpers.Maps+MapLocation>)", Justification = "We're printing a JSON value that needs to be lower case")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Faves(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "We're printing a JSON value that needs to be lower case")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#List(System.String,System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "We're printing a JSON value that needs to be lower case")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Profile(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "We're printing a JSON value that needs to be lower case")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Search(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "We're printing a JSON value that needs to be lower case")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Facepile", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#Facepile(System.Int32,System.Int32)", Justification = "Facebook related term")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Faves", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Faves(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Facebook related term")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Fbml", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#FbmlNamespaces()", Justification = "Facebook related term")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "num", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#Comments(System.String,System.Int32,System.Int32,System.Boolean,System.Boolean)", Justification = "num is not Hungarian notation")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "xid", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#Comments(System.String,System.Int32,System.Int32,System.Boolean,System.Boolean)", Justification = "Facebook related term")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "xid", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LiveStream(System.Int32,System.Int32,System.String,System.String,System.Boolean)", Justification = "Facebook related term")] [assembly: SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#TweetButton(System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.String)")] [assembly: SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Re", Scope = "type", Target = "Microsoft.Web.Helpers.ReCaptcha")] [assembly: SuppressMessage("Microsoft.Naming", "CA1719:ParameterNamesShouldNotMatchMemberNames", MessageId = "1#", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#List(System.String,System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "The parameter corresponds a Twitter API parameter")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Logout", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButtonTagOnly(System.String,System.Boolean,System.String,System.String,System.String,System.Boolean,System.String)", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Logout", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButtonTagOnly(System.String,System.Boolean,System.String,System.String,System.String,System.Boolean,System.String)", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#LoginButton(System.String,System.String,System.String,System.String,System.Boolean,System.String,System.String,System.Boolean,System.String)", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook.#MembershipLogin()", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login", Scope = "member", Target = "Microsoft.Web.Helpers.LinkShare.#BitlyLogin", Justification = "We use login and logout in WebMatrix.Security")] [assembly: SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ffffff", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Faves(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color value")] [assembly: SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ffffff", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#List(System.String,System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color value")] [assembly: SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ffffff", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Profile(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color value")] [assembly: SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ffffff", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Search(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)", Justification = "Value is a hex color value")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Bing.#SiteUrl", Justification = "Property name is used instead of the generic term value to make it simpler to debug.")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.GamerCard.#GetHtml(System.String)")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Faves(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#List(System.String,System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Profile(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.Int32,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Bing.#SiteTitle", Justification = "Property name is used instead of the generic term value to make it simpler to debug.")] [assembly: SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Scope = "member", Target = "Microsoft.Web.Helpers.Twitter.#Search(System.String,System.Int32,System.Int32,System.String,System.String,System.String,System.String,System.String,System.String,System.String,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.Boolean,System.String,System.Int32)")] [assembly: SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook+UserProfile.#Updated_Time", Justification = "This is serailzed from a JSON schema, so member names have to be exactly this way.")] [assembly: SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook+UserProfile.#Last_Name", Justification = "This is serailzed from a JSON schema, so member names have to be exactly this way.")] [assembly: SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook+UserProfile.#First_Name", Justification = "This is serailzed from a JSON schema, so member names have to be exactly this way.")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Timezone", Scope = "member", Target = "Microsoft.Web.Helpers.Facebook+UserProfile.#Timezone", Justification = "This is serailzed from a JSON schema, so member names have to be exactly this way.")]
322.492308
569
0.803358
[ "Apache-2.0" ]
Icenium/aspnetwebstack
src/Microsoft.Web.Helpers/GlobalSuppressions.cs
20,964
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.OpcUa.Registry.v2.Models { using Microsoft.Azure.IIoT.OpcUa.Registry.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; /// <summary> /// Application info model /// </summary> public class ApplicationInfoApiModel { /// <summary> /// Default constructor /// </summary> public ApplicationInfoApiModel() { } /// <summary> /// Create model from service model /// </summary> /// <param name="model"></param> public ApplicationInfoApiModel(ApplicationInfoModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } ApplicationId = model.ApplicationId; ApplicationType = model.ApplicationType; ApplicationUri = model.ApplicationUri; ApplicationName = model.ApplicationName; Locale = model.Locale; LocalizedNames = model.LocalizedNames; Certificate = model.Certificate; ProductUri = model.ProductUri; SiteId = model.SiteId; HostAddresses = model.HostAddresses; SupervisorId = model.SupervisorId; DiscoveryProfileUri = model.DiscoveryProfileUri; DiscoveryUrls = model.DiscoveryUrls; Capabilities = model.Capabilities; NotSeenSince = model.NotSeenSince; GatewayServerUri = model.GatewayServerUri; Created = model.Created == null ? null : new RegistryOperationApiModel(model.Created); Updated = model.Updated == null ? null : new RegistryOperationApiModel(model.Updated); } /// <summary> /// Create service model from model /// </summary> public ApplicationInfoModel ToServiceModel() { return new ApplicationInfoModel { ApplicationId = ApplicationId, ApplicationType = ApplicationType, ApplicationUri = ApplicationUri, ApplicationName = ApplicationName, Locale = Locale, LocalizedNames = LocalizedNames, Certificate = Certificate, ProductUri = ProductUri, SiteId = SiteId, HostAddresses = HostAddresses, SupervisorId = SupervisorId, DiscoveryProfileUri = DiscoveryProfileUri, DiscoveryUrls = DiscoveryUrls, Capabilities = Capabilities, NotSeenSince = NotSeenSince, GatewayServerUri = GatewayServerUri, Created = Created?.ToServiceModel(), Updated = Updated?.ToServiceModel(), }; } /// <summary> /// Unique application id /// </summary> [JsonProperty(PropertyName = "applicationId")] public string ApplicationId { get; set; } /// <summary> /// Type of application /// </summary> /// <example>Server</example> [JsonProperty(PropertyName = "applicationType")] public ApplicationType ApplicationType { get; set; } /// <summary> /// Unique application uri /// </summary> [JsonProperty(PropertyName = "applicationUri")] public string ApplicationUri { get; set; } /// <summary> /// Product uri /// </summary> [JsonProperty(PropertyName = "productUri", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string ProductUri { get; set; } /// <summary> /// Default name of application /// </summary> [JsonProperty(PropertyName = "applicationName", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string ApplicationName { get; set; } /// <summary> /// Locale of default name - defaults to "en" /// </summary> [JsonProperty(PropertyName = "locale", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string Locale { get; set; } /// <summary> /// Localized Names of application keyed on locale /// </summary> [JsonProperty(PropertyName = "localizedNames", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public Dictionary<string, string> LocalizedNames { get; set; } /// <summary> /// Application public cert /// </summary> [JsonProperty(PropertyName = "certificate", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public byte[] Certificate { get; set; } /// <summary> /// The capabilities advertised by the server. /// </summary> /// <example>LDS</example> /// <example>DA</example> [JsonProperty(PropertyName = "capabilities", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public HashSet<string> Capabilities { get; set; } /// <summary> /// Discovery urls of the server /// </summary> [JsonProperty(PropertyName = "discoveryUrls", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public HashSet<string> DiscoveryUrls { get; set; } /// <summary> /// Discovery profile uri /// </summary> [JsonProperty(PropertyName = "discoveryProfileUri", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string DiscoveryProfileUri { get; set; } /// <summary> /// Gateway server uri /// </summary> [JsonProperty(PropertyName = "gatewayServerUri", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string GatewayServerUri { get; set; } /// <summary> /// Host addresses of server application or null /// </summary> [JsonProperty(PropertyName = "hostAddresses", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public HashSet<string> HostAddresses { get; set; } /// <summary> /// Site of the application /// </summary> /// <example>productionlineA</example> /// <example>cellB</example> [JsonProperty(PropertyName = "siteId", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string SiteId { get; set; } /// <summary> /// Supervisor having registered the application /// </summary> [JsonProperty(PropertyName = "supervisorId", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public string SupervisorId { get; set; } /// <summary> /// Last time application was seen /// </summary> [JsonProperty(PropertyName = "notSeenSince", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public DateTime? NotSeenSince { get; set; } /// <summary> /// Created /// </summary> [JsonProperty(PropertyName = "created", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public RegistryOperationApiModel Created { get; set; } /// <summary> /// Updated /// </summary> [JsonProperty(PropertyName = "updated", NullValueHandling = NullValueHandling.Ignore)] [DefaultValue(null)] public RegistryOperationApiModel Updated { get; set; } } }
36.475336
99
0.573027
[ "MIT" ]
benjguin/Industrial-IoT
services/src/Microsoft.Azure.IIoT.Services.OpcUa.Registry/src/v2/Models/ApplicationInfoApiModel.cs
8,134
C#
using System; using System.Globalization; #if __WPF__ using System.Windows; using System.Windows.Data; #else using Windows.UI.Xaml; using Windows.UI.Xaml.Data; #endif namespace Wokhan.UI.BindingConverters { public sealed class NullableToValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return System.Convert.ChangeType(value, targetType); } public object ConvertBack(object value, Type targetType, object parameter, string language) { return value; } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) => Convert(value, targetType, parameter, String.Empty); public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => ConvertBack(value, targetType, parameter, String.Empty); } }
31.333333
163
0.717021
[ "MIT" ]
wokhansoft/Wokhan.UI
Wokhan.UI/BindingConverters/NullableToValueConverter.cs
942
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Uno.Extensions; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Core; using Windows.UI.Popups; 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; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SamplesApp { /// <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() { ConfigureFilters(LogExtensionPoint.AmbientLoggerFactory); AssertIssue1790(); this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Assert that ApplicationData.Current.[LocalFolder|RoamingFolder] is usable in the constructor of App.xaml.cs on all platforms. /// </summary> /// <seealso cref="https://github.com/unoplatform/uno/issues/1741"/> public void AssertIssue1790() { void AssertIsUsable(Windows.Storage.ApplicationDataContainer container) { const string issue1790 = nameof(issue1790); container.Values.Remove(issue1790); container.Values.Add(issue1790, "ApplicationData.Current.[LocalFolder|RoamingFolder] is usable in the constructor of App.xaml.cs on this platform."); Assert.IsTrue(container.Values.ContainsKey(issue1790)); } AssertIsUsable(Windows.Storage.ApplicationData.Current.LocalSettings); AssertIsUsable(Windows.Storage.ApplicationData.Current.RoamingSettings); } /// <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 __IOS__ // requires Xamarin Test Cloud Agent Xamarin.Calabash.Start(); #endif var sw = Stopwatch.StartNew(); var n = Windows.UI.Xaml.Window.Current.Dispatcher.RunIdleAsync( _ => Console.WriteLine("Done loading " + sw.Elapsed)); #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { // this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Windows.UI.Xaml.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; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Windows.UI.Xaml.Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { 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 Windows.UI.Xaml.Window.Current.Activate(); } DisplayLaunchArguments(e); } private async void DisplayLaunchArguments(LaunchActivatedEventArgs launchActivatedEventArgs) { if (!string.IsNullOrEmpty(launchActivatedEventArgs.Arguments)) { var dlg = new MessageDialog(launchActivatedEventArgs.Arguments, "Launch arguments"); await dlg.ShowAsync(); } } /// <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}: {e.Exception}"); } /// <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(); } static void ConfigureFilters(ILoggerFactory factory) { factory .WithFilter(new FilterLoggerSettings { { "Uno", LogLevel.Warning }, { "Windows", LogLevel.Warning }, // { "Uno.Foundation.WebAssemblyRuntime", LogLevel.Debug }, // { "Windows.UI.Xaml.Controls.PopupPanel", LogLevel.Debug }, // Generic Xaml events //{ "Windows.UI.Xaml", LogLevel.Debug }, // { "Windows.UI.Xaml.Shapes", LogLevel.Debug }, //{ "Windows.UI.Xaml.VisualStateGroup", LogLevel.Debug }, //{ "Windows.UI.Xaml.StateTriggerBase", LogLevel.Debug }, // { "Windows.UI.Xaml.UIElement", LogLevel.Debug }, // { "Windows.UI.Xaml.Controls.TextBlock", LogLevel.Debug }, // Layouter specific messages // { "Windows.UI.Xaml.Controls", LogLevel.Debug }, //{ "Windows.UI.Xaml.Controls.Layouter", LogLevel.Debug }, //{ "Windows.UI.Xaml.Controls.Panel", LogLevel.Debug }, // { "Windows.Storage", LogLevel.Debug }, // Binding related messages // { "Windows.UI.Xaml.Data", LogLevel.Debug }, // { "Windows.UI.Xaml.Data", LogLevel.Debug }, // Binder memory references tracking // { "ReferenceHolder", LogLevel.Debug }, } ) #if DEBUG .AddConsole(LogLevel.Debug); #else .AddConsole(LogLevel.Warning); #endif } #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed private static ImmutableHashSet<int> _doneTests = ImmutableHashSet<int>.Empty; private static int _testIdCounter = 0; public static string GetAllTests() => SampleControl.Presentation.SampleChooserViewModel.Instance.GetAllSamplesNames(); public static string RunTest(string metadataName) { try { Console.WriteLine($"Initiate Running Test {metadataName}"); var testId = Interlocked.Increment(ref _testIdCounter); Windows.UI.Xaml.Window.Current.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, async () => { try { #if __IOS__ || __ANDROID__ var statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView(); if (statusBar != null) { Windows.UI.Xaml.Window.Current.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, async () => await statusBar.HideAsync() ); } #endif #if HAS_UNO // Disable the TextBox caret for new instances Uno.UI.FeatureConfiguration.TextBox.HideCaret = true; #endif var t = SampleControl.Presentation.SampleChooserViewModel.Instance.SetSelectedSample(CancellationToken.None, metadataName); var timeout = Task.Delay(30000); await Task.WhenAny(t, timeout); if (!(t.IsCompleted && !t.IsFaulted)) { throw new TimeoutException(); } ImmutableInterlocked.Update(ref _doneTests, lst => lst.Add(testId)); } catch (Exception e) { Console.WriteLine($"Failed to run test {metadataName}, {e}"); } finally { #if HAS_UNO // Restore the caret for new instances Uno.UI.FeatureConfiguration.TextBox.HideCaret = false; #endif } } ); return testId.ToString(); } catch (Exception e) { Console.WriteLine($"Failed Running Test {metadataName}, {e}"); return ""; } } #if __IOS__ [Foundation.Export("runTest:")] // notice the colon at the end of the method name public Foundation.NSString RunTestBackdoor(Foundation.NSString value) => new Foundation.NSString(RunTest(value)); [Foundation.Export("isTestDone:")] // notice the colon at the end of the method name public Foundation.NSString IsTestDoneBackdoor(Foundation.NSString value) => new Foundation.NSString(IsTestDone(value).ToString()); #endif public static bool IsTestDone(string testId) => int.TryParse(testId, out var id) ? _doneTests.Contains(id) : false; } }
32.578014
153
0.705236
[ "Apache-2.0" ]
AnonProgrammer007/uno
src/SamplesApp/SamplesApp.Shared/App.xaml.cs
9,189
C#
// Copyright (c) homuler and The Vignette Authors // This file is part of MediaPipe.NET. // MediaPipe.NET is licensed under the MIT License. See LICENSE for details. using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace Mediapipe.Net.Native { internal unsafe partial class SafeNativeMethods : NativeMethods { [SupportedOSPlatform("Linux"), SupportedOSPlatform("Android")] [Pure, DllImport(MEDIAPIPE_LIBRARY)] public static extern void* eglGetCurrentContext(); } }
31.388889
76
0.748673
[ "MIT" ]
dbruning/MediaPipe.NET
Mediapipe.Net/Native/SafeNativeMethods/Gpu/Gl.cs
565
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.IO; using UnityEngine; namespace Microsoft.MixedReality.SpectatorView { internal class CanvasRendererBroadcaster : ComponentBroadcaster<CanvasRendererService, CanvasRendererBroadcaster.ChangeType> { [Flags] public enum ChangeType : byte { None = 0x0, Properties = 0x1, } private CanvasRenderer canvasRendererBroadcaster; private CanvasRendererProperties previousValues; protected override void Awake() { base.Awake(); this.canvasRendererBroadcaster = GetComponent<CanvasRenderer>(); } public static bool HasFlag(ChangeType changeType, ChangeType flag) { return (changeType & flag) == flag; } protected override bool HasChanges(ChangeType changeFlags) { return changeFlags != ChangeType.None; } protected override ChangeType CalculateDeltaChanges() { ChangeType changeType = ChangeType.None; CanvasRendererProperties newValues = new CanvasRendererProperties(canvasRendererBroadcaster); if (previousValues != newValues) { changeType |= ChangeType.Properties; previousValues = newValues; } return changeType; } protected override void SendCompleteChanges(IEnumerable<INetworkConnection> connections) { SendDeltaChanges(connections, ChangeType.Properties); } protected override void SendDeltaChanges(IEnumerable<INetworkConnection> connections, ChangeType changeFlags) { using (MemoryStream memoryStream = new MemoryStream()) using (BinaryWriter message = new BinaryWriter(memoryStream)) { ComponentBroadcasterService.WriteHeader(message, this); message.Write((byte)changeFlags); if (HasFlag(changeFlags, ChangeType.Properties)) { message.Write(previousValues.alpha); message.Write(previousValues.color); } message.Flush(); memoryStream.TryGetBuffer(out var buffer); StateSynchronizationSceneManager.Instance.Send(connections, buffer.Array, buffer.Offset, buffer.Count); } } private struct CanvasRendererProperties { public CanvasRendererProperties(CanvasRenderer canvasRenderer) { alpha = canvasRenderer.GetAlpha(); color = canvasRenderer.GetColor(); } public float alpha; public Color color; public static bool operator ==(CanvasRendererProperties first, CanvasRendererProperties second) { return first.Equals(second); } public static bool operator !=(CanvasRendererProperties first, CanvasRendererProperties second) { return !first.Equals(second); } public override bool Equals(object obj) { if (!(obj is CanvasRendererProperties)) { return false; } CanvasRendererProperties other = (CanvasRendererProperties)obj; return other.alpha == alpha && other.color == color; } public override int GetHashCode() { return alpha.GetHashCode(); } } } }
32.669421
129
0.568176
[ "MIT" ]
Bhaskers-Blu-Org2/MixedReality-SpectatorView
src/SpectatorView.Unity/Assets/SpectatorView/Scripts/StateSynchronization/NetworkedComponents/CanvasRenderer/CanvasRendererBroadcaster.cs
3,955
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Rhino; using Rhino.Geometry; using ARDB = Autodesk.Revit.DB; namespace RhinoInside.Revit.Convert.Geometry { using External.DB; using External.DB.Extensions; /// <summary> /// Converts a "complex" <see cref="Brep"/> to be transfered to a <see cref="ARDB.Solid"/>. /// </summary> static class BrepEncoder { #region Tolerances static double JoinTolerance => Math.Sqrt(Math.Pow(GeometryObjectTolerance.Internal.VertexTolerance, 2.0) * 2.0); static double EdgeTolerance => JoinTolerance * 0.5; #endregion #region Encode internal static Brep ToRawBrep(/*const*/ Brep brep, double scaleFactor) { brep = brep.DuplicateShallow() as Brep; return EncodeRaw(ref brep, scaleFactor) ? brep : default; } internal static bool EncodeRaw(ref Brep brep, double scaleFactor) { if (scaleFactor != 1.0 && !brep.Scale(scaleFactor)) return default; var tol = GeometryObjectTolerance.Internal; var bbox = brep.GetBoundingBox(false); if (!bbox.IsValid || bbox.Diagonal.Length < tol.ShortCurveTolerance) return default; // Split and Shrink faces { brep.Faces.SplitKinkyFaces(tol.AngleTolerance, true); brep.Faces.SplitClosedFaces(0); brep.Faces.ShrinkFaces(); } var options = AuditBrep(brep); return RebuildBrep(ref brep, options); } [Flags] enum BrepIssues { Nothing = 0, OutOfToleranceEdges = 1, OutOfToleranceSurfaceKnots = 2, } static BrepIssues AuditBrep(Brep brep) { var options = default(BrepIssues); var tol = GeometryObjectTolerance.Internal; // Edges { foreach (var edge in brep.Edges) { if (edge.Tolerance > tol.VertexTolerance) { options |= BrepIssues.OutOfToleranceEdges; GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Geometry contains out of tolerance edges, it will be rebuilt.", edge); } } } // Faces { foreach (var face in brep.Faces) { var deltaU = KnotListEncoder.MinDelta(face.GetSpanVector(0)); if (deltaU < 1e-5) { options |= BrepIssues.OutOfToleranceSurfaceKnots; break; } var deltaV = KnotListEncoder.MinDelta(face.GetSpanVector(1)); if (deltaV < 1e-5) { options |= BrepIssues.OutOfToleranceSurfaceKnots; break; } } } return options; } static bool RebuildBrep(ref Brep brep, BrepIssues options) { if(options != BrepIssues.Nothing) { var tol = GeometryObjectTolerance.Internal; var edgesToUnjoin = brep.Edges.Select(x => x.EdgeIndex); var shells = brep.UnjoinEdges(edgesToUnjoin); if (shells.Length == 0) shells = new Brep[] { brep }; var kinkyEdges = 0; var microEdges = 0; var mergedEdges = 0; foreach (var shell in shells) { // Edges { var edges = shell.Edges; int edgeCount = edges.Count; for (int ei = 0; ei < edgeCount; ++ei) edges.SplitKinkyEdge(ei, tol.AngleTolerance); kinkyEdges += edges.Count - edgeCount; microEdges += edges.RemoveNakedMicroEdges(tol.VertexTolerance, cleanUp: true); mergedEdges += edges.MergeAllEdges(tol.AngleTolerance) - edgeCount; } // Faces { foreach (var face in shell.Faces) { if(options.HasFlag(BrepIssues.OutOfToleranceSurfaceKnots)) { face.GetSurfaceSize(out var width, out var height); face.SetDomain(0, new Interval(0.0, width)); var deltaU = KnotListEncoder.MinDelta(face.GetSpanVector(0)); if (deltaU < 1e-6) face.SetDomain(0, new Interval(0.0, width * (1e-6 / deltaU))); face.SetDomain(1, new Interval(0.0, height)); var deltaV = KnotListEncoder.MinDelta(face.GetSpanVector(1)); if (deltaV < 1e-6) face.SetDomain(1, new Interval(0.0, height * (1e-6 / deltaV))); } face.RebuildEdges(1e-6, false, true); } } // Flags shell.SetTrimIsoFlags(); } if(kinkyEdges > 0) GeometryEncoder.Context.Peek.RuntimeMessage(10, $"{kinkyEdges} kinky-edges splitted", default); #if DEBUG if (microEdges > 0) GeometryEncoder.Context.Peek.RuntimeMessage(255, $"DEBUG - {microEdges} Micro-edges removed", default); if (mergedEdges > 0) GeometryEncoder.Context.Peek.RuntimeMessage(255, $"DEBUG - {mergedEdges} Edges merged", default); #endif //var join = shells; var join = Brep.JoinBreps(shells, tol.VertexTolerance); if (join.Length == 1) brep = join[0]; else { var merge = new Brep(); foreach (var shell in join) merge.Append(shell); //var joined = merge.JoinNakedEdges(tol.VertexTolerance); brep = merge; } #if DEBUG foreach (var edge in brep.Edges) { if (edge.Tolerance > tol.VertexTolerance) GeometryEncoder.Context.Peek.RuntimeMessage(255, $"DEBUG - Geometry contains out of tolerance edges", edge); } #endif } return brep.IsValid; } #endregion #region Transfer internal static ARDB.Mesh ToMesh(/*const*/ Brep brep, double factor) { using (var mp = MeshingParameters.Default) { mp.Tolerance = 0.0;// GeometryObjectTolerance.Internal.VertexTolerance / factor; mp.MinimumTolerance = 0.0; mp.RelativeTolerance = 0.0; mp.RefineGrid = false; mp.GridAspectRatio = 0.0; mp.GridAngle = 0.0; mp.GridMaxCount = 0; mp.GridMinCount = 0; mp.MinimumEdgeLength = MeshEncoder.ShortEdgeTolerance / factor; mp.MaximumEdgeLength = 0.0; mp.ClosedObjectPostProcess = brep.IsSolid; mp.JaggedSeams = brep.IsManifold; mp.SimplePlanes = true; if (Mesh.CreateFromBrep(brep, mp) is Mesh[] shells) return MeshEncoder.ToMesh(shells, factor); return default; } } internal static ARDB.Solid ToSolid(/*const*/Brep brep, double factor) { // Try on existing solids already in memory. if (GeometryCache.TryGetExistingGeometry(brep, factor, out ARDB.Solid existing, out var signature)) { #if DEBUG GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Using cached value {signature}…", default); #endif return AuditSolid(brep, existing); } // Try to convert... if (TryGetSolid(brep, factor, out var solid)) { GeometryCache.AddExistingGeometry(signature, solid); return AuditSolid(brep, solid); } return default; } static ARDB.Solid AuditSolid(Brep brep, ARDB.Solid solid) { if (brep.IsSolid) { //#if DEBUG // if (solid.TryGetNakedEdges(out var nakedEdges)) // { // GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Output geometry has {nakedEdges.Count} naked edges.", default); // foreach (var edge in nakedEdges) // GeometryEncoder.Context.Peek.RuntimeMessage(20, default, edge.AsCurve().ToCurve().InHostUnits()); // } //#else if (!solid.IsWatertight()) GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Output geometry has naked edges.", default); //#endif } // DirectShape geometry has aditional validation switch(GeometryEncoder.Context.Peek.Element) { case ARDB.DirectShape ds: if (!ds.IsValidGeometry(solid)) { GeometryEncoder.Context.Peek.RuntimeMessage(20, "Geometry does not satisfy DirectShape validation criteria", brep.InHostUnits()); return default; } break; case ARDB.DirectShapeType dst: if (!dst.IsValidShape(new ARDB.Solid[] { solid })) { GeometryEncoder.Context.Peek.RuntimeMessage(20, "Geometry does not satisfy DirectShapeType validation criteria", brep.InHostUnits()); return default; } break; } return solid; } internal static bool TryGetSolid(/*const*/Brep brep, double factor, out ARDB.Solid solid) { solid = default; // Try convert flat extrusions under tolerance as surfaces if (brep.TryGetExtrusion(out var extrusion)) { var tol = GeometryObjectTolerance.Internal; var height = extrusion.PathStart.DistanceTo(extrusion.PathEnd); if (height < tol.VertexTolerance / factor) { var curves = new List<Curve>(extrusion.ProfileCount); for (int p = 0; p < extrusion.ProfileCount; ++p) curves.Add(extrusion.Profile3d(p, 0.5)); var regions = Brep.CreatePlanarBreps(curves, tol.VertexTolerance / factor); if (regions.Length != 1) return false; brep = regions[0]; } } // Try using ARDB.BRepBuilder { var raw = ToRawBrep(brep, factor); if (ToSolid(raw) is ARDB.Solid converted) { solid = converted; return true; } } // Try using ARDB.ShapeImporter | ARDB.Document.Import { GeometryEncoder.Context.Peek.RuntimeMessage(255, "Using SAT…", default); if (ToSAT(brep, factor) is ARDB.Solid imported) { solid = imported; return true; } } GeometryEncoder.Context.Peek.RuntimeMessage(20, "Failed to convert geometry.", brep.InHostUnits()); return false; } /// <summary> /// Replaces <see cref="Raw.RawEncoder.ToHost(Brep)"/> to catch Revit Exceptions /// </summary> /// <param name="brep"></param> /// <returns></returns> internal static ARDB.Solid ToSolid(/*const*/ Brep brep) { if (brep is null) return null; try { var tol = GeometryObjectTolerance.Internal; var brepType = ARDB.BRepType.OpenShell; switch (brep.SolidOrientation) { case BrepSolidOrientation.Inward: brepType = ARDB.BRepType.Void; break; case BrepSolidOrientation.Outward: brepType = ARDB.BRepType.Solid; break; } using (var builder = new ARDB.BRepBuilder(brepType)) { #if REVIT_2018 builder.SetAllowShortEdges(); builder.AllowRemovalOfProblematicFaces(); #endif var brepEdges = new List<ARDB.BRepBuilderGeometryId>[brep.Edges.Count]; foreach (var face in brep.Faces) { var surfaceGeom = default(ARDB.BRepBuilderSurfaceGeometry); try { surfaceGeom = Raw.RawEncoder.ToHost(face); } catch (Autodesk.Revit.Exceptions.ArgumentException e) { var message = e.Message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, $"{message}{Environment.NewLine}Face will be removed from the output.", face); continue; } catch (Autodesk.Revit.Exceptions.InvalidOperationException e) { var message = e.Message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, $"{message}{Environment.NewLine}Face will be removed from the output.", face); continue; } bool error = false; var faceId = builder.AddFace(surfaceGeom, face.OrientationIsReversed); builder.SetFaceMaterialId(faceId, GeometryEncoder.Context.Peek.MaterialId); foreach (var loop in face.Loops) { switch (loop.LoopType) { case BrepLoopType.Outer: break; case BrepLoopType.Inner: break; default: GeometryEncoder.Context.Peek.RuntimeMessage(10, $"{loop.LoopType} loop skipped.", loop); continue; } var loopId = builder.AddLoop(faceId); IEnumerable<BrepTrim> trims = loop.Trims; if (face.OrientationIsReversed) trims = trims.Reverse(); foreach (var trim in trims) { if (trim.TrimType != BrepTrimType.Boundary && trim.TrimType != BrepTrimType.Mated) continue; var edge = trim.Edge; if (edge is null) continue; try { var edgeIds = brepEdges[edge.EdgeIndex]; if (edgeIds is null) { edgeIds = brepEdges[edge.EdgeIndex] = new List<ARDB.BRepBuilderGeometryId>(); edgeIds.AddRange(ToBRepBuilderEdgeGeometry(edge).Select(e => builder.AddEdge(e))); } bool trimReversed = face.OrientationIsReversed ? !trim.IsReversed() : trim.IsReversed(); if (trimReversed) { for (int e = edgeIds.Count - 1; e >= 0; --e) builder.AddCoEdge(loopId, edgeIds[e], true); } else { for (int e = 0; e < edgeIds.Count; ++e) builder.AddCoEdge(loopId, edgeIds[e], false); } } catch (Autodesk.Revit.Exceptions.ArgumentsInconsistentException e) { error = true; var message = e.Message.Replace("(as identified by Application.ShortCurveTolerance)", $"({GeometryObjectTolerance.Model.ShortCurveTolerance})"); message = message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, message, edge); break; } catch (Autodesk.Revit.Exceptions.ApplicationException e) { error = true; var message = e.Message.Replace("BRepBuilder::addCoEdgeInternal_()", "BRepBuilder"); message = message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, message, edge); return default; } } try { builder.FinishLoop(loopId); } catch (Autodesk.Revit.Exceptions.ArgumentException e) { if (!error) { var message = e.Message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, message, loop); } } } try { builder.FinishFace(faceId); } catch (Autodesk.Revit.Exceptions.ArgumentException e) { if (!error) { error = true; var message = e.Message.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0]; GeometryEncoder.Context.Peek.RuntimeMessage(20, message, face); } } } try { var brepBuilderOutcome = builder.Finish(); if (builder.IsResultAvailable()) { #if REVIT_2018 if (builder.RemovedSomeFaces()) GeometryEncoder.Context.Peek.RuntimeMessage(20, "Some problematic faces were removed from the output", default); #endif return builder.GetResult(); } } catch (Autodesk.Revit.Exceptions.InvalidOperationException) { /* BRepBuilder contains an incomplete Brep definiton */ } } } catch (Autodesk.Revit.Exceptions.ApplicationException e) { // Any unexpected Revit Exception will be catched here. GeometryEncoder.Context.Peek.RuntimeMessage(20, e.Message, default); } return null; } static ARDB.Line ToEdgeCurve(Line line) { var length = line.Length; var isShort = length < GeometryObjectTolerance.Internal.ShortCurveTolerance; var factor = isShort ? 1.0 / length : UnitConverter.NoScale; var curve = ARDB.Line.CreateBound ( line.From.ToXYZ(factor), line.To.ToXYZ(factor) ); return isShort ? (ARDB.Line) curve.CreateTransformed(ARDB.Transform.Identity.ScaleBasis(length)) : curve; } static ARDB.Arc ToEdgeCurve(Arc arc) { var length = arc.Length; var isShort = length < GeometryObjectTolerance.Internal.ShortCurveTolerance; var factor = isShort ? 1.0 / length : UnitConverter.NoScale; var curve = ARDB.Arc.Create ( arc.StartPoint.ToXYZ(factor), arc.EndPoint.ToXYZ(factor), arc.MidPoint.ToXYZ(factor) ); return isShort ? (ARDB.Arc) curve.CreateTransformed(ARDB.Transform.Identity.ScaleBasis(length)) : curve; } static ARDB.Curve ToEdgeCurve(NurbsCurve nurbs) { var length = nurbs.GetLength(); var isShort = length < GeometryObjectTolerance.Internal.ShortCurveTolerance; var factor = isShort ? 1.0 / length : UnitConverter.NoScale; var degree = nurbs.Degree; var knots = Raw.RawEncoder.ToHost(nurbs.Knots); var rational = nurbs.IsRational; var points = nurbs.Points; var count = points.Count; var controlPoints = new ARDB.XYZ[count]; var weights = rational ? new double[count] : default; for (int p = 0; p < count; ++p) { var location = points[p].Location; controlPoints[p] = new ARDB.XYZ(location.X * factor, location.Y * factor, location.Z * factor); if (rational) weights[p] = points[p].Weight; } var curve = rational ? ARDB.NurbSpline.CreateCurve(degree, knots, controlPoints, weights) : ARDB.NurbSpline.CreateCurve(degree, knots, controlPoints); curve = isShort ? curve.CreateTransformed(ARDB.Transform.Identity.ScaleBasis(1.0 / factor)) : curve; return curve; } static IEnumerable<ARDB.Curve> ToEdgeCurve(PolyCurve curve) { var tol = GeometryObjectTolerance.Internal; if (curve.RemoveShortSegments(tol.VertexTolerance)) { #if DEBUG GeometryEncoder.Context.Peek.RuntimeMessage(10, "Edge micro-segment removed.", curve); #endif } int segmentCount = curve.SegmentCount; for (int s = 0; s < segmentCount; ++s) { var segment = curve.SegmentCurve(s); switch (segment) { case LineCurve line: yield return ToEdgeCurve(line.Line); break; case ArcCurve arc: yield return ToEdgeCurve(arc.Arc); break; case NurbsCurve nurbs: yield return ToEdgeCurve(nurbs); break; default: throw new NotImplementedException(); } } } static IEnumerable<ARDB.Line> ToEdgeCurveMany(PolylineCurve curve) { var tol = GeometryObjectTolerance.Internal; if (curve.RemoveShortSegments(tol.VertexTolerance)) { #if DEBUG GeometryEncoder.Context.Peek.RuntimeMessage(10, "Edge micro-segment removed.", curve); #endif } int pointCount = curve.PointCount; if (pointCount > 1) { var point = curve.Point(0); var segment = new Line { From = point }; for (int p = 1; p < pointCount; segment.From = segment.To, ++p) { point = curve.Point(p); segment.To = point; yield return ToEdgeCurve(segment); } } } static IEnumerable<ARDB.Arc> ToEdgeCurveMany(ArcCurve curve) { var tol = GeometryObjectTolerance.Internal; if (curve.IsClosed(tol.ShortCurveTolerance * 1.01)) { var interval = curve.Domain; double min = interval.Min, mid = interval.Mid, max = interval.Max; var points = new Point3d[] { curve.PointAt(min), curve.PointAt(min + (mid - min) * 0.5), curve.PointAt(mid), curve.PointAt(mid + (max - mid) * 0.5), curve.PointAt(max), }; yield return ToEdgeCurve(new Arc(points[0], points[1], points[2])); yield return ToEdgeCurve(new Arc(points[2], points[3], points[4])); } else yield return ToEdgeCurve(curve.Arc); } static IEnumerable<ARDB.Curve> ToEdgeCurveMany(PolyCurve curve) { var tol = GeometryObjectTolerance.Internal; if (curve.RemoveShortSegments(tol.VertexTolerance)) { #if DEBUG GeometryEncoder.Context.Peek.RuntimeMessage(10, "Edge micro-segment removed.", curve); #endif } int segmentCount = curve.SegmentCount; for (int s = 0; s < segmentCount; ++s) { foreach (var segment in ToEdgeCurveMany(curve.SegmentCurve(s))) yield return segment; } } static IEnumerable<ARDB.Curve> ToEdgeCurveMany(NurbsCurve curve) { // Reparametrize edgeCurve here to avoid two knots overlap due tolerance. // In case overlap happens curve will be splitted in more segments. if (curve.Degree > 2) { var length = curve.GetLength(); curve.Domain = new Interval(0.0, length); var delta = KnotListEncoder.MinDelta(curve.GetSpanVector()); if (delta < 1e-6) curve.Domain = new Interval(0.0, length * (1e-6 / delta)); } if (curve.Degree == 1) { var curvePoints = curve.Points; int pointCount = curvePoints.Count; if (pointCount > 1) { var segment = new Line { From = curvePoints[0].Location }; for (int p = 1; p < pointCount; ++p) { segment.To = curvePoints[p].Location; yield return ToEdgeCurve(segment); segment.From = segment.To; } } yield break; } else if (curve.Degree == 2) { for (int s = 0; s < curve.SpanCount; ++s) { var segment = curve.Trim(curve.SpanDomain(s)) as NurbsCurve; yield return ToEdgeCurve(segment); } } else if (curve.TryGetPolyCurveC2(out var polyCurve)) { foreach (var segment in ToEdgeCurve(polyCurve)) yield return segment; yield break; } else if (curve.IsClosed(GeometryObjectTolerance.Internal.VertexTolerance)) { var segments = curve.DuplicateSegments(); if (segments.Length == 1) { if ( curve.NormalizedLengthParameter(0.5, out var mid) && curve.Split(mid) is Curve[] half ) { yield return ToEdgeCurve(half[0] as NurbsCurve); yield return ToEdgeCurve(half[1] as NurbsCurve); } else throw new ConversionException("Failed to Split closed Edge"); } else { foreach (var segment in segments) yield return ToEdgeCurve(segment as NurbsCurve); } } else { yield return ToEdgeCurve(curve); } } static IEnumerable<ARDB.Curve> ToEdgeCurveMany(Curve curve) { switch (curve) { case LineCurve lineCurve: yield return ToEdgeCurve(lineCurve.Line); yield break; case PolylineCurve polylineCurve: foreach (var line in ToEdgeCurveMany(polylineCurve)) yield return line; yield break; case ArcCurve arcCurve: foreach (var arc in ToEdgeCurveMany(arcCurve)) yield return arc; yield break; case PolyCurve polyCurve: foreach (var segment in ToEdgeCurveMany(polyCurve)) yield return segment; yield break; case NurbsCurve nurbsCurve: foreach (var nurbs in ToEdgeCurveMany(nurbsCurve)) yield return nurbs; yield break; default: if (curve.HasNurbsForm() != 0) { var nurbsForm = curve.ToNurbsCurve(); foreach (var c in ToEdgeCurveMany(nurbsForm)) yield return c; } else throw new ConversionException($"Unable to convert {curve} to {typeof(ARDB.Curve)}"); yield break; } } static IEnumerable<ARDB.BRepBuilderEdgeGeometry> ToBRepBuilderEdgeGeometry(BrepEdge edge) { var tol = GeometryObjectTolerance.Internal; var edgeCurve = edge.EdgeCurve.Trim(edge.Domain) ?? edge.EdgeCurve.DuplicateCurve(); if (edgeCurve is null || edge.IsShort(tol.VertexTolerance, edge.Domain)) { GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Micro edge skipped.", edge); yield break; } if (edge.ProxyCurveIsReversed) edgeCurve.Reverse(); edgeCurve = edgeCurve.Simplify ( CurveSimplifyOptions.AdjustG1 | CurveSimplifyOptions.Merge, tol.VertexTolerance, tol.AngleTolerance ) ?? edgeCurve; foreach (var segment in ToEdgeCurveMany(edgeCurve)) { var segmentLength = segment.Length; if (segmentLength <= tol.ShortCurveTolerance) GeometryEncoder.Context.Peek.RuntimeMessage(10, $"Geometry contains short edges.{Environment.NewLine}Geometry with short edges may not be as reliable as fully valid geometry.", Raw.RawDecoder.ToRhino(segment)); if (segmentLength <= tol.VertexTolerance) { #if DEBUG GeometryEncoder.Context.Peek.RuntimeMessage(20, $"The curve is degenerate (its length is too close to zero).", Raw.RawDecoder.ToRhino(segment)); #endif continue; } yield return ARDB.BRepBuilderEdgeGeometry.Create(segment); } } #endregion #region IO Support Methods static ARDB.Document ioDocument; static ARDB.Document IODocument => ioDocument.IsValid() ? ioDocument : ioDocument = Revit.ActiveDBApplication.NewProjectDocument(ARDB.UnitSystem.Imperial); static FileInfo NewSwapFileInfo(string extension) { var swapFile = Path.Combine(Core.SwapFolder, $"{Guid.NewGuid():N}.{extension}"); return new FileInfo(swapFile); } static bool ExportGeometry(string fileName, GeometryBase geometry, double factor) { var extension = Path.GetExtension(fileName); if (extension is null) throw new ArgumentException("File name does not contain a valid extension", nameof(fileName)); var activeDoc = RhinoDoc.ActiveDoc; if (activeDoc is null) return false; using (var rhinoDoc = RhinoDoc.CreateHeadless(default)) { if (factor == GeometryEncoder.ModelScaleFactor) { rhinoDoc.ModelUnitSystem = activeDoc.ModelUnitSystem; rhinoDoc.ModelAbsoluteTolerance = activeDoc.ModelAbsoluteTolerance; rhinoDoc.ModelAngleToleranceRadians = activeDoc.ModelAngleToleranceRadians; } else { rhinoDoc.ModelUnitSystem = UnitSystem.Feet; rhinoDoc.ModelAbsoluteTolerance = activeDoc.ModelAbsoluteTolerance * factor; rhinoDoc.ModelAngleToleranceRadians = activeDoc.ModelAngleToleranceRadians; if (factor != UnitConverter.NoScale) { geometry = geometry.Duplicate(); if (!geometry.Scale(factor)) return false; } } rhinoDoc.Objects.Add(geometry); using ( var options = new Rhino.FileIO.FileWriteOptions() { FileVersion = 6, UpdateDocumentPath = false, WriteUserData = false, WriteGeometryOnly = false, SuppressAllInput = true, SuppressDialogBoxes = true, IncludeHistory = false, IncludeBitmapTable = false, IncludeRenderMeshes = false, IncludePreviewImage = false } ) return rhinoDoc.WriteFile(fileName, options); } } static bool TryGetSolidFromInstance(ARDB.Document doc, ARDB.ElementId elementId, ARDB.XYZ center, out ARDB.Solid solid) { if (doc.GetElement(elementId) is ARDB.Element element) { using (var options = new ARDB.Options() { DetailLevel = ARDB.ViewDetailLevel.Fine }) { // <see cref="ARDB.GeometryInstance.GetInstanceGeometry"/> is like calling // <see cref="ARDB.SolidUtils.CreateTransformed"/> on <see cref="ARDB.GeometryInstance.SymbolGeometry"/>. // It creates a transformed copy of the solid that will survive the Rollback. // Unfortunately Paint information lives in the element so even if we paint the // instance before doing the duplicate this information is lost after Rollback. if ( element.get_Geometry(options) is ARDB.GeometryElement geometryElement && geometryElement.First() is ARDB.GeometryInstance instance && instance.GetSymbolGeometry().First() is ARDB.Solid symbolSolid ) { var solidBBox = symbolSolid.GetBoundingBox(); var translate = ARDB.Transform.CreateTranslation(new ARDB.XYZ(0.0, 0.0, center.Z - solidBBox.Transform.Origin.Z)); solid = ARDB.SolidUtils.CreateTransformed(symbolSolid, translate); return true; } } } solid = default; return false; } #endregion #region SAT internal static ARDB.Solid ToSAT(/*const*/ Brep brep, double factor) { var FileSAT = NewSwapFileInfo("sat"); try { if (ExportGeometry(FileSAT.FullName, brep, factor)) { var doc = GeometryEncoder.Context.Peek.Document ?? IODocument; if (ARDB.ShapeImporter.IsServiceAvailable()) { using (var importer = new ARDB.ShapeImporter()) { var list = importer.Convert(doc, FileSAT.FullName); if (list.OfType<ARDB.Solid>().FirstOrDefault() is ARDB.Solid shape) return shape; GeometryEncoder.Context.Peek.RuntimeMessage(10, "Revit Data conversion service failed to import geometry", default); // Looks like ARDB.Document.Import do more cleaning while importing, let's try it. //return null; } } else GeometryEncoder.Context.Peek.RuntimeMessage(255, "Revit Data conversion service is not available", default); // In case we don't have a destination document we create a new one here. using (doc.IsValid() ? default : doc = Revit.ActiveDBApplication.NewProjectDocument(ARDB.UnitSystem.Imperial)) { try { // Everything in this scope should be rolledback. using (doc.RollBackScope()) { using ( var OptionsSAT = new ARDB.SATImportOptions() { ReferencePoint = ARDB.XYZ.Zero, Placement = ARDB.ImportPlacement.Origin, CustomScale = ARDB.UnitUtils.Convert ( factor, External.DB.Schemas.UnitType.Feet, doc.GetUnits().GetFormatOptions(External.DB.Schemas.SpecType.Measurable.Length).GetUnitTypeId() ) } ) { // Create a 3D view to import the SAT file var typeId = doc.GetDefaultElementTypeId(ARDB.ElementTypeGroup.ViewType3D); var view = ARDB.View3D.CreatePerspective(doc, typeId); var instanceId = doc.Import(FileSAT.FullName, OptionsSAT, view); var center = brep.GetBoundingBox(accurate: true).Center.ToXYZ(factor); if (TryGetSolidFromInstance(doc, instanceId, center, out var solid)) return solid; } } } catch (Autodesk.Revit.Exceptions.OptionalFunctionalityNotAvailableException e) { GeometryEncoder.Context.Peek.RuntimeMessage(255, e.Message, default); } finally { if (!doc.IsEquivalent(ioDocument) && doc != GeometryEncoder.Context.Peek.Document) doc.Close(false); } } GeometryEncoder.Context.Peek.RuntimeMessage(10, "Revit SAT module failed to import geometry", default); } else GeometryEncoder.Context.Peek.RuntimeMessage(20, "Failed to export geometry to SAT file", default); } finally { try { FileSAT.Delete(); } catch { } } return default; } #endregion #region 3DM internal static ARDB.Solid To3DM(/*const*/ Brep brep, double factor) { var File3DM = NewSwapFileInfo("3dm"); try { if (ExportGeometry(File3DM.FullName, brep, factor)) { var doc = GeometryEncoder.Context.Peek.Document ?? IODocument; if (ARDB.ShapeImporter.IsServiceAvailable()) { using (var importer = new ARDB.ShapeImporter()) { var list = importer.Convert(doc, File3DM.FullName); if (list.OfType<ARDB.Solid>().FirstOrDefault() is ARDB.Solid shape) return shape; GeometryEncoder.Context.Peek.RuntimeMessage(10, "Revit Data conversion service failed to import geometry", default); // Looks like DB.Document.Import do more cleaning while importing, let's try it. //return null; } } else GeometryEncoder.Context.Peek.RuntimeMessage(255, "Revit Data conversion service is not available", default); #if REVIT_2022 // In case we don't have a destination document we create a new one here. using (doc.IsValid() ? default : doc = Revit.ActiveDBApplication.NewProjectDocument(ARDB.UnitSystem.Imperial)) { try { // Everything in this scope should be rolledback. using (doc.RollBackScope()) { using ( var Options3DM = new ARDB.ImportOptions3DM() { ReferencePoint = ARDB.XYZ.Zero, Placement = ARDB.ImportPlacement.Origin, CustomScale = ARDB.UnitUtils.Convert ( factor, External.DB.Schemas.UnitType.Feet, doc.GetUnits().GetFormatOptions(External.DB.Schemas.SpecType.Measurable.Length).GetUnitTypeId() ) } ) { // Create a 3D view to import the 3DM file var typeId = doc.GetDefaultElementTypeId(ARDB.ElementTypeGroup.ViewType3D); var view = ARDB.View3D.CreatePerspective(doc, typeId); var instanceId = doc.Import(File3DM.FullName, Options3DM, view); var center = brep.GetBoundingBox(accurate: true).Center.ToXYZ(factor); if (TryGetSolidFromInstance(doc, instanceId, center, out var solid)) return solid; } } } catch (Autodesk.Revit.Exceptions.OptionalFunctionalityNotAvailableException e) { GeometryEncoder.Context.Peek.RuntimeMessage(255, e.Message, default); } finally { if (!doc.IsEquivalent(ioDocument) && doc != GeometryEncoder.Context.Peek.Document) doc.Close(false); } } GeometryEncoder.Context.Peek.RuntimeMessage(10, "Revit 3DM module failed to import geometry", default); #endif } else GeometryEncoder.Context.Peek.RuntimeMessage(20, "Failed to export geometry to 3DM file", default); } finally { try { File3DM.Delete(); } catch { } } return default; } #endregion #region Debug static bool IsEquivalent(this ARDB.Solid solid, Brep brep) { var tol = GeometryObjectTolerance.Model; var hit = new bool[brep.Faces.Count]; foreach (var face in solid.Faces.Cast<ARDB.Face>()) { double[] samples = { 0.0, 1.0 / 5.0, 2.0 / 5.0, 3.0 / 5.0, 4.0 / 5.0, 1.0 }; foreach (var edges in face.EdgeLoops.Cast<ARDB.EdgeArray>()) { foreach (var edge in edges.Cast<ARDB.Edge>()) { foreach (var sample in samples) { var point = edge.Evaluate(sample).ToPoint3d(); if (!brep.ClosestPoint(point, out var closest, out var ci, out var s, out var t, tol.VertexTolerance, out var normal)) return false; } } } // Get some samples using (var mesh = face.Triangulate(0.0)) { foreach (var vertex in mesh.Vertices) { // Recover real position on face if (face.Project(vertex) is ARDB.IntersectionResult result) { using (result) { var point = result.XYZPoint.ToPoint3d(); // Check if is on Brep if (!brep.ClosestPoint(point, out var closest, out var ci, out var s, out var t, tol.VertexTolerance, out var normal)) return false; if (ci.ComponentIndexType == ComponentIndexType.BrepFace) hit[ci.Index] = true; } } } } } return !hit.Any(x => !x); } #endregion } }
34.138269
220
0.581724
[ "MIT" ]
chuongmep/rhino.inside-revit
src/RhinoInside.Revit/Convert/Geometry/BrepEncoder.cs
38,273
C#
using System.Runtime.Serialization; namespace Models.Password { public enum PasswordStrength { [EnumMember(Value = "Blank")] Blank = 0, [EnumMember(Value = "Very Weak")] VeryWeak = 1, [EnumMember(Value = "Weak")] Weak = 2, [EnumMember(Value = "Medium")] Medium = 3, [EnumMember(Value = "Strong")] Strong = 4, [EnumMember(Value = "Very Strong")] VeryStrong = 5 } }
22.571429
43
0.535865
[ "MIT" ]
Jay-Aye/Password
Models/Password/PasswordStrength.cs
476
C#
using Milou.Deployer.Web.Core; using Xunit; using Xunit.Abstractions; namespace Milou.Deployer.Web.Tests.Unit { public class VersionHelperTest { private readonly ITestOutputHelper _output; public VersionHelperTest(ITestOutputHelper output) { _output = output; } [Fact] public void VersionInfoShouldNotBeNull() { AppVersionInfo appVersionInfo = VersionHelper.GetAppVersion(); _output.WriteLine(appVersionInfo.AssemblyVersion); _output.WriteLine(appVersionInfo.FileVersion); _output.WriteLine(appVersionInfo.AssemblyFullName); _output.WriteLine(appVersionInfo.InformationalVersion); Assert.NotNull(appVersionInfo.AssemblyVersion); Assert.NotNull(appVersionInfo.FileVersion); Assert.NotNull(appVersionInfo.AssemblyFullName); Assert.NotNull(appVersionInfo.InformationalVersion); } } }
30.6875
74
0.675153
[ "MIT" ]
milou-se/milou.deployer.web
src/Milou.Deployer.Web.Tests.Unit/VersionHelperTest.cs
984
C#
/** * Autogenerated by Thrift Compiler (0.11.0) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using Thrift; using Thrift.Collections; using System.Runtime.Serialization; using Thrift.Protocol; using Thrift.Transport; namespace STB_Modeling_Techniques.DEISProject.ODEDataModel.ThriftContract { #if !SILVERLIGHT [Serializable] #endif public partial class TDDIHazardTypeRef : TBase { private TDDIHazardType _ref; public TDDIHazardType Ref { get { return _ref; } set { __isset.@ref = true; this._ref = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool @ref; } public TDDIHazardTypeRef() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.Struct) { Ref = new TDDIHazardType(); Ref.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("TDDIHazardTypeRef"); oprot.WriteStructBegin(struc); TField field = new TField(); if (Ref != null && __isset.@ref) { field.Name = "ref"; field.Type = TType.Struct; field.ID = 1; oprot.WriteFieldBegin(field); Ref.Write(oprot); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("TDDIHazardTypeRef("); bool __first = true; if (Ref != null && __isset.@ref) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Ref: "); __sb.Append(Ref); } __sb.Append(")"); return __sb.ToString(); } } }
21.576923
73
0.541889
[ "MIT" ]
DEIS-Project-EU/DDI-Scripting-Tools
ODE_Tooladapter/ThriftContract/ODEv2ThriftContract/gen_Thrift_ODE/csharp/STB_Modeling_Techniques/DEISProject/ODEDataModel/ThriftContract/TDDIHazardTypeRef.cs
2,805
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.ContainerRegistry.Models { using Newtonsoft.Json; using System.Linq; public partial class EncryptionProperty { /// <summary> /// Initializes a new instance of the EncryptionProperty class. /// </summary> public EncryptionProperty() { CustomInit(); } /// <summary> /// Initializes a new instance of the EncryptionProperty class. /// </summary> /// <param name="status">Indicates whether or not the encryption is /// enabled for container registry. Possible values include: 'enabled', /// 'disabled'</param> /// <param name="keyVaultProperties">Key vault properties.</param> public EncryptionProperty(string status = default(string), KeyVaultProperties keyVaultProperties = default(KeyVaultProperties)) { Status = status; KeyVaultProperties = keyVaultProperties; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets indicates whether or not the encryption is enabled for /// container registry. Possible values include: 'enabled', 'disabled' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Gets or sets key vault properties. /// </summary> [JsonProperty(PropertyName = "keyVaultProperties")] public KeyVaultProperties KeyVaultProperties { get; set; } } }
34.3
135
0.632653
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/containerregistry/Microsoft.Azure.Management.ContainerRegistry/src/Generated/Models/EncryptionProperty.cs
2,058
C#
/* * Licensed to SharpSoftware under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * SharpSoftware licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Itinero.Algorithms.Collections; using Itinero.Algorithms.Weights; namespace Itinero.Algorithms.Contracted { /// <summary> /// Contains extension methods related to path tree. /// </summary> public static class PathTreeExtensions { private const float WeightFactor = 1000; /// <summary> /// Adds a new settled vertex. /// </summary> public static uint AddSettledVertex(this PathTree tree, uint vertex, WeightAndDir<float> weightAndDir, uint hops) { var hopsAndDirection = hops * 4 + weightAndDir.Direction._val; return tree.Add(vertex, (uint)(weightAndDir.Weight * WeightFactor), hopsAndDirection); } /// <summary> /// Adds a new settled vertex. /// </summary> public static uint AddSettledVertex(this PathTree tree, uint vertex, WeightAndDir<float> weightAndDir, uint hops, uint pPointer) { var hopsAndDirection = hops * 4 + weightAndDir.Direction._val; return tree.Add(vertex, (uint)(weightAndDir.Weight * WeightFactor), hopsAndDirection, pPointer); } /// <summary> /// Adds a new settled vertex. /// </summary> public static uint AddSettledVertex(this PathTree tree, uint vertex, float weight, Dir dir, uint hops) { var hopsAndDirection = hops * 4 + dir._val; return tree.Add(vertex, (uint)(weight * WeightFactor), hopsAndDirection); } /// <summary> /// Adds a new settled vertex. /// </summary> public static uint AddSettledVertex(this PathTree tree, uint vertex, float weight, Dir dir, uint hops, uint pPointer) { var hopsAndDirection = hops * 4 + dir._val; return tree.Add(vertex, (uint)(weight * WeightFactor), hopsAndDirection, pPointer); } /// <summary> /// Gets a settled vertex. /// </summary> public static void GetSettledVertex(this PathTree tree, uint pointer, out uint vertex, out WeightAndDir<float> weightAndDir, out uint hops) { uint data0, data1, data2; tree.Get(pointer, out data0, out data1, out data2); vertex = data0; weightAndDir = new WeightAndDir<float>() { Weight = data1 / WeightFactor, Direction = new Dir() { _val = (byte)(data2 & 3) } }; hops = data2 / 4; } /// <summary> /// Gets a settled vertex. /// </summary> public static void GetSettledVertex(this PathTree tree, uint pointer, out uint vertex, out WeightAndDir<float> weightAndDir, out uint hops, out uint previous) { uint data0, data1, data2, data3; tree.Get(pointer, out data0, out data1, out data2, out data3); vertex = data0; previous = data3; weightAndDir = new WeightAndDir<float>() { Weight = data1 / WeightFactor, Direction = new Dir() { _val = (byte)(data2 & 3) } }; hops = data2 / 4; } /// <summary> /// Gets a settled vertex weight. /// </summary> public static WeightAndDir<float> GetSettledVertexWeight(this PathTree tree, uint pointer) { uint data0, data1, data2; tree.Get(pointer, out data0, out data1, out data2); return new WeightAndDir<float>() { Weight = data1 / WeightFactor, Direction = new Dir() { _val = (byte)(data2 & 3) } }; } } }
36.542636
136
0.567671
[ "Apache-2.0" ]
eraydin/routing
src/Itinero/Algorithms/Contracted/PathTreeExtensions.cs
4,714
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using PoeCraftLib.Crafting.CraftingSteps; using PoeCraftLib.Currency; using PoeCraftLib.Entities.Items; namespace PoeCraftLib.Crafting { public class CraftManager { public CraftMetadata Craft( List<ICraftingStep> craftingSteps, Equipment equipment, AffixManager affixManager, CancellationToken ct, ProgressManager progressManager) { CraftMetadata metadata = new CraftMetadata(); metadata.Result = equipment; return this.Craft(craftingSteps, equipment, affixManager, ct, metadata, progressManager); } public CraftMetadata Craft( List<ICraftingStep> craftingSteps, Equipment equipment, AffixManager affixManager, CancellationToken ct, CraftMetadata metadata, ProgressManager progressManager) { foreach (var craftingStep in craftingSteps) { if (equipment.Completed) { return metadata; } if (progressManager.Progress >= 100) { return metadata; } if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } var currency = craftingStep.Craft(equipment, affixManager); UpdateMetadataOnCraft(craftingStep, metadata, currency, progressManager); var times = 0; double previousProgress = 0; while (craftingStep.ShouldVisitChildren(equipment, times)) { metadata = Craft(craftingStep.Children, equipment, affixManager, ct, metadata, progressManager); UpdateMetadataOnChildrenVisit(craftingStep, metadata); times++; if (times > 1) { // Check for no crafting steps if (Math.Abs(previousProgress - progressManager.Progress) < double.Epsilon) { throw new ArgumentException("Crafting steps do not spend currency"); } previousProgress = progressManager.Progress; } } } return metadata; } private CraftMetadata UpdateMetadataOnCraft( ICraftingStep craftingStep, CraftMetadata craftMetadata, Dictionary<string, int> currencyAmounts, ProgressManager progressManager) { if (!craftMetadata.CraftingStepMetadata.ContainsKey(craftingStep)) { CraftingStepMetadata stepMetadata = new CraftingStepMetadata {TimesVisited = 0, CurrencyAmounts = currencyAmounts }; craftMetadata.CraftingStepMetadata.Add(craftingStep, stepMetadata); } craftMetadata.CraftingStepMetadata[craftingStep].TimesVisited++; if (currencyAmounts.Any()) { craftMetadata.CraftingStepMetadata[craftingStep].TimesModified++; } foreach (var currency in currencyAmounts) { progressManager.SpendCurrency(currency.Key, currency.Value); } return craftMetadata; } private void UpdateMetadataOnChildrenVisit(ICraftingStep craftingStep, CraftMetadata craftMetadata) { craftMetadata.CraftingStepMetadata[craftingStep].TimesChildrenVisited++; } } public class CraftMetadata { public double SpentCurrency = 0; public Equipment Result = new Equipment(); public Dictionary<ICraftingStep, CraftingStepMetadata> CraftingStepMetadata = new Dictionary<ICraftingStep, CraftingStepMetadata>(); } public class CraftingStepMetadata { public int TimesVisited = 0; public int TimesModified = 0; public int TimesChildrenVisited = 0; public Dictionary<string, int> CurrencyAmounts { get; set; } } }
33.453125
140
0.578935
[ "MIT" ]
DanielWieder/PoeCraftLib
src/CraftingSim/CraftManager.cs
4,284
C#
using System; namespace MockGen.Setup { internal class MethodSetupReturn<TReturn> : MethodSetup, IMethodSetupReturn<TReturn>, IReturnContinuation { private new ActionConfigurationWithReturn<TReturn> currentConfiguration; internal MethodSetupReturn() { currentConfiguration = new ActionConfigurationWithReturn<TReturn>(base.currentConfiguration); } public IReturnContinuation Returns(TReturn value) { EnsureConfigurationMethodsAreAllowed(nameof(Returns)); currentConfiguration.ReturnAction = () => value; return this; } public IReturnContinuation Returns(Func<TReturn> returnFunc) { EnsureConfigurationMethodsAreAllowed(nameof(Returns)); currentConfiguration.ReturnAction = returnFunc; return this; } public void AndExecute(Action callback) { base.Execute(callback); } public TReturn ExecuteSetup() { numberOfCalls++; return currentConfiguration.RunActions(); } } }
29.275
110
0.614005
[ "MIT" ]
thomas-girotto/MockGen
specs/MockGen.Specs/Generated/Setup/MethodSetupReturn.cs
1,173
C#
namespace DynamicVNET.Lib.Integration.Tests { public class TokenStub { public TokenStub InnerToken { get; set; } public string TokenNumber { get; set; } } }
20.666667
49
0.639785
[ "MIT" ]
rasulhsn/DynamicVNET
DynamicVNET.Lib.Integration.Tests/Helper/TokenStub.cs
188
C#
using UnityEngine; using Phenix.Unity.Utilities; using Phenix.Unity.AI; public class AnimFSMStateAttackRoll : AnimFSMState { enum AttackRollState { PREPARE, ROLL, STAND_UP, } AnimFSMEventAttackRoll _eventAttackRoll; Quaternion _finalRotation; Quaternion _startRotation; float _curRotationTime; float _rotationTime; float _endOfStateTime; float _hitTimer; bool _rotationOk = false; AttackRollState _state; public AnimFSMStateAttackRoll(Agent1 agent) : base((int)AnimFSMStateType.ATTACK_ROLL, agent) { } public override void OnEnter(FSMEvent ev = null) { base.OnEnter(ev); Agent.BlackBoard.invulnerable = true; } public override void OnExit() { Agent.BlackBoard.invulnerable = false; Agent.BlackBoard.speed = 0; Agent.MotionTrace.Stop(); } protected override void Initialize(FSMEvent ev) { _eventAttackRoll = ev as AnimFSMEventAttackRoll; _state = AttackRollState.PREPARE; AnimationTools.PlayAnim(Agent.AnimEngine, "attackRollStart", 0.4f); base.Initialize(_eventAttackRoll); Agent.BlackBoard.motionType = MotionType.NONE; _endOfStateTime = Agent.AnimEngine["attackRollStart"].length * 0.95f + Time.timeSinceLevelLoad; _hitTimer = 0; UpdateFinalRotation(); Agent.SoundComponent.SoundMgr.PlayOneShot((int)SoundType.ATTACK_ROLL_BEGIN); } public override void OnUpdate() { switch (_state) { case AttackRollState.PREPARE: { UpdateFinalRotation(); if (_rotationOk == false) { _curRotationTime += Time.deltaTime; if (_curRotationTime >= _rotationTime) { _curRotationTime = _rotationTime; _rotationOk = true; } float progress = _curRotationTime / _rotationTime; Quaternion q = Quaternion.Lerp(_startRotation, _finalRotation, progress); Agent.Transform.rotation = q; } if (_endOfStateTime < Time.timeSinceLevelLoad) InitializeRoll(); } break; case AttackRollState.ROLL: { if (TransformTools.Instance.MoveOnGround(Agent.Transform, Agent.CharacterController, Agent.Transform.forward * Agent.BlackBoard.attackRollSpeed * Time.deltaTime, false) == false) { HandleAttackResult.DoRollDamage(Agent, _eventAttackRoll.animAttackData, Agent.BlackBoard.attackRollWeaponRange); InitializeStandUp(); } else if (_hitTimer < Time.timeSinceLevelLoad) { HandleAttackResult.DoRollDamage(Agent, _eventAttackRoll.animAttackData, Agent.BlackBoard.attackRollWeaponRange); _hitTimer = Time.timeSinceLevelLoad + Agent.BlackBoard.attackRollHitTime;//0.2f; } } break; case AttackRollState.STAND_UP: { if (_endOfStateTime < Time.timeSinceLevelLoad) { IsFinished = true; _eventAttackRoll.IsFinished = true; } } break; } } void InitializeRoll() { _state = AttackRollState.ROLL; AnimationTools.PlayAnim(Agent.AnimEngine, "attackRollLoop", 0.1f); Agent.BlackBoard.motionType = MotionType.ROLL; Agent.MotionTrace.Play(); } void InitializeStandUp() { _state = AttackRollState.STAND_UP; AnimationTools.PlayAnim(Agent.AnimEngine, "attackRollEnd", 0.1f); Agent.BlackBoard.motionType = MotionType.ROLL; _endOfStateTime = Agent.AnimEngine["attackRollEnd"].length * 0.95f + Time.timeSinceLevelLoad; Agent.MotionTrace.Stop(); Agent.SoundComponent.SoundMgr.PlayOneShot((int)SoundType.ATTACK_ROLL_END); } void UpdateFinalRotation() { if (_eventAttackRoll.target == null) return; Vector3 dir = _eventAttackRoll.target.Position - Agent.Position; dir.Normalize(); _startRotation = Agent.Transform.rotation; _finalRotation.SetLookRotation(dir); float angle = Vector3.Angle(Agent.Transform.forward, dir); if (angle > 0) { _rotationTime = angle / 100.0f; _rotationOk = false; _curRotationTime = 0; } else { _rotationOk = true; _rotationTime = 0; } } }
32.24359
160
0.556859
[ "MIT" ]
tuita520/samurai
samurai/Assets/Scripts/FSM1/FSMState/AnimFSMStateAttackRoll.cs
5,032
C#
using System.Reflection; [assembly: AssemblyCompany("Index laboratory.")] [assembly: AssemblyCopyright("\x00a9 Kuroko Shirai.")] [assembly: AssemblyProduct("momiji")] [assembly: AssemblyTitle("*MapleStory character imitator.")] [assembly: AssemblyVersion("0.0.*")]
33.375
60
0.7603
[ "BSD-2-Clause" ]
SuperCatss/momiji
momiji/assembly.cs
269
C#
// Copyright 2017 Jose Luis Rovira Martin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Essence.Util.Events; namespace Essence.View.Models { public class AbsDrawing3DModel : AbsNotifyPropertyChanged, IDrawing3DModel { public virtual void OnInvalidate(Invalidate3DEventArgs args) { if (this.Invalidate != null) { this.Invalidate(this, args); } } #region IDrawing3DModel public virtual void Update(IRenderContext3D render) { } public event EventHandler<Invalidate3DEventArgs> Invalidate; #endregion } }
29.45
78
0.679117
[ "Apache-2.0" ]
jlroviramartin/Essence
Essence.View.GL/Models/AbsDrawing3DModel.cs
1,180
C#
namespace json2record.tests.sample2.DTOs { public record CustomerLedgerAccount { public string type { get; init; } public string number { get; init; } public string description { get; init; } } }
33.285714
49
0.630901
[ "MIT" ]
mikalst/dtolab
json2record.tests/DTOs/sample2/CustomerLedgerAccount.cs
233
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DocumentDB.Latest.Outputs { [OutputType] public sealed class ContinuousModeBackupPolicyResponse { /// <summary> /// Describes the mode of backups. /// </summary> public readonly string Type; [OutputConstructor] private ContinuousModeBackupPolicyResponse(string type) { Type = type; } } }
25.392857
81
0.668073
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/DocumentDB/Latest/Outputs/ContinuousModeBackupPolicyResponse.cs
711
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.ResourceManager.Sql.Models { public partial class PrivateEndpointConnectionListResult { internal static PrivateEndpointConnectionListResult DeserializePrivateEndpointConnectionListResult(JsonElement element) { Optional<IReadOnlyList<PrivateEndpointConnection>> value = default; Optional<string> nextLink = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("value")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<PrivateEndpointConnection> array = new List<PrivateEndpointConnection>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(PrivateEndpointConnection.DeserializePrivateEndpointConnection(item)); } value = array; continue; } if (property.NameEquals("nextLink")) { nextLink = property.Value.GetString(); continue; } } return new PrivateEndpointConnectionListResult(Optional.ToList(value), nextLink.Value); } } }
35.574468
127
0.568182
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/PrivateEndpointConnectionListResult.Serialization.cs
1,672
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Vibechat.DataLayer.Repositories.Specifications; namespace Vibechat.DataLayer.Repositories { public interface IAsyncRepository<T> where T: class { Task<T> GetByIdAsync(int id); Task<IReadOnlyList<T>> ListAllAsync(); Task<IReadOnlyList<T>> ListAsync(ISpecification<T> spec); Task<T> AddAsync(T entity); Task UpdateAsync(T entity); Task DeleteAsync(T entity); Task<int> CountAsync(ISpecification<T> spec); Task<T> SingleOrDefaultAsync(ISpecification<T> spec); Task<IQueryable<T>> AsQuerableAsync(ISpecification<T> spec); Task ClearAsync(); } }
29.08
68
0.691884
[ "MIT" ]
developeramarish/Vibechat.Core
Vibechat.Web/Vibechat.DataLayer/Repositories/IAsyncRepository.cs
729
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace KSaveDataMan { [System.Serializable] internal class MasterSaveJsonDefault { [SerializeField] internal string gameName = ""; [SerializeField] internal string companyName = ""; [SerializeField] internal string platform = ""; [SerializeField] internal string buildGUID = ""; [SerializeField] internal bool genuine = true; [SerializeField] internal string gameVer = ""; [SerializeField] internal string unityVer = ""; [SerializeField] internal string gameBundleID = ""; [SerializeField] internal EncodingType encoding = EncodingType.ASCII; [SerializeField] internal LocatorForMasterSaveData[] data = null; } [System.Serializable] internal class LocatorForMasterSaveData { [SerializeField] internal string[] keys; [SerializeField] internal string value; [SerializeField] internal string typeName; [SerializeField] internal bool game_wrote_it; } }
35.866667
77
0.69145
[ "MIT" ]
kaiyumcg/KSaveDataManager
KSaveDataManager/Code/MasterSaveJsonDefault.cs
1,076
C#
using System; using Bernie.Server.Core; using Xunit; namespace Bernie.Tests.Core { public class ThrottleTests { [Fact] public void PreventsEventsBeingRaisedTooManyTimes() { var now = DateTimeOffset.UtcNow; var throttle = new Throttle(TimeSpan.FromSeconds(30)); Assert.True(throttle.ShouldRaise(now)); Assert.False(throttle.ShouldRaise(now)); Assert.False(throttle.ShouldRaise(now.Subtract(TimeSpan.FromSeconds(10)))); Assert.False(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(10)))); Assert.False(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(20)))); Assert.False(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(30)))); Assert.True(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(31)))); Assert.False(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(31)))); throttle.Reset(); Assert.True(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(31)))); Assert.False(throttle.ShouldRaise(now.Add(TimeSpan.FromSeconds(31)))); } } }
39.310345
87
0.655263
[ "Apache-2.0" ]
PaulStovell/Bernie
source/Bernie.Tests/Core/ThrottleTests.cs
1,142
C#
using Robust.Shared.Interfaces.Reflection; using Robust.Shared.IoC; using System; using System.Collections.Generic; using System.Reflection; namespace Content.Server.GameObjects.Components.NodeContainer.NodeGroups { public interface INodeGroupFactory { /// <summary> /// Performs reflection to associate <see cref="INodeGroup"/> implementations with the /// string specified in their <see cref="NodeGroupAttribute"/>. /// </summary> void Initialize(); /// <summary> /// Returns a new <see cref="INodeGroup"/> instance. /// </summary> INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType); } public class NodeGroupFactory : INodeGroupFactory { private readonly Dictionary<NodeGroupID, Type> _groupTypes = new Dictionary<NodeGroupID, Type>(); #pragma warning disable 649 [Dependency] private readonly IReflectionManager _reflectionManager; [Dependency] private readonly IDynamicTypeFactory _typeFactory; #pragma warning restore 649 public void Initialize() { var nodeGroupTypes = _reflectionManager.GetAllChildren<BaseNodeGroup>(); foreach (var nodeGroupType in nodeGroupTypes) { var att = nodeGroupType.GetCustomAttribute<NodeGroupAttribute>(); if (att != null) { foreach (var groupID in att.NodeGroupIDs) { _groupTypes.Add(groupID, nodeGroupType); } } } } public INodeGroup MakeNodeGroup(NodeGroupID nodeGroupType) { if (_groupTypes.TryGetValue(nodeGroupType, out var type)) { return _typeFactory.CreateInstance<INodeGroup>(type); } throw new ArgumentException($"{nodeGroupType} did not have an associated {nameof(INodeGroup)}."); } } public enum NodeGroupID { Default, HVPower, MVPower, Apc, } }
31.621212
109
0.604696
[ "MIT" ]
Hughgent/space-station-14
Content.Server/GameObjects/Components/NodeContainer/NodeGroups/NodeGroupFactory.cs
2,089
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由T4模板自动生成 // 生成时间 2020-02-04 21:25:26 // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失 // 作者:Harbour CTS // </auto-generated> //------------------------------------------------------------------------------ using LQExtension.Model; using LQExtension.DAL; namespace LQExtension.BLL { public partial class EC_ProductBLL:BaseServiceDapperContrib<Model.EC_Product> { } }
21.291667
80
0.463796
[ "MIT" ]
haitongxuan/LQExtesion
LQExtension.BLL/T4.DapperExt/EC_ProductBLL.cs
621
C#
namespace Renting.Domain { public class TenantId { private readonly string _id; private TenantId(string id) { _id = id; } public static TenantId From(string tenantId) { return new TenantId(tenantId); } public override string ToString() { return _id; } } }
17.545455
52
0.5
[ "Apache-2.0" ]
rafalpienkowski/ddd-training
src/Renting/Domain/TenantId.cs
386
C#
using System; using CafeLib.Cryptography.BouncyCastle.Math; using CafeLib.Cryptography.BouncyCastle.Math.EC; using CafeLib.Cryptography.BouncyCastle.Math.Field; namespace CafeLib.Cryptography.BouncyCastle.Asn1.X9 { /** * ASN.1 def for Elliptic-Curve ECParameters structure. See * X9.62, for further details. */ public class X9ECParameters : Asn1Encodable { private X9FieldID fieldID; private ECCurve curve; private ECPoint g; private BigInteger n; private BigInteger h; private byte[] seed; public X9ECParameters( Asn1Sequence seq) { if (!(seq[0] is DerInteger) || !((DerInteger) seq[0]).Value.Equals(BigInteger.One)) { throw new ArgumentException("bad version in X9ECParameters"); } X9Curve x9c = null; if (seq[2] is X9Curve) { x9c = (X9Curve) seq[2]; } else { x9c = new X9Curve( new X9FieldID( (Asn1Sequence) seq[1]), (Asn1Sequence) seq[2]); } this.curve = x9c.Curve; if (seq[3] is X9ECPoint) { this.g = ((X9ECPoint) seq[3]).Point; } else { this.g = new X9ECPoint(curve, (Asn1OctetString) seq[3]).Point; } this.n = ((DerInteger) seq[4]).Value; this.seed = x9c.GetSeed(); if (seq.Count == 6) { this.h = ((DerInteger) seq[5]).Value; } } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n) : this(curve, g, n, BigInteger.One, null) { } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n, BigInteger h) : this(curve, g, n, h, null) { } public X9ECParameters( ECCurve curve, ECPoint g, BigInteger n, BigInteger h, byte[] seed) { this.curve = curve; this.g = g.Normalize(); this.n = n; this.h = h; this.seed = seed; if (ECAlgorithms.IsFpCurve(curve)) { this.fieldID = new X9FieldID(curve.Field.Characteristic); } else if (ECAlgorithms.IsF2mCurve(curve)) { IPolynomialExtensionField field = (IPolynomialExtensionField)curve.Field; int[] exponents = field.MinimalPolynomial.GetExponentsPresent(); if (exponents.Length == 3) { this.fieldID = new X9FieldID(exponents[2], exponents[1]); } else if (exponents.Length == 5) { this.fieldID = new X9FieldID(exponents[4], exponents[1], exponents[2], exponents[3]); } else { throw new ArgumentException("Only trinomial and pentomial curves are supported"); } } else { throw new ArgumentException("'curve' is of an unsupported type"); } } public ECCurve Curve { get { return curve; } } public ECPoint G { get { return g; } } public BigInteger N { get { return n; } } public BigInteger H { get { if (h == null) { // TODO - this should be calculated, it will cause issues with custom curves. return BigInteger.One; } return h; } } public byte[] GetSeed() { return seed; } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * ECParameters ::= Sequence { * version Integer { ecpVer1(1) } (ecpVer1), * fieldID FieldID {{FieldTypes}}, * curve X9Curve, * base X9ECPoint, * order Integer, * cofactor Integer OPTIONAL * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector( new DerInteger(1), fieldID, new X9Curve(curve, seed), new X9ECPoint(g), new DerInteger(n)); if (h != null) { v.Add(new DerInteger(h)); } return new DerSequence(v); } } }
26.989247
105
0.438845
[ "MIT" ]
chrissolutions/CafeLib
Cryptography/CafeLib.Cryptography.BouncyCastle/Asn1/X9/X9ECParameters.cs
5,020
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.dms_enterprise.Model.V20181101 { public class GrantUserPermissionResponse : AcsResponse { private string requestId; private bool? success; private string errorMessage; private string errorCode; public string RequestId { get { return requestId; } set { requestId = value; } } public bool? Success { get { return success; } set { success = value; } } public string ErrorMessage { get { return errorMessage; } set { errorMessage = value; } } public string ErrorCode { get { return errorCode; } set { errorCode = value; } } } }
19.094118
63
0.653728
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-dms-enterprise/Dms_enterprise/Model/V20181101/GrantUserPermissionResponse.cs
1,623
C#
using System.Web.Mvc; using System.Web.Routing; namespace cocolab { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); routes.MapRoute( name: "Default", url: "", defaults: new { controller = "Home", action = "Index"} ); } } }
21.818182
70
0.529167
[ "MIT" ]
TritiumMonoid/cocolab
src/cocolab/App_Start/RouteConfig.cs
482
C#
using System; using UnityEngine; using UnityEditor; using LEM_Effects; namespace LEM_Editor { public class RepeatMoveRotationToTNode : UpdateEffectNode { Transform m_TargetTransform = default; Transform m_ReferenceTransform = default; bool m_WorldRotation = false; float m_Duration = 0f; protected override string EffectTypeName => "RepeatMoveRotationToT"; public override void Initialise(Vector2 position, NodeSkinCollection nodeSkin, GUIStyle connectionPointStyle, Action<ConnectionPoint> onClickInPoint, Action<ConnectionPoint> onClickOutPoint, Action<Node> onSelectNode, Action<string> onDeSelectNode, Action<BaseEffectNodePair> updateEffectNodeInDictionary, Color topSkinColour) { base.Initialise(position, nodeSkin, connectionPointStyle, onClickInPoint, onClickOutPoint, onSelectNode, onDeSelectNode, updateEffectNodeInDictionary, topSkinColour); //Override the rect size n pos SetNodeRects(position, NodeTextureDimensions.BIG_MID_SIZE, NodeTextureDimensions.BIG_TOP_SIZE); } public override void Draw() { base.Draw(); //Draw a object field for inputting the gameobject to destroy Rect propertyRect = new Rect(m_MidRect.x + NodeGUIConstants.X_DIST_FROM_MIDRECT, m_MidRect.y + NodeGUIConstants.UPDATE_EFFNODE_Y_DIST_FROM_MIDRECT, m_MidRect.width - NodeGUIConstants.MIDRECT_WIDTH_OFFSET, EditorGUIUtility.singleLineHeight); LEMStyleLibrary.BeginEditorLabelColourChange(LEMStyleLibrary.CurrentLabelColour); m_TargetTransform = (Transform)EditorGUI.ObjectField(propertyRect, "Targeted Transform", m_TargetTransform, typeof(Transform), true); propertyRect.y += 20f; m_ReferenceTransform = (Transform)EditorGUI.ObjectField(propertyRect, "Reference Transform", m_ReferenceTransform, typeof(Transform), true); propertyRect.y += 20f; m_WorldRotation = EditorGUI.Toggle(propertyRect, "Use World Rotation", m_WorldRotation); propertyRect.y += 20f; m_Duration = EditorGUI.FloatField(propertyRect, "Duration", m_Duration); LEMStyleLibrary.EndEditorLabelColourChange(); } public override LEM_BaseEffect CompileToBaseEffect(GameObject go) { RepeatMoveRotationToT myEffect = go.AddComponent<RepeatMoveRotationToT>(); //RepeatMoveRotationToT myEffect = ScriptableObject.CreateInstance<RepeatMoveRotationToT>(); myEffect.bm_NodeEffectType = EffectTypeName; //myEffect.m_Description = m_LemEffectDescription; myEffect.bm_UpdateCycle = m_UpdateCycle; string[] connectedNextPointNodeIDs = TryToSaveNextPointNodeID(); myEffect.bm_NodeBaseData = new NodeBaseData(m_MidRect.position, NodeID, connectedNextPointNodeIDs/*, connectedPrevPointNodeIDs*/); myEffect.SetUp(m_TargetTransform, m_ReferenceTransform, m_WorldRotation, m_Duration); return myEffect; } public override void LoadFromBaseEffect(LEM_BaseEffect effectToLoadFrom) { RepeatMoveRotationToT loadFrom = effectToLoadFrom as RepeatMoveRotationToT; loadFrom.UnPack(out m_TargetTransform, out m_ReferenceTransform, out m_WorldRotation, out m_Duration); //Important m_UpdateCycle = effectToLoadFrom.bm_UpdateCycle; } } }
43.3625
334
0.721822
[ "MIT" ]
bestcolour/Linear-Event-Manager
LEM_Editor_Files/Node_LEM/Nodes/NodeTypes/TransformEffects/MoveTowards/Rotation/RepeatMoveRotationToTNode.cs
3,471
C#
namespace DDD.Light.Realtor.Domain.Model.Buyer { // value object public class Address { public string Address1 { get; private set; } public string Address2 { get; private set; } public string City { get; private set; } public string State { get; private set; } public string Zip { get; private set; } public Address(string address1, string address2, string city, string state, string zip) { Address1 = address1; Address2 = address2; City = city; State = state; Zip = zip; } } }
29.47619
95
0.563813
[ "MIT" ]
aksharp/DDD.Light
Examples/RealtorApp/DDD.Light.Realtor.Domain/Model/Buyer/Address.cs
621
C#
using UnityEngine; using System; using System.Reflection; namespace BehaviorDesigner.Runtime.Tasks { [TaskDescription("Compares the field value to the value specified. Returns success if the values are the same.")] [TaskCategory("Reflection")] [TaskIcon("{SkinColor}ReflectionIcon.png")] public class CompareFieldValue : Conditional { [Tooltip("The GameObject to compare the field on")] public SharedGameObject targetGameObject; [Tooltip("The component to compare the field on")] public SharedString componentName; [Tooltip("The name of the field")] public SharedString fieldName; [Tooltip("The value to compare to")] public SharedVariable compareValue; public override TaskStatus OnUpdate() { if (compareValue == null) { Debug.LogWarning("Unable to compare field - compare value is null"); return TaskStatus.Failure; } var type = TaskUtility.GetTypeWithinAssembly(componentName.Value); if (type == null) { Debug.LogWarning("Unable to compare field - type is null"); return TaskStatus.Failure; } var component = GetDefaultGameObject(targetGameObject.Value).GetComponent(type); if (component == null) { Debug.LogWarning("Unable to compare the field with component " + componentName.Value); return TaskStatus.Failure; } // If you are receiving a compiler error on the Windows Store platform see this topic: // https://www.opsive.com/support/documentation/behavior-designer/installation/ var field = component.GetType().GetField(fieldName.Value); var fieldValue = field.GetValue(component); if (fieldValue == null && compareValue.GetValue() == null) { return TaskStatus.Success; } return fieldValue.Equals(compareValue.GetValue()) ? TaskStatus.Success : TaskStatus.Failure; } public override void OnReset() { targetGameObject = null; componentName = null; fieldName = null; compareValue = null; } } }
39
118
0.600855
[ "MIT" ]
654306663/UnityExtensions
Tools/Behavior Designer/Runtime/Tasks/Conditionals/Reflection/CompareFieldValue.cs
2,340
C#
/* swfOP is an open source library for manipulation and examination of Macromedia Flash (SWF) ActionScript bytecode. Copyright (C) 2004 Florian Krüsch. see Licence.cs for LGPL full text! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace SwfOp.ByteCode.Actions { /// <summary> /// bytecode instruction object /// </summary> public class ActionThrow : BaseAction { /// <summary> /// constructor /// </summary> public ActionThrow():base(ActionCode.Throw) { } /// <see cref="SwfOp.ByteCode.Actions.BaseAction.PopCount"/> public override int PopCount { get { return 1; } } /// <see cref="SwfOp.ByteCode.Actions.BaseAction.PushCount"/> public override int PushCount { get { return 0; } } /// <summary>overriden ToString method</summary> public override string ToString() { return "throw"; } } }
34.686275
78
0.624647
[ "MIT" ]
Acidburn0zzz/flashdevelop
External/Tools/SwfOp/ByteCode/Actions/ActionThrow.cs
1,722
C#
using System; using Miningcore.Contracts; using Miningcore.Native; namespace Miningcore.Crypto.Hashing.Algorithms { public unsafe class Blake : IHashAlgorithm { public void Digest(ReadOnlySpan<byte> data, Span<byte> result, params object[] extra) { Contract.Requires<ArgumentException>(result.Length >= 32, $"{nameof(result)} must be greater or equal 32 bytes"); fixed (byte* input = data) { fixed (byte* output = result) { LibMultihash.blake(input, output, (uint) data.Length); } } } } }
27.956522
125
0.572317
[ "MIT" ]
4AlexG/miningcore
src/Miningcore/Crypto/Hashing/Algorithms/Blake.cs
643
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; namespace System.Runtime.CompilerServices { /// <summary>Represents a builder for asynchronous methods that returns a <see cref="ValueTask{TResult}"/>.</summary> /// <typeparam name="TResult">The type of the result.</typeparam> [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder<TResult> { /// <summary>The <see cref="AsyncTaskMethodBuilder{TResult}"/> to which most operations are delegated.</summary> private AsyncTaskMethodBuilder<TResult> _methodBuilder; // mutable struct; do not make it readonly /// <summary>The result for this builder, if it's completed before any awaits occur.</summary> private TResult _result; /// <summary>true if <see cref="_result"/> contains the synchronous result for the async method; otherwise, false.</summary> private bool _haveResult; /// <summary>true if the builder should be used for setting/getting the result; otherwise, false.</summary> private bool _useBuilder; /// <summary>Creates an instance of the <see cref="AsyncValueTaskMethodBuilder{TResult}"/> struct.</summary> /// <returns>The initialized instance.</returns> public static AsyncValueTaskMethodBuilder<TResult> Create() => #if CORERT // corert's AsyncTaskMethodBuilder<TResult>.Create() currently does additional debugger-related // work, so we need to delegate to it. new AsyncValueTaskMethodBuilder<TResult>() { _methodBuilder = AsyncTaskMethodBuilder<TResult>.Create() }; #else // _methodBuilder should be initialized to AsyncTaskMethodBuilder<TResult>.Create(), but on coreclr // that Create() is a nop, so we can just return the default here. default(AsyncValueTaskMethodBuilder<TResult>); #endif /// <summary>Begins running the builder with the associated state machine.</summary> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="stateMachine">The state machine instance, passed by reference.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine => // will provide the right ExecutionContext semantics #if netstandard _methodBuilder.Start(ref stateMachine); #else AsyncMethodBuilderCore.Start(ref stateMachine); #endif /// <summary>Associates the builder with the specified state machine.</summary> /// <param name="stateMachine">The state machine instance to associate with the builder.</param> public void SetStateMachine(IAsyncStateMachine stateMachine) => _methodBuilder.SetStateMachine(stateMachine); /// <summary>Marks the task as successfully completed.</summary> /// <param name="result">The result to use to complete the task.</param> public void SetResult(TResult result) { if (_useBuilder) { _methodBuilder.SetResult(result); } else { _result = result; _haveResult = true; } } /// <summary>Marks the task as failed and binds the specified exception to the task.</summary> /// <param name="exception">The exception to bind to the task.</param> public void SetException(Exception exception) => _methodBuilder.SetException(exception); /// <summary>Gets the task for this builder.</summary> public ValueTask<TResult> Task { get { if (_haveResult) { return new ValueTask<TResult>(_result); } else { _useBuilder = true; return new ValueTask<TResult>(_methodBuilder.Task); } } } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine); } /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary> /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam> /// <typeparam name="TStateMachine">The type of the state machine.</typeparam> /// <param name="awaiter">the awaiter</param> /// <param name="stateMachine">The state machine.</param> [SecuritySafeCritical] public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _useBuilder = true; _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } } }
49.457627
132
0.656957
[ "MIT" ]
davidfowl/coreclr
src/mscorlib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
5,836
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.Npp.V20190823.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class GetVirtualNumRequest : AbstractModel { /// <summary> /// 业务appid /// </summary> [JsonProperty("BizAppId")] public string BizAppId{ get; set; } /// <summary> /// 被叫号码(号码前加 0086,如 008613631686024) /// </summary> [JsonProperty("Dst")] public string Dst{ get; set; } /// <summary> /// 主叫号码(号码前加 0086,如 008613631686024),xb 模式下是不用填写,axb 模式下是必选 /// </summary> [JsonProperty("Src")] public string Src{ get; set; } /// <summary> /// {“accreditList”:[“008613631686024”,”008612345678910”]},主要用于 N-1 场景,号码绑定非共享是独占型,指定了 dst 独占中间号绑定,accreditList 表示这个列表成员可以拨打 dst 绑 定的中间号,默认值为空,表示所有号码都可以拨打独占型中间号绑定,最大集合不允许超过 30 个,仅适用于xb模式 /// </summary> [JsonProperty("AccreditList")] public string[] AccreditList{ get; set; } /// <summary> /// 指定中间号(格式:008617013541251),如果该中间号已被使用则返回绑定失败。如果不带该字段则由腾讯侧从号码池里自动分配 /// </summary> [JsonProperty("AssignVirtualNum")] public string AssignVirtualNum{ get; set; } /// <summary> /// 是否录音,0表示不录音,1表示录音。默认为不录音,注意如果需要录音回调,通话完成后需要等待一段时间,收到录音回调之后,再解绑中间号。 /// </summary> [JsonProperty("Record")] public string Record{ get; set; } /// <summary> /// 主被叫显号号码归属地,指定该参数说明显号归属该城市,如果没有该城市号码会随机选取一个城市或者后台配置返回107,返回码详见 《腾讯-中间号-城市id.xlsx》 /// </summary> [JsonProperty("CityId")] public string CityId{ get; set; } /// <summary> /// 应用二级业务 ID,bizId 需保证在该 appId 下全局唯一,最大长度不超过 16 个字节。 /// </summary> [JsonProperty("BizId")] public string BizId{ get; set; } /// <summary> /// 号码最大绑定时间,不填默认为 24 小时,最长绑定时间是168小时,单位秒 /// </summary> [JsonProperty("MaxAssignTime")] public string MaxAssignTime{ get; set; } /// <summary> /// 主叫发起呼叫状态:1 /// 被叫发起呼叫状态:256 /// 主叫响铃状态:2 /// 被叫响铃状态:512 /// 主叫接听状态:4 /// 被叫接听状态:1024 /// 主叫拒绝接听状态:8 /// 被叫拒绝接听状态:2048 /// 主叫正常挂机状态:16 /// 被叫正常挂机状态:4096 /// 主叫呼叫异常:32 /// 被叫呼叫异常:8192 /// /// 例如: /// 值为 0:表示所有状态不需要推送 /// 值为 4:表示只要推送主叫接听状态 /// 值为 16191:表示所有状态都需要推送(上面所有值和) /// </summary> [JsonProperty("StatusFlag")] public string StatusFlag{ get; set; } /// <summary> /// 请填写statusFlag并设置值,状态回调通知地址,正式环境可以配置默认推送地址 /// </summary> [JsonProperty("StatusUrl")] public string StatusUrl{ get; set; } /// <summary> /// 话单回调通知地址,正式环境可以配置默认推送地址 /// </summary> [JsonProperty("HangupUrl")] public string HangupUrl{ get; set; } /// <summary> /// 录单 URL 回调通知地址,正式环境可以配置默认推送地址 /// </summary> [JsonProperty("RecordUrl")] public string RecordUrl{ 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 + "BizAppId", this.BizAppId); this.SetParamSimple(map, prefix + "Dst", this.Dst); this.SetParamSimple(map, prefix + "Src", this.Src); this.SetParamArraySimple(map, prefix + "AccreditList.", this.AccreditList); this.SetParamSimple(map, prefix + "AssignVirtualNum", this.AssignVirtualNum); this.SetParamSimple(map, prefix + "Record", this.Record); this.SetParamSimple(map, prefix + "CityId", this.CityId); this.SetParamSimple(map, prefix + "BizId", this.BizId); this.SetParamSimple(map, prefix + "MaxAssignTime", this.MaxAssignTime); this.SetParamSimple(map, prefix + "StatusFlag", this.StatusFlag); this.SetParamSimple(map, prefix + "StatusUrl", this.StatusUrl); this.SetParamSimple(map, prefix + "HangupUrl", this.HangupUrl); this.SetParamSimple(map, prefix + "RecordUrl", this.RecordUrl); } } }
34.173611
194
0.589311
[ "Apache-2.0" ]
ImEdisonJiang/tencentcloud-sdk-dotnet
TencentCloud/Npp/V20190823/Models/GetVirtualNumRequest.cs
6,129
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("MediatorDesignPattern")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("MediatorDesignPattern")] [assembly: System.Reflection.AssemblyTitleAttribute("MediatorDesignPattern")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generado por la clase WriteCodeFragment de MSBuild.
43.916667
95
0.666983
[ "Apache-2.0" ]
choquejhoselin/ABC
trabajo 9/MediatorDesignPattern/obj/Debug/netcoreapp2.0/MediatorDesignPattern.AssemblyInfo.cs
1,059
C#
using Blish_HUD.Controls; using Blish_HUD.Input; using Snaid1.Blishpad.Controls; using Snaid1.Blishpad.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Snaid1.Blishpad.Types { public class NotesFile { private string filename; private string contents; private MenuItem menuItem; private NotesMultilineTextBox ContentTarget; public string FileName { get => filename; set { filename = FileHelper.SanitizeFileName( value ); } } public string Title { get { return FileHelper.StripExtension(filename); } } public string Contents { get { return contents; } set { contents = value; } } public MenuItem MenuItem { get { return menuItem; } } public NotesFile(string fname, NotesMultilineTextBox contentTarget) { this.FileName = fname; this.ContentTarget = contentTarget; this.contents = readFile(); BuildMenuItem(); if(contentTarget != null) { menuItem.Click += HandleItemSelected; } } public NotesFile(NotesFile nf) { this.FileName = nf.filename; this.Contents = nf.contents; this.menuItem = new MenuItem(nf.Title); this.ContentTarget = nf.ContentTarget; if (this.ContentTarget != null) { menuItem.Click += HandleItemSelected; } } public void HandleItemSelected(object sender, MouseEventArgs e) { ContentTarget.NoteFile = this; } private MenuItem BuildMenuItem() { menuItem = new MenuItem(Title); return menuItem; } public String readFile() { return FileHelper.ReadFile(FileName); } public void saveFile() { FileHelper.WriteFile(this.FileName, this.Contents); } public NotesFile clone() { return new NotesFile(this.filename, null) { contents = this.contents, menuItem = new MenuItem(this.Title) }; } public void DeleteFile() { FileHelper.DeleteFile(this.FileName); this.Unload(); } public void Unload() { this.MenuItem.Dispose(); } } }
25.888889
86
0.546235
[ "MIT" ]
Snaid1/BHUD-Blishpad
Types/NotesFile.cs
2,565
C#
// T4 code generation is enabled for model 'D:\Projects\Databases-Homeworks\11. Entity Framework\Entity-Framework-Homework\Task08-InheritClass\NorthwindEntities.edmx'. // To enable legacy code generation, change the value of the 'Code Generation Strategy' designer // property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model // is open in the designer. // If no context and entity classes have been generated, it may be because you created an empty model but // have not yet chosen which version of Entity Framework to use. To generate a context class and entity // classes for your model, open the model in the designer, right-click on the designer surface, and // select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation // Item...'.
82.6
169
0.773608
[ "MIT" ]
atanas-georgiev/TelerikAcademy
11.Databases/Homeworks/11. Entity Framework/Entity-Framework-Homework/Task08-InheritClass/NorthwindEntities.Designer.cs
828
C#
 namespace ModelGraph.Core { public class Property_ComputeX_Separator : PropertyOf<ComputeX, string> { internal override IdKey IdKey => IdKey.ComputeXSeparatorProperty; internal Property_ComputeX_Separator(PropertyRoot owner) { Owner = owner; Value = new StringValue(this); owner.Add(this); } internal override string GetValue(Item item) => Cast(item).Separator; internal override void SetValue(Item item, string val) => Cast(item).Separator = val; } }
27.65
93
0.647378
[ "MIT" ]
davetz/ModelGraph2
ModelGraph/ModelGraph.Core/Property/Property_ComputeX_Separator.cs
555
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.Cme.V20191029.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class VideoEncodingPresetAudioSetting : AbstractModel { /// <summary> /// 音频流的编码格式,可选值: /// AAC:AAC 编码。 /// /// 默认值:AAC。 /// </summary> [JsonProperty("Codec")] public string Codec{ get; set; } /// <summary> /// 音频码率,单位:bps。 /// 默认值:64K。 /// </summary> [JsonProperty("Bitrate")] public ulong? Bitrate{ get; set; } /// <summary> /// 音频声道数,可选值: /// <li>1:单声道;</li> /// <li>2:双声道。</li> /// 默认值:2。 /// </summary> [JsonProperty("Channels")] public ulong? Channels{ get; set; } /// <summary> /// 音频流的采样率,仅支持 16000; 32000; 44100; 48000。单位:Hz。 /// 默认值:16000。 /// </summary> [JsonProperty("SampleRate")] public ulong? SampleRate{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Codec", this.Codec); this.SetParamSimple(map, prefix + "Bitrate", this.Bitrate); this.SetParamSimple(map, prefix + "Channels", this.Channels); this.SetParamSimple(map, prefix + "SampleRate", this.SampleRate); } } }
29.876712
81
0.58276
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Cme/V20191029/Models/VideoEncodingPresetAudioSetting.cs
2,351
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Net.Cache; using System.Net.Http; using System.Net.Test.Common; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { public partial class HttpWebRequestTest : RemoteExecutorTestBase { private const string RequestBody = "This is data to POST."; private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody); private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain"); private readonly ITestOutputHelper _output; public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers; public HttpWebRequestTest(ITestOutputHelper output) { _output = output; } [Theory, MemberData(nameof(EchoServers))] public void Ctor_VerifyDefaults_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Null(request.Accept); Assert.True(request.AllowAutoRedirect); Assert.False(request.AllowReadStreamBuffering); Assert.True(request.AllowWriteStreamBuffering); Assert.Null(request.ContentType); Assert.Equal(350, request.ContinueTimeout); Assert.NotNull(request.ClientCertificates); Assert.Null(request.CookieContainer); Assert.Null(request.Credentials); Assert.False(request.HaveResponse); Assert.NotNull(request.Headers); Assert.True(request.KeepAlive); Assert.Equal(0, request.Headers.Count); Assert.Equal(HttpVersion.Version11, request.ProtocolVersion); Assert.Equal("GET", request.Method); Assert.Equal(HttpWebRequest.DefaultMaximumResponseHeadersLength, 64); Assert.NotNull(HttpWebRequest.DefaultCachePolicy); Assert.Equal(HttpWebRequest.DefaultCachePolicy.Level, RequestCacheLevel.BypassCache); Assert.Equal(PlatformDetection.IsFullFramework ? 64 : 0, HttpWebRequest.DefaultMaximumErrorResponseLength); Assert.NotNull(request.Proxy); Assert.Equal(remoteServer, request.RequestUri); Assert.True(request.SupportsCookieContainer); Assert.Equal(100000, request.Timeout); Assert.False(request.UseDefaultCredentials); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer) { string remoteServerString = remoteServer.ToString(); HttpWebRequest request = WebRequest.CreateHttp(remoteServerString); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string acceptType = "*/*"; request.Accept = acceptType; Assert.Equal(acceptType, request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = string.Empty; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = null; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = false; Assert.False(request.AllowReadStreamBuffering); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")] [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = true; Assert.True(request.AllowReadStreamBuffering); } [Theory, MemberData(nameof(EchoServers))] public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); using (WebResponse response = await request.GetResponseAsync()) using (Stream myStream = response.GetResponseStream()) using (StreamReader sr = new StreamReader(myStream)) { string strContent = sr.ReadToEnd(); long length = response.ContentLength; Assert.Equal(strContent.Length, length); } } [Theory, MemberData(nameof(EchoServers))] public void ContentLength_SetNegativeOne_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContentLength = -1); } [Theory, MemberData(nameof(EchoServers))] public void ContentLength_SetThenGetOne_Success(Uri remoteServer) { const int ContentLength = 1; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentLength = ContentLength; Assert.Equal(ContentLength, request.ContentLength); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string myContent = "application/x-www-form-urlencoded"; request.ContentType = myContent; Assert.Equal(myContent, request.ContentType); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentType = string.Empty; Assert.Null(request.ContentType); } [Fact] public async Task Headers_SetAfterRequestSubmitted_ThrowsInvalidOperationException() { await LoopbackServer.CreateServerAsync(async (server, uri) => { HttpWebRequest request = WebRequest.CreateHttp(uri); Task<WebResponse> getResponse = request.GetResponseAsync(); await LoopbackServer.ReadRequestAndSendResponseAsync(server); using (WebResponse response = await getResponse) { Assert.Throws<InvalidOperationException>(() => request.AutomaticDecompression = DecompressionMethods.Deflate); Assert.Throws<InvalidOperationException>(() => request.ContentLength = 255); Assert.Throws<InvalidOperationException>(() => request.ContinueTimeout = 255); Assert.Throws<InvalidOperationException>(() => request.Host = "localhost"); Assert.Throws<InvalidOperationException>(() => request.MaximumResponseHeadersLength = 255); Assert.Throws<InvalidOperationException>(() => request.SendChunked = true); Assert.Throws<InvalidOperationException>(() => request.Proxy = WebRequest.DefaultWebProxy); Assert.Throws<InvalidOperationException>(() => request.Headers = null); } }); } [Theory, MemberData(nameof(EchoServers))] public void MaximumResponseHeadersLength_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.MaximumResponseHeadersLength = -2); } [Theory, MemberData(nameof(EchoServers))] public void MaximumResponseHeadersLength_SetThenGetNegativeOne_Success(Uri remoteServer) { const int MaximumResponseHeaderLength = -1; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.MaximumResponseHeadersLength = MaximumResponseHeaderLength; Assert.Equal(MaximumResponseHeaderLength, request.MaximumResponseHeadersLength); } [Theory, MemberData(nameof(EchoServers))] public void MaximumAutomaticRedirections_SetZeroOrNegative_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = 0); AssertExtensions.Throws<ArgumentException>("value", () => request.MaximumAutomaticRedirections = -1); } [Theory, MemberData(nameof(EchoServers))] public void MaximumAutomaticRedirections_SetThenGetOne_Success(Uri remoteServer) { const int MaximumAutomaticRedirections = 1; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.MaximumAutomaticRedirections = MaximumAutomaticRedirections; Assert.Equal(MaximumAutomaticRedirections, request.MaximumAutomaticRedirections); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = 0; Assert.Equal(0, request.ContinueTimeout); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = -1; } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.ContinueTimeout = -2); } [Theory, MemberData(nameof(EchoServers))] public void Timeout_SetThenGetZero_ExpectZero(Uri remoteServer) { const int Timeout = 0; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Timeout = Timeout; Assert.Equal(Timeout, request.Timeout); } [Theory, MemberData(nameof(EchoServers))] public void Timeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Timeout = -1; } [Theory, MemberData(nameof(EchoServers))] public void Timeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => request.Timeout = -2); } [Theory, MemberData(nameof(EchoServers))] public void TimeOut_SetThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Timeout = 100; Assert.Equal(100, request.Timeout); request.Timeout = Threading.Timeout.Infinite; Assert.Equal(Threading.Timeout.Infinite, request.Timeout); request.Timeout = int.MaxValue; Assert.Equal(int.MaxValue, request.Timeout); } [ActiveIssue(22627)] [Fact] public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Timeout = 10; // ms. var sw = Stopwatch.StartNew(); WebException exception = Assert.Throws<WebException>(() => request.GetResponse()); sw.Stop(); Assert.InRange(sw.ElapsedMilliseconds, 1, 15 * 1000); Assert.Equal(WebExceptionStatus.Timeout, exception.Status); Assert.Equal(null, exception.InnerException); Assert.Equal(null, exception.Response); return Task.FromResult<object>(null); }); } [Theory, MemberData(nameof(EchoServers))] public void Address_CtorAddress_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.Address); } [Theory, MemberData(nameof(EchoServers))] public void UserAgent_SetThenGetWindows_ValuesMatch(Uri remoteServer) { const string UserAgent = "Windows"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UserAgent = UserAgent; Assert.Equal(UserAgent, request.UserAgent); } [Theory, MemberData(nameof(EchoServers))] public void Host_SetNullValue_ThrowsArgumentNullException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentNullException>("value", null, () => request.Host = null); } [Theory, MemberData(nameof(EchoServers))] public void Host_SetSlash_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "/localhost"); } [Theory, MemberData(nameof(EchoServers))] public void Host_SetInvalidUri_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", null, () => request.Host = "NoUri+-*"); } [Theory, MemberData(nameof(EchoServers))] public void Host_SetThenGetCustomUri_ValuesMatch(Uri remoteServer) { const string Host = "localhost"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Host = Host; Assert.Equal(Host, request.Host); } [Theory, MemberData(nameof(EchoServers))] public void Host_SetThenGetCustomUriWithPort_ValuesMatch(Uri remoteServer) { const string Host = "localhost:8080"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Host = Host; Assert.Equal(Host, request.Host); } [Theory, MemberData(nameof(EchoServers))] public void Host_GetDefaultHostSameAsAddress_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer.Host, request.Host); } [Theory] [InlineData("https://microsoft.com:8080")] public void Host_GetDefaultHostWithCustomPortSameAsAddress_ValuesMatch(string endpoint) { Uri endpointUri = new Uri(endpoint); HttpWebRequest request = WebRequest.CreateHttp(endpointUri); Assert.Equal(endpointUri.Host + ":" + endpointUri.Port, request.Host); } [Theory, MemberData(nameof(EchoServers))] public void Pipelined_SetThenGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Pipelined = true; Assert.True(request.Pipelined); request.Pipelined = false; Assert.False(request.Pipelined); } [Theory, MemberData(nameof(EchoServers))] public void Referer_SetThenGetReferer_ValuesMatch(Uri remoteServer) { const string Referer = "Referer"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Referer = Referer; Assert.Equal(Referer, request.Referer); } [Theory, MemberData(nameof(EchoServers))] public void TransferEncoding_NullOrWhiteSpace_ValuesMatch(Uri remoteServer) { const string TransferEncoding = "xml"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.SendChunked = true; request.TransferEncoding = TransferEncoding; Assert.Equal(TransferEncoding, request.TransferEncoding); request.TransferEncoding = null; Assert.Equal(null, request.TransferEncoding); } [Theory, MemberData(nameof(EchoServers))] public void TransferEncoding_SetChunked_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.TransferEncoding = "chunked"); } [Theory, MemberData(nameof(EchoServers))] public void TransferEncoding_SetWithSendChunkedFalse_ThrowsInvalidOperationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<InvalidOperationException>(() => request.TransferEncoding = "xml"); } [Theory, MemberData(nameof(EchoServers))] public void KeepAlive_SetThenGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.KeepAlive = true; Assert.True(request.KeepAlive); request.KeepAlive = false; Assert.False(request.KeepAlive); } [Theory] [InlineData(null)] [InlineData(false)] [InlineData(true)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")] public void KeepAlive_CorrectConnectionHeaderSent(bool? keepAlive) { HttpWebRequest request = WebRequest.CreateHttp(Test.Common.Configuration.Http.RemoteEchoServer); if (keepAlive.HasValue) { request.KeepAlive = keepAlive.Value; } using (var response = (HttpWebResponse)request.GetResponse()) using (var body = new StreamReader(response.GetResponseStream())) { string content = body.ReadToEnd(); if (!keepAlive.HasValue || keepAlive.Value) { // Validate that the request doesn't contain Connection: "close", but we can't validate // that it does contain Connection: "keep-alive", as that's optional as of HTTP 1.1. Assert.DoesNotContain("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase); } else { Assert.Contains("\"Connection\": \"close\"", content, StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain("\"Keep-Alive\"", content, StringComparison.OrdinalIgnoreCase); } } } [Theory, MemberData(nameof(EchoServers))] public void AutomaticDecompression_SetAndGetDeflate_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AutomaticDecompression = DecompressionMethods.Deflate; Assert.Equal(DecompressionMethods.Deflate, request.AutomaticDecompression); } [Theory, MemberData(nameof(EchoServers))] public void AllowWriteStreamBuffering_SetAndGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowWriteStreamBuffering = true; Assert.True(request.AllowWriteStreamBuffering); request.AllowWriteStreamBuffering = false; Assert.False(request.AllowWriteStreamBuffering); } [Theory, MemberData(nameof(EchoServers))] public void AllowAutoRedirect_SetAndGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowAutoRedirect = true; Assert.True(request.AllowAutoRedirect); request.AllowAutoRedirect = false; Assert.False(request.AllowAutoRedirect); } [Fact] public void ConnectionGroupName_SetAndGetGroup_ValuesMatch() { // Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior. // For app-compat reasons we allow applications to alter and read the property. HttpWebRequest request = WebRequest.CreateHttp("http://test"); Assert.Null(request.ConnectionGroupName); request.ConnectionGroupName = "Group"; Assert.Equal("Group", request.ConnectionGroupName); } [Theory, MemberData(nameof(EchoServers))] public void PreAuthenticate_SetAndGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.PreAuthenticate = true; Assert.True(request.PreAuthenticate); request.PreAuthenticate = false; Assert.False(request.PreAuthenticate); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19225")] [Theory, MemberData(nameof(EchoServers))] public void PreAuthenticate_SetAndGetBooleanResponse_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.PreAuthenticate = true; using (var response = (HttpWebResponse)request.GetResponse()) { Assert.True(request.PreAuthenticate); } } [Theory, MemberData(nameof(EchoServers))] public void Connection_NullOrWhiteSpace_ValuesMatch(Uri remoteServer) { const string Connection = "connect"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Connection = Connection; Assert.Equal(Connection, request.Connection); request.Connection = null; Assert.Equal(null, request.Connection); } [Theory, MemberData(nameof(EchoServers))] public void Connection_SetKeepAliveAndClose_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "keep-alive"); AssertExtensions.Throws<ArgumentException>("value", () => request.Connection = "close"); } [Theory, MemberData(nameof(EchoServers))] public void Expect_SetNullOrWhiteSpace_ValuesMatch(Uri remoteServer) { const string Expect = "101-go"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Expect = Expect; Assert.Equal(Expect, request.Expect); request.Expect = null; Assert.Equal(null, request.Expect); } [Theory, MemberData(nameof(EchoServers))] public void Expect_Set100Continue_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.Expect = "100-continue"); } [Fact] public void DefaultMaximumResponseHeadersLength_SetAndGetLength_ValuesMatch() { RemoteInvoke(() => { int defaultMaximumResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength; const int NewDefaultMaximumResponseHeadersLength = 255; try { HttpWebRequest.DefaultMaximumResponseHeadersLength = NewDefaultMaximumResponseHeadersLength; Assert.Equal(NewDefaultMaximumResponseHeadersLength, HttpWebRequest.DefaultMaximumResponseHeadersLength); } finally { HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength; } return SuccessExitCode; }).Dispose(); } [Fact] public void DefaultMaximumErrorResponseLength_SetAndGetLength_ValuesMatch() { RemoteInvoke(() => { int defaultMaximumErrorsResponseLength = HttpWebRequest.DefaultMaximumErrorResponseLength; const int NewDefaultMaximumErrorsResponseLength = 255; try { HttpWebRequest.DefaultMaximumErrorResponseLength = NewDefaultMaximumErrorsResponseLength; Assert.Equal(NewDefaultMaximumErrorsResponseLength, HttpWebRequest.DefaultMaximumErrorResponseLength); } finally { HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength; } return SuccessExitCode; }).Dispose(); } [Fact] public void DefaultCachePolicy_SetAndGetPolicyReload_ValuesMatch() { RemoteInvoke(() => { RequestCachePolicy requestCachePolicy = HttpWebRequest.DefaultCachePolicy; try { RequestCachePolicy newRequestCachePolicy = new RequestCachePolicy(RequestCacheLevel.Reload); HttpWebRequest.DefaultCachePolicy = newRequestCachePolicy; Assert.Equal(newRequestCachePolicy.Level, HttpWebRequest.DefaultCachePolicy.Level); } finally { HttpWebRequest.DefaultCachePolicy = requestCachePolicy; } return SuccessExitCode; }).Dispose(); } [Theory, MemberData(nameof(EchoServers))] public void IfModifiedSince_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); DateTime newIfModifiedSince = new DateTime(2000, 1, 1); request.IfModifiedSince = newIfModifiedSince; Assert.Equal(newIfModifiedSince, request.IfModifiedSince); DateTime ifModifiedSince = DateTime.MinValue; request.IfModifiedSince = ifModifiedSince; Assert.Equal(ifModifiedSince, request.IfModifiedSince); } [Theory, MemberData(nameof(EchoServers))] public void Date_SetMinDateAfterValidDate_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); DateTime newDate = new DateTime(2000, 1, 1); request.Date = newDate; Assert.Equal(newDate, request.Date); DateTime date = DateTime.MinValue; request.Date = date; Assert.Equal(date, request.Date); } [Theory, MemberData(nameof(EchoServers))] public void SendChunked_SetAndGetBoolean_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.SendChunked = true; Assert.True(request.SendChunked); request.SendChunked = false; Assert.False(request.SendChunked); } [Theory, MemberData(nameof(EchoServers))] public void ContinueDelegate_SetNullDelegate_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueDelegate = null; } [Theory, MemberData(nameof(EchoServers))] public void ContinueDelegate_SetDelegateThenGet_ValuesSame(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); HttpContinueDelegate continueDelegate = new HttpContinueDelegate((a, b) => { }); request.ContinueDelegate = continueDelegate; Assert.Same(continueDelegate, request.ContinueDelegate); } [Theory, MemberData(nameof(EchoServers))] public void ServicePoint_GetValue_ExpectedResult(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); if (PlatformDetection.IsFullFramework) { Assert.NotNull(request.ServicePoint); } else { Assert.Throws<PlatformNotSupportedException>(() => request.ServicePoint); } } [Theory, MemberData(nameof(EchoServers))] public void ServerCertificateValidationCallback_SetCallbackThenGet_ValuesSame(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); var serverCertificateVallidationCallback = new Security.RemoteCertificateValidationCallback((a, b, c, d) => true); request.ServerCertificateValidationCallback = serverCertificateVallidationCallback; Assert.Same(serverCertificateVallidationCallback, request.ServerCertificateValidationCallback); } [Theory, MemberData(nameof(EchoServers))] public void ClientCertificates_SetNullX509_ThrowsArgumentNullException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentNullException>("value", () => request.ClientCertificates = null); } [Theory, MemberData(nameof(EchoServers))] public void ClientCertificates_SetThenGetX509_ValuesSame(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); var certificateCollection = new System.Security.Cryptography.X509Certificates.X509CertificateCollection(); request.ClientCertificates = certificateCollection; Assert.Same(certificateCollection, request.ClientCertificates); } [Theory, MemberData(nameof(EchoServers))] public void ProtocolVersion_SetInvalidHttpVersion_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.ProtocolVersion = new Version()); } [Theory, MemberData(nameof(EchoServers))] public void ProtocolVersion_SetThenGetHttpVersions_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ProtocolVersion = HttpVersion.Version10; Assert.Equal(HttpVersion.Version10, request.ProtocolVersion); request.ProtocolVersion = HttpVersion.Version11; Assert.Equal(HttpVersion.Version11, request.ProtocolVersion); } [Fact] public void ReadWriteTimeout_SetThenGet_ValuesMatch() { // Note: In CoreFX changing this value will not have any effect on HTTP stack's behavior. // For app-compat reasons we allow applications to alter and read the property. HttpWebRequest request = WebRequest.CreateHttp("http://test"); request.ReadWriteTimeout = 5; Assert.Equal(5, request.ReadWriteTimeout); } [Fact] public void ReadWriteTimeout_InfiniteValue_Ok() { HttpWebRequest request = WebRequest.CreateHttp("http://test"); request.ReadWriteTimeout = Timeout.Infinite; } [Fact] public void ReadWriteTimeout_NegativeOrZeroValue_Fail() { HttpWebRequest request = WebRequest.CreateHttp("http://test"); Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = 0; }); Assert.Throws<ArgumentOutOfRangeException>(() => { request.ReadWriteTimeout = -10; }); } [Theory, MemberData(nameof(EchoServers))] public void CookieContainer_SetThenGetContainer_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.CookieContainer = null; var cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; Assert.Same(cookieContainer, request.CookieContainer); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; Assert.Equal(_explicitCredential, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = true; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = false; Assert.Equal(null, request.Credentials); } [OuterLoop] [Theory] [MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetGetResponse_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; WebResponse response = request.GetResponse(); response.Dispose(); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Head.Method; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = "CONNECT"; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")] public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = "POST"; IAsyncResult asyncResult = request.BeginGetRequestStream(null, null); Assert.Throws<InvalidOperationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = request.BeginGetResponse(null, null); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } public async Task BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); IAsyncResult asyncResult = request.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => request.BeginGetResponse(null, null)); return Task.FromResult<object>(null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); AssertExtensions.Throws<ArgumentException>(null, () => new StreamReader(requestStream)); } }); } public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { Assert.NotNull(requestStream); } }); } public async Task GetResponseAsync_GetResponseStream_ExpectNotNull() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); using (WebResponse response = await request.GetResponseAsync()) { Assert.NotNull(response.GetResponseStream()); } }); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; using (WebResponse response = await request.GetResponseAsync()) using (Stream myStream = response.GetResponseStream()) { Assert.NotNull(myStream); using (var sr = new StreamReader(myStream)) { string strContent = sr.ReadToEnd(); Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\"")); } } } [OuterLoop] [Theory, MemberData(nameof(EchoServers))] public void CookieContainer_Count_Add(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); DateTime now = DateTime.UtcNow; request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(remoteServer, new Cookie("1", "cookie1")); request.CookieContainer.Add(remoteServer, new Cookie("2", "cookie2")); Assert.True(request.SupportsCookieContainer); Assert.Equal(request.CookieContainer.GetCookies(remoteServer).Count, 2); } [Theory, MemberData(nameof(EchoServers))] public void Range_Add_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AddRange(1, 5); Assert.Equal(request.Headers["Range"], "bytes=1-5"); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } using (WebResponse response = await request.GetResponseAsync()) using (Stream myStream = response.GetResponseStream()) using (var sr = new StreamReader(myStream)) { string strContent = sr.ReadToEnd(); Assert.True(strContent.Contains(RequestBody)); } } [Theory] [MemberData(nameof(EchoServers))] public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; var response = await request.GetResponseAsync(); response.Dispose(); } [OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses [Fact] public async Task GetResponseAsync_ServerNameNotInDns_ThrowsWebException() { string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString()); HttpWebRequest request = WebRequest.CreateHttp(serverUrl); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status); } public static object[][] StatusCodeServers = { new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) }, new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) }, }; [Theory, MemberData(nameof(StatusCodeServers))] public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status); } [Theory, MemberData(nameof(EchoServers))] public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); using (WebResponse response = await request.GetResponseAsync()) { Assert.True(request.HaveResponse); } } [Theory] [MemberData(nameof(EchoServers))] public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) { string headersString = response.Headers.ToString(); string headersPartialContent = "Content-Type: application/json"; Assert.True(headersString.Contains(headersPartialContent)); } } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; Assert.Equal(HttpMethod.Get.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Assert.Equal(HttpMethod.Post.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetInvalidString_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); AssertExtensions.Throws<ArgumentException>("value", () => request.Method = null); AssertExtensions.Throws<ArgumentException>("value", () => request.Method = string.Empty); AssertExtensions.Throws<ArgumentException>("value", () => request.Method = "Method(2"); } [Theory, MemberData(nameof(EchoServers))] public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request.Proxy); } [Theory, MemberData(nameof(EchoServers))] public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.RequestUri); } [Theory, MemberData(nameof(EchoServers))] public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); using (WebResponse response = await request.GetResponseAsync()) { Assert.Equal(remoteServer, response.ResponseUri); } } [Theory, MemberData(nameof(EchoServers))] public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.True(request.SupportsCookieContainer); } [Theory, MemberData(nameof(EchoServers))] public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream responseStream = response.GetResponseStream()) using (var sr = new StreamReader(responseStream)) { string responseBody = sr.ReadToEnd(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [Theory, MemberData(nameof(EchoServers))] public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream responseStream = response.GetResponseStream()) using (var sr = new StreamReader(responseStream)) { string responseBody = sr.ReadToEnd(); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [Theory, MemberData(nameof(EchoServers))] public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer) { const string ContentType = "text/plain; charset=utf-8"; HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.ContentType = ContentType; using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) using (Stream responseStream = response.GetResponseStream()) using (var sr = new StreamReader(responseStream)) { string responseBody = sr.ReadToEnd(); _output.WriteLine(responseBody); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(responseBody.Contains($"\"Content-Type\": \"{ContentType}\"")); } } [Theory, MemberData(nameof(EchoServers))] public void MediaType_SetThenGet_ValuesMatch(Uri remoteServer) { const string MediaType = "text/plain"; HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.MediaType = MediaType; Assert.Equal(MediaType, request.MediaType); } public async Task HttpWebRequest_EndGetRequestStreamContext_ExpectedValue() { await LoopbackServer.CreateServerAsync((server, url) => { System.Net.TransportContext context; HttpWebRequest request = HttpWebRequest.CreateHttp(url); request.Method = "POST"; using (request.EndGetRequestStream(request.BeginGetRequestStream(null, null), out context)) { if (PlatformDetection.IsFullFramework) { Assert.NotNull(context); } else { Assert.Null(context); } } return Task.FromResult<object>(null); }); } [ActiveIssue(19083)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #19083")] [Fact] public async Task Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.Method = "POST"; RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state); request.Abort(); Assert.Equal(1, state.RequestStreamCallbackCallCount); WebException wex = state.SavedRequestStreamException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); return Task.FromResult<object>(null); }); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")] [Fact] public async Task Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(ResponseCallback), state); request.Abort(); Assert.Equal(1, state.ResponseCallbackCallCount); return Task.FromResult<object>(null); }); } [ActiveIssue(18800)] [Fact] public async Task Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(ResponseCallback), state); request.Abort(); WebException wex = state.SavedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); return Task.FromResult<object>(null); }); } [Fact] public async Task Abort_BeginGetResponseUsingNoCallbackThenAbort_Success() { await LoopbackServer.CreateServerAsync((server, url) => { HttpWebRequest request = WebRequest.CreateHttp(url); request.BeginGetResponse(null, null); request.Abort(); return Task.FromResult<object>(null); }); } [Theory, MemberData(nameof(EchoServers))] public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Abort(); } private void RequestStreamCallback(IAsyncResult asynchronousResult) { RequestState state = (RequestState)asynchronousResult.AsyncState; state.RequestStreamCallbackCallCount++; try { HttpWebRequest request = state.Request; state.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); Stream stream = request.EndGetRequestStream(asynchronousResult); stream.Dispose(); } catch (Exception ex) { state.SavedRequestStreamException = ex; } } private void ResponseCallback(IAsyncResult asynchronousResult) { RequestState state = (RequestState)asynchronousResult.AsyncState; state.ResponseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(asynchronousResult)) { state.SavedResponseHeaders = response.Headers; } } catch (Exception ex) { state.SavedResponseException = ex; } } [Fact] public void HttpWebRequest_Serialize_Fails() { using (MemoryStream fs = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); var hwr = HttpWebRequest.CreateHttp("http://localhost"); // .NET Framework throws // System.Runtime.Serialization.SerializationException: // Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0. // 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable. // While .NET Core throws // System.Runtime.Serialization.SerializationException: // Type 'System.Net.HttpWebRequest' in Assembly 'System.Net.Requests, Version=4.0.0. // 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable. Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr)); } } } public class RequestState { public HttpWebRequest Request; public HttpWebResponse Response; public WebHeaderCollection SavedResponseHeaders; public int RequestStreamCallbackCallCount; public int ResponseCallbackCallCount; public Exception SavedRequestStreamException; public Exception SavedResponseException; } }
43.375646
131
0.639398
[ "MIT" ]
AlexGhiondea/corefx
src/System.Net.Requests/tests/HttpWebRequestTest.cs
58,774
C#
using Ivvy.API.Json; using Newtonsoft.Json; namespace Ivvy.API.Crm { /// <summary> /// An iVvy CRM lead source. /// </summary> public class LeadSource : ISerializable { [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("cost")] public float Cost { get; set; } [JsonProperty("isReferral")] public bool IsReferral { get; set; } [JsonProperty("defaultType")] public int? DefaultType { get; set; } } }
18.765957
80
0.478458
[ "MIT" ]
ivvycode/ivvy-sdk-net
src/Crm/LeadSource.cs
882
C#
using Abp.AutoMapper; using Abp.Modules; using Abp.Reflection.Extensions; using <%= projectName %>.Authorization; namespace <%= projectName %> { [DependsOn( typeof(<%= projectName %>CoreModule), typeof(AbpAutoMapperModule))] public class <%= projectName %>ApplicationModule : AbpModule { public override void PreInitialize() { Configuration.Authorization.Providers.Add<<%= projectName %>AuthorizationProvider>(); } public override void Initialize() { var thisAssembly = typeof(<%= projectName %>ApplicationModule).GetAssembly(); IocManager.RegisterAssemblyByConvention(thisAssembly); Configuration.Modules.AbpAutoMapper().Configurators.Add( // Scan the assembly for classes which inherit from AutoMapper.Profile cfg => cfg.AddProfiles(thisAssembly) ); } } }
30.193548
97
0.634615
[ "MIT" ]
ronymaychan/Pln371
generators/generator-pln/generators/app/templates/aspnet-core/src/Plenumsoft.Application/PlenumsoftApplicationModule.cs
938
C#
using System; using Android.App; using Android.Runtime; namespace Iconize.Sample.Droid { [Application(Label = "Iconize", Theme = "@style/AppTheme")] public class MainApplication : Application { public MainApplication(IntPtr handle, JniHandleOwnership transer) : base(handle, transer) { // Intentionally left blank } public override void OnCreate() { base.OnCreate(); Plugin.Iconize.Iconize.With(new Plugin.Iconize.Fonts.EntypoPlusModule()) .With(new Plugin.Iconize.Fonts.FontAwesomeModule()) .With(new Plugin.Iconize.Fonts.IoniconsModule()) .With(new Plugin.Iconize.Fonts.MaterialModule()) .With(new Plugin.Iconize.Fonts.MeteoconsModule()) .With(new Plugin.Iconize.Fonts.SimpleLineIconsModule()) .With(new Plugin.Iconize.Fonts.TypiconsModule()) .With(new Plugin.Iconize.Fonts.WeatherIconsModule()); } } }
38.5
89
0.548918
[ "MIT" ]
Ali-YousefiTelori/Xamarin.Plugins
Iconize/Samples/Iconize.Sample.Droid/MainApplication.cs
1,155
C#
namespace Orderio.Domain.Models { public class UserRole : BaseModel<int> { public int UserId { get; set; } public User User { get; set; } public int RoleId { get; set; } public Role Role { get; set; } } }
24.9
42
0.566265
[ "MIT" ]
Yaroslav08/Orderio
Orderio/Orderio.Domain/Models/UserRole.cs
251
C#