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 GrpcCodeFirstServer; using ProtoBuf.Grpc.Server; var builder = WebApplication.CreateBuilder(args); builder.Services.AddCodeFirstGrpc(); var app = builder.Build(); app.UseRouting(); app.UseEndpoints(enpoints => { enpoints.MapGrpcService<GreeterService>(); }); app.Run();
20.142857
49
0.762411
[ "MIT" ]
yuriy-mythical/GrpcCodefirstPlayground
GrpcCodeFirstServer/Program.cs
282
C#
using System; using Intersoft.Crosslight; using PropertyCross_Intersoft.ViewModels; using System.Reflection; namespace PropertyCross_Intersoft.Core { public class FavouriteListBindingProvider : BindingProvider { public FavouriteListBindingProvider() { ItemBindingDescription itemBinding = new ItemBindingDescription() { DisplayMemberPath = "PriceFormatted2", DetailMemberPath = "Title", ImageMemberPath = "ThumbUrl", ImagePlaceholder = "item_placeholder.png" }; this.AddBinding("TableView", BindableProperties.ItemsSourceProperty, "Items"); this.AddBinding("TableView", BindableProperties.ItemTemplateBindingProperty, itemBinding, true); this.AddBinding("TableView", BindableProperties.SelectedItemProperty, "SelectedItem", BindingMode.TwoWay); this.AddBinding("TableView", BindableProperties.DetailNavigationTargetProperty, new NavigationTarget(typeof(PropertyDetailViewModel)), true); this.AddBinding("TableView", BindableProperties.SelectedItemsProperty, "SelectedItems", BindingMode.TwoWay); this.AddBinding("DeleteButton", BindableProperties.CommandProperty, "DeleteCommand"); this.AddBinding("DeleteButton", BindableProperties.CommandParameterProperty, "SelectedItem"); this.AddBinding("TableView", BindableProperties.DeleteItemCommandProperty, "DeleteCommand", BindingMode.TwoWay); } } }
49.354839
153
0.711111
[ "MIT" ]
ColinEberhardt/PropertyCross
crosslight/PropertyCross_Intersoft.Core/BindingProviders/FavouriteListBindingProvider.cs
1,532
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. #nullable enable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using WFD = Windows.Foundation.Diagnostics; namespace System.Threading.Tasks { internal static class AsyncCausalityTracer { internal static void EnableToETW(bool enabled) { if (enabled) f_LoggingOn |= Loggers.ETW; else f_LoggingOn &= ~Loggers.ETW; } internal static bool LoggingOn { get { return f_LoggingOn != 0; } } //s_PlatformId = {4B0171A6-F3D0-41A0-9B33-02550652B995} private static readonly Guid s_PlatformId = new Guid(0x4B0171A6, 0xF3D0, 0x41A0, 0x9B, 0x33, 0x02, 0x55, 0x06, 0x52, 0xB9, 0x95); //Indicates this information comes from the BCL Library private const WFD.CausalitySource s_CausalitySource = WFD.CausalitySource.Library; //Lazy initialize the actual factory private static WFD.IAsyncCausalityTracerStatics s_TracerFactory; // The loggers that this Tracer knows about. [Flags] private enum Loggers : byte { CausalityTracer = 1, ETW = 2 } //We receive the actual value for these as a callback private static Loggers f_LoggingOn; //assumes false by default // The precise static constructor will run first time somebody attempts to access this class static AsyncCausalityTracer() { if (!Environment.IsWinRTSupported) return; //COM Class Id string ClassId = "Windows.Foundation.Diagnostics.AsyncCausalityTracer"; //COM Interface GUID {50850B26-267E-451B-A890-AB6A370245EE} Guid guid = new Guid(0x50850B26, 0x267E, 0x451B, 0xA8, 0x90, 0XAB, 0x6A, 0x37, 0x02, 0x45, 0xEE); object? factory = null; try { int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory); if (hresult < 0 || factory == null) return; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered. s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory; EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler)); Debug.Assert(token != default, "EventRegistrationToken is null"); } catch (Exception ex) { // Although catching generic Exception is not recommended, this file is one exception // since we don't want to propagate any kind of exception to the user since all we are // doing here depends on internal state. LogAndDisable(ex); } } private static void TracingStatusChangedHandler(object sender, WFD.TracingStatusChangedEventArgs args) { if (args.Enabled) f_LoggingOn |= Loggers.CausalityTracer; else f_LoggingOn &= ~Loggers.CausalityTracer; } // // The TraceXXX methods should be called only if LoggingOn property returned true // [MethodImplAttribute(MethodImplOptions.NoInlining)] // Tracking is slow path. Disable inlining for it. internal static void TraceOperationCreation(Task task, string operationName) { try { int taskId = task.Id; if ((f_LoggingOn & Loggers.ETW) != 0) TplEventSource.Log.TraceOperationBegin(taskId, operationName, RelatedContext: 0); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationCreation(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext: 0); } catch (Exception ex) { //view function comment LogAndDisable(ex); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static void TraceOperationCompletion(Task task, AsyncCausalityStatus status) { try { int taskId = task.Id; if ((f_LoggingOn & Loggers.ETW) != 0) TplEventSource.Log.TraceOperationEnd(taskId, status); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationCompletion(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status); } catch (Exception ex) { //view function comment LogAndDisable(ex); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static void TraceOperationRelation(Task task, CausalityRelation relation) { try { int taskId = task.Id; if ((f_LoggingOn & Loggers.ETW) != 0) TplEventSource.Log.TraceOperationRelation(taskId, relation); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceOperationRelation(WFD.CausalityTraceLevel.Important, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation); } catch (Exception ex) { //view function comment LogAndDisable(ex); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static void TraceSynchronousWorkStart(Task task, CausalitySynchronousWork work) { try { int taskId = task.Id; if ((f_LoggingOn & Loggers.ETW) != 0) TplEventSource.Log.TraceSynchronousWorkBegin(taskId, work); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceSynchronousWorkStart(WFD.CausalityTraceLevel.Required, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work); } catch (Exception ex) { //view function comment LogAndDisable(ex); } } [MethodImplAttribute(MethodImplOptions.NoInlining)] internal static void TraceSynchronousWorkCompletion(CausalitySynchronousWork work) { try { if ((f_LoggingOn & Loggers.ETW) != 0) TplEventSource.Log.TraceSynchronousWorkEnd(work); if ((f_LoggingOn & Loggers.CausalityTracer) != 0) s_TracerFactory.TraceSynchronousWorkCompletion(WFD.CausalityTraceLevel.Required, s_CausalitySource, (WFD.CausalitySynchronousWork)work); } catch (Exception ex) { //view function comment LogAndDisable(ex); } } //fix for 796185: leaking internal exceptions to customers, //we should catch and log exceptions but never propagate them. private static void LogAndDisable(Exception ex) { f_LoggingOn = 0; Debugger.Log(0, "AsyncCausalityTracer", ex.ToString()); } private static ulong GetOperationId(uint taskId) { return (((ulong)Thread.GetDomainID()) << 32) + taskId; } } }
39.954774
195
0.60332
[ "MIT" ]
GroMaster1/coreclr
src/System.Private.CoreLib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
7,951
C#
using RegisterAssemblyTypesConsole.Interfaces; using System; namespace RegisterAssemblyTypesConsole.Implementations { class Messenger : IMessenger { public void SendMessage() { Console.WriteLine("SendMessage is working!"); } } }
21.384615
57
0.672662
[ "Apache-2.0" ]
reyou/Ggg.Autofac
apps/app-docs-demo/RegisterAssemblyTypesConsole/Implementations/Messenger.cs
280
C#
namespace CustomSecurity { partial class MainForm { private System.Windows.Forms.ToolBarButton btnViewUsers; private System.Windows.Forms.ToolBarButton btnEditUsers; private System.Windows.Forms.ImageList toolBoxIcons; private System.Windows.Forms.ToolBar toolBar; private System.Windows.Forms.ListView lstViewUsers; private System.Windows.Forms.ColumnHeader colUserName; private System.Windows.Forms.ColumnHeader colUserRole; private System.Windows.Forms.ColumnHeader colUserId; private System.ComponentModel.IContainer components; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Код, автоматически созданный конструктором форм Windows /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.toolBar = new System.Windows.Forms.ToolBar(); this.btnViewUsers = new System.Windows.Forms.ToolBarButton(); this.btnEditUsers = new System.Windows.Forms.ToolBarButton(); this.toolBoxIcons = new System.Windows.Forms.ImageList(this.components); this.lstViewUsers = new System.Windows.Forms.ListView(); this.colUserName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colUserRole = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.colUserId = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SuspendLayout(); // // toolBar // this.toolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.btnViewUsers, this.btnEditUsers}); this.toolBar.DropDownArrows = true; this.toolBar.ImageList = this.toolBoxIcons; this.toolBar.Location = new System.Drawing.Point(0, 0); this.toolBar.Name = "toolBar"; this.toolBar.ShowToolTips = true; this.toolBar.Size = new System.Drawing.Size(424, 28); this.toolBar.TabIndex = 0; this.toolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar_ButtonClick); // // btnViewUsers // this.btnViewUsers.ImageIndex = 0; this.btnViewUsers.Name = "btnViewUsers"; this.btnViewUsers.Tag = "view"; this.btnViewUsers.ToolTipText = "Вывести список пользователей"; // // btnEditUsers // this.btnEditUsers.ImageIndex = 1; this.btnEditUsers.Name = "btnEditUsers"; this.btnEditUsers.Tag = "edit"; this.btnEditUsers.ToolTipText = "Редактировать роль пользователя"; // // toolBoxIcons // this.toolBoxIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("toolBoxIcons.ImageStream"))); this.toolBoxIcons.TransparentColor = System.Drawing.Color.Transparent; this.toolBoxIcons.Images.SetKeyName(0, "1.png"); this.toolBoxIcons.Images.SetKeyName(1, "2.png"); // // lstViewUsers // this.lstViewUsers.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.colUserName, this.colUserRole, this.colUserId}); this.lstViewUsers.Cursor = System.Windows.Forms.Cursors.Hand; this.lstViewUsers.Dock = System.Windows.Forms.DockStyle.Fill; this.lstViewUsers.FullRowSelect = true; this.lstViewUsers.GridLines = true; this.lstViewUsers.Location = new System.Drawing.Point(0, 28); this.lstViewUsers.MultiSelect = false; this.lstViewUsers.Name = "lstViewUsers"; this.lstViewUsers.Size = new System.Drawing.Size(424, 238); this.lstViewUsers.SmallImageList = this.toolBoxIcons; this.lstViewUsers.TabIndex = 1; this.lstViewUsers.UseCompatibleStateImageBehavior = false; this.lstViewUsers.View = System.Windows.Forms.View.Details; // // colUserName // this.colUserName.Text = "Имя пользователя"; this.colUserName.Width = 125; // // colUserRole // this.colUserRole.Text = "Роль пользователя"; this.colUserRole.Width = 125; // // colUserId // this.colUserId.Text = "Уникальный идентификатор"; this.colUserId.Width = 175; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(424, 266); this.Controls.Add(this.lstViewUsers); this.Controls.Add(this.toolBar); this.Name = "MainForm"; this.Text = "Ролевая безопасность"; this.Load += new System.EventHandler(this.MainForm_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
45.468254
140
0.605865
[ "MIT" ]
Bullbushka/Lab10
Lab10/CustomSecurity/MainForm.Designer.cs
5,994
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 Microsoft.ML.Data; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Model; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Microsoft.ML.Runtime.Data { /// <summary> /// A helper class to create data views based on the user-provided types. /// </summary> [BestFriend] internal static class DataViewConstructionUtils { public static IDataView CreateFromList<TRow>(IHostEnvironment env, IList<TRow> data, SchemaDefinition schemaDefinition = null) where TRow : class { Contracts.AssertValue(env); env.AssertValue(data); env.AssertValueOrNull(schemaDefinition); var internalSchemaDefn = schemaDefinition == null ? InternalSchemaDefinition.Create(typeof(TRow), SchemaDefinition.Direction.Read) : InternalSchemaDefinition.Create(typeof(TRow), schemaDefinition); return new ListDataView<TRow>(env, data, internalSchemaDefn); } public static StreamingDataView<TRow> CreateFromEnumerable<TRow>(IHostEnvironment env, IEnumerable<TRow> data, SchemaDefinition schemaDefinition = null) where TRow : class { Contracts.AssertValue(env); env.AssertValue(data); env.AssertValueOrNull(schemaDefinition); var internalSchemaDefn = schemaDefinition == null ? InternalSchemaDefinition.Create(typeof(TRow), SchemaDefinition.Direction.Read) : InternalSchemaDefinition.Create(typeof(TRow), schemaDefinition); return new StreamingDataView<TRow>(env, data, internalSchemaDefn); } public static InputRow<TRow> CreateInputRow<TRow>(IHostEnvironment env, SchemaDefinition schemaDefinition = null) where TRow : class { Contracts.AssertValue(env); env.AssertValueOrNull(schemaDefinition); var internalSchemaDefn = schemaDefinition == null ? InternalSchemaDefinition.Create(typeof(TRow), SchemaDefinition.Direction.Read) : InternalSchemaDefinition.Create(typeof(TRow), schemaDefinition); return new InputRow<TRow>(env, internalSchemaDefn); } public static IDataView LoadPipeWithPredictor(IHostEnvironment env, Stream modelStream, IDataView view) { // Load transforms. var pipe = env.LoadTransforms(modelStream, view); // Load predictor (if present) and apply default scorer. // REVIEW: distinguish the case of predictor / no predictor? var predictor = env.LoadPredictorOrNull(modelStream); if (predictor != null) { var roles = ModelFileUtils.LoadRoleMappingsOrNull(env, modelStream); pipe = roles != null ? env.CreateDefaultScorer(new RoleMappedData(pipe, roles, opt: true), predictor) : env.CreateDefaultScorer(new RoleMappedData(pipe, label: null, "Features"), predictor); } return pipe; } public sealed class InputRow<TRow> : InputRowBase<TRow> where TRow : class { private TRow _value; private long _position; public override long Position => _position; public InputRow(IHostEnvironment env, InternalSchemaDefinition schemaDef) : base(env, SchemaBuilder.MakeSchema(GetSchemaColumns(schemaDef)), schemaDef, MakePeeks(schemaDef), c => true) { _position = -1; } private static Delegate[] MakePeeks(InternalSchemaDefinition schemaDef) { var peeks = new Delegate[schemaDef.Columns.Length]; for (var i = 0; i < peeks.Length; i++) { var currentColumn = schemaDef.Columns[i]; peeks[i] = currentColumn.IsComputed ? currentColumn.Generator : ApiUtils.GeneratePeek<InputRow<TRow>, TRow>(currentColumn); } return peeks; } public void ExtractValues(TRow row) { Host.CheckValue(row, nameof(row)); _value = row; _position++; } public override ValueGetter<RowId> GetIdGetter() { return IdGetter; } private void IdGetter(ref RowId val) => val = new RowId((ulong)Position, 0); protected override TRow GetCurrentRowObject() { Host.Check(Position >= 0, "Can't call a getter on an inactive cursor."); return _value; } } /// <summary> /// A row that consumes items of type <typeparamref name="TRow"/>, and provides an <see cref="Row"/>. This /// is in contrast to <see cref="IRowReadableAs{TRow}"/> which consumes a data view row and publishes them as the output type. /// </summary> /// <typeparam name="TRow">The input data type.</typeparam> public abstract class InputRowBase<TRow> : Row where TRow : class { private readonly int _colCount; private readonly Delegate[] _getters; protected readonly IHost Host; public override long Batch => 0; public override Schema Schema { get; } public InputRowBase(IHostEnvironment env, Schema schema, InternalSchemaDefinition schemaDef, Delegate[] peeks, Func<int, bool> predicate) { Contracts.AssertValue(env); Host = env.Register("Row"); Host.AssertValue(schema); Host.AssertValue(schemaDef); Host.AssertValue(peeks); Host.AssertValue(predicate); Host.Assert(schema.Count == schemaDef.Columns.Length); Host.Assert(schema.Count == peeks.Length); _colCount = schema.Count; Schema = schema; _getters = new Delegate[_colCount]; for (int c = 0; c < _colCount; c++) _getters[c] = predicate(c) ? CreateGetter(schema[c].Type, schemaDef.Columns[c], peeks[c]) : null; } //private Delegate CreateGetter(SchemaProxy schema, int index, Delegate peek) private Delegate CreateGetter(ColumnType colType, InternalSchemaDefinition.Column column, Delegate peek) { var outputType = column.OutputType; var genericType = outputType; Func<Delegate, Delegate> del; if (outputType.IsArray) { Host.Assert(colType.IsVector); // String[] -> ReadOnlyMemory<char> if (outputType.GetElementType() == typeof(string)) { Host.Assert(colType.ItemType.IsText); return CreateConvertingArrayGetterDelegate<string, ReadOnlyMemory<char>>(peek, x => x != null ? x.AsMemory() : ReadOnlyMemory<char>.Empty); } // T[] -> VBuffer<T> if (outputType.GetElementType().IsGenericType && outputType.GetElementType().GetGenericTypeDefinition() == typeof(Nullable<>)) Host.Assert(Nullable.GetUnderlyingType(outputType.GetElementType()) == colType.ItemType.RawType); else Host.Assert(outputType.GetElementType() == colType.ItemType.RawType); del = CreateDirectArrayGetterDelegate<int>; genericType = outputType.GetElementType(); } else if (colType.IsVector) { // VBuffer<T> -> VBuffer<T> // REVIEW: Do we care about accomodating VBuffer<string> -> ReadOnlyMemory<char>? Host.Assert(outputType.IsGenericType); Host.Assert(outputType.GetGenericTypeDefinition() == typeof(VBuffer<>)); Host.Assert(outputType.GetGenericArguments()[0] == colType.ItemType.RawType); del = CreateDirectVBufferGetterDelegate<int>; genericType = colType.ItemType.RawType; } else if (colType.IsPrimitive) { if (outputType == typeof(string)) { // String -> ReadOnlyMemory<char> Host.Assert(colType.IsText); return CreateConvertingGetterDelegate<String, ReadOnlyMemory<char>>(peek, x => x != null ? x.AsMemory() : ReadOnlyMemory<char>.Empty); } // T -> T if (outputType.IsGenericType && outputType.GetGenericTypeDefinition() == typeof(Nullable<>)) Host.Assert(colType.RawType == Nullable.GetUnderlyingType(outputType)); else Host.Assert(colType.RawType == outputType); if (!(colType is KeyType keyType)) del = CreateDirectGetterDelegate<int>; else { var keyRawType = colType.RawType; Host.Assert(keyType.Contiguous); Func<Delegate, ColumnType, Delegate> delForKey = CreateKeyGetterDelegate<uint>; return Utils.MarshalInvoke(delForKey, keyRawType, peek, colType); } } else { // REVIEW: Is this even possible? throw Host.ExceptNotSupp("Type '{0}' is not yet supported.", outputType.FullName); } return Utils.MarshalInvoke(del, genericType, peek); } // REVIEW: The converting getter invokes a type conversion delegate on every call, so it's inherently slower // than the 'direct' getter. We don't have good indication of this to the user, and the selection // of affected types is pretty arbitrary (signed integers and bools, but not uints and floats). private Delegate CreateConvertingArrayGetterDelegate<TSrc, TDst>(Delegate peekDel, Func<TSrc, TDst> convert) { var peek = peekDel as Peek<TRow, TSrc[]>; Host.AssertValue(peek); TSrc[] buf = default; return (ValueGetter<VBuffer<TDst>>)((ref VBuffer<TDst> dst) => { peek(GetCurrentRowObject(), Position, ref buf); var n = Utils.Size(buf); var dstEditor = VBufferEditor.Create(ref dst, n); for (int i = 0; i < n; i++) dstEditor.Values[i] = convert(buf[i]); dst = dstEditor.Commit(); }); } private Delegate CreateConvertingGetterDelegate<TSrc, TDst>(Delegate peekDel, Func<TSrc, TDst> convert) { var peek = peekDel as Peek<TRow, TSrc>; Host.AssertValue(peek); TSrc buf = default; return (ValueGetter<TDst>)((ref TDst dst) => { peek(GetCurrentRowObject(), Position, ref buf); dst = convert(buf); }); } private Delegate CreateDirectArrayGetterDelegate<TDst>(Delegate peekDel) { var peek = peekDel as Peek<TRow, TDst[]>; Host.AssertValue(peek); TDst[] buf = null; return (ValueGetter<VBuffer<TDst>>)((ref VBuffer<TDst> dst) => { peek(GetCurrentRowObject(), Position, ref buf); var n = Utils.Size(buf); var dstEditor = VBufferEditor.Create(ref dst, n); if (buf != null) buf.AsSpan(0, n).CopyTo(dstEditor.Values); dst = dstEditor.Commit(); }); } private Delegate CreateDirectVBufferGetterDelegate<TDst>(Delegate peekDel) { var peek = peekDel as Peek<TRow, VBuffer<TDst>>; Host.AssertValue(peek); VBuffer<TDst> buf = default; return (ValueGetter<VBuffer<TDst>>)((ref VBuffer<TDst> dst) => { // The peek for a VBuffer is just a simple assignment, so there is // no copy going on in the peek, so we must do that as a second // step to the destination. peek(GetCurrentRowObject(), Position, ref buf); buf.CopyTo(ref dst); }); } private Delegate CreateDirectGetterDelegate<TDst>(Delegate peekDel) { var peek = peekDel as Peek<TRow, TDst>; Host.AssertValue(peek); return (ValueGetter<TDst>)((ref TDst dst) => peek(GetCurrentRowObject(), Position, ref dst)); } private Delegate CreateKeyGetterDelegate<TDst>(Delegate peekDel, ColumnType colType) { // Make sure the function is dealing with key. KeyType keyType = colType as KeyType; Host.Check(keyType != null); // Following equations work only with contiguous key type. Host.Check(keyType.Contiguous); // Following equations work only with unsigned integers. Host.Check(typeof(TDst) == typeof(ulong) || typeof(TDst) == typeof(uint) || typeof(TDst) == typeof(byte) || typeof(TDst) == typeof(bool)); // Convert delegate function to a function which can fetch the underlying value. var peek = peekDel as Peek<TRow, TDst>; Host.AssertValue(peek); TDst rawKeyValue = default; ulong key = 0; // the raw key value as ulong ulong min = keyType.Min; ulong max = min + (ulong)keyType.Count - 1; ulong result = 0; // the result as ulong ValueGetter<TDst> getter = (ref TDst dst) => { peek(GetCurrentRowObject(), Position, ref rawKeyValue); key = (ulong)Convert.ChangeType(rawKeyValue, typeof(ulong)); if (min <= key && key <= max) result = key - min + 1; else result = 0; dst = (TDst)Convert.ChangeType(result, typeof(TDst)); }; return getter; } protected abstract TRow GetCurrentRowObject(); public override bool IsColumnActive(int col) { CheckColumnInRange(col); return _getters[col] != null; } private void CheckColumnInRange(int columnIndex) { if (columnIndex < 0 || columnIndex >= _colCount) throw Host.Except("Column index must be between 0 and {0}", _colCount); } public override ValueGetter<TValue> GetGetter<TValue>(int col) { if (!IsColumnActive(col)) throw Host.Except("Column {0} is not active in the cursor", col); var getter = _getters[col]; Contracts.AssertValue(getter); var fn = getter as ValueGetter<TValue>; if (fn == null) throw Host.Except("Invalid TValue in GetGetter for column #{0}: '{1}'", col, typeof(TValue)); return fn; } } /// <summary> /// The base class for the data view over items of user-defined type. /// </summary> /// <typeparam name="TRow">The user-defined data type.</typeparam> public abstract class DataViewBase<TRow> : IDataView where TRow : class { protected readonly IHost Host; private readonly Schema _schema; private readonly InternalSchemaDefinition _schemaDefn; // The array of generated methods that extract the fields of the current row object. private readonly Delegate[] _peeks; public abstract bool CanShuffle { get; } public Schema Schema => _schema; protected DataViewBase(IHostEnvironment env, string name, InternalSchemaDefinition schemaDefn) { Contracts.AssertValue(env); env.AssertNonWhiteSpace(name); Host = env.Register(name); Host.AssertValue(schemaDefn); _schemaDefn = schemaDefn; _schema = SchemaBuilder.MakeSchema(GetSchemaColumns(schemaDefn)); int n = schemaDefn.Columns.Length; _peeks = new Delegate[n]; for (var i = 0; i < n; i++) { var currentColumn = schemaDefn.Columns[i]; _peeks[i] = currentColumn.IsComputed ? currentColumn.Generator : ApiUtils.GeneratePeek<DataViewBase<TRow>, TRow>(currentColumn); } } public abstract long? GetRowCount(); public abstract RowCursor GetRowCursor(Func<int, bool> predicate, Random rand = null); public RowCursor[] GetRowCursorSet(out IRowCursorConsolidator consolidator, Func<int, bool> predicate, int n, Random rand = null) { consolidator = null; return new[] { GetRowCursor(predicate, rand) }; } public sealed class WrappedCursor : RowCursor { private readonly DataViewCursorBase _toWrap; public WrappedCursor(DataViewCursorBase toWrap) => _toWrap = toWrap; public override CursorState State => _toWrap.State; public override long Position => _toWrap.Position; public override long Batch => _toWrap.Batch; public override Schema Schema => _toWrap.Schema; protected override void Dispose(bool disposing) { if (disposing) _toWrap.Dispose(); } public override ValueGetter<TValue> GetGetter<TValue>(int col) => _toWrap.GetGetter<TValue>(col); public override ValueGetter<RowId> GetIdGetter() => _toWrap.GetIdGetter(); public override RowCursor GetRootCursor() => this; public override bool IsColumnActive(int col) => _toWrap.IsColumnActive(col); public override bool MoveMany(long count) => _toWrap.MoveMany(count); public override bool MoveNext() => _toWrap.MoveNext(); } public abstract class DataViewCursorBase : InputRowBase<TRow> { // There is no real concept of multiple inheritance and for various reasons it was better to // descend from the row class as opposed to wrapping it, so much of this class is regrettably // copied from RootCursorBase. protected readonly DataViewBase<TRow> DataView; protected readonly IChannel Ch; private long _position; /// <summary> /// Zero-based position of the cursor. /// </summary> public override long Position => _position; protected DataViewCursorBase(IHostEnvironment env, DataViewBase<TRow> dataView, Func<int, bool> predicate) : base(env, dataView.Schema, dataView._schemaDefn, dataView._peeks, predicate) { Contracts.AssertValue(env); Ch = env.Start("Cursor"); Ch.AssertValue(dataView); Ch.AssertValue(predicate); DataView = dataView; _position = -1; State = CursorState.NotStarted; } public CursorState State { get; private set; } /// <summary> /// Convenience property for checking whether the current state of the cursor is <see cref="CursorState.Good"/>. /// </summary> protected bool IsGood => State == CursorState.Good; protected sealed override void Dispose(bool disposing) { if (State == CursorState.Done) return; Ch.Dispose(); _position = -1; base.Dispose(disposing); State = CursorState.Done; } public bool MoveNext() { if (State == CursorState.Done) return false; Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); if (MoveNextCore()) { Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); _position++; State = CursorState.Good; return true; } Dispose(); return false; } public bool MoveMany(long count) { // Note: If we decide to allow count == 0, then we need to special case // that MoveNext() has never been called. It's not entirely clear what the return // result would be in that case. Ch.CheckParam(count > 0, nameof(count)); if (State == CursorState.Done) return false; Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); if (MoveManyCore(count)) { Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); _position += count; State = CursorState.Good; return true; } Dispose(); return false; } /// <summary> /// Default implementation is to simply call MoveNextCore repeatedly. Derived classes should /// override if they can do better. /// </summary> /// <param name="count">The number of rows to move forward.</param> /// <returns>Whether the move forward is on a valid row</returns> protected virtual bool MoveManyCore(long count) { Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); Ch.Assert(count > 0); while (MoveNextCore()) { Ch.Assert(State == CursorState.NotStarted || State == CursorState.Good); if (--count <= 0) return true; } return false; } /// <summary> /// Core implementation of <see cref="MoveNext"/>, called if the cursor state is not /// <see cref="CursorState.Done"/>. /// </summary> protected abstract bool MoveNextCore(); } } /// <summary> /// An in-memory data view based on the IList of data. /// Supports shuffling. /// </summary> private sealed class ListDataView<TRow> : DataViewBase<TRow> where TRow : class { private readonly IList<TRow> _data; public ListDataView(IHostEnvironment env, IList<TRow> data, InternalSchemaDefinition schemaDefn) : base(env, "ListDataView", schemaDefn) { Host.CheckValue(data, nameof(data)); _data = data; } public override bool CanShuffle { get { return true; } } public override long? GetRowCount() { return _data.Count; } public override RowCursor GetRowCursor(Func<int, bool> predicate, Random rand = null) { Host.CheckValue(predicate, nameof(predicate)); return new WrappedCursor(new Cursor(Host, "ListDataView", this, predicate, rand)); } private sealed class Cursor : DataViewCursorBase { private readonly int[] _permutation; private readonly IList<TRow> _data; private int Index { get { return _permutation == null ? (int)Position : _permutation[(int)Position]; } } public Cursor(IHostEnvironment env, string name, ListDataView<TRow> dataView, Func<int, bool> predicate, Random rand) : base(env, dataView, predicate) { Ch.AssertValueOrNull(rand); _data = dataView._data; if (rand != null) _permutation = Utils.GetRandomPermutation(rand, dataView._data.Count); } public override ValueGetter<RowId> GetIdGetter() { if (_permutation == null) { return (ref RowId val) => { Ch.Check(IsGood, "Cannot call ID getter in current state"); val = new RowId((ulong)Position, 0); }; } else { return (ref RowId val) => { Ch.Check(IsGood, "Cannot call ID getter in current state"); val = new RowId((ulong)Index, 0); }; } } protected override TRow GetCurrentRowObject() { Ch.Check(0 <= Position && Position < _data.Count, "Can't call a getter on an inactive cursor."); return _data[Index]; } protected override bool MoveNextCore() { Ch.Assert(State != CursorState.Done); Ch.Assert(Position < _data.Count); return Position + 1 < _data.Count; } protected override bool MoveManyCore(long count) { Ch.Assert(State != CursorState.Done); Ch.Assert(Position < _data.Count); return count < _data.Count - Position; } } } /// <summary> /// An in-memory data view based on the IEnumerable of data. /// Doesn't support shuffling. /// /// This class is public because prediction engine wants to call its <see cref="SetData"/> /// for performance reasons. /// </summary> public sealed class StreamingDataView<TRow> : DataViewBase<TRow> where TRow : class { private IEnumerable<TRow> _data; public StreamingDataView(IHostEnvironment env, IEnumerable<TRow> data, InternalSchemaDefinition schemaDefn) : base(env, "StreamingDataView", schemaDefn) { Contracts.CheckValue(data, nameof(data)); _data = data; } public override bool CanShuffle { get { return false; } } public override long? GetRowCount() { return (_data as ICollection<TRow>)?.Count; } public override RowCursor GetRowCursor(Func<int, bool> predicate, Random rand = null) { return new WrappedCursor (new Cursor(Host, this, predicate)); } /// <summary> /// Since all the cursors only depend on an enumerator (rather than the data itself), /// it's safe to 'swap' the data inside the streaming data view. This doesn't affect /// the current 'live' cursors, only the ones that will be created later. /// This is used for efficiency in <see cref="BatchPredictionEngine{TSrc,TDst}"/>. /// </summary> public void SetData(IEnumerable<TRow> data) { Contracts.CheckValue(data, nameof(data)); _data = data; } private sealed class Cursor : DataViewCursorBase { private readonly IEnumerator<TRow> _enumerator; private TRow _currentRow; public Cursor(IHostEnvironment env, StreamingDataView<TRow> dataView, Func<int, bool> predicate) : base(env, dataView, predicate) { _enumerator = dataView._data.GetEnumerator(); _currentRow = null; } public override ValueGetter<RowId> GetIdGetter() { return (ref RowId val) => { Ch.Check(IsGood, "Cannot call ID getter in current state"); val = new RowId((ulong)Position, 0); }; } protected override TRow GetCurrentRowObject() { return _currentRow; } protected override bool MoveNextCore() { Ch.Assert(State != CursorState.Done); var result = _enumerator.MoveNext(); _currentRow = result ? _enumerator.Current : null; if (result && _currentRow == null) throw Ch.Except("Encountered null when iterating over data, this is not supported."); return result; } } } /// <summary> /// This represents the 'infinite data view' over one (mutable) user-defined object. /// The 'current row' object can be updated at any time, this will affect all the /// newly created cursors, but not the ones already existing. /// </summary> public sealed class SingleRowLoopDataView<TRow> : DataViewBase<TRow> where TRow : class { private TRow _current; public SingleRowLoopDataView(IHostEnvironment env, InternalSchemaDefinition schemaDefn) : base(env, "SingleRowLoopDataView", schemaDefn) { } public override bool CanShuffle => false; public override long? GetRowCount() => null; public void SetCurrentRowObject(TRow value) { Host.AssertValue(value); _current = value; } public override RowCursor GetRowCursor(Func<int, bool> predicate, Random rand = null) { Contracts.Assert(_current != null, "The current object must be set prior to cursoring"); return new WrappedCursor (new Cursor(Host, this, predicate)); } private sealed class Cursor : DataViewCursorBase { private readonly TRow _currentRow; public Cursor(IHostEnvironment env, SingleRowLoopDataView<TRow> dataView, Func<int, bool> predicate) : base(env, dataView, predicate) { _currentRow = dataView._current; } public override ValueGetter<RowId> GetIdGetter() { return (ref RowId val) => { Ch.Check(IsGood, "Cannot call ID getter in current state"); val = new RowId((ulong)Position, 0); }; } protected override TRow GetCurrentRowObject() => _currentRow; protected override bool MoveNextCore() { Ch.Assert(State != CursorState.Done); return true; } protected override bool MoveManyCore(long count) { Ch.Assert(State != CursorState.Done); return true; } } } [BestFriend] internal static Schema.DetachedColumn[] GetSchemaColumns(InternalSchemaDefinition schemaDefn) { Contracts.AssertValue(schemaDefn); var columns = new Schema.DetachedColumn[schemaDefn.Columns.Length]; for (int i = 0; i < columns.Length; i++) { var col = schemaDefn.Columns[i]; var meta = new MetadataBuilder(); foreach (var kvp in col.Metadata) meta.Add(kvp.Value.Kind, kvp.Value.MetadataType, kvp.Value.GetGetterDelegate()); columns[i] = new Schema.DetachedColumn(col.ColumnName, col.ColumnType, meta.GetMetadata()); } return columns; } } /// <summary> /// A single instance of metadata information, associated with a column. /// </summary> public abstract partial class MetadataInfo { /// <summary> /// The type of the metadata. /// </summary> public ColumnType MetadataType; /// <summary> /// The string identifier of the metadata. Some identifiers have special meaning, /// like "SlotNames", but any other identifiers can be used. /// </summary> public readonly string Kind; public abstract ValueGetter<TDst> GetGetter<TDst>(); internal abstract Delegate GetGetterDelegate(); protected MetadataInfo(string kind, ColumnType metadataType) { Contracts.AssertValueOrNull(metadataType); Contracts.AssertNonEmpty(kind); Kind = kind; } } /// <summary> /// Strongly-typed version of <see cref="MetadataInfo"/>, that contains the actual value of the metadata. /// </summary> /// <typeparam name="T">Type of the metadata value.</typeparam> public sealed class MetadataInfo<T> : MetadataInfo { public readonly T Value; /// <summary> /// Constructor for metadata of value type T. /// </summary> /// <param name="kind">The string identifier of the metadata. Some identifiers have special meaning, /// like "SlotNames", but any other identifiers can be used.</param> /// <param name="value">Metadata value.</param> /// <param name="metadataType">Type of the metadata.</param> public MetadataInfo(string kind, T value, ColumnType metadataType = null) : base(kind, metadataType) { Contracts.Assert(value != null); bool isVector; DataKind dataKind; InternalSchemaDefinition.GetVectorAndKind(typeof(T), "metadata value", out isVector, out dataKind); if (metadataType == null) { // Infer a type as best we can. var itemType = PrimitiveType.FromKind(dataKind); metadataType = isVector ? new VectorType(itemType) : (ColumnType)itemType; } else { // Make sure that the types are compatible with the declared type, including whether it is a vector type. if (isVector != metadataType.IsVector) { throw Contracts.Except("Value inputted is supposed to be {0}, but type of Metadatainfo is {1}", isVector ? "vector" : "scalar", metadataType.IsVector ? "vector" : "scalar"); } if (dataKind != metadataType.ItemType.RawKind) { throw Contracts.Except( "Value inputted is supposed to have dataKind {0}, but type of Metadatainfo has {1}", dataKind.ToString(), metadataType.ItemType.RawKind.ToString()); } } MetadataType = metadataType; Value = value; } public override ValueGetter<TDst> GetGetter<TDst>() { var typeT = typeof(T); if (typeT.IsArray) { Contracts.Assert(MetadataType.IsVector); Contracts.Check(typeof(TDst).IsGenericType && typeof(TDst).GetGenericTypeDefinition() == typeof(VBuffer<>)); var itemType = typeT.GetElementType(); var dstItemType = typeof(TDst).GetGenericArguments()[0]; // String[] -> VBuffer<ReadOnlyMemory<char>> if (itemType == typeof(string)) { Contracts.Check(dstItemType == typeof(ReadOnlyMemory<char>)); ValueGetter<VBuffer<ReadOnlyMemory<char>>> method = GetStringArray; return method as ValueGetter<TDst>; } // T[] -> VBuffer<T> Contracts.Check(itemType == dstItemType); Func<ValueGetter<VBuffer<int>>> srcMethod = GetArrayGetter<int>; return srcMethod.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(dstItemType) .Invoke(this, new object[] { }) as ValueGetter<TDst>; } if (MetadataType.IsVector) { // VBuffer<T> -> VBuffer<T> // REVIEW: Do we care about accomodating VBuffer<string> -> VBuffer<ReadOnlyMemory<char>>? Contracts.Assert(typeT.IsGenericType); Contracts.Check(typeof(TDst).IsGenericType); Contracts.Assert(typeT.GetGenericTypeDefinition() == typeof(VBuffer<>)); Contracts.Check(typeof(TDst).GetGenericTypeDefinition() == typeof(VBuffer<>)); var dstItemType = typeof(TDst).GetGenericArguments()[0]; var itemType = typeT.GetGenericArguments()[0]; Contracts.Assert(itemType == MetadataType.ItemType.RawType); Contracts.Check(itemType == dstItemType); Func<ValueGetter<VBuffer<int>>> srcMethod = GetVBufferGetter<int>; return srcMethod.GetMethodInfo().GetGenericMethodDefinition() .MakeGenericMethod(MetadataType.ItemType.RawType) .Invoke(this, new object[] { }) as ValueGetter<TDst>; } if (MetadataType.IsPrimitive) { if (typeT == typeof(string)) { // String -> ReadOnlyMemory<char> Contracts.Assert(MetadataType.IsText); ValueGetter<ReadOnlyMemory<char>> m = GetString; return m as ValueGetter<TDst>; } // T -> T Contracts.Assert(MetadataType.RawType == typeT); return GetDirectValue; } throw Contracts.ExceptNotImpl("Type '{0}' is not yet supported.", typeT.FullName); } // We want to use MarshalInvoke instead of adding custom Reflection logic for calling GetGetter<TDst> private Delegate GetGetterCore<TDst>() { return GetGetter<TDst>(); } internal override Delegate GetGetterDelegate() { return Utils.MarshalInvoke(GetGetterCore<int>, MetadataType.RawType); } public class TElement { } private void GetStringArray(ref VBuffer<ReadOnlyMemory<char>> dst) { var value = (string[])(object)Value; var n = Utils.Size(value); var dstEditor = VBufferEditor.Create(ref dst, n); for (int i = 0; i < n; i++) dstEditor.Values[i] = value[i].AsMemory(); dst = dstEditor.Commit(); } private ValueGetter<VBuffer<TDst>> GetArrayGetter<TDst>() { var value = (TDst[])(object)Value; var n = Utils.Size(value); return (ref VBuffer<TDst> dst) => { var dstEditor = VBufferEditor.Create(ref dst, n); if (value != null) value.AsSpan(0, n).CopyTo(dstEditor.Values); dst = dstEditor.Commit(); }; } private ValueGetter<VBuffer<TDst>> GetVBufferGetter<TDst>() { var castValue = (VBuffer<TDst>)(object)Value; return (ref VBuffer<TDst> dst) => castValue.CopyTo(ref dst); } private void GetString(ref ReadOnlyMemory<char> dst) { dst = ((string)(object)Value).AsMemory(); } private void GetDirectValue<TDst>(ref TDst dst) { dst = (TDst)(object)Value; } } }
41.688735
163
0.522648
[ "MIT" ]
Zruty0/machinelearning
src/Microsoft.ML.Data/DataView/DataViewConstructionUtils.cs
42,189
C#
using System; namespace hiddenwasp_exploration { class Program { static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: <clean elf> <malicious elf>"); return; } ELFComparer.Compare(args[0], args[1]); } } }
18.578947
72
0.470255
[ "MIT" ]
jcapellman/malware-research
hiddenwasp_exploration/Program.cs
355
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace SportUp.Migrations { public partial class AddMeetingTime : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "MeetingTime", table: "Teams", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "MeetingTime", table: "Teams"); } } }
25.916667
71
0.565916
[ "MIT" ]
toastmalone/SportUp
SportUp/Migrations/20200222004128_AddMeetingTime.cs
624
C#
namespace Microsoft.TemplateEngine.Core.Matching { public abstract class TerminalBase { protected TerminalBase(int tokenLength, int start, int end) { Start = start; End = end != -1 ? end : (tokenLength - 1); Length = tokenLength; } public int Start { get; protected set; } public int End { get; protected set; } public int Length { get; } } }
24.210526
68
0.536957
[ "MIT" ]
ChadNedzlek/templating
src/Microsoft.TemplateEngine.Core/Matching/TerminalBase.cs
442
C#
namespace HDWallet.Core { public enum CoinType : uint { Bitcoin = 0, BitcoinTestnet = 1, CoinType1 = 1, Ethereum = 60, Tron = 195, Polkadot = 354, Kusama = 434, Cardano = 1815, Tezos = 1729, Avalanche = 9000, FileCoin = 461, Solana = 501, Blockstack = 5757 } }
19.842105
32
0.477454
[ "MIT" ]
TurgutKanceltik/HDWallet
src/HDWallet.Core/CoinType.cs
377
C#
using System; using System.Configuration; using System.Windows.Forms; using DevExpress.ExpressApp; using DevExpress.ExpressApp.Security; using DevExpress.ExpressApp.Win; using DevExpress.Persistent.Base; using DevExpress.Persistent.BaseImpl; namespace LDS.Win { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { #if EASYTEST DevExpress.ExpressApp.Win.EasyTest.EasyTestRemotingRegistration.Register(); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); EditModelPermission.AlwaysGranted = System.Diagnostics.Debugger.IsAttached; if(Tracing.GetFileLocationFromSettings() == DevExpress.Persistent.Base.FileLocation.CurrentUserApplicationDataFolder) { Tracing.LocalUserAppDataPath = Application.LocalUserAppDataPath; } Tracing.Initialize(); LDSWindowsFormsApplication winApplication = new LDSWindowsFormsApplication(); // Refer to the https://documentation.devexpress.com/eXpressAppFramework/CustomDocument112680.aspx help article for more details on how to provide a custom splash form. //winApplication.SplashScreen = new DevExpress.ExpressApp.Win.Utils.DXSplashScreen("YourSplashImage.png"); SecurityAdapterHelper.Enable(); if(ConfigurationManager.ConnectionStrings["ConnectionString"] != null) { winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; } #if EASYTEST if(ConfigurationManager.ConnectionStrings["EasyTestConnectionString"] != null) { winApplication.ConnectionString = ConfigurationManager.ConnectionStrings["EasyTestConnectionString"].ConnectionString; } #endif #if DEBUG if(System.Diagnostics.Debugger.IsAttached && winApplication.CheckCompatibilityType == CheckCompatibilityType.DatabaseSchema) { winApplication.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways; } #endif try { winApplication.Setup(); winApplication.Start(); } catch(Exception e) { winApplication.HandleException(e); } } } }
44.036364
180
0.687448
[ "Unlicense" ]
Nickautomatics/LDSXAF
LDS.Win/Program.cs
2,424
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Sql.Tests { public class ManagedInstanceCrudScenarioTests { [Fact] public void TestCreateUpdateGetDropManagedInstance() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); Dictionary<string, string> tags = new Dictionary<string, string>() { { "tagKey1", "TagValue1" } }; bool publicDataEndpointEnabled = true; string proxyOverride = ManagedInstanceProxyOverride.Proxy; string requestedBSR = "Geo"; string publicResourceName = "SQL_Default"; string maintenanceConfigurationId = ManagedInstanceTestUtilities.getManagedInstanceFullMaintenanceResourceid(); // Create resource group var resourceGroup = context.CreateResourceGroup(ManagedInstanceTestUtilities.Region); //Create server var managedInstance1 = context.CreateManagedInstance(resourceGroup, new ManagedInstance() { Tags = tags, MaintenanceConfigurationId = maintenanceConfigurationId }); SqlManagementTestUtilities.ValidateManagedInstance(managedInstance1, tags, shouldCheckState: true); // Create second server var managedInstance2 = context.CreateManagedInstance(resourceGroup, new ManagedInstance() { DnsZonePartner = string.Format( "/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Sql/managedInstances/{2}", ManagedInstanceTestUtilities.SubscriptionId, ManagedInstanceTestUtilities.ResourceGroupName, managedInstance1.Name), PublicDataEndpointEnabled = publicDataEndpointEnabled, ProxyOverride = proxyOverride }); SqlManagementTestUtilities.ValidateManagedInstance(managedInstance2, shouldCheckState: true); // Get first server var getMI1 = sqlClient.ManagedInstances.Get(resourceGroup.Name, managedInstance1.Name); SqlManagementTestUtilities.ValidateManagedInstance(getMI1, tags, shouldCheckState: true); // Get second server var getMI2 = sqlClient.ManagedInstances.Get(resourceGroup.Name, managedInstance2.Name); SqlManagementTestUtilities.ValidateManagedInstance(getMI2, shouldCheckState: true); // Verify that maintenanceConfigurationId value is correctly set Assert.Contains(publicResourceName, getMI1.MaintenanceConfigurationId); // Verify that storageAccountType value is correctly set Assert.Equal(requestedBSR, getMI1.RequestedBackupStorageRedundancy); Assert.Equal(requestedBSR, getMI2.RequestedBackupStorageRedundancy); Assert.Equal(requestedBSR, getMI1.CurrentBackupStorageRedundancy); Assert.Equal(requestedBSR, getMI2.CurrentBackupStorageRedundancy); // Verify that dns zone value is correctly inherited from dns zone partner Assert.Equal(getMI1.DnsZone, getMI2.DnsZone); // Verify PublicDataEndpointEnabled value for second server Assert.Equal(publicDataEndpointEnabled, getMI2.PublicDataEndpointEnabled); // Verify ProxyOverride value for second server Assert.Equal(proxyOverride, getMI2.ProxyOverride); var listMI = context.ListManagedInstanceByResourceGroup(resourceGroup.Name); Assert.Equal(2, listMI.Count()); // Update first server Dictionary<string, string> newTags = new Dictionary<string, string>() { { "asdf", "zxcv" } }; var updateMI1 = sqlClient.ManagedInstances.Update(resourceGroup.Name, getMI1.Name, new ManagedInstanceUpdate { Tags = newTags, LicenseType = "LicenseIncluded" }); SqlManagementTestUtilities.ValidateManagedInstance(updateMI1, newTags); // Drop server, update count sqlClient.ManagedInstances.Delete(resourceGroup.Name, getMI1.Name); var listMI2 = context.ListManagedInstanceByResourceGroup(resourceGroup.Name); Assert.Single(listMI2); sqlClient.ManagedInstances.Delete(resourceGroup.Name, managedInstance2.Name); var listMI3 = context.ListManagedInstanceByResourceGroup(resourceGroup.Name); Assert.Empty(listMI3); } } } }
47.867257
127
0.631355
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/sqlmanagement/Microsoft.Azure.Management.Sql/tests/ManagedInstanceCrudScenarioTests.cs
5,411
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12video.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.DirectX; /// <include file='D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.xml' path='doc/member[@name="D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT"]/*' /> public partial struct D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT { /// <include file='D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.xml' path='doc/member[@name="D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.NodeIndex"]/*' /> public uint NodeIndex; /// <include file='D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.xml' path='doc/member[@name="D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.Codec"]/*' /> public D3D12_VIDEO_ENCODER_CODEC Codec; /// <include file='D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.xml' path='doc/member[@name="D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.ResolutionRatiosCount"]/*' /> public uint ResolutionRatiosCount; }
65.65
209
0.82559
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d12video/D3D12_FEATURE_DATA_VIDEO_ENCODER_OUTPUT_RESOLUTION_RATIOS_COUNT.cs
1,315
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the glue-2017-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glue.Model { /// <summary> /// This is the response object from the UpdateJob operation. /// </summary> public partial class UpdateJobResponse : AmazonWebServiceResponse { private string _jobName; /// <summary> /// Gets and sets the property JobName. /// <para> /// Returns the name of the updated job definition. /// </para> /// </summary> [AWSProperty(Min=1, Max=255)] public string JobName { get { return this._jobName; } set { this._jobName = value; } } // Check to see if JobName property is set internal bool IsSetJobName() { return this._jobName != null; } } }
28.551724
102
0.649758
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Glue/Generated/Model/UpdateJobResponse.cs
1,656
C#
//------------------------------------------------------------ // Game Framework v3.x // Copyright © 2013-2018 Jiang Yin. All rights reserved. // Homepage: http://gameframework.cn/ // Feedback: mailto:jiangyin@gameframework.cn //------------------------------------------------------------ using GameFramework; using UnityEngine; namespace UnityGameFramework.Runtime { /// <summary> /// UnityEngine.Transform 变量类。 /// </summary> public sealed class VarTransform : Variable<Transform> { /// <summary> /// 初始化 UnityEngine.Transform 变量类的新实例。 /// </summary> public VarTransform() { } /// <summary> /// 初始化 UnityEngine.Transform 变量类的新实例。 /// </summary> /// <param name="value">值。</param> public VarTransform(Transform value) : base(value) { } /// <summary> /// 从 UnityEngine.Transform 到 UnityEngine.Transform 变量类的隐式转换。 /// </summary> /// <param name="value">值。</param> public static implicit operator VarTransform(Transform value) { return new VarTransform(value); } /// <summary> /// 从 UnityEngine.Transform 变量类到 UnityEngine.Transform 的隐式转换。 /// </summary> /// <param name="value">值。</param> public static implicit operator Transform(VarTransform value) { return value.Value; } } }
26.581818
69
0.518468
[ "MIT" ]
Data-XiaoYu/UnityWorld
FlappyBird/Assets/GameFramework/Scripts/Runtime/Variable/VarTransform.cs
1,573
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Jurassic.Library { /// <summary> /// Represents a non-native CLR object instance. /// </summary> public class ClrInstanceWrapper : ObjectInstance { // INITIALIZATION //_________________________________________________________________________________________ /// <summary> /// Creates a new ClrInstanceWrapper object. /// </summary> /// <param name="engine"> The associated script engine. </param> /// <param name="instance"> The CLR object instance to wrap. </param> public ClrInstanceWrapper(ScriptEngine engine, object instance) : base(GetPrototypeObject(engine, instance)) { this.WrappedInstance = instance; } /// <summary> /// Returns an object instance to serve as the next object in the prototype chain. /// </summary> /// <param name="engine"> The associated script engine. </param> /// <param name="instance"> The CLR object instance to wrap. </param> /// <returns> The next object in the prototype chain. </returns> private static ObjectInstance GetPrototypeObject(ScriptEngine engine, object instance) { if (engine == null) throw new ArgumentNullException(nameof(engine)); if (instance == null) throw new ArgumentNullException(nameof(instance)); return ClrInstanceTypeWrapper.FromCache(engine, instance.GetType()); } /// <summary> /// Creates an instance of ClrInstanceWrapper or ArrayInstance based on object type. /// </summary> /// <param name="engine"> The associated script engine. </param> /// <param name="instance"> The CLR object instance to wrap. </param> public static ObjectInstance Create(ScriptEngine engine, object instance) { if (instance is IEnumerable enumerable) { var wrappedList = instance is ICollection ? new List<object>(((ICollection)instance).Count) : new List<object>(); var enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) wrappedList.Add(Create(engine, enumerator.Current)); return engine.Array.New(wrappedList.ToArray()); } return new ClrInstanceWrapper(engine, instance); } // PROPERTIES //_________________________________________________________________________________________ /// <summary> /// Gets the .NET instance this object represents. /// </summary> public object WrappedInstance { get; private set; } // OBJECTINSTANCE OVERRIDES //_________________________________________________________________________________________ ///// <summary> ///// Returns a primitive value that represents the current object. Used by the addition and ///// equality operators. ///// </summary> ///// <param name="hint"> Indicates the preferred type of the result. </param> ///// <returns> A primitive value that represents the current object. </returns> //internal override object GetPrimitiveValue(PrimitiveTypeHint typeHint) //{ // // If this wrapper is for a primitive. // if (TypeUtilities.IsPrimitive(this.WrappedInstance) == true) // return this.WrappedInstance; // // Otherwise, use the default implementation. // return base.GetPrimitiveValue(typeHint); //} // OBJECT OVERRIDES //_________________________________________________________________________________________ /// <summary> /// Returns a textual representation of this object. /// </summary> /// <returns> A textual representation of this object. </returns> public override string ToString() { return this.WrappedInstance.ToString(); } } }
38.738739
130
0.602558
[ "MIT" ]
kpreisser/jurassic
Jurassic/Library/ClrWrapper/ClrInstanceWrapper.cs
4,302
C#
using System; using UnityEngine; using UnityEngine.Playables; using UnityEngine.Timeline; using UnityEngine.AI; public class NavigationControlMixerBehaviour : PlayableBehaviour { public override void ProcessFrame(Playable playable, FrameData info, object playerData) { NavMeshAgent trackBinding = playerData as NavMeshAgent; if (!trackBinding) return; int inputCount = playable.GetInputCount(); for (int i = 0; i < inputCount; i++) { float inputWeight = playable.GetInputWeight(i); ScriptPlayable<NavigationControlBehaviour> inputPlayable = (ScriptPlayable<NavigationControlBehaviour>)playable.GetInput(i); NavigationControlBehaviour input = inputPlayable.GetBehaviour(); if (inputWeight > 0.5f && !input.destinationSet && input.destination) { if (!trackBinding.isOnNavMesh) continue; trackBinding.SetDestination(input.destination.position); input.destinationSet = true; } } } }
31.342857
136
0.649043
[ "MIT" ]
JCx7/TSEiAVN
CustomTrack/NavigationControl/NavigationControlMixerBehaviour.cs
1,097
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Input; using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Examples.Demos.EyeTracking { /// <summary> /// Sample for allowing a GameObject to follow the user's eye gaze /// at a given distance of "DefaultDistanceInMeters". /// </summary> public class FollowEyeGaze : MonoBehaviour { [Tooltip("Display the game object along the eye gaze ray at a default distance (in meters).")] [SerializeField] private float defaultDistanceInMeters = 2f; private IMixedRealityInputSystem inputSystem = null; /// <summary> /// The active instance of the input system. /// </summary> private IMixedRealityInputSystem InputSystem { get { if (inputSystem == null) { MixedRealityServiceRegistry.TryGetService<IMixedRealityInputSystem>(out inputSystem); } return inputSystem; } } private void Update() { // Update GameObject to the current eye gaze position at a given distance if (InputSystem?.EyeGazeProvider?.IsEyeGazeValid == true) { GameObject target = InputSystem.EyeGazeProvider.GazeTarget; if (target != null) { // Show the object at the center of the currently looked at target. EyeTrackingTarget etTarget = target.GetComponent<EyeTrackingTarget>(); if ((etTarget != null) && (etTarget.cursor_snapToCenter)) { Ray rayToCenter = new Ray(CameraCache.Main.transform.position, target.transform.position - CameraCache.Main.transform.position); RaycastHit hitInfo; UnityEngine.Physics.Raycast(rayToCenter, out hitInfo); gameObject.transform.position = hitInfo.point; } else { // Show the object at the hit position of the user's eye gaze ray with the target. gameObject.transform.position = InputSystem.EyeGazeProvider.HitPosition; } } else { // If no target is hit, show the object at a default distance along the gaze ray. gameObject.transform.position = InputSystem.EyeGazeProvider.GazeOrigin + InputSystem.EyeGazeProvider.GazeDirection.normalized * defaultDistanceInMeters; } } } } }
42.1
173
0.566678
[ "MIT" ]
BrettPyle/MapsSDK-Unity
SampleProject/Assets/MixedRealityToolkit.Examples/Demos/EyeTracking/General/Scripts/FollowEyeGaze.cs
2,949
C#
using Amw.RabbitMq.Client.Enums; using Amw.RabbitMq.Client.Model; using Amw.RabbitMq.Client.Producer; using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Text; namespace Amw.RabbitMq.Client.Components { public class RabbitMQProducerFactory { /// <summary> /// 创建生产者 /// </summary> /// <param name="type"></param> /// <param name="server"></param> /// <param name="queue"></param> /// <returns></returns> public static BaseProducer CreateProducer(ExchangeTypes type, RabbitMQConnectionModel server, RabbitMQChannelModel queue) { return new RabbitMQDefaultProducer(server, queue); /*var producer = new RabbitMQProducerModel(); //创建连接 producer.Connection = server.Factory.CreateConnection(); //创建通道 producer.Channel = producer.Connection.CreateModel(); //队列配置 producer.Queue = queue; switch (type) { case ExchangeTypes.topic: //声明一个队列 producer.Channel.QueueDeclare(queue.QueueName, queue.Durable, queue.Exclusive, queue.AutoDelete); break; } return producer;*/ } } }
31.214286
129
0.583524
[ "MIT" ]
amwitx/Amw.Core
MessageQueue/Amw.RabbitMq.Client/Components/RabbitMQProducerFactory.cs
1,359
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Reflection; using Tensorflow; using Console = Colorful.Console; namespace TensorFlowNET.Examples { class Program { static void Main(string[] args) { var errors = new List<string>(); var success = new List<string>(); var disabled = new List<string>(); var examples = Assembly.GetEntryAssembly().GetTypes() .Where(x => x.GetInterfaces().Contains(typeof(IExample))) .Select(x => (IExample)Activator.CreateInstance(x)) .ToArray(); Console.WriteLine($"TensorFlow v{tf.VERSION}", Color.Yellow); Console.WriteLine($"TensorFlow.NET v{Assembly.GetAssembly(typeof(TF_DataType)).GetName().Version}", Color.Yellow); var sw = new Stopwatch(); foreach (IExample example in examples) { if (args.Length > 0 && !args.Contains(example.Name)) continue; Console.WriteLine($"{DateTime.UtcNow} Starting {example.Name}", Color.White); try { if (example.Enabled || args.Length > 0) // if a specific example was specified run it, regardless of enabled value { sw.Restart(); bool isSuccess = example.Run(); sw.Stop(); if (isSuccess) success.Add($"Example: {example.Name} in {sw.Elapsed.TotalSeconds}s"); else errors.Add($"Example: {example.Name} in {sw.Elapsed.TotalSeconds}s"); } else { disabled.Add($"Example: {example.Name} in {sw.ElapsedMilliseconds}ms"); } } catch (Exception ex) { errors.Add($"Example: {example.Name}"); Console.WriteLine(ex); } Console.WriteLine($"{DateTime.UtcNow} Completed {example.Name}", Color.White); } success.ForEach(x => Console.WriteLine($"{x} is OK!", Color.Green)); disabled.ForEach(x => Console.WriteLine($"{x} is Disabled!", Color.Tan)); errors.ForEach(x => Console.WriteLine($"{x} is Failed!", Color.Red)); Console.Write("Please [Enter] to quit."); Console.ReadLine(); } } }
37.042254
134
0.504183
[ "Apache-2.0" ]
AndreiDegtiarev/TensorFlow.NET
test/TensorFlowNET.Examples/Program.cs
2,632
C#
using System; using System.Diagnostics; using System.Text; namespace Confuser.Core.Project { internal class PatternTokenizer { private int index; private string rulePattern; public void Initialize(string pattern) { rulePattern = pattern; index = 0; } private void SkipWhitespace() { while (index < rulePattern.Length && char.IsWhiteSpace(rulePattern[index])) index++; } private char? PeekChar() { if (index >= rulePattern.Length) return null; return rulePattern[index]; } private char NextChar() { if (index >= rulePattern.Length) throw new InvalidPatternException("Unexpected end of pattern."); return rulePattern[index++]; } private string ReadLiteral() { var ret = new StringBuilder(); char delim = NextChar(); Debug.Assert(delim == '"' || delim == '\''); char chr = NextChar(); while (chr != delim) { // Escape sequence if (chr == '\\') ret.Append(NextChar()); else ret.Append(chr); chr = NextChar(); } return ret.ToString(); } private string ReadIdentifier() { var ret = new StringBuilder(); char? chr = PeekChar(); while (chr != null && (char.IsLetterOrDigit(chr.Value) || chr == '_' || chr == '-')) { ret.Append(NextChar()); chr = PeekChar(); } return ret.ToString(); } public PatternToken? NextToken() { if (rulePattern == null) throw new InvalidOperationException("Tokenizer not initialized."); SkipWhitespace(); char? tokenBegin = PeekChar(); if (tokenBegin == null) return null; int pos = index; switch (tokenBegin.Value) { case ',': index++; return new PatternToken(pos, TokenType.Comma); case '(': index++; return new PatternToken(pos, TokenType.LParens); case ')': index++; return new PatternToken(pos, TokenType.RParens); case '"': case '\'': return new PatternToken(pos, TokenType.Literal, ReadLiteral()); default: if (!char.IsLetter(tokenBegin.Value)) throw new InvalidPatternException(string.Format("Unknown token '{0}' at position {1}.", tokenBegin, pos)); return new PatternToken(pos, TokenType.Identifier, ReadIdentifier()); } } } }
23.052083
112
0.633077
[ "MIT" ]
codekgithub/ConfuserEx
Confuser.Core/Project/PatternTokenizer.cs
2,215
C#
/* -*- mode:CSharp; coding:utf-8-with-signature -*- */ using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode, RequireComponent(typeof(MeshFilter),typeof(MeshRenderer))] public class GeodegicDome : MonoBehaviour { Mesh mesh_; private Vector3[] normalize(Vector3[] vertices) { var result = new Vector3[vertices.Length]; for (var i = 0; i < result.Length; ++i) { result[i] = vertices[i].normalized; } return result; } private int make_hash(int a, int b) { int a0 = a < b ? a : b; int b0 = a < b ? b : a; return (a0<<16)+b0; } private int proc_edge(int a, int b, Dictionary<int, int> dict, Vector3[] dst_vertices, ref int append_idx) { Debug.Assert(a < append_idx); Debug.Assert(b < append_idx); int edge = -1; var hash = make_hash(a, b); if (dict.ContainsKey(hash)) { edge = dict[hash]; } else { var v = (dst_vertices[a] + dst_vertices[b])*0.5f; dst_vertices[append_idx] = v; edge = append_idx; dict[hash] = append_idx; ++append_idx; } return edge; } private void submesh(Vector3[] vertices, int[] triangles, out Vector3[] dst_vertices, out int[] dst_triangles) { var edge_num = triangles.Length*2; // (face_num*4)*3/2 var dict = new Dictionary<int, int>(); dst_vertices = new Vector3[vertices.Length + edge_num]; dst_triangles = new int[triangles.Length * 4]; for (var i = 0; i < vertices.Length; ++i) { dst_vertices[i] = vertices[i]; } var idx = 0; var append_idx = vertices.Length; for (var face = 0; face < triangles.Length/3; ++face) { var i0 = triangles[face*3+0]; var i1 = triangles[face*3+1]; var i2 = triangles[face*3+2]; var i01 = proc_edge(i0, i1, dict, dst_vertices, ref append_idx); var i12 = proc_edge(i1, i2, dict, dst_vertices, ref append_idx); var i20 = proc_edge(i2, i0, dict, dst_vertices, ref append_idx); dst_triangles[idx*3+0] = i0; dst_triangles[idx*3+1] = i01; dst_triangles[idx*3+2] = i20; ++idx; dst_triangles[idx*3+0] = i01; dst_triangles[idx*3+1] = i1; dst_triangles[idx*3+2] = i12; ++idx; dst_triangles[idx*3+0] = i2; dst_triangles[idx*3+1] = i20; dst_triangles[idx*3+2] = i12; ++idx; dst_triangles[idx*3+0] = i01; dst_triangles[idx*3+1] = i12; dst_triangles[idx*3+2] = i20; ++idx; } } private void triming(Vector3[] vertices, int[] triangles, float limit_upper_y, out Vector3[] dst_vertices, out int[] dst_triangles) { var tmp_triangles = new List<int>(); for (var face = 0; face < triangles.Length/3; ++face) { var i0 = triangles[face*3+0]; var i1 = triangles[face*3+1]; var i2 = triangles[face*3+2]; int over_cnt = 0; if (vertices[i0].y <= limit_upper_y) { ++over_cnt; } if (vertices[i1].y <= limit_upper_y) { ++over_cnt; } if (vertices[i2].y <= limit_upper_y) { ++over_cnt; } if (over_cnt < 3) { tmp_triangles.Add(i0); tmp_triangles.Add(i1); tmp_triangles.Add(i2); } } var cnt_list = new int[vertices.Length]; System.Array.Clear(cnt_list, 0, cnt_list.Length); foreach (var idx in tmp_triangles) { ++cnt_list[idx]; } var tmp_vertices = new List<Vector3>(); int slide_idx = 0; for (var i = 0; i < cnt_list.Length; ++i) { if (cnt_list[i] <= 0) { for (var j = 0; j < tmp_triangles.Count; ++j) { if (i-slide_idx == tmp_triangles[j]) { Debug.LogFormat("{0}:{1}:{2}", i-slide_idx, j, tmp_triangles[j]); } if (i-slide_idx < tmp_triangles[j]) { --tmp_triangles[j]; } } ++slide_idx; } else { var v = vertices[i]; if (v.y < limit_upper_y) { v.y = limit_upper_y; } tmp_vertices.Add(v); } } dst_vertices = tmp_vertices.ToArray(); dst_triangles = tmp_triangles.ToArray(); } void Start() { const float G = 1.618033988749895f; var vertices = new Vector3[14] { new Vector3( G, 0f, 1f), new Vector3( G, 0f, -1f), new Vector3( -G, 0f, 1f), new Vector3( -G, 0f, -1f), new Vector3( 1f, G, 0f), new Vector3(-1f, G, 0f), new Vector3( 1f, -G, 0f), new Vector3(-1f, -G, 0f), new Vector3( 0f, 1f, G), new Vector3( 0f, -1f, G), new Vector3( 0f, 1f, -G), new Vector3( 0f, -1f, -G), new Vector3( 0f, 0f, G), // extra new Vector3( 0f, 0f, -G), // extra }; var triangles = new int[24*3] { 0, 4, 1, 0, 1, 6, 0, 8, 4, 0, 6, 9, // 0, 9, 8, 0, 9, 12, 0, 12, 8, 1, 11, 6, 1, 4, 10, // 1, 10, 11, 1, 10, 13, 1, 13, 11, 2, 3, 5, 2, 5, 8, // 2, 8, 9, 2, 12, 9, 2, 8, 12, 2, 9, 7, 2, 7, 3, 3, 10, 5, // 3, 11, 10, 3, 13, 10, 3, 11, 13, 3, 7, 11, 5, 4, 8, 5, 10, 4, 6, 7, 9, 6, 11, 7, }; // submesh(vertices, triangles, out vertices, out triangles); // submesh(vertices, triangles, out vertices, out triangles); // submesh(vertices, triangles, out vertices, out triangles); Vector3[] vertices_t; int[] triangles_t; triming(vertices, triangles, -0.2f /* limit_upper_y */, out vertices_t, out triangles_t); Vector3[] vertices_n = normalize(vertices_t); int[] triangles_n = triangles_t; mesh_ = new Mesh(); mesh_.name = "skybox"; mesh_.vertices = vertices_n; mesh_.triangles = triangles_n; mesh_.bounds = new Bounds(Vector3.zero, Vector3.one * 99999999); GetComponent<MeshFilter>().sharedMesh = mesh_; } } /* * End of GeodegicDome.cs */
23.960699
91
0.593767
[ "MIT" ]
aizwellenstan/WaveShooter
Assets/Scripts/GeodegicDome.cs
5,489
C#
using System; using System.Collections.Generic; using System.Text; using NAudio.Wave; using NAudio.Utils; using System.Diagnostics; using System.ComponentModel.Composition; namespace AudioFileInspector { [Export(typeof(IAudioFileInspector))] public class WaveFileInspector : IAudioFileInspector { public string FileExtension { get { return ".wav"; } } public string FileTypeDescription { get { return "Wave File"; } } public string Describe(string fileName) { StringBuilder stringBuilder = new StringBuilder(); using (WaveFileReader wf = new WaveFileReader(fileName)) { stringBuilder.AppendFormat("{0} {1}Hz {2} channels {3} bits per sample\r\n", wf.WaveFormat.Encoding, wf.WaveFormat.SampleRate, wf.WaveFormat.Channels, wf.WaveFormat.BitsPerSample); stringBuilder.AppendFormat("Extra Size: {0} Block Align: {1} Average Bytes Per Second: {2}\r\n", wf.WaveFormat.ExtraSize, wf.WaveFormat.BlockAlign, wf.WaveFormat.AverageBytesPerSecond); stringBuilder.AppendFormat("WaveFormat: {0}\r\n",wf.WaveFormat); stringBuilder.AppendFormat("Length: {0} bytes: {1} \r\n", wf.Length, wf.TotalTime); foreach (RiffChunk chunk in wf.ExtraChunks) { stringBuilder.AppendFormat("Chunk: {0}, length {1}\r\n", chunk.IdentifierAsString, chunk.Length); byte[] data = wf.GetChunkData(chunk); DescribeChunk(chunk, stringBuilder, data); } } return stringBuilder.ToString(); } private static void DescribeChunk(RiffChunk chunk, StringBuilder stringBuilder, byte[] data) { switch(chunk.IdentifierAsString) { case "strc": DescribeStrc(stringBuilder, data); break; case "bext": DescribeBext(stringBuilder, data); break; case "iXML": stringBuilder.Append(UTF8Encoding.UTF8.GetString(data)); break; default: { if (ByteArrayExtensions.IsEntirelyNull(data)) { stringBuilder.AppendFormat("{0} null bytes\r\n", data.Length); } else { stringBuilder.AppendFormat("{0}\r\n", ByteArrayExtensions.DescribeAsHex(data," ",32)); } } break; } } private static void DescribeBext(StringBuilder sb, byte[] data) { int offset = 0; sb.AppendFormat("Description: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, 0, 256, ASCIIEncoding.ASCII)); offset += 256; sb.AppendFormat("Originator: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, 32, ASCIIEncoding.ASCII)); offset += 32; sb.AppendFormat("Originator Reference: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, 32, ASCIIEncoding.ASCII)); offset += 32; sb.AppendFormat("Origination Date: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, 10, ASCIIEncoding.ASCII)); offset += 10; sb.AppendFormat("Origination Time: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, 8, ASCIIEncoding.ASCII)); offset += 8; sb.AppendFormat("Time Reference Low: {0}\r\n", BitConverter.ToUInt32(data, offset)); offset += 4; sb.AppendFormat("Time Reference High: {0}\r\n", BitConverter.ToUInt32(data, offset)); offset += 4; sb.AppendFormat("Version: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; sb.AppendFormat("SMPTE UMID: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, 64, Encoding.ASCII)); //byte[] smpteumid = 64 bytes; offset += 64; sb.AppendFormat("Loudness Value: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; sb.AppendFormat("Loudness Range: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; sb.AppendFormat("Max True Peak Level: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; sb.AppendFormat("Max Momentary Loudness: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; sb.AppendFormat("Max short term loudness: {0}\r\n", BitConverter.ToUInt16(data, offset)); offset += 2; //byte[] reserved = 180 bytes; offset += 180; sb.AppendFormat("Coding History: {0}\r\n", ByteArrayExtensions.DecodeAsString(data, offset, data.Length-offset, Encoding.ASCII)); } private static void DescribeStrc(StringBuilder stringBuilder, byte[] data) { // First 28 bytes are header int header1 = BitConverter.ToInt32(data, 0); // always 0x1C? int sliceCount = BitConverter.ToInt32(data, 4); int header2 = BitConverter.ToInt32(data, 8); // 0x19 or 0x41? int header3 = BitConverter.ToInt32(data, 12); // 0x05 or 0x0A? (linked with header 2 - 0x41 0x05 go together and 0x19 0x0A go together) int header4 = BitConverter.ToInt32(data, 16); // always 1? int header5 = BitConverter.ToInt32(data, 20); // 0x00, 0x01 or 0x0A? int header6 = BitConverter.ToInt32(data, 24); // 0x02, 0x04. 0x05 stringBuilder.AppendFormat("{0} slices. unknown: {1},{2},{3},{4},{5},{6}\r\n", sliceCount,header1,header2,header3,header4,header5,header6); int offset = 28; for (int slice = 0; slice < sliceCount; slice++) { int unknown1 = BitConverter.ToInt32(data, offset); // 0 or 2 int uniqueId1 = BitConverter.ToInt32(data, offset + 4); // another unique ID - doesn't change? long samplePosition = BitConverter.ToInt64(data, offset + 8); long samplePos2 = BitConverter.ToInt64(data, offset + 16); // is zero the first time through, equal to sample position next time round int unknown5 = BitConverter.ToInt32(data, offset + 24); // large number first time through, zero second time through, not flags, not a float int uniqueId2 = BitConverter.ToInt32(data, offset + 28); // always the same offset += 32; stringBuilder.AppendFormat("Pos: {2},{3} unknown: {0},{4}\r\n", unknown1, uniqueId1, samplePosition, samplePos2, unknown5, uniqueId2); } } } }
46.886667
156
0.56306
[ "MIT" ]
skor98/DtWPF
speechKit/NAudio-master/AudioFileInspector/FileInspectors/WaveFileInspector.cs
7,033
C#
using System; using Automated.Arca.Abstractions.Core; namespace Automated.Arca.Attributes.DependencyInjection { [AttributeUsage( validOn: AttributeTargets.Class, AllowMultiple = true )] public class InstantiatePerInjectionWithInterfaceAttribute : ProcessableWithInterfaceAttribute { public InstantiatePerInjectionWithInterfaceAttribute() { } public InstantiatePerInjectionWithInterfaceAttribute( Type interfaceType ) : base( interfaceType ) { } } }
24.789474
95
0.806794
[ "MIT" ]
georgehara/Arca
Automated.Arca.Attributes.DependencyInjection/InstantiatePerInjectionWithInterfaceAttribute.cs
473
C#
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using CookComputing.Blogger; using CookComputing.MetaWeblog; using CookComputing.XmlRpc; using Kooboo.CMS.Common.Persistence.Non_Relational; using Kooboo.CMS.Content.Models; using Kooboo.CMS.Content.Models.Paths; using Kooboo.CMS.Content.Query; using Kooboo.CMS.Content.Services; using Kooboo.Globalization; using Kooboo.IO; using Kooboo.Web.Url; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Text; namespace Kooboo.CMS.Web.Interoperability.MetaWeblog { public class MetaWeblogAPIHandler : XmlRpcService, IMetaWeblog, IBlogger { #region .ctor public MetaWeblogAPIHandler(string repositoryName) { this.repositoryName = repositoryName; } #endregion #region MetaWeblogHelper private static class MetaWeblogHelper { public static string CompositePostId(TextContent content) { return content.FolderName + "$$$" + content.UUID + "$$$" + content.UserKey; } public static string ParsePostId(string postId, out string folderName, out string userKey) { string[] s = postId.Split(new string[] { "$$$" }, StringSplitOptions.RemoveEmptyEntries); folderName = s[0]; userKey = s[2]; return s[1]; } } #endregion #region fields private string repositoryName; public string RepositoryName { get { if (string.IsNullOrEmpty(repositoryName)) { return Context.Request.QueryString["repository"]; } return repositoryName; } set { repositoryName = value; } } private Repository Repository { get { if (!string.IsNullOrEmpty(repositoryName)) { return new Repository(RepositoryName); } return Repository.Current; } } #endregion #region CheckUserPassword private void CheckUserPassword(string userName, string password) { if (Repository == null) { throw new KoobooException("The repository is null.".Localize()); } if (!CMS.Account.Services.ServiceFactory.UserManager.ValidateUser(userName, password)) { throw new KoobooException("The user or password is invalid.".Localize()); } bool allow = false; if (Kooboo.CMS.Sites.Models.Site.Current != null) { allow = CMS.Sites.Services.ServiceFactory.UserManager.Authorize(Kooboo.CMS.Sites.Models.Site.Current, userName, Kooboo.CMS.Account.Models.Permission.Contents_ContentPermission); } else { allow = CMS.Sites.Services.ServiceFactory.UserManager.IsAdministrator(userName); } if (!allow) { throw new KoobooException("The user have no permission to edit content.".Localize()); } } #endregion #region IMetaWeblog Members public object editPost(string postid, string username, string password, CookComputing.MetaWeblog.Post post, bool publish) { CheckUserPassword(username, password); string folderName; string userKey; string contentId = MetaWeblogHelper.ParsePostId(postid, out folderName, out userKey); var textFolder = new TextFolder(Repository, FolderHelper.SplitFullName(folderName)); var content = textFolder.CreateQuery().WhereEquals("UUID", contentId).First(); var values = new NameValueCollection(); values["title"] = post.title; values["description"] = post.description; values["body"] = post.description; values["userKey"] = userKey; values["published"] = publish.ToString(); ServiceFactory.GetService<TextContentManager>().Update(Repository, textFolder, content.UUID, values, username); var old_categories = GetCategories(textFolder, content); var removedCategories = old_categories.Where(it => !post.categories.Any(c => string.Compare(c, it, true) == 0)); var addedCategories = post.categories.Where(it => !old_categories.Any(c => string.Compare(c, it, true) == 0)); var removed = GetCategories(textFolder, removedCategories).ToArray(); if (removed.Length > 0) { ServiceFactory.GetService<TextContentManager>().RemoveCategories(Repository, (TextContent)content, removed); } var added = GetCategories(textFolder, addedCategories).ToArray(); if (added.Length > 0) { ServiceFactory.GetService<TextContentManager>().AddCategories(Repository, (TextContent)content, added); } return MetaWeblogHelper.CompositePostId(content); } public CategoryInfo[] getCategories(string blogid, string username, string password) { CheckUserPassword(username, password); var folder = (TextFolder)(FolderHelper.Parse<TextFolder>(Repository, blogid).AsActual()); var categories = GetFolderCategories(folder); return categories.Select(it => new CategoryInfo() { categoryid = MetaWeblogHelper.CompositePostId(it), description = it.GetSummary(), title = it.GetSummary(), htmlUrl = "", rssUrl = "" }).ToArray(); } private IEnumerable<TextContent> GetFolderCategories(TextFolder folder) { folder = folder.AsActual(); IEnumerable<TextContent> categories = new TextContent[0]; if (folder.Categories != null) { foreach (var categoryFolderName in folder.Categories) { var categoryFolder = (TextFolder)(FolderHelper.Parse<TextFolder>(Repository, categoryFolderName.FolderName).AsActual()); var contents = categoryFolder.CreateQuery(); categories = categories.Concat(contents).ToArray(); } } return categories; } public CookComputing.MetaWeblog.Post getPost(string postid, string username, string password) { string folderName; string userKey; string contentId = MetaWeblogHelper.ParsePostId(postid, out folderName, out userKey); var textFolder = new TextFolder(Repository, FolderHelper.SplitFullName(folderName)); var content = textFolder.CreateQuery().WhereEquals("UUID", contentId).First(); return new CookComputing.MetaWeblog.Post() { postid = postid, categories = GetCategories(textFolder, content), description = content["description"] == null ? content["body"] == null ? "" : content["body"].ToString() : content["description"].ToString(), title = content["title"] == null ? "" : content["title"].ToString(), userid = content.UserId }; } public CookComputing.MetaWeblog.Post[] getRecentPosts(string blogid, string username, string password, int numberOfPosts) { CheckUserPassword(username, password); var folder = new TextFolder(Repository, FolderHelper.SplitFullName(blogid)); return folder.CreateQuery().Take(numberOfPosts).ToArray().Select(it => new CookComputing.MetaWeblog.Post() { categories = GetCategories(folder, it), dateCreated = it.UtcCreationDate, description = it["description"] == null ? "" : it["description"].ToString(), postid = it.UUID, title = it["title"] == null ? "" : it["title"].ToString(), userid = it.UserId }).ToArray(); } private string[] GetCategories(TextFolder textFolder, TextContent content) { var folder = textFolder.AsActual(); IEnumerable<string> categories = new string[0]; if (folder.Categories != null) { foreach (var categoryFolderName in folder.Categories) { var categoryFolder = (TextFolder)(FolderHelper.Parse<TextFolder>(Repository, categoryFolderName.FolderName).AsActual()); categories = categories.Concat(textFolder.CreateQuery().WhereEquals("UUID", content.UUID).Categories(categoryFolder).ToArray() .Select(it => it.GetSummary())); } } return categories.ToArray(); } private IEnumerable<TextContent> GetCategories(TextFolder textFolder, IEnumerable<string> categories) { return GetFolderCategories(textFolder).Where(it => categories.Any(c => string.Compare(c, it.GetSummary(), true) == 0)); } public string newPost(string blogid, string username, string password, CookComputing.MetaWeblog.Post post, bool publish) { CheckUserPassword(username, password); var folder = (new TextFolder(Repository, FolderHelper.SplitFullName(blogid))).AsActual(); var values = new NameValueCollection(); values["title"] = post.title; values["description"] = post.description; values["body"] = post.description; values["published"] = publish.ToString(); var content = ServiceFactory.GetService<TextContentManager>().Add(Repository, folder, values, null , GetCategories(folder, post.categories), username); var categories = GetCategories(folder, post.categories).ToArray(); if (categories.Length > 0) { ServiceFactory.GetService<TextContentManager>().AddCategories(Repository, (TextContent)content, categories); } return MetaWeblogHelper.CompositePostId((TextContent)content); } public UrlData newMediaObject(string blogid, string username, string password, FileData file) { CheckUserPassword(username, password); var folder = new TextFolder(Repository, FolderHelper.SplitFullName(blogid)); var metaweblogPath = new MetaWeblogPath(folder); var fileName = Path.GetFileName(file.name); var filePath = Path.Combine(metaweblogPath.PhysicalPath, fileName); Kooboo.IO.StreamExtensions.SaveAs(file.bits, filePath, true); Uri absoluteUri = new Uri(new Uri(Context.Request.Url.AbsoluteUri), UrlUtility.ResolveUrl(UrlUtility.Combine(metaweblogPath.VirtualPath, fileName))); return new UrlData() { url = absoluteUri.ToString() }; } #endregion #region getUsersBlogs public BlogInfo[] getUsersBlogs(string appKey, string username, string password) { CheckUserPassword(username, password); string folderName = Context.Request.QueryString["Folder"]; var folders = ServiceFactory.TextFolderManager.All(Repository, folderName); return folders.Select(it => new BlogInfo() { blogid = it.FullName, blogName = string.Join("/", it.NamePaths.ToArray()), url = "" }).ToArray(); } #endregion #region IBlogger Members public bool deletePost(string appKey, string postid, string username, string password, bool publish) { throw new NotImplementedException(); } public object editPost(string appKey, string postid, string username, string password, string content, bool publish) { throw new NotImplementedException(); } CookComputing.Blogger.Category[] IBlogger.getCategories(string blogid, string username, string password) { throw new NotImplementedException(); } public CookComputing.Blogger.Post getPost(string appKey, string postid, string username, string password) { throw new NotImplementedException(); } public CookComputing.Blogger.Post[] getRecentPosts(string appKey, string blogid, string username, string password, int numberOfPosts) { throw new NotImplementedException(); } public string getTemplate(string appKey, string blogid, string username, string password, string templateType) { throw new NotImplementedException(); } public UserInfo getUserInfo(string appKey, string username, string password) { throw new NotImplementedException(); } public string newPost(string appKey, string blogid, string username, string password, string content, bool publish) { throw new NotImplementedException(); } public bool setTemplate(string appKey, string blogid, string username, string password, string template, string templateType) { throw new NotImplementedException(); } #endregion } }
38.90085
193
0.601588
[ "BSD-3-Clause" ]
ertan2002/CMS
Kooboo.CMS/Kooboo.CMS.Web/Interoperability/MetaWeblog/MetaWeblogAPIHandler.cs
13,734
C#
using Doublelives.Domain.Sys; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace Doublelives.Persistence.TableBuilders { public class SysFileInfoBuilder : IEntityTypeConfiguration<SysFileInfo> { public void Configure(EntityTypeBuilder<SysFileInfo> builder) { builder .HasComment("文件信息") .ToTable("sys_file_info"); builder.Property(e => e.Id) .HasColumnName("id") .HasComment("主键") .ValueGeneratedOnAdd(); builder.Property(e => e.OriginalFileName) .HasMaxLength(255) .HasComment("实际名称") .HasColumnName("original_file_name"); builder.Property(e => e.RealFileName) .HasMaxLength(255) .HasComment("显示名称") .HasColumnName("real_file_name"); builder.Property(e => e.CreateBy) .HasComment("创建者") .HasColumnName("create_by"); builder.Property(e => e.CreateTime) .HasComment("创建时间") .HasColumnName("create_time"); builder.Property(e => e.ModifyBy) .HasComment("最后修改者") .HasColumnName("modify_by"); builder.Property(e => e.ModifyTime) .HasComment("最后修改时间") .HasColumnName("modify_time"); } } }
31.446809
75
0.546008
[ "MIT" ]
lzw5399/dl-admin
dl-api-csharp/Doublelives.Persistence/TableBuilders/SysFileInfoBuilder.cs
1,544
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. namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer { internal class ClientDefinition : ServiceDefinition { public string RedirectUri { get; set; } public string LogoutUri { get; set; } public string ClientSecret { get; set; } } }
34.384615
111
0.711409
[ "Apache-2.0" ]
06b/AspNetCore
src/Identity/ApiAuthorization.IdentityServer/src/Configuration/ClientDefinition.cs
449
C#
using Microsoft.AspNetCore.Components; using PointOfSale.Model; using PointOfSale.Web.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PointOfSale.Web.ComponentBaseClass { public class ListBarangBase : ComponentBase { [Inject] public IBarangService barangService { get; set; } protected Components.KonfirmasiHapus ConfirmRef { get; set; } protected int noUrut { get; set; } protected List<Barang> Barangs { get; set; } = new List<Barang>(); protected async override Task OnInitializedAsync() { Barangs = (await barangService.GetAllBarang()).ToList(); } public int IdBarang { get; set; } protected void ShowModalHapusBarang(int id) { IdBarang = id; ConfirmRef.Tampil(); } protected async Task HapusKonfirmasiBarang(bool konfirmHapus) { if(konfirmHapus) { await barangService.DeleteBarang(IdBarang); await OnInitializedAsync(); } } } }
24.956522
74
0.617596
[ "MIT" ]
pepega90/PointOfSaleBlazor
PointOfSale.Web/ComponentBaseClass/ListBarangBase.cs
1,150
C#
using System; using Xamarin.Forms.Platform.Tizen.Native; using EButton = ElmSharp.Button; using Specific = Xamarin.Forms.PlatformConfiguration.TizenSpecific.VisualElement; namespace Xamarin.Forms.Platform.Tizen { public class ButtonRenderer : ViewRenderer<Button, EButton> { public ButtonRenderer() { RegisterPropertyHandler(Button.TextProperty, UpdateText); RegisterPropertyHandler(Button.FontFamilyProperty, UpdateFontFamily); RegisterPropertyHandler(Button.FontSizeProperty, UpdateFontSize); RegisterPropertyHandler(Button.FontAttributesProperty, UpdateFontAttributes); RegisterPropertyHandler(Button.TextColorProperty, UpdateTextColor); RegisterPropertyHandler(Button.ImageSourceProperty, UpdateBitmap); RegisterPropertyHandler(Button.BorderColorProperty, UpdateBorder); RegisterPropertyHandler(Button.CornerRadiusProperty, UpdateBorder); RegisterPropertyHandler(Button.BorderWidthProperty, UpdateBorder); } protected override void OnElementChanged(ElementChangedEventArgs<Button> e) { if (Control == null) { SetNativeControl(CreateNativeControl()); Control.Clicked += OnButtonClicked; Control.Pressed += OnButtonPressed; Control.Released += OnButtonReleased; } base.OnElementChanged(e); } protected virtual EButton CreateNativeControl() { if (Device.Idiom == TargetIdiom.Watch) return new Native.Watch.WatchButton(Forms.NativeParent); else return new Native.Button(Forms.NativeParent); } protected override Size MinimumSize() { Size measured; if(Control is IMeasurable im) { measured = im.Measure(Control.MinimumWidth, Control.MinimumHeight).ToDP(); } else { measured = base.MinimumSize(); } return measured; } protected override void UpdateThemeStyle() { var style = Specific.GetStyle(Element); if (!string.IsNullOrEmpty(style)) { (Control as IButton)?.UpdateStyle(style); ((IVisualElementController)Element).NativeSizeChanged(); } } protected override void Dispose(bool disposing) { if (disposing) { if (Control != null) { Control.Clicked -= OnButtonClicked; Control.Pressed -= OnButtonPressed; Control.Released -= OnButtonReleased; } } base.Dispose(disposing); } void OnButtonClicked(object sender, EventArgs e) { (Element as IButtonController)?.SendClicked(); } void OnButtonPressed(object sender, EventArgs e) { (Element as IButtonController)?.SendPressed(); } void OnButtonReleased(object sender, EventArgs e) { (Element as IButtonController)?.SendReleased(); } void UpdateText() { (Control as IButton).Text = Element.Text ?? ""; } void UpdateFontSize() { //(Control as IButton).FontSize = Element.FontSize; if (Control is IButton ib) { ib.FontSize = Element.FontSize; } } void UpdateFontAttributes() { if (Control is IButton ib) { ib.FontAttributes = Element.FontAttributes; } } void UpdateFontFamily() { if (Control is IButton ib) { ib.FontFamily = Element.FontFamily.ToNativeFontFamily(); } } void UpdateTextColor() { if (Control is IButton ib) { ib.TextColor = Element.TextColor.ToNative(); } } void UpdateBitmap() { if (Control is IButton ib) { if (Element.ImageSource != null) { ib.Image = new Native.Image(Control); if (Element.ImageSource is FileImageSource fis) { ib.Image.LoadFromFile(fis.File); } else { var task = ib.Image.LoadFromImageSourceAsync(Element.ImageSource); } } else { ib.Image = null; } } } void UpdateBorder() { /* The simpler way is to create some specialized theme for button in * tizen-theme */ // TODO: implement border handling } } }
22.797619
81
0.694256
[ "MIT" ]
AndreiMisiukevich/Xamarin.Forms
Xamarin.Forms.Platform.Tizen/Renderers/ButtonRenderer.cs
3,830
C#
using System; using XSharp; using XSharp.Assembler; using static XSharp.XSRegisters; namespace Cosmos.IL2CPU.X86.IL { /// <summary> /// Convert to unsigned int16, pushing int32 on stack. /// </summary> [OpCode(ILOpCode.Code.Conv_U2)] public class Conv_U2 : ILOp { public Conv_U2(Assembler aAsmblr) : base(aAsmblr) { } public override void Execute(Il2cpuMethodInfo aMethod, ILOpCode aOpCode) { var xSource = aOpCode.StackPopTypes[0]; var xSourceSize = SizeOfType(xSource); var xSourceIsFloat = TypeIsFloat(xSource); DoExecute(xSourceSize, xSourceIsFloat, TypeIsSigned(xSource), false, Assembler, aMethod, aOpCode); } public static void DoExecute(uint xSourceSize, bool xSourceIsFloat, bool xSourceIsSigned, bool checkOverflow, Assembler assembler, Il2cpuMethodInfo aMethod, ILOpCode aOpCode) { var xBaseLabel = GetLabel(aMethod, aOpCode) + "."; var xSuccessLabel = xBaseLabel + "Success"; var xOverflowLabel = xBaseLabel + "Overflow"; var xPositiveLabel = xBaseLabel + "Positive"; var xNegativeLabel = xBaseLabel + "Negative"; if (xSourceSize <= 4) { if (xSourceIsFloat) { XS.SSE.MoveSS(XMM0, ESP, sourceIsIndirect: true); XS.SSE.ConvertSS2SIAndTruncate(EAX, XMM0); XS.MoveZeroExtend(EAX, AX); XS.Set(ESP, EAX, destinationIsIndirect: true); } else { if (checkOverflow) { ConvOverflowChecks.CheckOverflowForSmall(2, xSourceIsSigned, false, assembler, aMethod, aOpCode, xSuccessLabel, xOverflowLabel); } XS.Pop(EAX); XS.MoveZeroExtend(EAX, AX); XS.Push(EAX); } } else if (xSourceSize <= 8) { if (xSourceIsFloat) { XS.SSE2.MoveSD(XMM0, ESP, sourceIsIndirect: true); XS.Add(ESP, 4); XS.SSE2.ConvertSD2SIAndTruncate(EAX, XMM0); XS.MoveZeroExtend(EAX, AX); XS.Set(ESP, EAX, destinationIsIndirect: true); } else { if (checkOverflow) { ConvOverflowChecks.CheckOverflowForLong(2, xSourceIsSigned, false, assembler, aMethod, aOpCode, xSuccessLabel, xOverflowLabel, xPositiveLabel, xNegativeLabel); } XS.Pop(EAX); XS.Add(ESP, 4); XS.MoveZeroExtend(EAX, AX); XS.Push(EAX); } } else { throw new NotImplementedException("Cosmos.IL2CPU.x86->IL->Conv_U2.cs->Error: StackSize > 8 not supported"); } } } }
30.670588
178
0.611814
[ "BSD-3-Clause" ]
xccoreco/IL2CPU
source/Cosmos.IL2CPU/IL/Conv_U2.cs
2,607
C#
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Copyright (C) 2006-2007 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.Collections.Generic; using System.ComponentModel; using Microsoft.DotNet.XUnitExtensions; using Xunit; namespace System.Drawing.Drawing2D.Tests { public class GraphicsPathTests { private const float Pi4 = (float)(Math.PI / 4); private const float Delta = 0.0003f; [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Default_Success() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(FillMode.Alternate, gp.FillMode); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_FillMode_Success() { using (GraphicsPath gpa = new GraphicsPath(FillMode.Alternate)) using (GraphicsPath gpw = new GraphicsPath(FillMode.Winding)) { Assert.Equal(FillMode.Alternate, gpa.FillMode); AssertEmptyGrahicsPath(gpa); Assert.Equal(FillMode.Winding, gpw.FillMode); AssertEmptyGrahicsPath(gpw); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_SamePoints_Success() { byte[] types = new byte[6] { 0, 1, 1, 1, 1, 1 }; Point[] points = new Point[] { new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), new Point (1, 1), }; PointF[] fPoints = new PointF[] { new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f), }; using (GraphicsPath gp = new GraphicsPath(points, types)) using (GraphicsPath gpf = new GraphicsPath(fPoints, types)) { Assert.Equal(FillMode.Alternate, gp.FillMode); Assert.Equal(6, gp.PointCount); Assert.Equal(FillMode.Alternate, gpf.FillMode); Assert.Equal(6, gpf.PointCount); types[0] = 1; Assert.Equal(FillMode.Alternate, gp.FillMode); Assert.Equal(6, gp.PointCount); Assert.Equal(FillMode.Alternate, gpf.FillMode); Assert.Equal(6, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PointsNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("pts", () => new GraphicsPath((Point[])null, new byte[1])); } public static IEnumerable<object[]> AddCurve_PointsTypesLengthMismatch_TestData() { yield return new object[] { 1, 2 }; yield return new object[] { 2, 1 }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_PointsTypesLengthMismatch_TestData))] public void Ctor_PointsTypesLengthMismatch_ThrowsArgumentException(int pointsLength, int typesLength) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new Point[pointsLength], new byte[typesLength])); AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new PointF[pointsLength], new byte[typesLength])); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Clone_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { Assert.Equal(FillMode.Alternate, clone.FillMode); AssertEmptyGrahicsPath(clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reset_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.Reset(); Assert.Equal(FillMode.Alternate, gp.FillMode); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GraphicsPath_FillModeChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.FillMode = FillMode.Winding; Assert.Equal(FillMode.Winding, gp.FillMode); } } [ConditionalTheory(Helpers.IsWindowsOrAtLeastLibgdiplus6)] [InlineData(FillMode.Alternate - 1)] [InlineData(FillMode.Winding + 1)] public void GraphicsPath_InvalidFillMode_ThrowsInvalidEnumArgumentException(FillMode fillMode) { using (GraphicsPath gp = new GraphicsPath()) { Assert.ThrowsAny<ArgumentException>(() => gp.FillMode = fillMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathData_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(0, gp.PathData.Points.Length); Assert.Equal(0, gp.PathData.Types.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathData_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(1f, gp.PathData.Points[0].X); Assert.Equal(1f, gp.PathData.Points[0].Y); gp.PathData.Points[0] = new Point(0, 0); Assert.Equal(1f, gp.PathData.Points[0].X); Assert.Equal(1f, gp.PathData.Points[0].Y); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathPoints_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(1f, gp.PathPoints[0].X); Assert.Equal(1f, gp.PathPoints[0].Y); gp.PathPoints[0] = new Point(0, 0); Assert.Equal(1f, gp.PathPoints[0].X); Assert.Equal(1f, gp.PathPoints[0].Y); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathPoints_EmptyPath_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<ArgumentException>(() => gp.PathPoints); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathTypes_CannotChange() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(0, gp.PathTypes[0]); gp.PathTypes[0] = 1; Assert.Equal(0, gp.PathTypes[0]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void PathTypes_EmptyPath_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<ArgumentException>(() => gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetLastPoint_ReturnsExpected() { byte[] types = new byte[3] { 0, 1, 1 }; PointF[] points = new PointF[] { new PointF (1f, 1f), new PointF (2f, 2f), new PointF (3f, 3f), }; using (GraphicsPath gp = new GraphicsPath(points, types)) { Assert.Equal(gp.GetLastPoint(), points[2]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLine_Success() { using (GraphicsPath gpInt = new GraphicsPath()) using (GraphicsPath gpFloat = new GraphicsPath()) using (GraphicsPath gpPointsInt = new GraphicsPath()) using (GraphicsPath gpfPointsloat = new GraphicsPath()) { gpInt.AddLine(1, 1, 2, 2); // AssertLine() method expects line drawn between points with coordinates 1, 1 and 2, 2, here and below. AssertLine(gpInt); gpFloat.AddLine(1, 1, 2, 2); AssertLine(gpFloat); gpPointsInt.AddLine(new Point(1, 1), new Point(2, 2)); AssertLine(gpPointsInt); gpfPointsloat.AddLine(new PointF(1, 1), new PointF(2, 2)); AssertLine(gpfPointsloat); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLine_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLine(new Point(49, 157), new Point(75, 196)); gpi.AddLine(new Point(75, 196), new Point(102, 209)); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes); gpi.AddLine(new Point(102, 209), new Point(75, 196)); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes); gpf.AddLine(new PointF(49, 157), new PointF(75, 196)); gpf.AddLine(new PointF(75, 196), new PointF(102, 209)); Assert.Equal(3, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpf.PathTypes); gpf.AddLine(new PointF(102, 209), new PointF(75, 196)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(new Point[] { new Point(1, 1), new Point(2, 2) }); AssertLine(gpi); gpf.AddLines(new PointF[] { new PointF(1, 1), new PointF(2, 2) }); AssertLine(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_SinglePoint_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(new PointF[] { new PointF(1, 1) }); Assert.Equal(1, gpi.PointCount); Assert.Equal(0, gpi.PathTypes[0]); gpf.AddLines(new PointF[] { new PointF(1, 1) }); Assert.Equal(1, gpf.PointCount); Assert.Equal(0, gpf.PathTypes[0]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_SamePoint_Success() { Point[] intPoints = new Point[] { new Point(49, 157), new Point(49, 157) }; PointF[] floatPoints = new PointF[] { new PointF(49, 57), new PointF(49, 57), new PointF(49, 57), new PointF(49, 57) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddLines(intPoints); Assert.Equal(2, gpi.PointCount); Assert.Equal(new byte[] { 0, 1 }, gpi.PathTypes); gpi.AddLines(intPoints); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes); gpi.AddLines(intPoints); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes); gpf.AddLines(floatPoints); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes); gpf.AddLines(floatPoints); Assert.Equal(7, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 1, 1, 1, 1 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((Point[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((PointF[])null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddLines_ZeroPoints_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new Point[0])); AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new PointF[0])); } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddArc_Values_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddArc(1, 1, 2, 2, Pi4, Pi4); // AssertArc() method expects added Arc with parameters // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below. AssertArc(gpi); gpf.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); AssertArc(gpf); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddArc_Rectangle_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddArc(new Rectangle(1, 1, 2, 2), Pi4, Pi4); AssertArc(gpi); gpf.AddArc(new RectangleF(1, 1, 2, 2), Pi4, Pi4); AssertArc(gpf); } } [ConditionalTheory(Helpers.IsWindowsOrAtLeastLibgdiplus6)] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(0, 1)] public void AddArc_ZeroWidthHeight_ThrowsArgumentException(int width, int height) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1, 1, width, height, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1.0f, 1.0f, (float)width, (float)height, Pi4, Pi4)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_Points_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddBezier(new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4)); // AssertBezier() method expects added Bezier with points (1, 1), (2, 2), (3, 3), (4, 4), here and below. AssertBezier(gpi); gpf.AddBezier(new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4)); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_SamePoints_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)); Assert.Equal(4, gp.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3 }, gp.PathTypes); gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0)); Assert.Equal(7, gp.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gp.PathTypes); gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3 }, gpf.PathTypes); gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0)); Assert.Equal(7, gpf.PointCount); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBezier_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddBezier(1, 1, 2, 2, 3, 3, 4, 4); AssertBezier(gpi); gpf.AddBezier(1f, 1f, 2f, 2f, 3f, 3f, 4f, 4f); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBeziers_Points_Success() { PointF[] points = new PointF[] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4) }; using (GraphicsPath gpf = new GraphicsPath()) { gpf.AddBeziers(points); AssertBezier(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddBeziers_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((Point[])null)); } } public static IEnumerable<object[]> AddBeziers_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; yield return new object[] { new PointF[3] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddBeziers_InvalidFloatPointsLength_TestData))] public void AddBeziers_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddBeziers(points)); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_TwoPoints_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpf.AddCurve(floatPoints); // AssertCurve() method expects added Curve with points (1, 1), (2, 2), here and below. AssertCurve(gpf); gpi.AddCurve(intPoints); AssertCurve(gpi); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_TwoPointsWithTension_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints, 0.5f); AssertCurve(gpi); gpf.AddCurve(floatPoints, 0.5f); AssertCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_SamePoints_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(1, 1) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(1, 1) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints); Assert.Equal(4, gpi.PointCount); gpi.AddCurve(intPoints); Assert.Equal(7, gpi.PointCount); gpf.AddCurve(floatPoints); Assert.Equal(4, gpf.PointCount); gpf.AddCurve(floatPoints); Assert.Equal(7, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_LargeTension_Success() { Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) }; PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddCurve(intPoints, float.MaxValue); Assert.Equal(4, gpi.PointCount); gpf.AddCurve(floatPoints, float.MaxValue); Assert.Equal(4, gpf.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_Success() { PointF[] points = new PointF[] { new PointF (37f, 185f), new PointF (99f, 185f), new PointF (161f, 159f), new PointF (223f, 185f), new PointF (285f, 54f), }; PointF[] expectedPoints = new PointF[] { new PointF (37f, 185f), new PointF (47.33333f, 185f), new PointF (78.3333f, 189.3333f), new PointF (99f, 185f), new PointF (119.6667f, 180.6667f), new PointF (140.3333f, 159f), new PointF (161f, 159f), new PointF (181.6667f, 159f), new PointF (202.3333f, 202.5f), new PointF (223f, 185f), new PointF (243.6667f, 167.5f), new PointF (274.6667f, 75.8333f), new PointF (285f, 54f), }; byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; int[] pointsCount = { 4, 7, 10, 13 }; using (GraphicsPath gp = new GraphicsPath()) { for (int i = 0; i < points.Length - 1; i++) { gp.AddCurve(points, i, 1, 0.5f); Assert.Equal(pointsCount[i], gp.PointCount); } AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta); Assert.Equal(expectedTypes, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((Point[])null)); } } public static IEnumerable<object[]> AddCurve_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidFloatPointsLength_TestData))] public void AddCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f)); } } public static IEnumerable<object[]> AddCurve_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))] public void AddCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f)); } } public static IEnumerable<object[]> AddCurve_InvalidSegment_TestData() { yield return new object[] { 0 }; yield return new object[] { -1 }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidSegment_TestData))] public void AddCurve_InvalidSegment_ThrowsArgumentException(int segment) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) }, 0, segment, 0.5f)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new Point[2] { new Point(1, 1), new Point(2, 2) }, 0, segment, 0.5f)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddCurve_OffsetTooLarge_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new PointF[3] { new PointF(1f, 1f), new PointF(0f, 20f), new PointF(20f, 0f) }, 1, 2, 0.5f)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve( new Point[3] { new Point(1, 1), new Point(0, 20), new Point(20, 0) }, 1, 2, 0.5f)); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_Points_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); // AssertClosedCurve() method expects added ClosedCurve with points (1, 1), (2, 2), (3, 3), here and below. AssertClosedCurve(gpi); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); AssertClosedCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) }); Assert.Equal(10, gpi.PointCount); gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) }); Assert.Equal(20, gpi.PointCount); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) }); Assert.Equal(10, gpf.PointCount); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) }); Assert.Equal(20, gpf.PointCount); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_Tension_Success() { if (PlatformDetection.IsArmOrArm64Process) { //ActiveIssue: 35744 throw new SkipTestException("Precision on float numbers"); } using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }, 0.5f); AssertClosedCurve(gpi); gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }, 0.5f); AssertClosedCurve(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddClosedCurve_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((PointF[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((Point[])null)); } } public static IEnumerable<object[]> AddClosedCurve_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))] public void AddClosedCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points)); } } public static IEnumerable<object[]> AddClosedCurve_InvalidFloatPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddClosedCurve_InvalidFloatPointsLength_TestData))] public void AddClosedCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 1, 2, 2)); // AssertRectangle() method expects added Rectangle with parameters x=1, y=1, width=2, height=2, here and below. AssertRectangle(gpi); gpf.AddRectangle(new RectangleF(1, 1, 2, 2)); AssertRectangle(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangle_SameRectangles_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 1, 1, 1)); Assert.Equal(4, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpi.PathTypes); PointF endI = gpi.PathPoints[3]; gpi.AddRectangle(new Rectangle((int)endI.X, (int)endI.Y, 1, 1)); Assert.Equal(8, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpi.PathTypes); gpf.AddRectangle(new RectangleF(1, 1, 1, 1)); Assert.Equal(4, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpf.PathTypes); Assert.Equal(129, gpf.PathTypes[3]); PointF endF = gpf.PathPoints[3]; gpf.AddRectangle(new RectangleF(endF.X, endF.Y, 1, 1)); Assert.Equal(8, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpf.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(3, 0)] [InlineData(0, 4)] public void AddRectangle_ZeroWidthHeight_Success(int width, int height) { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangle(new Rectangle(1, 2, width, height)); Assert.Equal(0, gpi.PathData.Points.Length); gpf.AddRectangle(new RectangleF(1f, 2f, (float)width, (float)height)); Assert.Equal(0, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_Success() { Rectangle[] rectInt = new Rectangle[] { new Rectangle(1, 1, 2, 2), new Rectangle(3, 3, 4, 4) }; RectangleF[] rectFloat = new RectangleF[] { new RectangleF(1, 1, 2, 2), new RectangleF(3, 3, 4, 4) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangles(rectInt); Assert.Equal(8, gpi.PathPoints.Length); Assert.Equal(8, gpi.PathTypes.Length); Assert.Equal(8, gpi.PathData.Points.Length); gpf.AddRectangles(rectFloat); Assert.Equal(8, gpf.PathPoints.Length); Assert.Equal(8, gpf.PathTypes.Length); Assert.Equal(8, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_SamePoints_Success() { Rectangle[] rectInt = new Rectangle[] { new Rectangle(1, 1, 0, 0), new Rectangle(1, 1, 2, 2), new Rectangle(1, 1, 2, 2) }; RectangleF[] rectFloat = new RectangleF[] { new RectangleF(1, 1, 0f, 0f), new RectangleF(1, 1, 2, 2), new RectangleF(1, 1, 2, 2) }; using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddRectangles(rectInt); Assert.Equal(8, gpi.PathPoints.Length); Assert.Equal(8, gpi.PathTypes.Length); Assert.Equal(8, gpi.PathData.Points.Length); gpf.AddRectangles(rectFloat); Assert.Equal(8, gpf.PathPoints.Length); Assert.Equal(8, gpf.PathTypes.Length); Assert.Equal(8, gpf.PathData.Points.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddRectangles_RectangleNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((RectangleF[])null)); AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((Rectangle[])null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddEllipse_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(new Rectangle(1, 1, 2, 2)); // AssertEllipse() method expects added Ellipse with parameters x=1, y=1, width=2, height=2, here and below. AssertEllipse(gpi); gpf.AddEllipse(new RectangleF(1, 1, 2, 2)); AssertEllipse(gpf); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddEllipse_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(1, 1, 2, 2); AssertEllipse(gpi); gpf.AddEllipse(1f, 1f, 2f, 2f); AssertEllipse(gpf); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0, 0)] [InlineData(2, 0)] [InlineData(0, 2)] public void AddEllipse_ZeroWidthHeight_Success(int width, int height) { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddEllipse(1, 1, width, height); Assert.Equal(13, gpi.PathData.Points.Length); gpf.AddEllipse(1f, 2f, (float)width, (float)height); Assert.Equal(13, gpf.PathData.Points.Length); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPie_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) { gpi.AddPie(new Rectangle(1, 1, 2, 2), Pi4, Pi4); // AssertPie() method expects added Pie with parameters // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below. AssertPie(gpi); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPie_Values_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPie(1, 1, 2, 2, Pi4, Pi4); AssertPie(gpi); gpf.AddPie(1f, 1f, 2f, 2f, Pi4, Pi4); AssertPie(gpf); } } [ConditionalTheory(Helpers.IsWindowsOrAtLeastLibgdiplus6)] [InlineData(0, 0)] [InlineData(2, 0)] [InlineData(0, 2)] public void AddPie_ZeroWidthHeight_ThrowsArgumentException(int width, int height) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1, 1, height, width, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1f, 1f, height, width, Pi4, Pi4)); AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(new Rectangle(1, 1, height, width), Pi4, Pi4)); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_Points_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); // AssertPolygon() method expects added Polygon with points (1, 1), (2, 2), (3, 3), here and below. AssertPolygon(gpi); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); AssertPolygon(gpf); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_SamePoints_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(3, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(6, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(9, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); Assert.Equal(12, gpi.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(3, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(6, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(9, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }); Assert.Equal(12, gpf.PointCount); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPolygon_PointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((Point[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((PointF[])null)); } } public static IEnumerable<object[]> AddPolygon_InvalidFloadPointsLength_TestData() { yield return new object[] { new PointF[0] }; yield return new object[] { new PointF[1] { new PointF(1f, 1f) } }; yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddPolygon_InvalidFloadPointsLength_TestData))] public void AddPolygon_InvalidFloadPointsLength_ThrowsArgumentException(PointF[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points)); } } public static IEnumerable<object[]> AddPolygon_InvalidPointsLength_TestData() { yield return new object[] { new Point[0] }; yield return new object[] { new Point[1] { new Point(1, 1) } }; yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(AddPolygon_InvalidPointsLength_TestData))] public void AddPolygon_InvalidPointsLength_ThrowsArgumentException(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPath_Success() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath gp = new GraphicsPath()) { inner.AddRectangle(new Rectangle(1, 1, 2, 2)); gp.AddPath(inner, true); AssertRectangle(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddPath_PathNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("addingPath", () => new GraphicsPath().AddPath(null, false)); } } [ConditionalFact(Helpers.IsWindowsOrAtLeastLibgdiplus6)] public void AddString_Point_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); } } [ConditionalFact(Helpers.IsWindowsOrAtLeastLibgdiplus6)] public void AddString_Rectangle_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); } } [ConditionalFact(Helpers.IsWindowsOrAtLeastLibgdiplus6)] public void AddString_NegativeSize_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Point(10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, 0); int gpiLenghtOld = gpi.PathPoints.Length; gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpi.PointCount, gpiLenghtOld); gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new PointF(10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, 0); int pgfLenghtOld = gpf.PathPoints.Length; gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); AssertExtensions.GreaterThan(gpf.PointCount, pgfLenghtOld); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_StringFormat_Success() { using (GraphicsPath gp1 = new GraphicsPath()) using (GraphicsPath gp2 = new GraphicsPath()) using (GraphicsPath gp3 = new GraphicsPath()) { gp1.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), null); AssertExtensions.GreaterThan(gp1.PointCount, 0); gp2.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault); Assert.Equal(gp1.PointCount, gp2.PointCount); gp3.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericTypographic); Assert.NotEqual(gp1.PointCount, gp3.PointCount); } } [ConditionalFact(Helpers.IsWindowsOrAtLeastLibgdiplus6)] public void AddString_EmptyString_Success() { using (GraphicsPath gpi = new GraphicsPath()) using (GraphicsPath gpf = new GraphicsPath()) { gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); Assert.Equal(0, gpi.PointCount); gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault); Assert.Equal(0, gpf.PointCount); } } [ConditionalFact(Helpers.IsWindowsOrAtLeastLibgdiplus6)] public void AddString_StringNull_ThrowsNullReferenceException() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault)); Assert.Throws<NullReferenceException>(() => gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void AddString_FontFamilyNull_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddString("mono", null, 0, 10, new Point(10, 10), StringFormat.GenericDefault)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f)) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); AssertRectangle(gp); gp.Transform(matrix); Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements); Assert.Equal(new RectangleF(6f, 6f, 6f, 6f), gp.GetBounds()); Assert.Equal(new PointF[] { new PointF(6f, 6f), new PointF(8f, 8f), new PointF(12f, 12f), new PointF(10f, 10f) }, gp.PathPoints); Assert.Equal(new byte[] { 0, 1, 1, 129 }, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_PathEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f)) { gp.Transform(matrix); Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements); AssertEmptyGrahicsPath(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_MatrixNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("matrix", () => gp.Transform(null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_PathEmpty_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) { Assert.Equal(new RectangleF(0f, 0f, 0f, 0f), gp.GetBounds()); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_Rectangle_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { RectangleF rectangle = new RectangleF(1f, 1f, 2f, 2f); gp.AddRectangle(rectangle); Assert.Equal(rectangle, gp.GetBounds()); Assert.Equal(rectangle, gp.GetBounds(null)); Assert.Equal(rectangle, gp.GetBounds(matrix)); Assert.Equal(rectangle, gp.GetBounds(null, null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void GetBounds_Pie_ReturnsExpected() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { Rectangle rectangle = new Rectangle(10, 10, 100, 100); gp.AddPie(rectangle, 30, 45); AssertRectangleEqual(new RectangleF(60f, 60f, 43.3f, 48.3f), gp.GetBounds(), 0.1f); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Empty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_MatrixNull_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(null); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_MatrixNullFloat_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.Flatten(null, 1f); Assert.Equal(gp.PointCount, clone.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Arc_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddArc(0f, 0f, 100f, 100f, 30, 30); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Bezier_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddBezier(0, 0, 100, 100, 30, 30, 60, 60); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_ClosedCurve_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddClosedCurve(new Point[4] { new Point (0, 0), new Point (40, 20), new Point (20, 40), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Curve_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddCurve(new Point[4] { new Point (0, 0), new Point (40, 20), new Point (20, 40), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Ellipse_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddEllipse(10f, 10f, 100f, 100f); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Line_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddLine(10f, 10f, 100f, 100f); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Pie_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddPie(0, 0, 100, 100, 30, 30); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Polygon_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddPolygon(new Point[4] { new Point (0, 0), new Point (10, 10), new Point (20, 20), new Point (40, 40) }); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Flatten_Rectangle_Success() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone())) { gp.AddRectangle(new Rectangle(0, 0, 100, 100)); gp.Flatten(); AssertFlats(gp, clone); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_DestinationPointsNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("destPoints", () => gp.Warp(null, new RectangleF())); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_DestinationPointsZero_ThrowsArgumentException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().Warp(new PointF[0], new RectangleF())); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_PathEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { Assert.Equal(0, gp.PointCount); gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix); Assert.Equal(0, gp.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_WarpModeInvalid_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Matrix matrix = new Matrix()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix, (WarpMode)int.MinValue); Assert.Equal(0, gp.PointCount); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Warp_RectangleEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Warp(new PointF[1] { new PointF(0, 0) }, new Rectangle(), null); AssertWrapNaN(gp); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetMarkers_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.SetMarkers(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetMarkers_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.SetMarkers(); Assert.Equal(33, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ClearMarkers_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.SetMarkers(); Assert.Equal(33, gp.PathTypes[1]); gp.ClearMarkers(); Assert.Equal(1, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ClearMarkers_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.ClearMarkers(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseFigure_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); Assert.Equal(1, gp.PathTypes[1]); gp.CloseFigure(); Assert.Equal(129, gp.PathTypes[1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseFigure_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.CloseFigure(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseAllFigures_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(new Point(1, 1), new Point(2, 2)); gp.StartFigure(); gp.AddLine(new Point(3, 3), new Point(4, 4)); Assert.Equal(1, gp.PathTypes[1]); Assert.Equal(1, gp.PathTypes[3]); gp.CloseAllFigures(); Assert.Equal(129, gp.PathTypes[1]); Assert.Equal(129, gp.PathTypes[3]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CloseAllFigures_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) { gp.CloseAllFigures(); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddArc() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddArc(10, 10, 100, 100, 90, 180); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddBezier() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddBezier(10, 10, 100, 100, 20, 20, 200, 200); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddBeziers() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddBeziers(new Point[7] { new Point (10, 10), new Point (20, 10), new Point (20, 20), new Point (30, 20), new Point (40, 40), new Point (50, 40), new Point (50, 50) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddClosedCurve() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(131, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddCurve() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddEllipse() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddEllipse(10, 10, 100, 100); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(131, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddLine() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddLine(5, 5, 10, 10); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(1, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddLines() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddLines(new Point[4] { new Point(10, 10), new Point(20, 10), new Point(20, 20), new Point(30, 20) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(1, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPath_Connect() { using (GraphicsPath gp = new GraphicsPath()) using (GraphicsPath inner = new GraphicsPath()) { inner.AddArc(10, 10, 100, 100, 90, 180); gp.AddLine(1, 1, 2, 2); gp.AddPath(inner, true); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(1, types[2]); Assert.Equal(3, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPath_NoConnect() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath path = new GraphicsPath()) { inner.AddArc(10, 10, 100, 100, 90, 180); path.AddLine(1, 1, 2, 2); path.AddPath(inner, false); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(3, types[path.PointCount - 3]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPie() { using (GraphicsPath path = new GraphicsPath()) { path.AddLine(1, 1, 2, 2); path.AddPie(10, 10, 10, 10, 90, 180); path.AddLine(10, 10, 20, 20); byte[] types = path.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(128, (types[path.PointCount - 3] & 128)); Assert.Equal(0, types[path.PointCount - 2]); Assert.Equal(1, types[path.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddPolygon() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddRectangle() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddRectangle(new RectangleF(10, 10, 20, 20)); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddRectangles() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddRectangles(new RectangleF[2] { new RectangleF (10, 10, 20, 20), new RectangleF (20, 20, 10, 10) }); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(129, types[gp.PointCount - 3]); Assert.Equal(0, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void StartClose_AddString() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 1, 2, 2); gp.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(20, 20), StringFormat.GenericDefault); gp.AddLine(10, 10, 20, 20); byte[] types = gp.PathTypes; Assert.Equal(0, types[0]); Assert.Equal(0, types[2]); Assert.Equal(163, types[gp.PointCount - 3]); Assert.Equal(1, types[gp.PointCount - 2]); Assert.Equal(1, types[gp.PointCount - 1]); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_Pen_Success() { PointF[] expectedPoints = new PointF[] { new PointF(0.5f, 0.5f), new PointF(3.5f, 0.5f), new PointF(3.5f, 3.5f), new PointF(0.5f, 3.5f), new PointF(1.5f, 3.0f), new PointF(1.0f, 2.5f), new PointF(3.0f, 2.5f), new PointF(2.5f, 3.0f), new PointF(2.5f, 1.0f), new PointF(3.0f, 1.5f), new PointF(1.0f, 1.5f), new PointF(1.5f, 1.0f), }; byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 1, 1, 1, 1, 1, 1, 129 }; using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { gp.AddRectangle(new Rectangle(1, 1, 2, 2)); Assert.Equal(4, gp.PointCount); gp.Widen(pen); Assert.Equal(12, gp.PointCount); AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta); Assert.Equal(expectedTypes, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_EmptyPath_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { Assert.Equal(0, gp.PointCount); gp.Widen(pen); Assert.Equal(0, gp.PointCount); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_PenNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix())); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix(), 0.67f)); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_MatrixNull_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Widen(pen, null); Assert.Equal(9, gp.PointCount); AssertWiden3(gp); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Widen_MatrixEmpty_Success() { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Blue)) using (Matrix matrix = new Matrix()) { gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) }); gp.Widen(pen, new Matrix()); Assert.Equal(9, gp.PointCount); AssertWiden3(gp); } } public static IEnumerable<object[]> Widen_PenSmallWidth_TestData() { yield return new object[] { new Rectangle(1, 1, 2, 2), 0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 0.5f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 1.0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) }; yield return new object[] { new Rectangle(1, 1, 2, 2), 1.1f, new RectangleF(0.45f, 0.45f, 3.10f, 3.10f) }; } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Widen_PenSmallWidth_TestData))] public void Widen_Pen_SmallWidth_Succes( Rectangle rectangle, float penWidth, RectangleF expectedBounds) { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Aqua, 0)) using (Matrix matrix = new Matrix()) { pen.Width = penWidth; gp.AddRectangle(rectangle); gp.Widen(pen); AssertRectangleEqual(expectedBounds, gp.GetBounds(null), Delta); AssertRectangleEqual(expectedBounds, gp.GetBounds(matrix), Delta); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_PenNull_ThrowsArgumentNullException() { using (GraphicsPath gp = new GraphicsPath()) { AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1, 1, null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1.0f, 1.0f, null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new Point(), null)); AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new PointF(), null)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithoutGraphics_ReturnsExpected() { AssertIsOutlineVisibleLine(null); } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineInsideGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineOutsideGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(5, 5)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsTransform_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) using (Matrix matrix = new Matrix(2, 0, 0, 2, 50, -50)) { graphics.Transform = matrix; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsPageUnit_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.PageUnit = GraphicsUnit.Millimeter; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_LineWithGraphicsPageScale_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(20, 20)) using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.PageScale = 2.0f; AssertIsOutlineVisibleLine(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsOutlineVisible_RectangleWithoutGraphics_ReturnsExpected() { AssertIsOutlineVisibleRectangle(null); } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_RectangleWithoutGraphics_ReturnsExpected() { AssertIsVisibleRectangle(null); } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_RectangleWithGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(40, 40)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsVisibleRectangle(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_EllipseWithoutGraphics_ReturnsExpected() { AssertIsVisibleEllipse(null); } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsVisible_EllipseWithGraphics_ReturnsExpected() { using (Bitmap bitmap = new Bitmap(40, 40)) using (Graphics graphics = Graphics.FromImage(bitmap)) { AssertIsVisibleEllipse(graphics); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Arc_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Bezier_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddBezier(1, 2, 3, 4, 5, 6, 7, 8); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } public static IEnumerable<object[]> Reverse_TestData() { yield return new object[] { new Point[] { new Point (1,2), new Point (3,4), new Point (5,6), new Point (7,8), new Point (9,10), new Point (11,12), new Point (13,14) } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Beziers_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddBeziers(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_ClosedCurve_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddClosedCurve(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Curve_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddCurve(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Ellipse_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(1, 2, 3, 4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Line_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 2, 3, 4); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_LineClosed_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(1, 2, 3, 4); gp.CloseFigure(); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Lines_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLines(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Reverse_TestData))] public void Reverse_Polygon_Succes(Point[] points) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPolygon(points); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Rectangle_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(1, 2, 3, 4)); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Rectangles_Succes() { using (GraphicsPath gp = new GraphicsPath()) { Rectangle[] rects = new Rectangle[] { new Rectangle(1, 2, 3, 4), new Rectangle(5, 6, 7, 8) }; gp.AddRectangles(rects); AssertReverse(gp, gp.PathPoints, gp.PathTypes); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Pie_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddPie(1, 2, 3, 4, 10, 20); byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_ArcLineInnerPath_Succes() { using (GraphicsPath inner = new GraphicsPath()) using (GraphicsPath gp = new GraphicsPath()) { inner.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4); inner.AddLine(1, 2, 3, 4); byte[] expectedTypes = new byte[] { 0, 1, 1, 3, 3, 3 }; gp.AddPath(inner, true); AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_EllipseRectangle_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(50, 51, 50, 100); gp.AddRectangle(new Rectangle(200, 201, 60, 61)); byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/20884", TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_String_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddString("Mono::", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault); byte[] expectedTypes = new byte[] { 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129, 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161, 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,131,0,3, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,163,0,3,3,3, 3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3, 3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3, 3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3, 3,3,3,3,3,3,3,3,3,3,3,161,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3,3,131,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,163,0,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3, 3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1, 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3, 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_Marker_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(200, 201, 60, 61)); gp.SetMarkers(); byte[] expectedTypes = new byte[] { 0, 1, 1, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Reverse_SubpathMarker_Succes() { using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(0, 1, 2, 3); gp.SetMarkers(); gp.CloseFigure(); gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12); gp.CloseFigure(); byte[] expectedTypes = new byte[] { 0, 3, 3, 163, 0, 129 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } using (GraphicsPath gp = new GraphicsPath()) { gp.AddLine(0, 1, 2, 3); gp.SetMarkers(); gp.StartFigure(); gp.AddLine(20, 21, 22, 23); gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12); byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 1, 33, 0, 1 }; AssertReverse(gp, gp.PathPoints, expectedTypes); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PointsTypes_Succes() { int dX = 520; int dY = 320; Point[] expectedPoints = new Point[] { new Point(dX-64, dY-24), new Point(dX-59, dY-34), new Point(dX-52, dY-54), new Point(dX-18, dY-66), new Point(dX-34, dY-47), new Point(dX-43, dY-27), new Point(dX-44, dY-8), }; byte[] expectedTypes = new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier }; using (GraphicsPath path = new GraphicsPath(expectedPoints, expectedTypes)) { Assert.Equal(7, path.PointCount); byte[] actualTypes = path.PathTypes; Assert.Equal(expectedTypes, actualTypes); } } private void AssertEmptyGrahicsPath(GraphicsPath gp) { Assert.Equal(0, gp.PathData.Points.Length); Assert.Equal(0, gp.PathData.Types.Length); Assert.Equal(0, gp.PointCount); } private void AssertEqual(float expexted, float actual, float tollerance) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expexted - actual), tollerance); } private void AssertLine(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f) }; Assert.Equal(2, path.PathPoints.Length); Assert.Equal(2, path.PathTypes.Length); Assert.Equal(2, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1 }, path.PathTypes); } private void AssertArc(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(2.99990582f, 2.01370716f), new PointF(2.99984312f, 2.018276f), new PointF(2.99974918f, 2.02284455f), new PointF(2.999624f, 2.027412f), }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(2.99962401f, 2.01370716f, 0f, 0.0137047768f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertBezier(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f), new PointF(4f, 4f), }; Assert.Equal(4, path.PointCount); Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 3f, 3f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertCurve(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(1.16666663f, 1.16666663f), new PointF(1.83333325f, 1.83333325f), new PointF(2f, 2f) }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds()); AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta); Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes); } private void AssertClosedCurve(GraphicsPath path) { Assert.Equal(10, path.PathPoints.Length); Assert.Equal(10, path.PathTypes.Length); Assert.Equal(10, path.PathData.Points.Length); Assert.Equal(new RectangleF(0.8333333f, 0.8333333f, 2.33333278f, 2.33333278f), path.GetBounds()); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes); } private void AssertRectangle(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(3f, 1f), new PointF(3f, 3f), new PointF(1f, 3f) }; Assert.Equal(4, path.PathPoints.Length); Assert.Equal(4, path.PathTypes.Length); Assert.Equal(4, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1, 1, 129 }, path.PathTypes); } private void AssertEllipse(GraphicsPath path) { Assert.Equal(13, path.PathPoints.Length); Assert.Equal(13, path.PathTypes.Length); Assert.Equal(13, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes); } private void AssertPie(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(2f, 2f), new PointF(2.99990582f, 2.01370716f), new PointF(2.99984312f, 2.018276f), new PointF(2.99974918f, 2.02284455f), new PointF(2.999624f, 2.027412f) }; Assert.Equal(5, path.PathPoints.Length); Assert.Equal(5, path.PathTypes.Length); Assert.Equal(5, path.PathData.Points.Length); AssertRectangleEqual(new RectangleF(2f, 2f, 0.9999058f, 0.0274119377f), path.GetBounds(), Delta); AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta); Assert.Equal(new byte[] { 0, 1, 3, 3, 131 }, path.PathTypes); } private void AssertPolygon(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f) }; Assert.Equal(3, path.PathPoints.Length); Assert.Equal(3, path.PathTypes.Length); Assert.Equal(3, path.PathData.Points.Length); Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds()); Assert.Equal(expectedPoints, path.PathPoints); Assert.Equal(new byte[] { 0, 1, 129 }, path.PathTypes); } private void AssertFlats(GraphicsPath flat, GraphicsPath original) { AssertExtensions.GreaterThanOrEqualTo(flat.PointCount, original.PointCount); for (int i = 0; i < flat.PointCount; i++) { Assert.NotEqual(3, flat.PathTypes[i]); } } private void AssertWrapNaN(GraphicsPath path) { byte[] expectedTypes = new byte[] { 0, 1, 129 }; Assert.Equal(3, path.PointCount); Assert.Equal(float.NaN, path.PathPoints[0].X); Assert.Equal(float.NaN, path.PathPoints[0].Y); Assert.Equal(float.NaN, path.PathPoints[1].X); Assert.Equal(float.NaN, path.PathPoints[1].Y); Assert.Equal(float.NaN, path.PathPoints[2].X); Assert.Equal(float.NaN, path.PathPoints[2].Y); Assert.Equal(expectedTypes, path.PathTypes); } private void AssertWiden3(GraphicsPath path) { PointF[] expectedPoints = new PointF[] { new PointF(4.2f, 4.5f), new PointF(15.8f, 4.5f), new PointF(10.0f, 16.1f), new PointF(10.4f, 14.8f), new PointF(9.6f, 14.8f), new PointF(14.6f, 4.8f), new PointF(15.0f, 5.5f), new PointF(5.0f, 5.5f), new PointF(5.4f, 4.8f) }; AssertPointsSequenceEqual(expectedPoints, path.PathPoints, 0.25f); Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 1, 1, 1, 129 }, path.PathTypes); } private void AssertIsOutlineVisibleLine(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) using (Pen pen = new Pen(Color.Red, 3.0f)) { gp.AddLine(10, 1, 14, 1); Assert.True(gp.IsOutlineVisible(10, 1, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(10, 2, pen, graphics)); Assert.False(gp.IsOutlineVisible(10, 2, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, pen, graphics)); Assert.False(gp.IsOutlineVisible(11.0f, 2.0f, Pens.Red, graphics)); Point point = new Point(12, 2); Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(point, pen, graphics)); point.Y = 1; Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics)); PointF fPoint = new PointF(13.0f, 2.0f); Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); fPoint.Y = 1; Assert.True(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); } } private void AssertIsOutlineVisibleRectangle(Graphics graphics) { using (Pen pen = new Pen(Color.Red, 3.0f)) using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(10, 10, 20, 20)); Assert.True(gp.IsOutlineVisible(10, 10, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(10, 11, pen, graphics)); Assert.False(gp.IsOutlineVisible(11, 11, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 10.0f, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(11.0f, 11.0f, pen, graphics)); Assert.False(gp.IsOutlineVisible(11.0f, 11.0f, Pens.Red, graphics)); Point point = new Point(15, 10); Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(point, pen, graphics)); point.Y = 15; Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics)); PointF fPoint = new PointF(29.0f, 29.0f); Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics)); Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); fPoint.Y = 31.0f; Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics)); } } private void AssertIsVisibleRectangle(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddRectangle(new Rectangle(10, 10, 20, 20)); Assert.False(gp.IsVisible(9, 9, graphics)); Assert.True(gp.IsVisible(10, 10, graphics)); Assert.True(gp.IsVisible(20, 20, graphics)); Assert.True(gp.IsVisible(29, 29, graphics)); Assert.False(gp.IsVisible(30, 29, graphics)); Assert.False(gp.IsVisible(29, 30, graphics)); Assert.False(gp.IsVisible(30, 30, graphics)); Assert.False(gp.IsVisible(9.4f, 9.4f, graphics)); Assert.True(gp.IsVisible(9.5f, 9.5f, graphics)); Assert.True(gp.IsVisible(10f, 10f, graphics)); Assert.True(gp.IsVisible(20f, 20f, graphics)); Assert.True(gp.IsVisible(29.4f, 29.4f, graphics)); Assert.False(gp.IsVisible(29.5f, 29.5f, graphics)); Assert.False(gp.IsVisible(29.5f, 29.4f, graphics)); Assert.False(gp.IsVisible(29.4f, 29.5f, graphics)); } } private void AssertIsVisibleEllipse(Graphics graphics) { using (GraphicsPath gp = new GraphicsPath()) { gp.AddEllipse(new Rectangle(10, 10, 20, 20)); Assert.False(gp.IsVisible(10, 10, graphics)); Assert.True(gp.IsVisible(20, 20, graphics)); Assert.False(gp.IsVisible(29, 29, graphics)); Assert.False(gp.IsVisible(10f, 10f, graphics)); Assert.True(gp.IsVisible(20f, 20f, graphics)); Assert.False(gp.IsVisible(29.4f, 29.4f, graphics)); } } private void AssertReverse(GraphicsPath gp, PointF[] expectedPoints, byte[] expectedTypes) { gp.Reverse(); PointF[] reversedPoints = gp.PathPoints; byte[] reversedTypes = gp.PathTypes; int count = gp.PointCount; Assert.Equal(expectedPoints.Length, gp.PointCount); Assert.Equal(expectedTypes, gp.PathTypes); for (int i = 0; i < count; i++) { Assert.Equal(expectedPoints[i], reversedPoints[count - i - 1]); Assert.Equal(expectedTypes[i], reversedTypes[i]); } } private void AssertPointsSequenceEqual(PointF[] expected, PointF[] actual, float tolerance) { int count = expected.Length; Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < count; i++) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].X - actual[i].X), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].Y - actual[i].Y), tolerance); } } private void AssertRectangleEqual(RectangleF expected, RectangleF actual, float tolerance) { AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.X - actual.X), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Y - actual.Y), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Width - actual.Width), tolerance); AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Height - actual.Height), tolerance); } } }
40.334795
145
0.544293
[ "MIT" ]
Drawaes/runtime
src/libraries/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs
110,356
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Swashbuckle.AspNetCore.Annotations; using Nmro.Security.IAM.Core.UseCases.Users.Queries; using Nmro.Security.IAM.Core.UseCases.Users.Commands; using Nmro.Security.IAM.Core.UseCases.Users.Dtos; namespace Nmro.Security.IAM.Faces.API.Controllers { [ApiController] [ApiExplorerSettings(GroupName="iams")] [Route("users")] public class UsersController : NmroControllerBase { private readonly ILogger<UsersController> _logger; public UsersController(ILogger<UsersController> logger) { _logger = logger; } [HttpGet] [SwaggerOperation("Query a bunch of users by name")] public async Task<PageIdentityUserModel> Filter([FromQuery] string email = "", int limit = 50, int offset = 0) => await Mediator.Send(new ListIdentityUsersQuery{Email = email, Limit = limit, Offset = offset}); [HttpGet("{id}")] [SwaggerOperation("Read an user")] public async Task<IdentityUser> GetById(long id) => await Mediator.Send(new GetIdentityUsersQuery{UserId = id}); [HttpPost] [SwaggerOperation("Create new user")] public async Task<int> Create([FromBody] CreatingUserModel user) => await Mediator.Send(new CreateIdentityUserCommand{Model = user}); [HttpPut] [SwaggerOperation("Update a user")] public async Task<int> Update([FromBody] UpdatingUserModel user) => await Mediator.Send(new UpdateIdentityUserCommand{Model = user}); [HttpDelete("{id}")] [SwaggerOperation("Delete a user")] public async Task<int> Delete(int id) => await Mediator.Send(new DeleteIdentityUserCommand{ Id = id }); } }
35.192308
118
0.670492
[ "MIT" ]
TamVoMinh/netmicro
business/security/IAM/Faces/Api/Controllers/UsersController.cs
1,830
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 codeartifact-2018-09-22.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.CodeArtifact { /// <summary> /// Configuration for accessing Amazon CodeArtifact service /// </summary> public partial class AmazonCodeArtifactConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.5.2.29"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonCodeArtifactConfig() { this.AuthenticationServiceName = "codeartifact"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "codeartifact"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-09-22"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.325
110
0.591168
[ "Apache-2.0" ]
rbx-rchall/aws-sdk-net
sdk/src/Services/CodeArtifact/Generated/AmazonCodeArtifactConfig.cs
2,106
C#
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/Beef using NUnit.Framework; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Commands; using System; using System.Diagnostics; namespace Beef.Test.NUnit { /// <summary> /// Sets up the <see cref="ExecutionContext"/> for the likes of an <see cref="AgentTester"/> test execution, as well as performing a <see cref="Factory.ResetLocal"/>. /// </summary> [DebuggerStepThrough()] #pragma warning disable CA1813 // Avoid unsealed attributes; by-design, needs to be inherited from. public class TestSetUpAttribute : PropertyAttribute, IWrapSetUpTearDown, ICommandWrapper #pragma warning restore CA1813 { private readonly string _username; private readonly bool _needsSetUp; private readonly object _args; /// <summary> /// Initializes a new instance of the <see cref="TestSetUpAttribute"/> class for a <paramref name="username"/>. /// </summary> /// <param name="username">The username (<c>null</c> indicates to use the <see cref="AgentTester.DefaultUsername"/>).</param> /// <param name="args">Optional argument that will be passed into the creation of the <see cref="ExecutionContext"/> (via the <see cref="AgentTester.CreateExecutionContext"/> function).</param> /// <param name="needsSetUp">Indicates whether the registered set up is required to be invoked for the test.</param> public TestSetUpAttribute(string username = null, object args = null, bool needsSetUp = true) : base(username ?? AgentTester.DefaultUsername) { _username = username ?? AgentTester.DefaultUsername; _needsSetUp = needsSetUp; _args = args; } /// <summary> /// Initializes a new instance of the <see cref="TestSetUpAttribute"/> class for a <paramref name="userIdentifier"/>. /// </summary> /// <param name="userIdentifier">The user identifier (<c>null</c> indicates to use the <see cref="ExecutionContext.Current"/> <see cref="ExecutionContext.Username"/>).</param> /// <param name="args">Optional argument that will be passed into the creation of the <see cref="ExecutionContext"/> (via the <see cref="AgentTester.CreateExecutionContext"/> function).</param> /// <param name="needsSetUp">Indicates whether the registered set up is required to be invoked for the test.</param> public TestSetUpAttribute(object userIdentifier, object args = null, bool needsSetUp = true) : base(AgentTester.UsernameConverter(userIdentifier) ?? AgentTester.DefaultUsername) { _username = AgentTester.UsernameConverter(userIdentifier) ?? AgentTester.DefaultUsername; _needsSetUp = needsSetUp; _args = args; } /// <summary> /// Wraps a command and returns the result. /// </summary> /// <param name="command">The <see cref="TestCommand"/> to be wrapped.</param> /// <returns>The wrapped <see cref="TestCommand"/>.</returns> public TestCommand Wrap(TestCommand command) { TestSetUp.ShouldContinueRunningTestsAssert(); return new ExecutionContextCommand(command, _username, _needsSetUp, _args); } /// <summary> /// The test command for the <see cref="TestSetUpAttribute"/>. /// </summary> [DebuggerStepThrough()] internal class ExecutionContextCommand : DelegatingTestCommand { private readonly string _username; private readonly bool _needsSetUp; private readonly object _args; /// <summary> /// Initializes a new instance of the <see cref="ExecutionContextCommand"/> class. /// </summary> /// <param name="innerCommand">The inner <see cref="TestCommand"/>.</param> /// <param name="username">The username.</param> /// <param name="needsSetUp">Indicates whether the registered set up is required to be invoked.</param> /// <param name="args">Optional args.</param> public ExecutionContextCommand(TestCommand innerCommand, string username = null, bool needsSetUp = true, object args = null) : base(innerCommand) { _username = username; _needsSetUp = needsSetUp; _args = args; } /// <summary> /// Executes the test, saving a <see cref="TestResult"/> in the supplied <see cref="TestExecutionContext"/>. /// </summary> /// <param name="context">The <see cref="TestExecutionContext"/>.</param> /// <returns>The <see cref="TestResult"/>.</returns> public override TestResult Execute(TestExecutionContext context) { try { if (_needsSetUp) TestSetUp.InvokeRegisteredSetUp(); ExecutionContext.Reset(false); ExecutionContext.SetCurrent(AgentTester.CreateExecutionContext(_username, _args)); ExecutionContext.Current.Properties["InvokeRegisteredSetUp"] = _needsSetUp; context.CurrentResult = this.innerCommand.Execute(context); } #pragma warning disable CA1031 // Do not catch general exception types; by-design, need to catch them all. catch (Exception exception) { Exception ex = exception; if (ex is AggregateException aex && aex.InnerExceptions.Count == 1) ex = aex.InnerException; if (ex is NUnitException nex && nex.InnerException is AggregateException aex2) ex = aex2.InnerException; if (context.CurrentResult == null) context.CurrentResult = context.CurrentTest.MakeTestResult(); context.CurrentResult.RecordException(ex); } #pragma warning restore CA1031 finally { ExecutionContext.Reset(false); Factory.ResetLocal(); } // Remove any extraneous assertion results as this clutters/confuses the output. for (int i = context.CurrentResult.AssertionResults.Count - 1; i > 0; i--) { context.CurrentResult.AssertionResults.RemoveAt(i); } return context.CurrentResult; } } } }
49.348148
201
0.613329
[ "MIT" ]
vishal-sharma/Beef
tools/Beef.Test.NUnit/TestSetUpAttribute.cs
6,664
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. namespace EdFi.Ods.Admin.Services { public interface IRouteService { string GetRouteForPasswordReset(string marker); string GetRouteForActivation(string marker); } }
31.133333
86
0.736617
[ "Apache-2.0" ]
gmcelhanon/Ed-Fi-ODS-1
Application/EdFi.Ods.Admin/Services/IRouteService.cs
469
C#
using System; namespace ExampleWebSite.Manage { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) {} } }
21.625
58
0.716763
[ "BSD-2-Clause" ]
Letractively/securityswitch
ExampleWebSite/Manage/Default.aspx.cs
175
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using UnityEngine; using UnityEngine.VFX; namespace UnityEditor.VFX { class VFXUniformMapper { public VFXUniformMapper(VFXExpressionMapper mapper, bool filterOutConstants) { m_FilterOutConstants = filterOutConstants; Init(mapper); } private void CollectAndAddUniforms(VFXExpression exp, IEnumerable<string> names, HashSet<VFXExpression> processedExp) { if (!exp.IsAny(VFXExpression.Flags.NotCompilableOnCPU)) { string prefix; Dictionary<VFXExpression, List<string>> expressions; if (VFXExpression.IsUniform(exp.valueType)) { if (m_FilterOutConstants && exp.Is(VFXExpression.Flags.Constant)) // Filter out constant uniform that should be patched directly in shader return; prefix = "uniform_"; expressions = m_UniformToName; } else if (VFXExpression.IsTexture(exp.valueType)) { prefix = "texture_"; expressions = m_TextureToName; } else { if (VFXExpression.IsTypeValidOnGPU(exp.valueType)) { throw new InvalidOperationException(string.Format("Missing handling for type: {0}", exp.valueType)); } return; } List<string> previousNames; expressions.TryGetValue(exp, out previousNames); if (previousNames == null) { previousNames = new List<string>(); expressions[exp] = previousNames; } if (names == null) previousNames.Add(prefix + VFXCodeGeneratorHelper.GeneratePrefix((uint)expressions.Count())); else previousNames.AddRange(names); } else { foreach (var parent in exp.parents) { if (processedExp.Contains(parent)) continue; processedExp.Add(parent); CollectAndAddUniforms(parent, null, processedExp); } } } private void Init(VFXExpressionMapper mapper) { m_UniformToName = new Dictionary<VFXExpression, List<string>>(); m_TextureToName = new Dictionary<VFXExpression, List<string>>(); var processedExp = new HashSet<VFXExpression>(); foreach (var exp in mapper.expressions) { processedExp.Clear(); var initialNames = mapper.GetData(exp).Select(d => d.fullName); CollectAndAddUniforms(exp, initialNames, processedExp); } } public IEnumerable<VFXExpression> uniforms { get { return m_UniformToName.Keys; } } public IEnumerable<VFXExpression> textures { get { return m_TextureToName.Keys; } } // Get only the first name of a uniform (For generated code, we collapse all uniforms using the same expression into a single one) public string GetName(VFXExpression exp) { return VFXExpression.IsTexture(exp.valueType) ? m_TextureToName[exp].First() : m_UniformToName[exp].First(); } public List<string> GetNames(VFXExpression exp) { return VFXExpression.IsTexture(exp.valueType) ? m_TextureToName[exp] : m_UniformToName[exp]; } // This retrieves expression to name with additional type conversion where suitable public Dictionary<VFXExpression, string> expressionToCode { get { return m_UniformToName.Select(s => { string code = null; string firstName = s.Value.First(); switch (s.Key.valueType) { case VFXValueType.Int32: code = "asint(" + firstName + ")"; break; case VFXValueType.Uint32: code = "asuint(" + firstName + ")"; break; case VFXValueType.Boolean: code = "(bool)asuint(" + firstName + ")"; break; default: code = firstName; break; } return new KeyValuePair<VFXExpression, string>(s.Key, code); }).Union(m_TextureToName.Select(s => new KeyValuePair<VFXExpression, string>(s.Key, s.Value.First()))).ToDictionary(s => s.Key, s => s.Value); } } private Dictionary<VFXExpression, List<string>> m_UniformToName; private Dictionary<VFXExpression, List<string>> m_TextureToName; private bool m_FilterOutConstants; } }
40.792308
169
0.517254
[ "MIT" ]
jannabel/Galushi-vs-Balloons
Library/PackageCache/com.unity.visualeffectgraph@7.1.8/Editor/Compiler/VFXUniformMapper.cs
5,303
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// Container for the parameters to the CreateProxySession operation. /// /// </summary> public partial class CreateProxySessionRequest : AmazonChimeRequest { private List<string> _capabilities = new List<string>(); private int? _expiryMinutes; private GeoMatchLevel _geoMatchLevel; private GeoMatchParams _geoMatchParams; private string _name; private NumberSelectionBehavior _numberSelectionBehavior; private List<string> _participantPhoneNumbers = new List<string>(); private string _voiceConnectorId; /// <summary> /// Gets and sets the property Capabilities. /// </summary> [AWSProperty(Required=true)] public List<string> Capabilities { get { return this._capabilities; } set { this._capabilities = value; } } // Check to see if Capabilities property is set internal bool IsSetCapabilities() { return this._capabilities != null && this._capabilities.Count > 0; } /// <summary> /// Gets and sets the property ExpiryMinutes. /// </summary> [AWSProperty(Min=1)] public int ExpiryMinutes { get { return this._expiryMinutes.GetValueOrDefault(); } set { this._expiryMinutes = value; } } // Check to see if ExpiryMinutes property is set internal bool IsSetExpiryMinutes() { return this._expiryMinutes.HasValue; } /// <summary> /// Gets and sets the property GeoMatchLevel. /// </summary> public GeoMatchLevel GeoMatchLevel { get { return this._geoMatchLevel; } set { this._geoMatchLevel = value; } } // Check to see if GeoMatchLevel property is set internal bool IsSetGeoMatchLevel() { return this._geoMatchLevel != null; } /// <summary> /// Gets and sets the property GeoMatchParams. /// </summary> public GeoMatchParams GeoMatchParams { get { return this._geoMatchParams; } set { this._geoMatchParams = value; } } // Check to see if GeoMatchParams property is set internal bool IsSetGeoMatchParams() { return this._geoMatchParams != null; } /// <summary> /// Gets and sets the property Name. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NumberSelectionBehavior. /// </summary> public NumberSelectionBehavior NumberSelectionBehavior { get { return this._numberSelectionBehavior; } set { this._numberSelectionBehavior = value; } } // Check to see if NumberSelectionBehavior property is set internal bool IsSetNumberSelectionBehavior() { return this._numberSelectionBehavior != null; } /// <summary> /// Gets and sets the property ParticipantPhoneNumbers. /// </summary> [AWSProperty(Required=true, Min=2, Max=2)] public List<string> ParticipantPhoneNumbers { get { return this._participantPhoneNumbers; } set { this._participantPhoneNumbers = value; } } // Check to see if ParticipantPhoneNumbers property is set internal bool IsSetParticipantPhoneNumbers() { return this._participantPhoneNumbers != null && this._participantPhoneNumbers.Count > 0; } /// <summary> /// Gets and sets the property VoiceConnectorId. /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string VoiceConnectorId { get { return this._voiceConnectorId; } set { this._voiceConnectorId = value; } } // Check to see if VoiceConnectorId property is set internal bool IsSetVoiceConnectorId() { return this._voiceConnectorId != null; } } }
31.188235
103
0.60298
[ "Apache-2.0" ]
playstudios/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/CreateProxySessionRequest.cs
5,302
C#
using System; using System.IO; using Avalonia.Win32.Interop; using SharpDX.WIC; using APixelFormat = Avalonia.Platform.PixelFormat; using AlphaFormat = Avalonia.Platform.AlphaFormat; using D2DBitmap = SharpDX.Direct2D1.Bitmap; namespace Avalonia.Direct2D1.Media { /// <summary> /// A WIC implementation of a <see cref="Avalonia.Media.Imaging.Bitmap"/>. /// </summary> public class WicBitmapImpl : BitmapImpl { private BitmapDecoder _decoder; private static BitmapInterpolationMode ConvertInterpolationMode(Avalonia.Visuals.Media.Imaging.BitmapInterpolationMode interpolationMode) { switch (interpolationMode) { case Visuals.Media.Imaging.BitmapInterpolationMode.Default: return BitmapInterpolationMode.Fant; case Visuals.Media.Imaging.BitmapInterpolationMode.LowQuality: return BitmapInterpolationMode.NearestNeighbor; case Visuals.Media.Imaging.BitmapInterpolationMode.MediumQuality: return BitmapInterpolationMode.Fant; default: case Visuals.Media.Imaging.BitmapInterpolationMode.HighQuality: return BitmapInterpolationMode.HighQualityCubic; } } /// <summary> /// Initializes a new instance of the <see cref="WicBitmapImpl"/> class. /// </summary> /// <param name="fileName">The filename of the bitmap to load.</param> public WicBitmapImpl(string fileName) { using (BitmapDecoder decoder = new BitmapDecoder(Direct2D1Platform.ImagingFactory, fileName, DecodeOptions.CacheOnDemand)) { WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnDemand); Dpi = new Vector(96, 96); } } private WicBitmapImpl(Bitmap bmp) { WicImpl = bmp; Dpi = new Vector(96, 96); } /// <summary> /// Initializes a new instance of the <see cref="WicBitmapImpl"/> class. /// </summary> /// <param name="stream">The stream to read the bitmap from.</param> public WicBitmapImpl(Stream stream) { // https://stackoverflow.com/questions/48982749/decoding-image-from-stream-using-wic/48982889#48982889 _decoder = new BitmapDecoder(Direct2D1Platform.ImagingFactory, stream, DecodeOptions.CacheOnLoad); WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, _decoder.GetFrame(0), BitmapCreateCacheOption.CacheOnLoad); Dpi = new Vector(96, 96); } /// <summary> /// Initializes a new instance of the <see cref="WicBitmapImpl"/> class. /// </summary> /// <param name="size">The size of the bitmap in device pixels.</param> /// <param name="dpi">The DPI of the bitmap.</param> /// <param name="pixelFormat">Pixel format</param> /// <param name="alphaFormat">Alpha format.</param> public WicBitmapImpl(PixelSize size, Vector dpi, APixelFormat? pixelFormat = null, AlphaFormat? alphaFormat = null) { if (!pixelFormat.HasValue) { pixelFormat = APixelFormat.Bgra8888; } if (!alphaFormat.HasValue) { alphaFormat = AlphaFormat.Premul; } PixelFormat = pixelFormat; WicImpl = new Bitmap( Direct2D1Platform.ImagingFactory, size.Width, size.Height, pixelFormat.Value.ToWic(alphaFormat.Value), BitmapCreateCacheOption.CacheOnLoad); Dpi = dpi; } public WicBitmapImpl(APixelFormat format, AlphaFormat alphaFormat, IntPtr data, PixelSize size, Vector dpi, int stride) { WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, size.Width, size.Height, format.ToWic(alphaFormat), BitmapCreateCacheOption.CacheOnDemand); WicImpl.SetResolution(dpi.X, dpi.Y); PixelFormat = format; Dpi = dpi; using (var l = WicImpl.Lock(BitmapLockFlags.Write)) { for (var row = 0; row < size.Height; row++) { UnmanagedMethods.CopyMemory( (l.Data.DataPointer + row * l.Stride), (data + row * stride), (UIntPtr)l.Data.Pitch); } } } public WicBitmapImpl(Stream stream, int decodeSize, bool horizontal, Avalonia.Visuals.Media.Imaging.BitmapInterpolationMode interpolationMode) { _decoder = new BitmapDecoder(Direct2D1Platform.ImagingFactory, stream, DecodeOptions.CacheOnLoad); var frame = _decoder.GetFrame(0); // now scale that to the size that we want var realScale = horizontal ? ((double)frame.Size.Height / frame.Size.Width) : ((double)frame.Size.Width / frame.Size.Height); PixelSize desired; if (horizontal) { desired = new PixelSize(decodeSize, (int)(realScale * decodeSize)); } else { desired = new PixelSize((int)(realScale * decodeSize), decodeSize); } if (frame.Size.Width != desired.Width || frame.Size.Height != desired.Height) { using (var scaler = new BitmapScaler(Direct2D1Platform.ImagingFactory)) { scaler.Initialize(frame, desired.Width, desired.Height, ConvertInterpolationMode(interpolationMode)); WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, scaler, BitmapCreateCacheOption.CacheOnLoad); } } else { WicImpl = new Bitmap(Direct2D1Platform.ImagingFactory, frame, BitmapCreateCacheOption.CacheOnLoad); } Dpi = new Vector(96, 96); } public override Vector Dpi { get; } public override PixelSize PixelSize => WicImpl.Size.ToAvalonia(); protected APixelFormat? PixelFormat { get; } public override void Dispose() { WicImpl.Dispose(); _decoder?.Dispose(); } /// <summary> /// Gets the WIC implementation of the bitmap. /// </summary> public Bitmap WicImpl { get; } /// <summary> /// Gets a Direct2D bitmap to use on the specified render target. /// </summary> /// <param name="renderTarget">The render target.</param> /// <returns>The Direct2D bitmap.</returns> public override OptionalDispose<D2DBitmap> GetDirect2DBitmap(SharpDX.Direct2D1.RenderTarget renderTarget) { FormatConverter converter = new FormatConverter(Direct2D1Platform.ImagingFactory); converter.Initialize(WicImpl, SharpDX.WIC.PixelFormat.Format32bppPBGRA); return new OptionalDispose<D2DBitmap>(D2DBitmap.FromWicBitmap(renderTarget, converter), true); } public override void Save(Stream stream) { using (var encoder = new PngBitmapEncoder(Direct2D1Platform.ImagingFactory, stream)) using (var frame = new BitmapFrameEncode(encoder)) { frame.Initialize(); frame.WriteSource(WicImpl); frame.Commit(); encoder.Commit(); } } } }
38.580808
158
0.592748
[ "MIT" ]
AU-tomata/Avalonia
src/Windows/Avalonia.Direct2D1/Media/Imaging/WicBitmapImpl.cs
7,639
C#
/* Copyright (c) 2019 Mezumona Kosaki Copyright (c) 2019 RyujuOrchestra This software is released under the MIT License. */ #if UNITY_ANDROID using System; using System.IO; using UnityEngine; namespace RyujuEngine.IO { using JavaActivity = IntPtr; using JavaAssetManager = IntPtr; using AAssetManager = IntPtr; using AAsset = IntPtr; /// <summary> /// Android AssetManager. /// </summary> public static class AndroidAssetManager { /// <summary> /// Open an asset stream. /// </summary> /// <param name="path">A relative path from assets directory in apk.</param> /// <returns>A pointer to native AAsset instance.</returns> public static AAsset Open(string path) { if (_assetManager == IntPtr.Zero) { _assetManager = GetAssetManager(); } var asset = NativeMethods.Open(_assetManager, path, AndroidAssetMode.Buffer); if (asset == IntPtr.Zero) { throw new FileNotFoundException("File not found in assets."); } return asset; } private static AAssetManager GetAssetManager() { var javaAssetManager = GetJavaAssetManager(); var assetManagerClass = AndroidJNI.GetObjectClass(javaAssetManager); var mObjectField = AndroidJNI.GetFieldID(assetManagerClass, "mObject", "J"); return (AAssetManager)AndroidJNI.GetLongField(javaAssetManager, mObjectField); } private static JavaAssetManager GetJavaAssetManager() { var activity = GetJavaActivity(); var activityClass = AndroidJNI.GetObjectClass(activity); var getAssetsMethod = AndroidJNI.GetMethodID(activityClass, "getAssets", "()Landroid/content/res/AssetManager;"); return AndroidJNI.CallObjectMethod(activity, getAssetsMethod, Array.Empty<jvalue>()); } private static JavaActivity GetJavaActivity() { var unityPlayerClass = AndroidJNI.FindClass("com/unity3d/player/UnityPlayer"); var currentActivityField = AndroidJNI.GetStaticFieldID(unityPlayerClass, "currentActivity", "Landroid/app/Activity;"); return AndroidJNI.GetStaticObjectField(unityPlayerClass, currentActivityField); } private static AAssetManager _assetManager = IntPtr.Zero; } } #endif
30.128571
121
0.744903
[ "MIT" ]
mezum/RyujuEngine.IO
Runtime/AndroidAssetManager.cs
2,109
C#
using Okta.Xamarin.Demo.ViewModels; using Okta.Xamarin.Demo.Views; using System; using System.Collections.Generic; using Xamarin.Forms; namespace Okta.Xamarin.Demo { public partial class AppShell : Shell { public AppShell() { InitializeComponent(); Routing.RegisterRoute(nameof(ItemDetailPage), typeof(ItemDetailPage)); Routing.RegisterRoute(nameof(NewItemPage), typeof(NewItemPage)); } private async void OnMenuItemClicked(object sender, EventArgs e) { await Shell.Current.GoToAsync("//LoginPage"); } } }
25.708333
82
0.654781
[ "Apache-2.0" ]
kensykora/samples-xamarin
Okta.Xamarin.Demo/AppShell.xaml.cs
619
C#
using System; using System.Data.SqlClient; using System.Reflection; using System.Linq; using System.Collections.Generic; namespace SqlMapper { [ServiceStack.DataAnnotations.Alias("Posts")] [Soma.Core.Table(Name = "Posts")] public class Post { [Soma.Core.Id(Soma.Core.IdKind.Identity)] public int Id { get; set; } public string Text { get; set; } public DateTime CreationDate { get; set; } public DateTime LastChangeDate { get; set; } public int? Counter1 { get; set; } public int? Counter2 { get; set; } public int? Counter3 { get; set; } public int? Counter4 { get; set; } public int? Counter5 { get; set; } public int? Counter6 { get; set; } public int? Counter7 { get; set; } public int? Counter8 { get; set; } public int? Counter9 { get; set; } } class Program { public const string ConnectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=True", OleDbConnectionString = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI"; public static SqlConnection GetOpenConnection() { var connection = new SqlConnection(ConnectionString); connection.Open(); return connection; } static void RunPerformanceTests() { var test = new PerformanceTests(); const int iterations = 500; Console.WriteLine("Running {0} iterations that load up a post entity", iterations); test.Run(iterations); } static void Main() { #if DEBUG RunTests(); #else EnsureDBSetup(); RunPerformanceTests(); #endif Console.WriteLine("(end of tests; press any key)"); Console.ReadKey(); } private static void EnsureDBSetup() { using (var cnn = GetOpenConnection()) { var cmd = cnn.CreateCommand(); cmd.CommandText = @" if (OBJECT_ID('Posts') is null) begin create table Posts ( Id int identity primary key, [Text] varchar(max) not null, CreationDate datetime not null, LastChangeDate datetime not null, Counter1 int, Counter2 int, Counter3 int, Counter4 int, Counter5 int, Counter6 int, Counter7 int, Counter8 int, Counter9 int ) set nocount on declare @i int declare @c int declare @id int set @i = 0 while @i <= 5001 begin insert Posts ([Text],CreationDate, LastChangeDate) values (replicate('x', 2000), GETDATE(), GETDATE()) set @id = @@IDENTITY set @i = @i + 1 end end "; cmd.Connection = cnn; cmd.ExecuteNonQuery(); } } private static void RunTests() { var tester = new Tests(); int fail = 0; MethodInfo[] methods = typeof(Tests).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); var activeTests = methods.Where(m => Attribute.IsDefined(m, typeof(ActiveTestAttribute))).ToArray(); if (activeTests.Length != 0) methods = activeTests; List<string> failNames = new List<string>(); foreach (var method in methods) { Console.Write("Running " + method.Name); try { method.Invoke(tester, null); Console.WriteLine(" - OK!"); } catch(TargetInvocationException tie) { fail++; Console.WriteLine(" - " + tie.InnerException.Message); failNames.Add(method.Name); }catch (Exception ex) { fail++; Console.WriteLine(" - " + ex.Message); } } Console.WriteLine(); if(fail == 0) { Console.WriteLine("(all tests successful)"); } else { Console.WriteLine("#### FAILED: {0}", fail); foreach(var failName in failNames) { Console.WriteLine(failName); } } } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public sealed class ActiveTestAttribute : Attribute {} }
28.888199
134
0.523113
[ "Apache-2.0" ]
AdamRamdane/dapper-dot-net
Tests/Program.cs
4,653
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Threading.Tasks; using Algolia.Search; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Squidex.Domain.Apps.Core.Contents; using Squidex.Domain.Apps.Core.Rules; using Squidex.Domain.Apps.Core.Rules.Actions; using Squidex.Domain.Apps.Events; using Squidex.Domain.Apps.Events.Contents; using Squidex.Infrastructure; using Squidex.Infrastructure.EventSourcing; namespace Squidex.Domain.Apps.Core.HandleRules.Actions { public sealed class AlgoliaActionHandler : RuleActionHandler<AlgoliaAction> { private readonly ClientPool<(string AppId, string ApiKey, string IndexName), Index> clients; private readonly RuleEventFormatter formatter; public AlgoliaActionHandler(RuleEventFormatter formatter) { Guard.NotNull(formatter, nameof(formatter)); this.formatter = formatter; clients = new ClientPool<(string AppId, string ApiKey, string IndexName), Index>(key => { var client = new AlgoliaClient(key.AppId, key.ApiKey); return client.InitIndex(key.IndexName); }); } protected override (string Description, RuleJobData Data) CreateJob(Envelope<AppEvent> @event, string eventName, AlgoliaAction action) { var ruleDescription = string.Empty; var ruleData = new RuleJobData { ["AppId"] = action.AppId, ["ApiKey"] = action.ApiKey }; if (@event.Payload is ContentEvent contentEvent) { ruleData["ContentId"] = contentEvent.ContentId.ToString(); ruleData["Operation"] = "Upsert"; ruleData["IndexName"] = formatter.FormatString(action.IndexName, @event); var timestamp = @event.Headers.Timestamp().ToString(); switch (@event.Payload) { case ContentCreated created: { ruleDescription = $"Add entry to Algolia index: {action.IndexName}"; ruleData["Content"] = new JObject( new JProperty("id", contentEvent.ContentId), new JProperty("created", timestamp), new JProperty("createdBy", created.Actor.ToString()), new JProperty("lastModified", timestamp), new JProperty("lastModifiedBy", created.Actor.ToString()), new JProperty("status", Status.Draft.ToString()), new JProperty("data", formatter.ToRouteData(created.Data))); break; } case ContentUpdated updated: { ruleDescription = $"Update entry in Algolia index: {action.IndexName}"; ruleData["Content"] = new JObject( new JProperty("lastModified", timestamp), new JProperty("lastModifiedBy", updated.Actor.ToString()), new JProperty("data", formatter.ToRouteData(updated.Data))); break; } case ContentStatusChanged statusChanged: { ruleDescription = $"Update entry in Algolia index: {action.IndexName}"; ruleData["Content"] = new JObject( new JProperty("lastModified", timestamp), new JProperty("lastModifiedBy", statusChanged.Actor.ToString()), new JProperty("status", statusChanged.Status.ToString())); break; } case ContentDeleted deleted: { ruleDescription = $"Delete entry from Algolia index: {action.IndexName}"; ruleData["Content"] = new JObject(); ruleData["Operation"] = "Delete"; break; } } } return (ruleDescription, ruleData); } public override async Task<(string Dump, Exception Exception)> ExecuteJobAsync(RuleJobData job) { if (!job.TryGetValue("Operation", out var operationToken)) { return (null, new InvalidOperationException("The action cannot handle this event.")); } var appId = job["AppId"].Value<string>(); var apiKey = job["ApiKey"].Value<string>(); var indexName = job["IndexName"].Value<string>(); var index = clients.GetClient((appId, apiKey, indexName)); var operation = operationToken.Value<string>(); var content = job["Content"].Value<JObject>(); var contentId = job["ContentId"].Value<string>(); try { switch (operation) { case "Upsert": { content["objectID"] = contentId; var response = await index.PartialUpdateObjectAsync(content); return (response.ToString(Formatting.Indented), null); } case "Delete": { var response = await index.DeleteObjectAsync(contentId); return (response.ToString(Formatting.Indented), null); } default: return (null, null); } } catch (AlgoliaException ex) { return (ex.Message, ex); } } } }
38.85625
142
0.499598
[ "MIT" ]
SarensDev/squidex
src/Squidex.Domain.Apps.Core.Operations/HandleRules/Actions/AlgoliaActionHandler.cs
6,219
C#
using Microsoft.AspNetCore.Http; using System; namespace SolviaOcrMyPdf.Models { public class OcrModel { public string DestinationLanguage { get; set; } public IFormFile Image { get; set; } } }
18.666667
55
0.669643
[ "MIT" ]
itsChris/SolviaOcrMyPdf
SolviaOcrMyPdf/Models/OcrModel.cs
226
C#
using System.Collections.Generic; using System.Linq; namespace Lextm.ReStructuredText { public class Classifier { public IList<ITextArea> TextAreas; public Classifier(List<ITextArea> textAreas) { textAreas.Last().Content.RemoveEnd(); textAreas.First().Content.RemoveStart(); TextAreas = new List<ITextArea>(); foreach (var item in textAreas) { if (string.IsNullOrWhiteSpace(item.Content.Text)) { continue; } TextAreas.Add(item); } } } }
24.615385
65
0.528125
[ "MIT" ]
lextm/restructuredtext-antlr
ReStructuredText/Classifier.cs
642
C#
using System; using System.Collections.Generic; using System.Linq; using SysAnalytics.Web.Core.ViewModels; namespace SysAnalytics.Web.ViewModels { public class GridViewModel<T> { public GridViewModel() { this.Data = new List<T>(); CreateColumns(); } public string Id { get; set; } public string Url { get; set; } public string Caption { get; set; } public int Width { get; set; } public int Height { get; set; } public string UrlTempl { get; set; } public List<T> Data { get; set; } public IEnumerable<JQGridColumn> Columns { get; set; } public IEnumerable<TemplateViewModel> Templates { get; set; } private void CreateColumns() { var modelType = typeof(T); var columns = new List<JQGridColumn>(); var properties = modelType.GetProperties(); if (properties != null) { foreach (var property in properties) { var column = new JQGridColumn(); column.Name = property.Name; var attrs = Attribute.GetCustomAttributes(property); foreach (var attr in attrs) { var a = attr as JQGridColumnAttribute; if (a != null) { column.Width = a.Width; column.IsHidden = a.IsHidden; column.IsSortable = a.IsSortable; column.Align = a.Align; column.Formatter = a.Formatter; column.Entity = a.Entity; column.TypeName = property.PropertyType.Name; } } columns.Add(column); //if (property.Name.Equals("Customer")) //{ // var customerProperties = property.PropertyType.GetProperties(); // foreach (var customerProperty in customerProperties) // { // var customerColumn = new JQGridColumn(); // customerColumn.Name = customerProperty.Name; // var customerAttrs = Attribute.GetCustomAttributes(customerProperty); // foreach (var attr in customerAttrs) // { // var a = attr as JQGridColumnAttribute; // if (a != null) // { // customerColumn.Width = a.Width; // customerColumn.IsHidden = a.IsHidden; // customerColumn.IsSortable = a.IsSortable; // customerColumn.Align = a.Align; // customerColumn.Formatter = a.Formatter; // customerColumn.Entity = a.Entity; // } // } // columns.Add(customerColumn); // } //} } } Columns = columns; } } }
39.229885
98
0.428948
[ "MIT" ]
kostyrin/SysAnalytics
SysAnalytics.Web/ViewModels/GridViewModel.cs
3,415
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; using FluentValidation.Attributes; using SmartStore.Admin.Models.Stores; using SmartStore.Admin.Validators.Topics; using SmartStore.Web.Framework; using SmartStore.Web.Framework.Localization; using SmartStore.Web.Framework.Modelling; namespace SmartStore.Admin.Models.Topics { [Validator(typeof(TopicValidator))] public class TopicModel : TabbableModel, ILocalizedModel<TopicLocalizedModel> { public TopicModel() { WidgetWrapContent = true; Locales = new List<TopicLocalizedModel>(); AvailableStores = new List<StoreModel>(); AvailableTitleTags = new List<SelectListItem>(); AvailableTitleTags.Add(new SelectListItem { Text = "h1", Value = "h1" }); AvailableTitleTags.Add(new SelectListItem { Text = "h2", Value = "h2" }); AvailableTitleTags.Add(new SelectListItem { Text = "h3", Value = "h3" }); AvailableTitleTags.Add(new SelectListItem { Text = "h4", Value = "h4" }); AvailableTitleTags.Add(new SelectListItem { Text = "h5", Value = "h5" }); AvailableTitleTags.Add(new SelectListItem { Text = "h6", Value = "h6" }); AvailableTitleTags.Add(new SelectListItem { Text = "div", Value = "div" }); AvailableTitleTags.Add(new SelectListItem { Text = "span", Value = "span" }); } [SmartResourceDisplayName("Admin.Common.Store.LimitedTo")] public bool LimitedToStores { get; set; } [SmartResourceDisplayName("Admin.Common.Store.AvailableFor")] public List<StoreModel> AvailableStores { get; set; } public int[] SelectedStoreIds { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.SystemName")] [AllowHtml] public string SystemName { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.IncludeInSitemap")] public bool IncludeInSitemap { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.IsPasswordProtected")] public bool IsPasswordProtected { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Password")] [DataType(DataType.Password)] public string Password { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.URL")] [AllowHtml] public string Url { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Title")] [AllowHtml] public string Title { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Body")] [AllowHtml] public string Body { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaKeywords")] [AllowHtml] public string MetaKeywords { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaDescription")] [AllowHtml] public string MetaDescription { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaTitle")] [AllowHtml] public string MetaTitle { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.RenderAsWidget")] public bool RenderAsWidget { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.WidgetZone")] [UIHint("WidgetZone")] public string WidgetZone { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.WidgetWrapContent")] public bool WidgetWrapContent { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.WidgetShowTitle")] public bool WidgetShowTitle { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.WidgetBordered")] public bool WidgetBordered { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Priority")] public int Priority { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.TitleTag")] public string TitleTag { get; set; } public IList<SelectListItem> AvailableTitleTags { get; private set; } public IList<TopicLocalizedModel> Locales { get; set; } } public class TopicLocalizedModel : ILocalizedModelLocal { public int LanguageId { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Title")] [AllowHtml] public string Title { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.Body")] [AllowHtml] public string Body { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaKeywords")] [AllowHtml] public string MetaKeywords { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaDescription")] [AllowHtml] public string MetaDescription { get; set; } [SmartResourceDisplayName("Admin.ContentManagement.Topics.Fields.MetaTitle")] [AllowHtml] public string MetaTitle { get; set; } } }
40.992188
95
0.690299
[ "MIT" ]
jenmcquade/csharp-snippets
SmartStoreNET-3.x/src/Presentation/SmartStore.Web/Administration/Models/Topics/TopicModel.cs
5,249
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Wall : MonoBehaviour { private float wallLength; private float wallAngleR; private Vector3 start; private Vector3 end; // Start is called before the first frame update void Start() { wallAngleR = -Mathf.Deg2Rad * this.transform.eulerAngles.y; wallLength = this.transform.localScale.x; start = new Vector3(this.transform.position.x + 0.5f * wallLength * Mathf.Cos(wallAngleR), this.transform.position.y, this.transform.position.z + 0.5f * wallLength * Mathf.Sin(wallAngleR)); end = new Vector3(this.transform.position.x - 0.5f * wallLength * Mathf.Cos(wallAngleR), this.transform.position.y, this.transform.position.z - 0.5f * wallLength * Mathf.Sin(wallAngleR)); } public Vector3 GetNearestPoint(Vector3 pos) { Vector3 relativeEnd, relativePos, relativeEndScaled, relativePosScaled; float dotProduct; Vector3 nearestPoint; // Relative vector to start position relativeEnd = end - start; relativePos = pos - start; relativeEndScaled = relativeEnd.normalized; relativePosScaled = relativePos * (1.0f / Vector3.Magnitude(relativeEnd)); // Dot Product of Scaled Vectors dotProduct = Vector3.Dot(relativeEndScaled, relativePosScaled); if (dotProduct < 0.0) // Position of agent is located before wall's 'start' nearestPoint = start; else if (dotProduct > 1.0) // Position of agent is located after wall's 'end' nearestPoint = end; else // Position of agent is located between wall's 'start' and 'end' nearestPoint = (relativeEnd * dotProduct) + start; return nearestPoint; } public float GetSqrDistanceTo(Vector3 pos) { Vector3 vectorToWall = pos - GetNearestPoint(pos); return Vector3.SqrMagnitude(vectorToWall); } public float GetSqrDistanceTo(Transform transform) => GetSqrDistanceTo(transform.position); }
35.758065
100
0.633288
[ "MIT" ]
trinhthanhtrung/unity-pedestrian-rl
SocialForceModel/Wall.cs
2,219
C#
using System; using NetOffice; namespace NetOffice.ExcelApi.Enums { /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff196160.aspx </remarks> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] [EntityTypeAttribute(EntityType.IsEnum)] public enum XlAxisGroup { /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>1</remarks> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] xlPrimary = 1, /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks>2</remarks> [SupportByVersionAttribute("Excel", 9,10,11,12,14,15,16)] xlSecondary = 2 } }
29.888889
119
0.653036
[ "MIT" ]
Engineerumair/NetOffice
Source/Excel/Enums/XlAxisGroup.cs
807
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit)] internal struct AA { [FieldOffset(12)] public ulong tmp1; [FieldOffset(5)] public sbyte tmp2; [FieldOffset(0)] public byte tmp3; [FieldOffset(8)] public byte q; //this field is the testing subject [FieldOffset(40)] public uint tmp4; [FieldOffset(38)] public byte tmp5; public AA(byte qq) { tmp1 = 0; tmp2 = 0; tmp3 = 0; tmp4 = 0; tmp5 = 0; q = qq; } public static AA[] a_init = new AA[101]; public static AA[] a_zero = new AA[101]; public static AA[,,] aa_init = new AA[1, 101, 2]; public static AA[,,] aa_zero = new AA[1, 101, 2]; public static object b_init = new AA(100); public static AA _init, _zero; public static byte call_target(byte arg) { return arg; } public static byte call_target_ref(ref byte arg) { return arg; } public void verify() { } public static void verify_all() { a_init[100].verify(); a_zero[100].verify(); aa_init[0, 99, 1].verify(); aa_zero[0, 99, 1].verify(); _init.verify(); _zero.verify(); BB.f_init.verify(); BB.f_zero.verify(); } public static void reset() { a_init[100] = new AA(100); a_zero[100] = new AA(0); aa_init[0, 99, 1] = new AA(100); aa_zero[0, 99, 1] = new AA(0); _init = new AA(100); _zero = new AA(0); BB.f_init = new AA(100); BB.f_zero = new AA(0); } } internal struct BB { public static AA f_init, f_zero; }
23.607595
71
0.580161
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/Methodical/explicit/coverage/expl_byte_1.cs
1,865
C#
using System; using Equinor.ProCoSys.IPO.Domain.AggregateModels.PersonAggregate; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Equinor.ProCoSys.IPO.Domain.Tests.AggregateModels.PersonAggregate { [TestClass] public class SavedFilterTests { private const string TestPlant = "PCS$PlantA"; private const string ProjectName = "Project name"; private const string Title = "title"; private const string Criteria = "criteria"; private bool DefaultFilterValue = true; private SavedFilter _dut; [TestInitialize] public void Setup() => _dut = new SavedFilter(TestPlant, ProjectName, Title, Criteria) { DefaultFilter = DefaultFilterValue }; [TestMethod] public void Constructor_SetsProperties() { Assert.AreEqual(TestPlant, _dut.Plant); Assert.AreEqual(ProjectName, _dut.ProjectName); Assert.AreEqual(Title, _dut.Title); Assert.AreEqual(Criteria, _dut.Criteria); Assert.AreEqual(DefaultFilterValue, _dut.DefaultFilter); } [TestMethod] public void Constructor_ShouldThrowException_WhenProjectNameNotGiven() => Assert.ThrowsException<ArgumentNullException>(() => new SavedFilter(TestPlant, null, Title, Criteria) { DefaultFilter = DefaultFilterValue } ); [TestMethod] public void Constructor_ShouldThrowException_WhenTitleNotGiven() => Assert.ThrowsException<ArgumentNullException>(() => new SavedFilter(TestPlant, ProjectName, null, Criteria) { DefaultFilter = DefaultFilterValue } ); [TestMethod] public void Constructor_ShouldThrowException_WhenCriteriaNotGiven() => Assert.ThrowsException<ArgumentNullException>(() => new SavedFilter(TestPlant, ProjectName, Title, null) { DefaultFilter = DefaultFilterValue } ); } }
34.587302
81
0.605782
[ "MIT" ]
equinor/procosys-call-for-punch-out-api
src/tests/Equinor.ProCoSys.IPO.Domain.Tests/AggregateModels/PersonAggregate/SavedFilterTests.cs
2,181
C#
// Developed by Softeq Development Corporation // http://www.softeq.com using System; using Softeq.XToolkit.Common.Disposables; using Xunit; namespace Softeq.XToolkit.Common.Tests.Disposables { public class DisposableTests { [Fact] public void Create() { var instance = Disposable.Create(() => { }); Assert.True(instance is IDisposable); } [Fact] public void Create_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Disposable.Create(null!)); } [Fact] public void Dispose() { var disposed = false; var d = Disposable.Create(() => { disposed = true; }); Assert.False(disposed); d.Dispose(); Assert.True(disposed); } } }
21.948718
81
0.556075
[ "MIT" ]
Softeq/XToolkit.WhiteLabel
Softeq.XToolkit.Common.Tests/Disposables/DisposableTests.cs
858
C#
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006-2019, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2019. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.480) // Version 5.480.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// Base class used for implementation of simple controls. /// </summary> [ToolboxItem(false)] [DesignerCategory("code")] [ClassInterface(ClassInterfaceType.AutoDispatch)] [ComVisible(true)] public abstract class VisualSimple : VisualControl { #region Identity /// <summary> /// Initialize a new instance of the VisualSimple class. /// </summary> protected VisualSimple() { } #endregion #region Public /// <summary> /// Gets and sets the auto size mode. /// </summary> [Category("Layout")] [Description("Specifies if the control grows and shrinks to fit the contents exactly.")] [DefaultValue(typeof(AutoSizeMode), "GrowOnly")] public virtual AutoSizeMode AutoSizeMode { // ReSharper disable RedundantBaseQualifier get => base.GetAutoSizeMode(); // ReSharper restore RedundantBaseQualifier set { // ReSharper disable RedundantBaseQualifier if (value != base.GetAutoSizeMode()) { base.SetAutoSizeMode(value); // ReSharper restore RedundantBaseQualifier // Only perform an immediate layout if // currently performing auto size operations if (AutoSize) { PerformNeedPaint(true); } } } } /// <summary> /// Get the preferred size of the control based on a proposed size. /// </summary> /// <param name="proposedSize">Starting size proposed by the caller.</param> /// <returns>Calculated preferred size.</returns> public override Size GetPreferredSize(Size proposedSize) { // Do we have a manager to ask for a preferred size? if (ViewManager != null) { // Ask the view to peform a layout Size retSize = ViewManager.GetPreferredSize(Renderer, proposedSize); // Apply the maximum sizing if (MaximumSize.Width > 0) { retSize.Width = Math.Min(MaximumSize.Width, retSize.Width); } if (MaximumSize.Height > 0) { retSize.Height = Math.Min(MaximumSize.Height, retSize.Width); } // Apply the minimum sizing if (MinimumSize.Width > 0) { retSize.Width = Math.Max(MinimumSize.Width, retSize.Width); } if (MinimumSize.Height > 0) { retSize.Height = Math.Max(MinimumSize.Height, retSize.Height); } return retSize; } else { // Fall back on default control processing return base.GetPreferredSize(proposedSize); } } /// <summary> /// Gets or sets the background color for the control. /// </summary> [Browsable(false)] [Bindable(false)] public override Color BackColor { get => base.BackColor; set => base.BackColor = value; } /// <summary> /// Gets or sets the font of the text displayed by the control. /// </summary> [Browsable(false)] [Bindable(false)] public override Font Font { get => base.Font; set => base.Font = value; } /// <summary> /// Gets or sets the foreground color for the control. /// </summary> [Browsable(false)] [Bindable(false)] public override Color ForeColor { get => base.ForeColor; set => base.ForeColor = value; } #endregion } }
29.486486
157
0.601742
[ "BSD-3-Clause" ]
MarketingInternetOnlines/Krypton-NET-5.480
Source/Krypton Components/ComponentFactory.Krypton.Toolkit/Controls Visuals/VisualSimple.cs
4,367
C#
using System; using System.Windows; namespace ImageComparisonViewer.Common.Wpf { // http://proprogrammer.hatenadiary.jp/entry/2018/08/18/172739 public readonly struct ImmutableRect { public readonly double X; public readonly double Y; public readonly double Width; public readonly double Height; public ImmutableRect(double x, double y, double width, double height) => (X, Y, Width, Height) = (x, y, width, height); public static implicit operator ImmutableRect(Rect source) => new ImmutableRect(source.X, source.Y, source.Width, source.Height); public static implicit operator Rect(in ImmutableRect source) => new Rect(source.X, source.Y, source.Width, source.Height); } }
31.52
82
0.667513
[ "MIT" ]
hsytkm/ImageComparisonViewer
Source/ImageComparisonViewer.Common/Wpf/ImmutableRect.cs
790
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using VirtualLiveStudio; using VirtualLiveStudio.Shared.MessagePackObjects; public class Chat : MonoBehaviour { private ChatHub chatHub = new ChatHub(); private void Start() { chatHub.Connect(); chatHub.OnJoinAction += ChatHub_OnJoin; chatHub.OnLeaveAction += ChatHub_OnLeave; chatHub.OnSendMessageEvent += ChatHub_OnSendMessage; } private async void OnDestroy() => await chatHub.DisposeAsync(); private void ChatHub_OnJoin(string name) => messagelog += $"Join [{name}]\n"; private void ChatHub_OnLeave(string name) => messagelog += $"Leave [{name}]\n"; private void ChatHub_OnSendMessage(ChatMessageResponse message) => messagelog += $"{message.UserName} : {message.Message}\n"; private string roomName = "Room Name"; private string userName = "User Name"; private string message = "MessageToSend"; private string messagelog = "Received:\n"; private void OnGUI() { roomName = GUI.TextField(new Rect(200, 10, 200, 24), roomName); userName = GUI.TextField(new Rect(400, 10, 200, 24), userName); if (GUI.Button(new Rect(600, 10, 100, 24), "Join")) join(roomName, userName); if (GUI.Button(new Rect(700, 10, 100, 24), "Leave")) leave(); message = GUI.TextField(new Rect(200, 34, 500, 24), message); if (GUI.Button(new Rect(700, 34, 100, 24), "Send")) sendMessage(message); messagelog = GUI.TextArea(new Rect(200, 58, 600, 600), messagelog); } private async void join(string roomName, string userName) => await chatHub.JoinAsync(roomName, userName); private async void leave() => await chatHub.LeaveAsync(); private async void sendMessage(string message) => await chatHub.SendMessageAsync(message); }
36.27451
129
0.680541
[ "MIT" ]
sh-akira/VirtualLiveStudio
VirtualLiveStudio-Client/Assets/Scripts/Chat.cs
1,852
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Globalization; #nullable enable namespace Microsoft.EntityFrameworkCore { /// <summary> /// <para> /// A unique identifier for the context instance and pool lease, if any. /// </para> /// <para> /// This identifier is primarily intended as a correlation ID for logging and debugging such /// that it is easy to identify that multiple events are using the same or different context instances. /// </para> /// </summary> public readonly struct DbContextId { /// <summary> /// Compares this ID to another ID to see if they represent the same leased context. /// </summary> /// <param name="other"> The other ID. </param> /// <returns> <see langword="true" /> if they represent the same leased context; <see langword="false" /> otherwise. </returns> public bool Equals(DbContextId other) => InstanceId == other.InstanceId && Lease == other.Lease; /// <summary> /// Compares this ID to another ID to see if they represent the same leased context. /// </summary> /// <param name="obj"> The other ID. </param> /// <returns> <see langword="true" /> if they represent the same leased context; <see langword="false" /> otherwise. </returns> public override bool Equals(object? obj) => obj is DbContextId other && Equals(other); /// <summary> /// A hash code for this ID. /// </summary> /// <returns> The hash code. </returns> public override int GetHashCode() => HashCode.Combine(InstanceId, Lease); /// <summary> /// Compares one ID to another ID to see if they represent the same leased context. /// </summary> /// <param name="left"> The first ID. </param> /// <param name="right"> The second ID. </param> /// <returns> <see langword="true" /> if they represent the same leased context; <see langword="false" /> otherwise. </returns> public static bool operator ==(DbContextId left, DbContextId right) => left.Equals(right); /// <summary> /// Compares one ID to another ID to see if they represent different leased contexts. /// </summary> /// <param name="left"> The first ID. </param> /// <param name="right"> The second ID. </param> /// <returns> <see langword="true" /> if they represent different leased contexts; <see langword="false" /> otherwise. </returns> public static bool operator !=(DbContextId left, DbContextId right) => !left.Equals(right); /// <summary> /// Creates a new <see cref="DbContextId" /> with the given <see cref="InstanceId" /> and lease number. /// </summary> /// <param name="id"> A unique identifier for the <see cref="DbContext" /> being used. </param> /// <param name="lease"> A number indicating whether this is the first, second, third, etc. lease of this instance. </param> public DbContextId(Guid id, int lease) { InstanceId = id; Lease = lease; } /// <summary> /// <para> /// A unique identifier for the <see cref="DbContext" /> being used. /// </para> /// <para> /// When context pooling is being used, then this ID must be combined with /// the <see cref="Lease" /> in order to get a unique ID for the effective instance being used. /// </para> /// </summary> public Guid InstanceId { get; } /// <summary> /// <para> /// A number that is incremented each time this particular <see cref="DbContext" /> instance is leased /// from the context pool. /// </para> /// <para> /// Will be zero if context pooling is not being used. /// </para> /// </summary> public int Lease { get; } /// <summary>Returns the fully qualified type name of this instance.</summary> /// <returns>The fully qualified type name.</returns> public override string ToString() { return InstanceId + ":" + Lease.ToString(CultureInfo.InvariantCulture); } } }
43.628571
137
0.570181
[ "Apache-2.0" ]
Emill/efcore
src/EFCore/DbContextId.cs
4,581
C#
namespace Cars.Tests.JustMock.Fakes { using Cars.Models; public class FakeCar : Car { private string make; private int year; public virtual new int Id { get { return 0; } } public virtual new string Make { get { return string.Empty; } set { base.Make = value; this.make = value; } } public virtual new int Year { get { return this.year; } set { base.Year = value; this.year = value; } } } }
16.5625
38
0.343396
[ "MIT" ]
DragomirPetrov/TelerikAcademy
C #/QPC/01.Unit-Testing/03.Mocking/Cars/Cars.Tests.JustMock/Fakes/FakeCar.cs
797
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { [DataContract] public class SlackActionResult { [DataMember(Name ="account")] public string Account { get; set; } [DataMember(Name ="sent_messages")] public IEnumerable<SlackActionMessageResult> SentMessages { get; set; } } }
26.65
76
0.757974
[ "Apache-2.0" ]
Atharvpatel21/elasticsearch-net
src/Nest/XPack/Watcher/Execution/Slack/SlackActionResult.cs
533
C#
using System; using System.Runtime.Serialization; using System.Security.Permissions; namespace Jannesen.PushNotification { [Serializable] public class PushNotificationConfigException: Exception { public PushNotificationConfigException(string message): base(message) { } public PushNotificationConfigException(string message, Exception innerException): base(message, innerException) { } protected PushNotificationConfigException(SerializationInfo info, StreamingContext context): base(info, context) { } } [Serializable] public class PushNotificationConnectionException: Exception { public PushNotificationConnectionException(string message): base(message) { } public PushNotificationConnectionException(string message, Exception innerException): base(message, innerException) { } protected PushNotificationConnectionException(SerializationInfo info, StreamingContext context): base(info, context) { } } [Serializable] public class PushNotificationException: Exception { public Notification Notification { get; private set; } public PushNotificationException(Notification notification, string message): base(message) { this.Notification = notification; } public PushNotificationException(Notification notification, string message, Exception innerException): base(message, innerException) { this.Notification = notification; } protected PushNotificationException(SerializationInfo info, StreamingContext context): base(info, context) { Notification = (Notification)info.GetValue(nameof(Notification), typeof(Notification)); } [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(Notification), Notification); } } [Serializable] public class PushNotificationInvalidDeviceException: PushNotificationException { public PushNotificationInvalidDeviceException(Notification notification): base(notification, "Invalid device-token '" + notification.DeviceAddress + "'.") { } protected PushNotificationInvalidDeviceException(SerializationInfo info, StreamingContext context): base(info, context) { } } [Serializable] public class PushNotificationExpiredException: PushNotificationException { public PushNotificationExpiredException(Notification notification): base(notification, "Notification expired device-token '" + notification.DeviceAddress + "'.") { } protected PushNotificationExpiredException(SerializationInfo info, StreamingContext context): base(info, context) { } } [Serializable] public class PushNotificationServiceException: Exception { public PushNotificationServiceException(string message): base(message) { } public PushNotificationServiceException(string message, Exception innerException): base(message, innerException) { } protected PushNotificationServiceException(SerializationInfo info, StreamingContext context): base(info, context) { } } }
39.343137
198
0.611513
[ "Apache-2.0" ]
jannesen/Jannesen.PushNotification
Exceptions.cs
4,015
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Windows; using System.Windows.Controls; using ICSharpCode.Core; using ICSharpCode.SharpDevelop.Project; namespace ICSharpCode.SharpDevelop.Gui.OptionPanels { /// <summary> /// Interaction logic for AssemblyInfo.xaml /// </summary> public partial class AssemblyInfoPanel { private AssemblyInfo assemblyInfo; public AssemblyInfoPanel() { InitializeComponent(); } protected override void Load(MSBuildBasedProject project, string configuration, string platform) { var assemblyInfoFileName = GetAssemblyInfoFileName(project); if (string.IsNullOrEmpty(assemblyInfoFileName)) { assemblyInfo = new AssemblyInfo(); MessageService.ShowError("${res:Dialog.ProjectOptions.AssemblyInfo.AssemblyInfoNotFound}"); } else { var assemblyInfoProvider = new AssemblyInfoProvider(); assemblyInfo = assemblyInfoProvider.ReadAssemblyInfo(assemblyInfoFileName); } var assemblyInfoViewModel = new AssemblyInfoViewModel(assemblyInfo); assemblyInfoViewModel.PropertyChanged += OnAssemblyInfoChanged; DataContext = assemblyInfoViewModel; base.Load(project, configuration, platform); } protected override bool Save(MSBuildBasedProject project, string configuration, string platform) { if (!CheckForValidationErrors()) { return false; } var assemblyInfoFileName = GetAssemblyInfoFileName(project); if (!string.IsNullOrEmpty(assemblyInfoFileName)) { if (assemblyInfo != null) { var assemblyInfoProvider = new AssemblyInfoProvider(); assemblyInfoProvider.MergeAssemblyInfo(assemblyInfo, assemblyInfoFileName); } } else { MessageService.ShowError("${res:Dialog.ProjectOptions.AssemblyInfo.AssemblyInfoNotFound}"); } return base.Save(project, configuration, platform); } private string GetAssemblyInfoFileName(MSBuildBasedProject project) { var assemblyInfoProjectItem = project.Items .FirstOrDefault(projectItem => projectItem.FileName.GetFileNameWithoutExtension() == "AssemblyInfo"); if (assemblyInfoProjectItem == null || assemblyInfoProjectItem.FileName == null) return null; return assemblyInfoProjectItem.FileName.ToString(); } private void OnAssemblyInfoChanged(object sender, EventArgs e) { this.IsDirty = true; } private bool CheckForValidationErrors() { var wrongControl = RootGrid.Children.OfType<UIElement>().FirstOrDefault(Validation.GetHasError); if (wrongControl != null) { MessageService.ShowError("${res:Dialog.ProjectOptions.AssemblyInfo.IncorrectValue}"); wrongControl.Focus(); var textBox = wrongControl as TextBox; if (textBox != null) textBox.SelectAll(); return false; } return true; } } }
32.239669
105
0.753397
[ "MIT" ]
TetradogOther/SharpDevelop
src/Main/Base/Project/Src/Gui/Dialogs/OptionPanels/ProjectOptions/AssemblyInfo/AssemblyInfoPanel.xaml.cs
3,903
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Commands.AnalysisServices.Dataplane.Models; using Microsoft.Azure.Commands.AnalysisServices.Dataplane.Properties; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Commands.AnalysisServices.Dataplane { /// <summary> /// Cmdlet to log into an Analysis Services environment /// </summary> [Cmdlet(VerbsData.Sync, "AzureAnalysisServicesInstance", SupportsShouldProcess = true)] [Alias("Sync-AzureAsInstance")] [OutputType(typeof(ScaleOutServerDatabaseSyncDetails))] public class SynchronizeAzureAzureAnalysisServer : AzurePSCmdlet { private static TimeSpan DefaultPollingInterval = TimeSpan.FromSeconds(30); public static TimeSpan DefaultRetryIntervalForPolling = TimeSpan.FromSeconds(10); private static string RootActivityIdHeaderName = "x-ms-root-activity-id"; private static string CurrentUtcDateHeaderName = "x-ms-current-utc-date"; private string serverName; private ClusterResolutionResult clusterResolveResult; private Guid correlationId; private string syncRequestRootActivityId; private string syncRequestTimeStamp; [Parameter( Mandatory = true, HelpMessage = "Name of the Azure Analysis Services server to synchronize. E.x. asazure://westus.asazure.windows.net/contososerver:rw", Position = 0, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string Instance { get; set; } [Parameter( Mandatory = true, HelpMessage = "Identity of the database need to be synchronized", Position = 1, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string Database { get; set; } [Parameter(Mandatory = false)] public SwitchParameter PassThru { get; set; } protected override IAzureContext DefaultContext { get { // Nothing to do with Azure Resource Management context return null; } } public IAsAzureHttpClient AsAzureHttpClient { get; private set; } public ITokenCacheItemProvider TokenCacheItemProvider { get; private set; } public SynchronizeAzureAzureAnalysisServer() { this.AsAzureHttpClient = new AsAzureHttpClient(() => { HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.AllowAutoRedirect = false; return new HttpClient(httpClientHandler); }); this.TokenCacheItemProvider = new TokenCacheItemProvider(); this.syncRequestRootActivityId = string.Empty; this.correlationId = Guid.Empty; this.syncRequestTimeStamp = string.Empty; } public SynchronizeAzureAzureAnalysisServer(IAsAzureHttpClient AsAzureHttpClient, ITokenCacheItemProvider TokenCacheItemProvider) { this.AsAzureHttpClient = AsAzureHttpClient; this.TokenCacheItemProvider = TokenCacheItemProvider; } protected override void SetupDebuggingTraces() { // nothing to do here. } protected override void TearDownDebuggingTraces() { // nothing to do here. } protected override void SetupHttpClientPipeline() { // nothing to do here. } protected override void TearDownHttpClientPipeline() { // nothing to do here. } public override void ExecuteCmdlet() { if (ShouldProcess(Instance, Resources.SynchronizingAnalysisServicesServer)) { correlationId = Guid.NewGuid(); WriteObject(string.Format("Sending sync request for database '{0}' to server '{1}'. Correlation Id: '{2}'.", Database, Instance, correlationId.ToString())); var context = AsAzureClientSession.Instance.Profile.Context; AsAzureClientSession.Instance.Login(context); WriteProgress(new ProgressRecord(0, "Sync-AzureAnalysisServicesInstance.", string.Format("Authenticating user for '{0}' environment.", context.Environment.Name))); var clusterResolveResult = ClusterResolve(context, serverName); var virtualServerName = clusterResolveResult.CoreServerName.Split(":".ToCharArray())[0]; if (!serverName.Equals(virtualServerName) && !clusterResolveResult.CoreServerName.EndsWith(":rw")) { throw new SynchronizationFailedException("Sync request can only be sent to the management endpoint"); } this.clusterResolveResult = clusterResolveResult; Uri clusterBaseUri = new Uri(string.Format("{0}{1}{2}", Uri.UriSchemeHttps, Uri.SchemeDelimiter, clusterResolveResult.ClusterFQDN)); var accessToken = this.TokenCacheItemProvider.GetTokenFromTokenCache(AsAzureClientSession.TokenCache, context.Account.UniqueId, context.Environment.Name); ScaleOutServerDatabaseSyncDetails syncResult = null; try { WriteProgress(new ProgressRecord(0, "Sync-AzureAnalysisServicesInstance.", string.Format("Successfully authenticated for '{0}' environment.", context.Environment.Name))); syncResult = SynchronizeDatabaseAsync(context, clusterBaseUri, Database, accessToken).GetAwaiter().GetResult(); } catch (AggregateException aex) { foreach (var innerException in aex.Flatten().InnerExceptions) { WriteExceptionError(innerException); } } catch (Exception ex) { WriteExceptionError(ex); } if (syncResult == null) { throw new SynchronizationFailedException(string.Format(Resources.SyncASPollStatusUnknownMessage.FormatInvariant( this.clusterResolveResult.CoreServerName, correlationId, DateTime.Now.ToString(CultureInfo.InvariantCulture), string.Format("RootActivityId: {0}, Date Time UTC: {1}", syncRequestRootActivityId, syncRequestTimeStamp)))); } if (syncResult.SyncState != DatabaseSyncState.Completed) { var serializedDetails = JsonConvert.SerializeObject(syncResult); throw new SynchronizationFailedException(serializedDetails); } if (PassThru.IsPresent) { WriteObject(syncResult, true); } } } protected override void BeginProcessing() { this._dataCollectionProfile = new AzurePSDataCollectionProfile(false); if (AsAzureClientSession.Instance.Profile.Environments.Count == 0) { throw new PSInvalidOperationException(string.Format(Resources.NotLoggedInMessage, "")); } serverName = Instance; Uri uriResult; // if the user specifies the FQN of the server, then extract the servername out of that. // and set the current context if (Uri.TryCreate(Instance, UriKind.Absolute, out uriResult) && uriResult.Scheme == "asazure") { serverName = uriResult.PathAndQuery.Trim('/'); if (string.Compare(AsAzureClientSession.Instance.Profile.Context.Environment.Name, uriResult.DnsSafeHost, StringComparison.InvariantCultureIgnoreCase) != 0) { throw new PSInvalidOperationException(string.Format(Resources.NotLoggedInMessage, Instance)); } } else { var currentContext = AsAzureClientSession.Instance.Profile.Context; if (currentContext != null && AsAzureClientSession.AsAzureRolloutEnvironmentMapping.ContainsKey(currentContext.Environment.Name)) { throw new PSInvalidOperationException(string.Format(Resources.InvalidServerName, serverName)); } } if (this.AsAzureHttpClient == null) { this.AsAzureHttpClient = new AsAzureHttpClient(() => { HttpClientHandler httpClientHandler = new HttpClientHandler(); httpClientHandler.AllowAutoRedirect = false; return new HttpClient(); }); } if (this.TokenCacheItemProvider == null) { this.TokenCacheItemProvider = new TokenCacheItemProvider(); } base.BeginProcessing(); } protected override void InitializeQosEvent() { // No data collection for this commandlet } protected override string DataCollectionWarning { get { return Resources.ARMDataCollectionMessage; } } /// <summary> /// Worker Method for the synchronize request. /// </summary> /// <param name="context">The AS azure context</param> /// <param name="syncBaseUri">Base Uri for sync</param> /// <param name="databaseName">Database name</param> /// <param name="accessToken">Access token</param> /// <param name="maxNumberOfAttempts">Max number of retries for get command</param> /// <returns></returns> private async Task<ScaleOutServerDatabaseSyncDetails> SynchronizeDatabaseAsync( AsAzureContext context, Uri syncBaseUri, string databaseName, string accessToken) { Tuple<Uri, RetryConditionHeaderValue> pollingUrlAndRetryAfter = new Tuple<Uri, RetryConditionHeaderValue>(null, null); ScaleOutServerDatabaseSyncDetails syncResult = null; return await Task.Run(async () => { try { var synchronize = string.Format((string)context.Environment.Endpoints[AsAzureEnvironment.AsRolloutEndpoints.SyncEndpoint], this.serverName, databaseName); this.AsAzureHttpClient.resetHttpClient(); using (var message = await AsAzureHttpClient.CallPostAsync( syncBaseUri, synchronize, accessToken, correlationId, null)) { this.syncRequestRootActivityId = message.Headers.Contains(RootActivityIdHeaderName) ? message.Headers.GetValues(RootActivityIdHeaderName).FirstOrDefault() : string.Empty; this.syncRequestTimeStamp = message.Headers.Contains(CurrentUtcDateHeaderName) ? message.Headers.GetValues(CurrentUtcDateHeaderName).FirstOrDefault() : string.Empty; message.EnsureSuccessStatusCode(); if (message.StatusCode != HttpStatusCode.Accepted) { var timestampNow = DateTime.Now; syncResult = new ScaleOutServerDatabaseSyncDetails { CorrelationId = correlationId.ToString(), Database = databaseName, SyncState = DatabaseSyncState.Completed, Details = string.Format("Http status code: {0}. Nothing readonly instances found to replicate databases.", message.StatusCode), UpdatedAt = timestampNow, StartedAt = timestampNow }; return syncResult; } pollingUrlAndRetryAfter = new Tuple< Uri, RetryConditionHeaderValue>(message.Headers.Location, message.Headers.RetryAfter); } } catch (Exception e) { var timestampNow = DateTime.Now; // Return sync details with exception message as details return new ScaleOutServerDatabaseSyncDetails { CorrelationId = correlationId.ToString(), Database = databaseName, SyncState = DatabaseSyncState.Invalid, Details = Resources.PostSyncRequestFailureMessage.FormatInvariant( this.clusterResolveResult.CoreServerName, this.syncRequestRootActivityId, this.syncRequestTimeStamp, string.Format(e.Message)), UpdatedAt = timestampNow, StartedAt = timestampNow }; } Uri pollingUrl = pollingUrlAndRetryAfter.Item1; var retryAfter = pollingUrlAndRetryAfter.Item2; try { ScaleOutServerDatabaseSyncResult result = await this.PollSyncStatusWithRetryAsync( databaseName, accessToken, pollingUrl, retryAfter.Delta ?? DefaultPollingInterval); syncResult = ScaleOutServerDatabaseSyncDetails.FromResult(result, correlationId.ToString()); } catch (Exception e) { var timestampNow = DateTime.Now; // Append exception message to sync details and return syncResult = new ScaleOutServerDatabaseSyncDetails { CorrelationId = correlationId.ToString(), Database = databaseName, SyncState = DatabaseSyncState.Invalid, Details = Resources.SyncASPollStatusFailureMessage.FormatInvariant( serverName, string.Empty, timestampNow.ToString(CultureInfo.InvariantCulture), string.Format(e.StackTrace)), UpdatedAt = timestampNow, StartedAt = timestampNow }; } return syncResult; }); } /// <summary> /// /// </summary> /// <param name="databaseName">Database name</param> /// <param name="accessToken">Access token</param> /// <param name="pollingUrl">URL for polling</param> /// <param name="pollingInterval">Polling interval set by the post response</param> /// <param name="maxNumberOfAttempts">Max number of attempts for each poll before the attempt is declared a failure</param> /// <returns></returns> private async Task<ScaleOutServerDatabaseSyncResult> PollSyncStatusWithRetryAsync(string databaseName, string accessToken, Uri pollingUrl, TimeSpan pollingInterval, int maxNumberOfAttempts = 3) { return await Task.Run(async () => { ScaleOutServerDatabaseSyncResult response = null; var syncCompleted = false; var retryCount = 0; while (!syncCompleted && retryCount < maxNumberOfAttempts) { // Wait for specified polling interval other than retries. if (retryCount == 0) { await Task.Delay(pollingInterval); } else { await Task.Delay(DefaultRetryIntervalForPolling); } this.AsAzureHttpClient.resetHttpClient(); using (HttpResponseMessage message = await AsAzureHttpClient.CallGetAsync( pollingUrl, string.Empty, accessToken, correlationId)) { bool shouldRetry = false; if (message.IsSuccessStatusCode && message.Content != null) { var responseString = await message.Content.ReadAsStringAsync(); response = JsonConvert.DeserializeObject<ScaleOutServerDatabaseSyncResult>(responseString); if (response != null) { var state = response.SyncState; if (state == DatabaseSyncState.Completed || state == DatabaseSyncState.Failed) { syncCompleted = true; } else { pollingUrl = message.Headers.Location ?? pollingUrl; pollingInterval = message.Headers.RetryAfter.Delta ?? pollingInterval; } } else { shouldRetry = true; } } else { shouldRetry = true; } if(shouldRetry) { retryCount++; response = new ScaleOutServerDatabaseSyncResult() { Database = databaseName, SyncState = DatabaseSyncState.Invalid }; response.Details = string.Format( "Http Error code: {0}. Message: {1}", message.StatusCode.ToString(), message.Content != null ? await message.Content.ReadAsStringAsync() : string.Empty); if (message.StatusCode >= (HttpStatusCode)400 && message.StatusCode <= (HttpStatusCode)499) { break; } } else { retryCount = 0; } } } return response; }); } /// <summary> /// Resolves the cluster to which the request needs to be sent for the current environment /// </summary> /// <param name="context"></param> /// <param name="serverName"></param> /// <returns></returns> private ClusterResolutionResult ClusterResolve(AsAzureContext context, string serverName) { Uri clusterResolveBaseUri = new Uri(string.Format("{0}{1}{2}", Uri.UriSchemeHttps, Uri.SchemeDelimiter, context.Environment.Name)); UriBuilder resolvedUriBuilder = new UriBuilder(clusterResolveBaseUri); string rolloutAccessToken = this.TokenCacheItemProvider.GetTokenFromTokenCache(AsAzureClientSession.TokenCache, context.Account.UniqueId, context.Environment.Name); var resolveEndpoint = "/webapi/clusterResolve"; var content = new StringContent($"ServerName={serverName}"); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); this.AsAzureHttpClient.resetHttpClient(); using (HttpResponseMessage message = AsAzureHttpClient.CallPostAsync( clusterResolveBaseUri, resolveEndpoint, rolloutAccessToken, content).Result) { message.EnsureSuccessStatusCode(); var rawResult = message.Content.ReadAsStringAsync().Result; ClusterResolutionResult result = JsonConvert.DeserializeObject<ClusterResolutionResult>(rawResult); return result; } } } }
45.475806
202
0.534714
[ "MIT" ]
Philippe-Morin/azure-powershell
src/ResourceManager/AnalysisServices/Commands.AnalysisServices.Dataplane/Commands/Synchronize-AzureASInstance.cs
22,063
C#
using Newtonsoft.Json; namespace AL.Data.Achievements { /// <summary> /// <inheritdoc /> /// </summary> /// <seealso cref="DatumBase{T}" /> public class AchievementsDatum : DatumBase<GAchievement> { /// <summary> /// Defeat 1,000 Bosses. /// </summary> [JsonProperty("1000boss")] public GAchievement _1000boss { get; init; } = null!; /// <summary> /// Defeat 100 Bosses. /// </summary> [JsonProperty("100boss")] public GAchievement _100boss { get; init; } = null!; /// <summary> /// Find the lair of the Spider Queen. /// </summary> public GAchievement Discoverlair { get; init; } = null!; /// <summary> /// Deal 400K damage to Grinch. /// </summary> public GAchievement Festive { get; init; } = null!; /// <summary> /// Last hit 20,000 monsters consecutively with only burn damage using same weapon! /// </summary> public GAchievement Firehazard { get; init; } = null!; /// <summary> /// Receive 60M damage from Goo's. /// </summary> public GAchievement Gooped { get; init; } = null!; /// <summary> /// Succeed with the exact % on an upgrade or compound. /// </summary> public GAchievement Lucky { get; init; } = null!; /// <summary> /// Kill 1,000,000 Monsters. /// </summary> public GAchievement Monsterhunter { get; init; } = null!; /// <summary> /// Become Level 40. /// </summary> public GAchievement Reach40 { get; init; } = null!; /// <summary> /// Become Level 50. /// </summary> public GAchievement Reach50 { get; init; } = null!; /// <summary> /// Become Level 60. /// </summary> public GAchievement Reach60 { get; init; } = null!; /// <summary> /// Become Level 70. /// </summary> public GAchievement Reach70 { get; init; } = null!; /// <summary> /// Become Level 80. /// </summary> public GAchievement Reach80 { get; init; } = null!; /// <summary> /// Become Level 90 /// </summary> public GAchievement Reach90 { get; init; } = null!; /// <summary> /// Get hit 1,200 times randomly by Stompy, without getting hit by any other monster! /// </summary> public GAchievement Stomped { get; init; } = null!; /// <summary> /// Upgrade an item to +X. /// </summary> public GAchievement Upgrade10 { get; init; } = null!; } }
34.873418
97
0.501996
[ "MIT" ]
Sichii/ALClientCS
AL.Data/Achievements/AchievementsDatum.cs
2,757
C#
using System; using System.Security.Cryptography; using System.Text; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Newtonsoft.Json; using OpenTracing; namespace Epsagon.Dotnet.Instrumentation.Handlers.DynamoDB.Operations { public class PutItemRequestHandler : IOperationHandler { public void HandleOperationAfter(IExecutionContext context, IScope scope) { } public void HandleOperationBefore(IExecutionContext context, IScope scope) { var request = context.RequestContext.OriginalRequest as PutItemRequest; var item = JsonConvert.SerializeObject(request.Item, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); scope.Span.SetTag("resource.name", request.TableName); scope.Span.SetTag("aws.dynamodb.item", item); scope.Span.SetTag("aws.dynamodb.item_hash", CalculateMD5(item)); } private string CalculateMD5(string input) { using (var md5 = MD5.Create()) { var inputBytes = Encoding.ASCII.GetBytes(input); var hashBytes = md5.ComputeHash(inputBytes); return Convert.ToBase64String(hashBytes); } } } }
34.405405
95
0.670071
[ "MIT" ]
epsagon/epsagon-dotnet
src/Epsagon.Dotnet.Instrumentation/Handlers/DynamoDB/Operations/PutItemRequestHandler.cs
1,273
C#
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using System.Linq.Expressions; using System.Globalization; namespace Nest { public class FilterDescriptor<T> : FilterContainer where T : class { internal IFilterContainer Self { get { return this; } } public FilterDescriptor<T> Name(string name) { Self.FilterName = name; return this; } public FilterDescriptor<T> CacheKey(string cacheKey) { Self.CacheKey = cacheKey; return this; } public FilterDescriptor<T> Cache(bool cache) { Self.Cache = cache; return this; } public FilterDescriptor<T> Strict(bool strict = true) { var f = new FilterDescriptor<T>(); f.Self.IsStrict = strict; f.Self.IsVerbatim = Self.IsVerbatim; return f; } public FilterDescriptor<T> Verbatim(bool verbatim = true) { var f = new FilterDescriptor<T>(); f.Self.IsStrict = Self.IsStrict; f.Self.IsVerbatim = verbatim; return f; } /// <summary> /// A thin wrapper allowing fined grained control what should happen if a filter is conditionless /// if you need to fallback to something other than a match_all query /// </summary> public FilterContainer Conditionless(Action<ConditionlessFilterDescriptor<T>> selector) { var filter = new ConditionlessFilterDescriptor<T>(); selector(filter); return (filter.FilterDescriptor == null || filter.FilterDescriptor.IsConditionless) ? filter._Fallback : filter.FilterDescriptor; } internal FilterContainer Raw(string rawJson) { var f = new FilterDescriptor<T>(); f.Self.IsStrict = Self.IsStrict; f.Self.IsVerbatim = Self.IsVerbatim; f.Self.RawFilter = rawJson; return f; } /// <summary> /// Filters documents where a specific field has a value in them. /// </summary> public FilterContainer Exists(Expression<Func<T, object>> fieldDescriptor) { IExistsFilter filter = new ExistsFilterDescriptor(); filter.Field = fieldDescriptor; this.SetCacheAndName(filter); return this.New(filter, f => f.Exists = filter); } /// <summary> /// Filters documents where a specific field has a value in them. /// </summary> public FilterContainer Exists(string field) { IExistsFilter filter = new ExistsFilterDescriptor(); filter.Field = field; this.SetCacheAndName(filter); return this.New(filter, f => f.Exists = filter); } /// <summary> /// Filters documents where a specific field has no value in them. /// </summary> public FilterContainer Missing(Expression<Func<T, object>> fieldDescriptor, Action<MissingFilterDescriptor> selector = null) { var mf = new MissingFilterDescriptor(); if (selector != null) selector(mf); IMissingFilter filter = mf; filter.Field = fieldDescriptor; this.SetCacheAndName(filter); return this.New(filter, f => f.Missing = filter); } /// <summary> /// Filters documents where a specific field has no value in them. /// </summary> public FilterContainer Missing(string field, Action<MissingFilterDescriptor> selector = null) { var mf = new MissingFilterDescriptor(); if (selector != null) selector(mf); IMissingFilter filter = mf; filter.Field = field; this.SetCacheAndName(filter); return this.New(filter, f => f.Missing = filter); } /// <summary> /// Filters documents that only have the provided ids. /// Note, this filter does not require the _id field to be indexed since it works using the _uid field. /// </summary> public FilterContainer Ids(IEnumerable<string> values) { IIdsFilter filter = new IdsFilterDescriptor(); filter.Values = values; this.SetCacheAndName(filter); return this.New(filter, f => f.Ids = filter); } /// <summary> /// Filters documents that only have the provided ids. /// Note, this filter does not require the _id field to be indexed since it works using the _uid field. /// </summary> public FilterContainer Ids(string type, IEnumerable<string> values) { IIdsFilter filter = new IdsFilterDescriptor(); if (type.IsNullOrEmpty()) return CreateConditionlessFilterDescriptor(filter, null); filter.Values = values; filter.Type = new [] { type }; this.SetCacheAndName(filter); return this.New(filter, f => f.Ids = filter); } /// <summary> /// Filters documents that only have the provided ids. /// Note, this filter does not require the _id field to be indexed since it works using the _uid field. /// </summary> public FilterContainer Ids(IEnumerable<string> types, IEnumerable<string> values) { IIdsFilter filter = new IdsFilterDescriptor(); if (!types.HasAny() || types.All(t=>t.IsNullOrEmpty())) return CreateConditionlessFilterDescriptor(filter, null); filter.Values = values; filter.Type = types; this.SetCacheAndName(filter); return this.New(filter, f => f.Ids = filter); } /// <summary> /// A filter allowing to filter hits based on a point location using a bounding box /// </summary> public FilterContainer GeoBoundingBox(Expression<Func<T, object>> fieldDescriptor, double topLeftX, double topLeftY, double bottomRightX, double bottomRightY, GeoExecution? type = null) { var c = CultureInfo.InvariantCulture; topLeftX.ThrowIfNull("topLeftX"); topLeftY.ThrowIfNull("topLeftY"); bottomRightX.ThrowIfNull("bottomRightX"); bottomRightY.ThrowIfNull("bottomRightY"); var geoHashTopLeft = "{0}, {1}".F(topLeftX.ToString(c), topLeftY.ToString(c)); var geoHashBottomRight = "{0}, {1}".F(bottomRightX.ToString(c), bottomRightY.ToString(c)); return this.GeoBoundingBox(fieldDescriptor, geoHashTopLeft, geoHashBottomRight, type); } /// <summary> /// A filter allowing to filter hits based on a point location using a bounding box /// </summary> public FilterContainer GeoBoundingBox(string fieldName, double topLeftX, double topLeftY, double bottomRightX, double bottomRightY, GeoExecution? type = null) { var c = CultureInfo.InvariantCulture; topLeftX.ThrowIfNull("topLeftX"); topLeftY.ThrowIfNull("topLeftY"); bottomRightX.ThrowIfNull("bottomRightX"); bottomRightY.ThrowIfNull("bottomRightY"); var geoHashTopLeft = "{0}, {1}".F(topLeftX.ToString(c), topLeftY.ToString(c)); var geoHashBottomRight = "{0}, {1}".F(bottomRightX.ToString(c), bottomRightY.ToString(c)); return this.GeoBoundingBox(fieldName, geoHashTopLeft, geoHashBottomRight, type); } /// <summary> /// A filter allowing to filter hits based on a point location using a bounding box /// </summary> public FilterContainer GeoBoundingBox(Expression<Func<T, object>> fieldDescriptor, string geoHashTopLeft, string geoHashBottomRight, GeoExecution? type = null) { IGeoBoundingBoxFilter filter = new GeoBoundingBoxFilterDescriptor(); filter.TopLeft = geoHashTopLeft; filter.BottomRight = geoHashBottomRight; filter.GeoExecution = type; filter.Field = fieldDescriptor; return this.New(filter, f => f.GeoBoundingBox = filter); } /// <summary> /// A filter allowing to filter hits based on a point location using a bounding box /// </summary> public FilterContainer GeoBoundingBox(string fieldName, string geoHashTopLeft, string geoHashBottomRight, GeoExecution? type = null) { IGeoBoundingBoxFilter filter = new GeoBoundingBoxFilterDescriptor(); filter.TopLeft = geoHashTopLeft; filter.BottomRight = geoHashBottomRight; filter.GeoExecution = type; filter.Field = fieldName; return this.New(filter, f => f.GeoBoundingBox = filter); } /// <summary> /// Filters documents that include only hits that exists within a specific distance from a geo point. /// </summary> public FilterContainer GeoDistance(Expression<Func<T, object>> fieldDescriptor, Action<GeoDistanceFilterDescriptor> filterDescriptor) { return _GeoDistance(fieldDescriptor, filterDescriptor); } /// <summary> /// Filters documents that include only hits that exists within a specific distance from a geo point. /// </summary> public FilterContainer GeoDistance(string field, Action<GeoDistanceFilterDescriptor> filterDescriptor) { return _GeoDistance(field, filterDescriptor); } private FilterContainer _GeoDistance(PropertyPathMarker field, Action<GeoDistanceFilterDescriptor> filterDescriptor) { var filter = new GeoDistanceFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); IGeoDistanceFilter ff = filter; ff.Field = field; return this.New(filter, f => f.GeoDistance = filter); } /// <summary> /// Filters documents that exists within a range from a specific point: /// </summary> public FilterContainer GeoDistanceRange(Expression<Func<T, object>> fieldDescriptor, Action<GeoDistanceRangeFilterDescriptor> filterDescriptor) { return _GeoDistanceRange(fieldDescriptor, filterDescriptor); } /// <summary> /// Filters documents that exists within a range from a specific point: /// </summary> public FilterContainer GeoDistanceRange(string field, Action<GeoDistanceRangeFilterDescriptor> filterDescriptor) { return _GeoDistanceRange(field, filterDescriptor); } private FilterContainer _GeoDistanceRange(PropertyPathMarker field, Action<GeoDistanceRangeFilterDescriptor> filterDescriptor) { var filter = new GeoDistanceRangeFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); IGeoDistanceRangeFilter ff = filter; ff.Field = field; return this.New(ff, f => f.GeoDistanceRange = ff); } /// <summary> /// Filter documents indexed using the circle geo_shape type. /// </summary> public FilterContainer GeoShapeCircle(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeCircleFilterDescriptor> filterDescriptor) { return _GeoShapeCircle(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the circle geo_shape type. /// </summary> public FilterContainer GeoShapeCircle(string field, Action<GeoShapeCircleFilterDescriptor> filterDescriptor) { return _GeoShapeCircle(field, filterDescriptor); } private FilterContainer _GeoShapeCircle(PropertyPathMarker field, Action<GeoShapeCircleFilterDescriptor> filterDescriptor) { var filter = new GeoShapeCircleFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeCircleFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the envelope geo_shape type. /// </summary> public FilterContainer GeoShapeEnvelope(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeEnvelopeFilterDescriptor> filterDescriptor) { return _GeoShapeEnvelope(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the envelope geo_shape type. /// </summary> public FilterContainer GeoShapeEnvelope(string field, Action<GeoShapeEnvelopeFilterDescriptor> filterDescriptor) { return _GeoShapeEnvelope(field, filterDescriptor); } private FilterContainer _GeoShapeEnvelope(PropertyPathMarker field, Action<GeoShapeEnvelopeFilterDescriptor> filterDescriptor) { var filter = new GeoShapeEnvelopeFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeEnvelopeFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the linestring geo_shape type. /// </summary> public FilterContainer GeoShapeLineString(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeLineStringFilterDescriptor> filterDescriptor) { return _GeoShapeLineString(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the linestring geo_shape type. /// </summary> public FilterContainer GeoShapeLineString(string field, Action<GeoShapeLineStringFilterDescriptor> filterDescriptor) { return _GeoShapeLineString(field, filterDescriptor); } private FilterContainer _GeoShapeLineString(PropertyPathMarker field, Action<GeoShapeLineStringFilterDescriptor> filterDescriptor) { var filter = new GeoShapeLineStringFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeLineStringFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the multilinestring geo_shape type. /// </summary> public FilterContainer GeoShapeMultiLineString(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeMultiLineStringFilterDescriptor> filterDescriptor) { return _GeoShapeMultiLineString(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the multilinestring geo_shape type. /// </summary> public FilterContainer GeoShapeMultiLineString(string field, Action<GeoShapeMultiLineStringFilterDescriptor> filterDescriptor) { return _GeoShapeMultiLineString(field, filterDescriptor); } private FilterContainer _GeoShapeMultiLineString(PropertyPathMarker field, Action<GeoShapeMultiLineStringFilterDescriptor> filterDescriptor) { var filter = new GeoShapeMultiLineStringFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeMultiLineStringFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the point geo_shape type. /// </summary> public FilterContainer GeoShapePoint(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapePointFilterDescriptor> filterDescriptor) { return _GeoShapePoint(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the point geo_shape type. /// </summary> public FilterContainer GeoShapePoint(string field, Action<GeoShapePointFilterDescriptor> filterDescriptor) { return _GeoShapePoint(field, filterDescriptor); } private FilterContainer _GeoShapePoint(PropertyPathMarker field, Action<GeoShapePointFilterDescriptor> filterDescriptor) { var filter = new GeoShapePointFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapePointFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the multipoint geo_shape type. /// </summary> public FilterContainer GeoShapeMultiPoint(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeMultiPointFilterDescriptor> filterDescriptor) { return _GeoShapeMultiPoint(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the multipoint geo_shape type. /// </summary> public FilterContainer GeoShapeMultiPoint(string field, Action<GeoShapeMultiPointFilterDescriptor> filterDescriptor) { return _GeoShapeMultiPoint(field, filterDescriptor); } private FilterContainer _GeoShapeMultiPoint(PropertyPathMarker field, Action<GeoShapeMultiPointFilterDescriptor> filterDescriptor) { var filter = new GeoShapeMultiPointFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeMultiPointFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the polygon geo_shape type. /// </summary> public FilterContainer GeoShapePolygon(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapePolygonFilterDescriptor> filterDescriptor) { return _GeoShapePolygon(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the polygon geo_shape type. /// </summary> public FilterContainer GeoShapePolygon(string field, Action<GeoShapePolygonFilterDescriptor> filterDescriptor) { return _GeoShapePolygon(field, filterDescriptor); } private FilterContainer _GeoShapePolygon(PropertyPathMarker field, Action<GeoShapePolygonFilterDescriptor> filterDescriptor) { var filter = new GeoShapePolygonFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapePolygonFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the multipolygon geo_shape type. /// </summary> public FilterContainer GeoShapeMultiPolygon(Expression<Func<T, object>> fieldDescriptor, Action<GeoShapeMultiPolygonFilterDescriptor> filterDescriptor) { return _GeoShapeMultiPolygon(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the multipolygon geo_shape type. /// </summary> public FilterContainer GeoShapeMultiPolygon(string field, Action<GeoShapeMultiPolygonFilterDescriptor> filterDescriptor) { return _GeoShapeMultiPolygon(field, filterDescriptor); } private FilterContainer _GeoShapeMultiPolygon(PropertyPathMarker field, Action<GeoShapeMultiPolygonFilterDescriptor> filterDescriptor) { var filter = new GeoShapeMultiPolygonFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoShapeMultiPolygonFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// Filter documents indexed using the geo_shape type. /// </summary> public FilterContainer GeoIndexedShape(Expression<Func<T, object>> fieldDescriptor, Action<GeoIndexedShapeFilterDescriptor> filterDescriptor) { return this._GeoIndexedShape(fieldDescriptor, filterDescriptor); } /// <summary> /// Filter documents indexed using the geo_shape type. /// </summary> public FilterContainer GeoIndexedShape(string field, Action<GeoIndexedShapeFilterDescriptor> filterDescriptor) { return _GeoIndexedShape(field, filterDescriptor); } private FilterContainer _GeoIndexedShape(PropertyPathMarker field, Action<GeoIndexedShapeFilterDescriptor> filterDescriptor) { var filter = new GeoIndexedShapeFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((IGeoIndexedShapeFilter)filter).Field = field; return this.New(filter, f => f.GeoShape = filter); } /// <summary> /// A filter allowing to include hits that only fall within a polygon of points. /// </summary> public FilterContainer GeoPolygon(Expression<Func<T, object>> fieldDescriptor, IEnumerable<Tuple<double, double>> points) { var c = CultureInfo.InvariantCulture; return this._GeoPolygon(fieldDescriptor, points.Select(p => "{0}, {1}".F(p.Item1.ToString(c), p.Item2.ToString(c))).ToArray()); } /// <summary> /// A filter allowing to include hits that only fall within a polygon of points. /// </summary> public FilterContainer GeoPolygon(string field, IEnumerable<Tuple<double, double>> points) { var c = CultureInfo.InvariantCulture; return this.GeoPolygon(field, points.Select(p => "{0}, {1}".F(p.Item1.ToString(c), p.Item2.ToString(c))).ToArray()); } /// <summary> /// A filter allowing to include hits that only fall within a polygon of points. /// </summary> public FilterContainer GeoPolygon(Expression<Func<T, object>> fieldDescriptor, params string[] points) { return this._GeoPolygon(fieldDescriptor, points); } /// <summary> /// A filter allowing to include hits that only fall within a polygon of points. /// </summary> public FilterContainer GeoPolygon(string fieldName, params string[] points) { return _GeoPolygon(fieldName, points); } private FilterContainer _GeoPolygon(PropertyPathMarker fieldName, string[] points) { IGeoPolygonFilter filter = new GeoPolygonFilterDescriptor(); filter.Points = points; filter.Field = fieldName; return this.New(filter, f => f.GeoPolygon = filter); } /// <summary> /// The has_child filter accepts a query and the child type to run against, /// and results in parent documents that have child docs matching the query. /// </summary> /// <typeparam name="K">Type of the child</typeparam> public FilterContainer HasChild<K>(Action<HasChildFilterDescriptor<K>> filterSelector) where K : class { var filter = new HasChildFilterDescriptor<K>(); if (filterSelector != null) filterSelector(filter); return this.New(filter, f => f.HasChild = filter); } /// <summary> /// The has_child filter accepts a query and the child type to run against, /// and results in parent documents that have child docs matching the query. /// </summary> /// <typeparam name="K">Type of the child</typeparam> public FilterContainer HasParent<K>(Action<HasParentFilterDescriptor<K>> filterSelector) where K : class { var filter = new HasParentFilterDescriptor<K>(); if (filterSelector != null) filterSelector(filter); return this.New(filter, f => f.HasParent = filter); } /// <summary> /// A limit filter limits the number of documents (per shard) to execute on. /// </summary> public FilterContainer Limit(int? limit) { ILimitFilter filter = new LimitFilterDescriptor {}; filter.Value = limit; return this.New(filter, f => f.Limit = filter); } /// <summary> /// Filters documents matching the provided document / mapping type. /// Note, this filter can work even when the _type field is not indexed /// (using the _uid field). /// </summary> public FilterContainer Type(string type) { ITypeFilter filter = new TypeFilterDescriptor {}; filter.Value = type; return this.New(filter, f => f.Type = filter); } /// <summary> /// Filters documents matching the provided document / mapping type. /// Note, this filter can work even when the _type field is not indexed /// (using the _uid field). /// </summary> public FilterContainer Type(Type type) { ITypeFilter filter = new TypeFilterDescriptor {}; filter.Value = type; return this.New(filter, f=> f.Type = filter); } /// <summary> /// A filter that matches on all documents. /// </summary> public FilterContainer MatchAll() { var filter = new MatchAllFilterDescriptor { }; return this.New(filter, f=> f.MatchAll = filter); } /// <summary> /// Filters documents with fields that have terms within a certain range. /// Similar to range query, except that it acts as a filter. /// </summary> public FilterContainer Range(Action<RangeFilterDescriptor<T>> rangeSelector) { var filter = new RangeFilterDescriptor<T>(); if (rangeSelector != null) rangeSelector(filter); return this.New(filter, f=>f.Range = filter); } /// <summary> /// A filter allowing to define scripts as filters. /// </summary> public FilterContainer Script(Action<ScriptFilterDescriptor> scriptSelector) { var descriptor = new ScriptFilterDescriptor(); if (scriptSelector != null) scriptSelector(descriptor); return this.New(descriptor, f=>f.Script = descriptor); } /// <summary> /// Filters documents that have fields containing terms with a specified prefix /// (not analyzed). Similar to phrase query, except that it acts as a filter. /// </summary> public FilterContainer Prefix(Expression<Func<T, object>> fieldDescriptor, string prefix) { IPrefixFilter filter = new PrefixFilterDescriptor(); filter.Field = fieldDescriptor; filter.Prefix = prefix; return this.New(filter, f=>f.Prefix = filter); } /// <summary> /// Filters documents that have fields containing terms with a specified prefix /// (not analyzed). Similar to phrase query, except that it acts as a filter. /// </summary> public FilterContainer Prefix(string field, string prefix) { IPrefixFilter filter = new PrefixFilterDescriptor(); filter.Field = field; filter.Prefix = prefix; return this.New(filter, f=>f.Prefix = filter); } /// <summary> /// Filters documents that have fields that contain a term (not analyzed). /// Similar to term query, except that it acts as a filter /// </summary> public FilterContainer Term<K>(Expression<Func<T, K>> fieldDescriptor, K term) { ITermFilter filter = new TermFilterDescriptor(); filter.Field = fieldDescriptor; filter.Value = term; return this.New(filter, f=>f.Term = filter); } /// <summary> /// Filters documents that have fields that contain a term (not analyzed). /// Similar to term query, except that it acts as a filter /// </summary> public FilterContainer Term(Expression<Func<T, object>> fieldDescriptor, object term) { ITermFilter filter = new TermFilterDescriptor(); filter.Field = fieldDescriptor; filter.Value = term; return this.New(filter, f=>f.Term = filter); } /// <summary> /// Filters documents that have fields that contain a term (not analyzed). /// Similar to term query, except that it acts as a filter /// </summary> public FilterContainer Term(string field, object term) { ITermFilter filter = new TermFilterDescriptor(); filter.Field = field; filter.Value = term; return this.New(filter, f=>f.Term = filter); } /// <summary> /// Filters documents that have fields that match any of the provided terms (not analyzed). /// </summary> public FilterContainer Terms<K>(Expression<Func<T, K>> fieldDescriptor, IEnumerable<K> terms, TermsExecution? Execution = null) { ITermsFilter filter = new TermsFilterDescriptor(); filter.Field = fieldDescriptor; filter.Terms = (terms != null) ? terms.Cast<object>() : null; filter.Execution = Execution; return this.New(filter, f=>f.Terms = filter); } /// <summary> /// Filters documents that have fields that match any of the provided terms (not analyzed). /// </summary> public FilterContainer Terms(Expression<Func<T, object>> fieldDescriptor, IEnumerable<string> terms, TermsExecution? Execution = null) { ITermsFilter filter = new TermsFilterDescriptor(); filter.Field = fieldDescriptor; filter.Terms = terms; filter.Execution = Execution; return this.New(filter, f=>f.Terms = filter); } /// <summary> /// Filters documents that have fields that match any of the provided terms (not analyzed). /// </summary> public FilterContainer Terms(string field, IEnumerable<string> terms, TermsExecution? Execution = null) { ITermsFilter filter = new TermsFilterDescriptor(); filter.Field = field; filter.Terms = terms ?? Enumerable.Empty<string>(); filter.Execution = Execution; return this.New(filter, f=>f.Terms = filter); } /// <summary> /// Filter documents indexed using the geo_shape type. /// </summary> public FilterContainer TermsLookup(Expression<Func<T, object>> fieldDescriptor, Action<TermsLookupFilterDescriptor> filterDescriptor) { var filter = new TermsLookupFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((ITermsBaseFilter)filter).Field = fieldDescriptor; return this.New(filter, f=>f.Terms = filter); } /// <summary> /// Filter documents indexed using the geo_shape type. /// </summary> public FilterContainer TermsLookup(string field, Action<TermsLookupFilterDescriptor> filterDescriptor) { var filter = new TermsLookupFilterDescriptor(); if (filterDescriptor != null) filterDescriptor(filter); ((ITermsBaseFilter)filter).Field = field; return this.New(filter, f=>f.Terms = filter); } /// <summary> /// A filter that matches documents using AND boolean operator on other queries. /// This filter is more performant then bool filter. /// </summary> public FilterContainer And(params Func<FilterDescriptor<T>, FilterContainer>[] selectors) { return this.And((from selector in selectors let filter = new FilterDescriptor<T>() { IsConditionless = true} select selector(filter)).ToArray()); } /// <summary> /// A filter that matches documents using AND boolean operator on other queries. /// This filter is more performant then bool filter. /// </summary> public FilterContainer And(params FilterContainer[] filtersDescriptor) { var andFilter = new AndFilterDescriptor(); ((IAndFilter)andFilter).Filters = filtersDescriptor.Cast<IFilterContainer>().ToList(); return this.New(andFilter, f=>f.And = andFilter); } /// <summary> /// A filter that matches documents using OR boolean operator on other queries. /// This filter is more performant then bool filter /// </summary> public FilterContainer Or(params Func<FilterDescriptor<T>, FilterContainer>[] selectors) { var descriptors = (from selector in selectors let filter = new FilterDescriptor<T>() { IsConditionless = true} select selector(filter) ).ToArray(); return this.Or(descriptors); } /// <summary> /// A filter that matches documents using OR boolean operator on other queries. /// This filter is more performant then bool filter /// </summary> public FilterContainer Or(params FilterContainer[] filtersDescriptor) { var orFilter = new OrFilterDescriptor(); ((IOrFilter)orFilter).Filters = filtersDescriptor.Cast<IFilterContainer>().ToList(); return this.New(orFilter, f=> f.Or = orFilter); } /// <summary> /// A filter that filters out matched documents using a query. /// This filter is more performant then bool filter. /// </summary> public FilterContainer Not(Func<FilterDescriptor<T>, FilterContainer> selector) { var notFilter = new NotFilterDescriptor(); var filter = new FilterDescriptor<T>() { IsConditionless = true }; FilterContainer bf = filter; if (selector != null) bf = selector(filter); ((INotFilter)notFilter).Filter = bf; return this.New(notFilter, f=>f.Not = notFilter); } /// <summary> /// /// A filter that matches documents matching boolean combinations of other queries. /// Similar in concept to Boolean query, except that the clauses are other filters. /// </summary> public FilterContainer Bool(Action<BoolFilterDescriptor<T>> booleanFilter) { var filter = new BoolFilterDescriptor<T>(); if (booleanFilter != null) booleanFilter(filter); return this.New(filter, f=>f.Bool = filter); } /// <summary> /// Wraps any query to be used as a filter. /// </summary> public FilterContainer Query(Func<QueryDescriptor<T>, QueryContainer> querySelector) { var filter = new QueryFilterDescriptor(); var descriptor = new QueryDescriptor<T>(); QueryContainer bq = descriptor; if (querySelector != null) bq = querySelector(descriptor); ((IQueryFilter)filter).Query = bq; return this.New(filter, f=>f.Query = filter); } /// <summary> /// A nested filter, works in a similar fashion to the nested query, except used as a filter. /// It follows exactly the same structure, but also allows to cache the results /// (set _cache to true), and have it named (set the _name value). /// </summary> /// <param name="selector"></param> public FilterContainer Nested(Action<NestedFilterDescriptor<T>> selector) { var filter = new NestedFilterDescriptor<T>(); if (selector != null) selector(filter); return this.New(filter, f=>f.Nested = filter); } /// <summary> /// The regexp filter allows you to use regular expression term queries. /// </summary> /// <param name="selector"></param> public FilterContainer Regexp(Action<RegexpFilterDescriptor<T>> selector) { var filter = new RegexpFilterDescriptor<T>(); if (selector != null) selector(filter); return this.New(filter, f=>f.Regexp = filter); } private FilterDescriptor<T> CreateConditionlessFilterDescriptor(IFilter filter, string type = null) { var self = Self; if (self.IsStrict && !self.IsVerbatim) throw new DslException("Filter resulted in a conditionless '{1}' filter (json by approx):\n{0}" .F( JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }) , type ?? filter.GetType().Name.Replace("Descriptor", "").Replace("`1", "") ) ); var f = new FilterDescriptor<T>(); f.Self.IsStrict = self.IsStrict; f.Self.IsVerbatim = self.IsVerbatim; f.IsConditionless = true; return f; } private FilterDescriptor<T> New(IFilter filter, Action<IFilterContainer> fillProperty) { var self = Self; if (filter.IsConditionless && !self.IsVerbatim) { this.ResetCache(); return CreateConditionlessFilterDescriptor(filter); } this.SetCacheAndName(filter); var f = new FilterDescriptor<T>(); f.Self.IsStrict = self.IsStrict; f.Self.IsVerbatim = self.IsVerbatim; if (fillProperty != null) fillProperty(f); this.ResetCache(); return f; } private void ResetCache() { Self.Cache = null; Self.CacheKey = null; Self.FilterName = null; } private void SetCacheAndName(IFilter filter) { var self = Self; filter.IsStrict = self.IsStrict; filter.IsVerbatim = self.IsVerbatim; if (Self.Cache.HasValue) filter.Cache = Self.Cache; if (!string.IsNullOrWhiteSpace(Self.FilterName)) filter.FilterName = Self.FilterName; if (!string.IsNullOrWhiteSpace(Self.CacheKey)) filter.CacheKey = Self.CacheKey; } } }
36
187
0.72153
[ "Apache-2.0" ]
Tasteful/elasticsearch-net
src/Nest/DSL/Filter/FilterDescriptor.cs
33,230
C#
using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; namespace Frank.Libraries.Fiken.Models { /// <summary> /// /// </summary> public class InvoiceRequest { /// <summary> /// UUID are represented as 32 hexadecimal (base-16) digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters. If not provided, API will generate a UUID. /// </summary> /// <value>UUID are represented as 32 hexadecimal (base-16) digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters. If not provided, API will generate a UUID.</value> [DataMember(Name = "uuid", EmitDefaultValue = false)] [JsonProperty(PropertyName = "uuid")] public string Uuid { get; set; } /// <summary> /// Date that the invoice was issued, format yyyy-mm-dd /// </summary> /// <value>Date that the invoice was issued, format yyyy-mm-dd</value> [DataMember(Name = "issueDate", EmitDefaultValue = false)] [JsonProperty(PropertyName = "issueDate")] public DateTime? IssueDate { get; set; } /// <summary> /// Due date of invoice, format yyyy-mm-dd /// </summary> /// <value>Due date of invoice, format yyyy-mm-dd</value> [DataMember(Name = "dueDate", EmitDefaultValue = false)] [JsonProperty(PropertyName = "dueDate")] public DateTime? DueDate { get; set; } /// <summary> /// Gets or Sets Lines /// </summary> [DataMember(Name = "lines", EmitDefaultValue = false)] [JsonProperty(PropertyName = "lines")] public List<InvoiceLineRequest> Lines { get; set; } /// <summary> /// Gets or Sets OurReference /// </summary> [DataMember(Name = "ourReference", EmitDefaultValue = false)] [JsonProperty(PropertyName = "ourReference")] public string OurReference { get; set; } /// <summary> /// Your reference for invoice, free string format /// </summary> /// <value>Your reference for invoice, free string format</value> [DataMember(Name = "yourReference", EmitDefaultValue = false)] [JsonProperty(PropertyName = "yourReference")] public string YourReference { get; set; } /// <summary> /// Reference if sending via EHF. /// </summary> /// <value>Reference if sending via EHF.</value> [DataMember(Name = "orderReference", EmitDefaultValue = false)] [JsonProperty(PropertyName = "orderReference")] public string OrderReference { get; set; } /// <summary> /// customerId = contactId where customer = true /// </summary> /// <value>customerId = contactId where customer = true</value> [DataMember(Name = "customerId", EmitDefaultValue = false)] [JsonProperty(PropertyName = "customerId")] public long? CustomerId { get; set; } /// <summary> /// Id of the contact person. Must be associated with the provided customer. /// </summary> /// <value>Id of the contact person. Must be associated with the provided customer.</value> [DataMember(Name = "contactPersonId", EmitDefaultValue = false)] [JsonProperty(PropertyName = "contactPersonId")] public long? ContactPersonId { get; set; } /// <summary> /// Bank account code associated with invoice, format 1920:XXXXX /// </summary> /// <value>Bank account code associated with invoice, format 1920:XXXXX</value> [DataMember(Name = "bankAccountCode", EmitDefaultValue = false)] [JsonProperty(PropertyName = "bankAccountCode")] public string BankAccountCode { get; set; } /// <summary> /// ISO 4217 currency code. Defaults to \"NOK\" if unspecified. /// </summary> /// <value>ISO 4217 currency code. Defaults to \"NOK\" if unspecified.</value> [DataMember(Name = "currency", EmitDefaultValue = false)] [JsonProperty(PropertyName = "currency")] public string Currency { get; set; } /// <summary> /// Gets or Sets InvoiceText /// </summary> [DataMember(Name = "invoiceText", EmitDefaultValue = false)] [JsonProperty(PropertyName = "invoiceText")] public string InvoiceText { get; set; } /// <summary> /// Payment taken in cash (True) or not (False). /// </summary> /// <value>Payment taken in cash (True) or not (False).</value> [DataMember(Name = "cash", EmitDefaultValue = false)] [JsonProperty(PropertyName = "cash")] public bool? Cash { get; set; } /// <summary> /// For Cash Invoices only. For instance \"1920:10001\". /// </summary> /// <value>For Cash Invoices only. For instance \"1920:10001\".</value> [DataMember(Name = "paymentAccount", EmitDefaultValue = false)] [JsonProperty(PropertyName = "paymentAccount")] public string PaymentAccount { get; set; } /// <summary> /// Optional - Associated project for the invoice to be created. /// </summary> /// <value>Optional - Associated project for the invoice to be created.</value> [DataMember(Name = "projectId", EmitDefaultValue = false)] [JsonProperty(PropertyName = "projectId")] public long? ProjectId { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InvoiceRequest {\n"); sb.Append(" Uuid: ") .Append(Uuid) .Append("\n"); sb.Append(" IssueDate: ") .Append(IssueDate) .Append("\n"); sb.Append(" DueDate: ") .Append(DueDate) .Append("\n"); sb.Append(" Lines: ") .Append(Lines) .Append("\n"); sb.Append(" OurReference: ") .Append(OurReference) .Append("\n"); sb.Append(" YourReference: ") .Append(YourReference) .Append("\n"); sb.Append(" OrderReference: ") .Append(OrderReference) .Append("\n"); sb.Append(" CustomerId: ") .Append(CustomerId) .Append("\n"); sb.Append(" ContactPersonId: ") .Append(ContactPersonId) .Append("\n"); sb.Append(" BankAccountCode: ") .Append(BankAccountCode) .Append("\n"); sb.Append(" Currency: ") .Append(Currency) .Append("\n"); sb.Append(" InvoiceText: ") .Append(InvoiceText) .Append("\n"); sb.Append(" Cash: ") .Append(Cash) .Append("\n"); sb.Append(" PaymentAccount: ") .Append(PaymentAccount) .Append("\n"); sb.Append(" ProjectId: ") .Append(ProjectId) .Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
39.860963
223
0.556211
[ "MIT" ]
frankhaugen/Frank.Extensions
src/Frank.Libraries.Fiken/Models/InvoiceRequest.cs
7,454
C#
using MixERP.Net.FrontEnd.Base; using MixERP.Net.FrontEnd.Controls; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace MixERP.Net.Core.Modules.Sales.Reports { public partial class SalesOrderReport : MixERPUserControl { public override void OnControlLoad(object sender, EventArgs e) { Collection<KeyValuePair<string, object>> list = new Collection<KeyValuePair<string, object>>(); list.Add(new KeyValuePair<string, object>("@non_gl_stock_master_id", this.Page.Request["TranId"])); using (WebReport report = new WebReport()) { report.AddParameterToCollection(list); report.AddParameterToCollection(list); report.AutoInitialize = true; report.Path = "~/Modules/Sales/Reports/Source/Sales.Order.xml"; this.Controls.Add(report); } } } }
35.407407
111
0.64749
[ "MPL-2.0" ]
asine/mixerp
src/FrontEnd/Modules/Sales/Reports/SalesOrderReport.ascx.cs
958
C#
using System; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using NLog.Web; namespace RecipeBook.Api { public class Program { public static void Main(string[] args) { // NLog: setup the logger first to catch all errors var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateWebHostBuilder(args).Build().Run(); } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Trace); }) .UseNLog(); } }
31.181818
127
0.539359
[ "MIT" ]
XardasLord/RecipeBook
RecipeBook.Api/Program.cs
1,374
C#
using Abp.Domain.Entities; using Abp.Events.Bus.Entities; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Abp.EntityHistory { [Table("AbpEntityChanges")] public class EntityChange : Entity<Guid>, IMayHaveTenant { /// <summary> /// Maximum length of <see cref="EntityId"/> property. /// Value: 48. /// </summary> public const int MaxEntityIdLength = 48; /// <summary> /// Maximum length of <see cref="EntityTypeFullName"/> property. /// Value: 192. /// </summary> public const int MaxEntityTypeFullNameLength = 192; /// <summary> /// ChangeTime. /// </summary> public virtual DateTime ChangeTime { get; set; } /// <summary> /// ChangeType. /// </summary> public virtual EntityChangeType ChangeType { get; set; } /// <summary> /// Gets/sets change set id, used to group entity changes. /// </summary> public virtual Guid EntityChangeSetId { get; set; } /// <summary> /// Gets/sets primary key of the entity. /// </summary> [MaxLength(MaxEntityIdLength)] public virtual string EntityId { get; set; } /// <summary> /// FullName of the entity type. /// </summary> [MaxLength(MaxEntityTypeFullNameLength)] public virtual string EntityTypeFullName { get; set; } /// <summary> /// TenantId. /// </summary> public virtual Guid? TenantId { get; set; } /// <summary> /// PropertyChanges. /// </summary> public virtual ICollection<EntityPropertyChange> PropertyChanges { get; set; } #region Not mapped [NotMapped] public virtual object EntityEntry { get; set; } #endregion } }
27.9
86
0.580133
[ "MIT" ]
aprognimak/aspnetboilerplate
src/Abp/EntityHistory/EntityChange.cs
1,955
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; namespace IronPython.Runtime.Types { [PythonType("getset_descriptor")] public sealed class PythonTypeWeakRefSlot : PythonTypeSlot, ICodeFormattable { PythonType _type; public PythonTypeWeakRefSlot(PythonType parent) { this._type = parent; } internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (instance == null) { value = this; return true; } IWeakReferenceable reference; if (context.GetPythonContext().TryConvertToWeakReferenceable(instance, out reference)) { WeakRefTracker tracker = reference.GetWeakRef(); if (tracker == null || tracker.HandlerCount == 0) { value = null; } else { value = tracker.GetHandlerCallback(0); } return true; } value = null; return false; } internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { IWeakReferenceable reference; if (context.GetPythonContext().TryConvertToWeakReferenceable(instance, out reference)) { return reference.SetWeakRef(new WeakRefTracker(value, instance)); } return false; } internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.TypeError("__weakref__ attribute cannot be deleted"); } public override string ToString() { return String.Format("<attribute '__weakref__' of '{0}' objects>", _type.Name); } #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return String.Format("<attribute '__weakref__' of {0} objects", PythonOps.Repr(context, _type)); } #endregion } }
37.355263
118
0.587883
[ "Apache-2.0" ]
0xFireball/exascript2
Src/IronPython/Runtime/Types/PythonTypeWeakRefSlot.cs
2,839
C#
using HidApiSharp; namespace JoyConSharp { public sealed class JoyConManager : IDisposable { public readonly Dictionary<string, JoyCon> JoyCons = new(); public event Action<JoyCon> Connected = delegate { }; public event Action<JoyCon> Disconnected = delegate { }; readonly CancellationTokenSource cts = new(); Task? loopTask; public void Start() { loopTask = LoopAsync(); } async Task LoopAsync() { while (!cts.IsCancellationRequested) { try { var connectedInfos = Enumerable.Empty<HidDeviceInfo>() .Concat(HidDeviceInfo.Enumerate((ushort)JoyConVendorID.Nintendo, (ushort)JoyConProductID.JoyConLeft)) .Concat(HidDeviceInfo.Enumerate((ushort)JoyConVendorID.Nintendo, (ushort)JoyConProductID.JoyConRight)) .ToDictionary(inf => inf.SerialNumber, inf => inf); foreach (var (serial, disconnectedJoyCon) in JoyCons.Where(kvp => !connectedInfos.ContainsKey(kvp.Key)).ToArray()) { JoyCons.Remove(serial); disconnectedJoyCon.Dispose(); Disconnected(disconnectedJoyCon); } foreach (var newInfo in connectedInfos.Values.Where(inf => !JoyCons.ContainsKey(inf.SerialNumber)).ToArray()) { var device = HidDevice.Open(newInfo); if (device == null) continue; var joyCon = new JoyCon(device); JoyCons.Add(newInfo.SerialNumber, joyCon); Connected(joyCon); } } catch (Exception e) { Console.WriteLine($"[JoyConManager] Error: {e}"); } await Task.Delay(100, cts.Token); } } public void Dispose() { cts.Cancel(); cts.Dispose(); try { loopTask?.Wait(); } catch (TaskCanceledException) { } catch (Exception e) { Console.WriteLine($"[JoyConManager] Error: {e}"); } foreach (var joyCon in JoyCons.Values) { joyCon.Dispose(); } } } }
33.766234
153
0.466923
[ "MIT" ]
chiepomme/NonDominant
JoyConSharp/Source/JoyCon/JoyConManager.cs
2,602
C#
//------------------------------------------------------------------------------ // <copyright file="ApplicationManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Hosting { using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Util; public enum HostSecurityPolicyResults { DefaultPolicy = 0, FullTrust = 1, AppDomainTrust = 2, Nothing = 3 }; [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] public class HostSecurityPolicyResolver { public virtual HostSecurityPolicyResults ResolvePolicy(Evidence evidence) { return HostSecurityPolicyResults.DefaultPolicy; } } internal class LockableAppDomainContext { internal HostingEnvironment HostEnv { get; set; } internal string PreloadContext { get; set; } internal bool RetryingPreload { get; set; } internal LockableAppDomainContext() { } } public sealed class ApplicationManager : MarshalByRefObject { private const string _regexMatchTimeoutKey = "REGEX_DEFAULT_MATCH_TIMEOUT"; private static readonly StrongName _mwiV1StrongName = GetMicrosoftWebInfrastructureV1StrongName(); private static Object _applicationManagerStaticLock = new Object(); // open count (when last close goes to 0 it shuts down everything) int _openCount = 0; bool _shutdownInProgress = false; // table of app domains (LockableAppDomainContext objects) by app id // To simplify per-appdomain synchronization we will never remove LockableAppDomainContext objects from this table even when the AD is unloaded // We may need to fix it if profiling shows a noticeable impact on performance private Dictionary <string, LockableAppDomainContext> _appDomains = new Dictionary<string, LockableAppDomainContext>(StringComparer.OrdinalIgnoreCase); // count of HostingEnvironment instances that is referenced in _appDomains collection private int _accessibleHostingEnvCount; // could differ from _appDomains or _accessibleHostingEnvCount count (host env is active some time after it is removed) private int _activeHostingEnvCount; // pending callback to respond to ping (typed as Object to do Interlocked operations) private Object _pendingPingCallback; // delegate OnRespondToPing private WaitCallback _onRespondToPingWaitCallback; // single instance of app manager private static ApplicationManager _theAppManager; // single instance of cache manager private static CacheManager _cm; // store fatal exception to assist debugging private static Exception _fatalException = null; internal ApplicationManager() { _onRespondToPingWaitCallback = new WaitCallback(this.OnRespondToPingWaitCallback); // VSWhidbey 555767: Need better logging for unhandled exceptions (http://support.microsoft.com/?id=911816) // We only add a handler in the default domain because it will be notified when an unhandled exception // occurs in ANY domain. // WOS 1983175: (weird) only the handler in the default domain is notified when there is an AV in a native module // while we're in a call to MgdIndicateCompletion. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException); } private void InitCacheManager(long privateBytesLimit) { if (_cm == null) { lock (_applicationManagerStaticLock) { if (_cm == null && !_shutdownInProgress) { _cm = new CacheManager(this, privateBytesLimit); } } } } private void DisposeCacheManager() { if (_cm != null) { lock (_applicationManagerStaticLock) { if (_cm != null) { _cm.Dispose(); _cm = null; } } } } // Each cache must update the total with the difference between it's current size and it's previous size. // To reduce cross-domain costs, this also returns the updated total size. internal long GetUpdatedTotalCacheSize(long sizeUpdate) { CacheManager cm = _cm; return (cm != null) ? cm.GetUpdatedTotalCacheSize(sizeUpdate) : 0; } internal long TrimCaches(int percent) { long trimmedOrExpired = 0; Dictionary<string, LockableAppDomainContext> apps = CloneAppDomainsCollection(); foreach (LockableAppDomainContext ac in apps.Values) { lock (ac) { HostingEnvironment env = ac.HostEnv; if (_shutdownInProgress) { break; } if (env == null) { continue; } trimmedOrExpired += env.TrimCache(percent); } } return trimmedOrExpired; } internal bool ShutdownInProgress { get { return _shutdownInProgress; } } internal static void RecordFatalException(Exception e) { RecordFatalException(AppDomain.CurrentDomain, e); } internal static void RecordFatalException(AppDomain appDomain, Exception e) { // store the exception from the first caller to assist debugging object originalValue = Interlocked.CompareExchange(ref _fatalException, e, null); if (originalValue == null) { // create event log entry Misc.WriteUnhandledExceptionToEventLog(appDomain, e); } } private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs eventArgs) { // if the CLR is not terminating, ignore the notification if (!eventArgs.IsTerminating) { return; } Exception exception = eventArgs.ExceptionObject as Exception; if (exception == null) { return; } AppDomain appDomain = sender as AppDomain; if (appDomain == null) { return; } RecordFatalException(appDomain, exception); } public override Object InitializeLifetimeService() { return null; // never expire lease } // // public ApplicationManager methods // public static ApplicationManager GetApplicationManager() { if (_theAppManager == null) { lock (_applicationManagerStaticLock) { if (_theAppManager == null) { if (HostingEnvironment.IsHosted) _theAppManager = HostingEnvironment.GetApplicationManager(); if (_theAppManager == null) _theAppManager = new ApplicationManager(); } } } return _theAppManager; } [SecurityPermission(SecurityAction.Demand, Unrestricted=true)] public void Open() { Interlocked.Increment(ref _openCount); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public void Close() { if (Interlocked.Decrement(ref _openCount) > 0) return; // need to shutdown everything ShutdownAll(); } private string CreateSimpleAppID(VirtualPath virtualPath, string physicalPath, string siteName) { // Put together some unique app id string appId = String.Concat(virtualPath.VirtualPathString, physicalPath); if (!String.IsNullOrEmpty(siteName)) { appId = String.Concat(appId, siteName); } return appId.GetHashCode().ToString("x", CultureInfo.InvariantCulture); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public IRegisteredObject CreateObject(IApplicationHost appHost, Type type) { if (appHost == null) { throw new ArgumentNullException("appHost"); } if (type == null) { throw new ArgumentNullException("type"); } string appID = CreateSimpleAppID(appHost); return CreateObjectInternal(appID, type, appHost, false); } [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)] public IRegisteredObject CreateObject(String appId, Type type, string virtualPath, string physicalPath, bool failIfExists) { return CreateObject(appId, type, virtualPath, physicalPath, failIfExists, false /*throwOnError*/); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public IRegisteredObject CreateObject(String appId, Type type, string virtualPath, string physicalPath, bool failIfExists, bool throwOnError) { // check args if (appId == null) throw new ArgumentNullException("appId"); SimpleApplicationHost appHost = new SimpleApplicationHost(VirtualPath.CreateAbsolute(virtualPath), physicalPath); // if throw on error flag is set, create hosting parameters accordingly HostingEnvironmentParameters hostingParameters = null; if (throwOnError) { hostingParameters = new HostingEnvironmentParameters(); hostingParameters.HostingFlags = HostingEnvironmentFlags.ThrowHostingInitErrors; } // call the internal method return CreateObjectInternal(appId, type, appHost, failIfExists, hostingParameters); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] internal IRegisteredObject CreateObjectInternal(String appId, Type type, IApplicationHost appHost, bool failIfExists) { // check args if (appId == null) throw new ArgumentNullException("appId"); if (type == null) throw new ArgumentNullException("type"); if (appHost == null) throw new ArgumentNullException("appHost"); // call the internal method return CreateObjectInternal(appId, type, appHost, failIfExists, null /*hostingParameters*/); } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] internal IRegisteredObject CreateObjectInternal( String appId, Type type, IApplicationHost appHost, bool failIfExists, HostingEnvironmentParameters hostingParameters) { // check that type is as IRegisteredObject if (!typeof(IRegisteredObject).IsAssignableFrom(type)) throw new ArgumentException(SR.GetString(SR.Not_IRegisteredObject, type.FullName), "type"); // get hosting environment HostingEnvironment env = GetAppDomainWithHostingEnvironment(appId, appHost, hostingParameters); // create the managed object in the worker app domain // When marshaling Type, the AppDomain must have FileIoPermission to the assembly, which is not // always the case, so we marshal the assembly qualified name instead ObjectHandle h = env.CreateWellKnownObjectInstance(type.AssemblyQualifiedName, failIfExists); return (h != null) ? h.Unwrap() as IRegisteredObject : null; } internal IRegisteredObject CreateObjectWithDefaultAppHostAndAppId( String physicalPath, string virtualPath, Type type, out String appId, out IApplicationHost appHost) { return CreateObjectWithDefaultAppHostAndAppId(physicalPath, VirtualPath.CreateNonRelative(virtualPath), type, out appId, out appHost); } internal IRegisteredObject CreateObjectWithDefaultAppHostAndAppId( String physicalPath, VirtualPath virtualPath, Type type, out String appId, out IApplicationHost appHost) { HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters(); hostingParameters.HostingFlags = HostingEnvironmentFlags.DontCallAppInitialize; return CreateObjectWithDefaultAppHostAndAppId( physicalPath, virtualPath, type, false, hostingParameters, out appId, out appHost); } internal IRegisteredObject CreateObjectWithDefaultAppHostAndAppId( String physicalPath, VirtualPath virtualPath, Type type, bool failIfExists, HostingEnvironmentParameters hostingParameters, out String appId, out IApplicationHost appHost) { #if !FEATURE_PAL // FEATURE_PAL does not enable IIS-based hosting features if (physicalPath == null) { // If the physical path is null, we use an ISAPIApplicationHost based // on the virtual path (or metabase id). // Make sure the static HttpRuntime is created so isapi assembly can be loaded properly. HttpRuntime.ForceStaticInit(); ISAPIApplicationHost isapiAppHost = new ISAPIApplicationHost(virtualPath.VirtualPathString, null, true, null, hostingParameters.IISExpressVersion); appHost = isapiAppHost; appId = isapiAppHost.AppId; virtualPath = VirtualPath.Create(appHost.GetVirtualPath()); physicalPath = FileUtil.FixUpPhysicalDirectory(appHost.GetPhysicalPath()); } else { #endif // !FEATURE_PAL // If the physical path was passed in, don't use an Isapi host. Instead, // use a simple app host which does simple virtual to physical mappings // Put together some unique app id appId = CreateSimpleAppID(virtualPath, physicalPath, null); appHost = new SimpleApplicationHost(virtualPath, physicalPath); } string precompTargetPhysicalDir = hostingParameters.PrecompilationTargetPhysicalDirectory; if (precompTargetPhysicalDir != null) { // Change the appID so we use a different codegendir in precompile for deployment scenario, // this ensures we don't use or pollute the regular codegen files. Also, use different // ID's depending on whether the precompilation is Updatable (VSWhidbey 383239) if ((hostingParameters.ClientBuildManagerParameter != null) && (hostingParameters.ClientBuildManagerParameter.PrecompilationFlags & PrecompilationFlags.Updatable) == 0) appId = appId + "_precompile"; else appId = appId + "_precompile_u"; } return CreateObjectInternal(appId, type, appHost, failIfExists, hostingParameters); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public IRegisteredObject GetObject(String appId, Type type) { // check args if (appId == null) throw new ArgumentNullException("appId"); if (type == null) throw new ArgumentNullException("type"); LockableAppDomainContext ac = GetLockableAppDomainContext(appId); lock (ac) { HostingEnvironment env = ac.HostEnv; if (env == null) return null; // find the instance by type // When marshaling Type, the AppDomain must have FileIoPermission to the assembly, which is not // always the case, so we marshal the assembly qualified name instead ObjectHandle h = env.FindWellKnownObject(type.AssemblyQualifiedName); return (h != null) ? h.Unwrap() as IRegisteredObject : null; } } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public AppDomain GetAppDomain(string appId) { if (appId == null) { throw new ArgumentNullException("appId"); } LockableAppDomainContext ac = GetLockableAppDomainContext(appId); lock (ac) { HostingEnvironment env = ac.HostEnv; if (env == null) { return null; } return env.HostedAppDomain; } } public AppDomain GetAppDomain(IApplicationHost appHost) { if (appHost == null) { throw new ArgumentNullException("appHost"); } string appID = CreateSimpleAppID(appHost); return GetAppDomain(appID); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This isn't a dangerous method.")] private string CreateSimpleAppID(IApplicationHost appHost) { if (appHost == null) { throw new ArgumentNullException("appHost"); } return CreateSimpleAppID(VirtualPath.Create(appHost.GetVirtualPath()), appHost.GetPhysicalPath(), appHost.GetSiteName()); } // if a "well-known" object of the specified type already exists in the application, // remove the app from the managed application table. This is // used in IIS7 integrated mode when IIS7 determines that it is necessary to create // a new application and shutdown the old one. internal void RemoveFromTableIfRuntimeExists(String appId, Type runtimeType) { // check args if (appId == null) throw new ArgumentNullException("appId"); if (runtimeType == null) throw new ArgumentNullException("runtimeType"); LockableAppDomainContext ac = GetLockableAppDomainContext(appId); lock (ac) { // get hosting environment HostingEnvironment env = ac.HostEnv; if (env == null) return; // find the instance by type // When marshaling Type, the AppDomain must have FileIoPermission to the assembly, which is not // always the case, so we marshal the assembly qualified name instead ObjectHandle h = env.FindWellKnownObject(runtimeType.AssemblyQualifiedName); if (h != null) { // ensure that it is removed from _appDomains by calling // HostingEnvironmentShutdownInitiated directly. HostingEnvironmentShutdownInitiated(appId, env); } } } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public void StopObject(String appId, Type type) { // check args if (appId == null) throw new ArgumentNullException("appId"); if (type == null) throw new ArgumentNullException("type"); LockableAppDomainContext ac = GetLockableAppDomainContext(appId); lock (ac) { HostingEnvironment env = ac.HostEnv; if (env != null) { // When marshaling Type, the AppDomain must have FileIoPermission to the assembly, which is not // always the case, so we marshal the assembly qualified name instead env.StopWellKnownObject(type.AssemblyQualifiedName); } } } public bool IsIdle() { Dictionary<string, LockableAppDomainContext> apps = CloneAppDomainsCollection(); foreach (LockableAppDomainContext ac in apps.Values) { lock (ac) { HostingEnvironment env = ac.HostEnv; bool idle = (null == env) ? true : env.IsIdle(); if (!idle) return false; } } return true; } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public void ShutdownApplication(String appId) { if (appId == null) throw new ArgumentNullException("appId"); LockableAppDomainContext ac = GetLockableAppDomainContext(appId); lock (ac) { if (ac.HostEnv != null) { ac.HostEnv.InitiateShutdownInternal(); } } } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public void ShutdownAll() { _shutdownInProgress = true; Dictionary <string, LockableAppDomainContext> oldTable = null; DisposeCacheManager(); lock (this) { oldTable = _appDomains; // don't keep references to hosting environments anymore _appDomains = new Dictionary<string, LockableAppDomainContext>(StringComparer.OrdinalIgnoreCase); } foreach (KeyValuePair <string, LockableAppDomainContext> p in oldTable) { LockableAppDomainContext ac = p.Value; lock (ac) { HostingEnvironment env = ac.HostEnv; if (null != env) { env.InitiateShutdownInternal(); } } } for (int iter=0; _activeHostingEnvCount > 0 && iter < 3000; iter++) // Wait at most 5 minutes Thread.Sleep(100); } [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] public ApplicationInfo[] GetRunningApplications() { ArrayList appList = new ArrayList(); Dictionary<string, LockableAppDomainContext> apps = CloneAppDomainsCollection(); foreach (LockableAppDomainContext ac in apps.Values) { lock (ac) { HostingEnvironment env = ac.HostEnv; if (env != null) { appList.Add(env.GetApplicationInfo()); } } } int n = appList.Count; ApplicationInfo[] result = new ApplicationInfo[n]; if (n > 0) { appList.CopyTo(result); } return result; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This method fails due to serialization issues if not called by ASP.NET.")] internal AppDomainInfo [] GetAppDomainInfos() { ArrayList appList = new ArrayList(); Dictionary<string, LockableAppDomainContext> apps = CloneAppDomainsCollection(); foreach (LockableAppDomainContext ac in apps.Values) { lock (ac) { HostingEnvironment hostEnv = ac.HostEnv; if (hostEnv == null) { continue; } IApplicationHost appHost = hostEnv.InternalApplicationHost; ApplicationInfo appInfo = hostEnv.GetApplicationInfo(); int siteId = 0; if (appHost != null) { try { siteId = Int32.Parse(appHost.GetSiteID(), CultureInfo.InvariantCulture); } catch { } } AppDomainInfo appDomainInfo = new AppDomainInfo(appInfo.ID, appInfo.VirtualPath, appInfo.PhysicalPath, siteId, hostEnv.GetIdleValue()); appList.Add(appDomainInfo); } } return (AppDomainInfo[]) appList.ToArray(typeof(AppDomainInfo)); } // // APIs for the process host to suspend / resume all running applications // [SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity", Justification = "'this' is never a MBRO proxy object.")] internal object SuspendAllApplications() { LockableAppDomainContext[] allAppDomainContexts; lock (this) { allAppDomainContexts = _appDomains.Values.ToArray(); } ApplicationResumeStateContainer[] resumeContainers = Task.WhenAll(allAppDomainContexts.Select(CreateSuspendTask)).Result; return resumeContainers; } private static Task<ApplicationResumeStateContainer> _dummyCompletedSuspendTask = Task.FromResult<ApplicationResumeStateContainer>(null); private static Task<ApplicationResumeStateContainer> CreateSuspendTask(LockableAppDomainContext appDomainContext) { // dictionary contained a null entry? if (appDomainContext == null) { return _dummyCompletedSuspendTask; } HostingEnvironment hostEnv; lock (appDomainContext) { hostEnv = appDomainContext.HostEnv; } // Quick check: is this a dummy context that had no associated application? if (hostEnv == null) { return _dummyCompletedSuspendTask; } // QUWI since we want to run each application's suspend method in parallel. // Unsafe since we don't care about impersonation, identity, etc. // Don't use Task.Run since it captures the EC and could execute inline. TaskCompletionSource<ApplicationResumeStateContainer> tcs = new TaskCompletionSource<ApplicationResumeStateContainer>(); ThreadPool.UnsafeQueueUserWorkItem(_ => { // We're not locking on the appDomainContext here. The reason for this is two-fold: // a) We don't want to cause a potential deadlock issue whereby Suspend could kick // off user code that tries calling InitiateShutdown and thus taking a lock on // appDomainContext. // b) It's easier to try calling into the captured HostingEnvironment and just // ---- the "no AD" exception than it is to try to synchronize the Suspend, // Resume, and Stop methods. The CLR protects us from ourselves here. // // We need to use the captured 'hostEnv' to prevent null refs. IntPtr state; try { state = hostEnv.SuspendApplication(); } catch (AppDomainUnloadedException) { // AD unloads aren't considered a failure tcs.TrySetResult(null); return; } tcs.TrySetResult(new ApplicationResumeStateContainer(hostEnv, state)); }, null); return tcs.Task; } internal void ResumeAllApplications(object state) { foreach (var resumeContainer in (ApplicationResumeStateContainer[])state) { if (resumeContainer != null) { // could be null if the application went away resumeContainer.Resume(); } } } // // ping implementation // // called from process host internal void Ping(IProcessPingCallback callback) { if (callback == null || _pendingPingCallback != null) return; // remember active callback but only if none is remembered already if (Interlocked.CompareExchange(ref _pendingPingCallback, callback, null) == null) { // queue a work item to respond to ping ThreadPool.QueueUserWorkItem(_onRespondToPingWaitCallback); } } // threadpool callback (also called on some activity from hosting environment) internal void OnRespondToPingWaitCallback(Object state) { RespondToPingIfNeeded(); } // respond to ping on callback internal void RespondToPingIfNeeded() { IProcessPingCallback callback = _pendingPingCallback as IProcessPingCallback; // make sure we call the callback once if (callback != null) { if (Interlocked.CompareExchange(ref _pendingPingCallback, null, callback) == callback) { callback.Respond(); } } } // // communication with hosting environments // internal void HostingEnvironmentActivated(long privateBytesLimit) { int count = Interlocked.Increment(ref _activeHostingEnvCount); // initialize CacheManager once, without blocking if (count == 1) { InitCacheManager(privateBytesLimit); } } internal void HostingEnvironmentShutdownComplete(String appId, IApplicationHost appHost) { try { if (appHost != null) { // make sure application host can be GC'd MarshalByRefObject realApplicationHost = appHost as MarshalByRefObject; if (realApplicationHost != null) { RemotingServices.Disconnect(realApplicationHost); } } } finally { Interlocked.Decrement(ref _activeHostingEnvCount); } } internal void HostingEnvironmentShutdownInitiated(String appId, HostingEnvironment env) { if (!_shutdownInProgress) { // don't bother during shutdown (while enumerating) LockableAppDomainContext ac = GetLockableAppDomainContext (appId); lock (ac){ if (!env.HasBeenRemovedFromAppManagerTable) { env.HasBeenRemovedFromAppManagerTable = true; ac.HostEnv = null; Interlocked.Decrement(ref _accessibleHostingEnvCount); // Autorestart the application right away if (ac.PreloadContext != null && !ac.RetryingPreload) { ProcessHost.PreloadApplicationIfNotShuttingdown(appId, ac); } } } } } internal int AppDomainsCount { get { return _accessibleHostingEnvCount; } } internal void ReduceAppDomainsCount(int limit) { // Dictionary<string, LockableAppDomainContext> apps = CloneAppDomainsCollection(); while (_accessibleHostingEnvCount >= limit && !_shutdownInProgress) { LockableAppDomainContext bestCandidateForShutdown = null; int bestCandidateLruScore = 0; foreach (LockableAppDomainContext ac in apps.Values) { // Don't lock on LockableAppDomainContext before we check that ac.HostEnv != null. // Otherwise we may end up with a deadlock between 2 app domains trying to unload each other HostingEnvironment h = ac.HostEnv; if (h == null) { continue; } lock (ac) { h = ac.HostEnv; // Avoid ---- by checking again under lock if (h == null) { continue; } int newLruScore = h.LruScore; if (bestCandidateForShutdown == null || bestCandidateForShutdown.HostEnv == null || newLruScore < bestCandidateLruScore) { bestCandidateLruScore = newLruScore; bestCandidateForShutdown = ac; } } } if (bestCandidateForShutdown == null) break; lock (bestCandidateForShutdown) { if (bestCandidateForShutdown.HostEnv != null) { bestCandidateForShutdown.HostEnv.InitiateShutdownInternal(); } } } } // // helper to support legacy APIs (AppHost.CreateAppHost) // internal ObjectHandle CreateInstanceInNewWorkerAppDomain( Type type, String appId, VirtualPath virtualPath, String physicalPath) { Debug.Trace("AppManager", "CreateObjectInNewWorkerAppDomain, type=" + type.FullName); IApplicationHost appHost = new SimpleApplicationHost(virtualPath, physicalPath); HostingEnvironmentParameters hostingParameters = new HostingEnvironmentParameters(); hostingParameters.HostingFlags = HostingEnvironmentFlags.HideFromAppManager; HostingEnvironment env = CreateAppDomainWithHostingEnvironmentAndReportErrors(appId, appHost, hostingParameters); // When marshaling Type, the AppDomain must have FileIoPermission to the assembly, which is not // always the case, so we marshal the assembly qualified name instead return env.CreateInstance(type.AssemblyQualifiedName); } // // helpers to facilitate app domain creation // private HostingEnvironment GetAppDomainWithHostingEnvironment(String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { LockableAppDomainContext ac = GetLockableAppDomainContext (appId); lock (ac) { HostingEnvironment env = ac.HostEnv; if (env != null) { try { env.IsUnloaded(); } catch(AppDomainUnloadedException) { env = null; } } if (env == null) { env = CreateAppDomainWithHostingEnvironmentAndReportErrors(appId, appHost, hostingParameters); ac.HostEnv = env; Interlocked.Increment(ref _accessibleHostingEnvCount); } return env; } } private HostingEnvironment CreateAppDomainWithHostingEnvironmentAndReportErrors( String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { try { return CreateAppDomainWithHostingEnvironment(appId, appHost, hostingParameters); } catch (Exception e) { Misc.ReportUnhandledException(e, new string[] {SR.GetString(SR.Failed_to_initialize_AppDomain), appId}); throw; } } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "We carefully control the callers.")] [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Boolean.TryParse(System.String,System.Boolean@)", Justification = "Sets parameter to default(bool) on conversion failure, which is semantic we need.")] private HostingEnvironment CreateAppDomainWithHostingEnvironment( String appId, IApplicationHost appHost, HostingEnvironmentParameters hostingParameters) { String physicalPath = appHost.GetPhysicalPath(); if (!StringUtil.StringEndsWith(physicalPath, Path.DirectorySeparatorChar)) physicalPath = physicalPath + Path.DirectorySeparatorChar; String domainId = ConstructAppDomainId(appId); String appName = (StringUtil.GetStringHashCode(String.Concat(appId.ToLower(CultureInfo.InvariantCulture), physicalPath.ToLower(CultureInfo.InvariantCulture)))).ToString("x", CultureInfo.InvariantCulture); VirtualPath virtualPath = VirtualPath.Create(appHost.GetVirtualPath()); Debug.Trace("AppManager", "CreateAppDomainWithHostingEnvironment, path=" + physicalPath + "; appId=" + appId + "; domainId=" + domainId); IDictionary bindings = new Hashtable(20); AppDomainSetup setup = new AppDomainSetup(); AppDomainSwitches switches = new AppDomainSwitches(); PopulateDomainBindings(domainId, appId, appName, physicalPath, virtualPath, setup, bindings); // Create the app domain AppDomain appDomain = null; Dictionary<string, object> appDomainAdditionalData = new Dictionary<string, object>(); Exception appDomainCreationException = null; string siteID = appHost.GetSiteID(); string appSegment = virtualPath.VirtualPathStringNoTrailingSlash; bool inClientBuildManager = false; Configuration appConfig = null; PolicyLevel policyLevel = null; PermissionSet permissionSet = null; List<StrongName> fullTrustAssemblies = new List<StrongName>(); string[] defaultPartialTrustVisibleAssemblies = new[] { "System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293", "System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.Abstractions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.Routing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.DynamicData, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.DataVisualization, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9", "System.Web.ApplicationServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" }; Exception appDomainStartupConfigurationException = null; ImpersonationContext ictxConfig = null; IntPtr uncTokenConfig = IntPtr.Zero; HostingEnvironmentFlags hostingFlags = HostingEnvironmentFlags.Default; if (hostingParameters != null) { hostingFlags = hostingParameters.HostingFlags; if ((hostingFlags & HostingEnvironmentFlags.ClientBuildManager) != 0) { inClientBuildManager = true; // The default hosting policy in VS has changed (from MultiDomainHost to MultiDomain), // so we need to specify explicitly to allow generated assemblies // to be unloaded subsequently. (Dev10 bug) setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; } } try { bool requireHostExecutionContextManager = false; bool requireHostSecurityManager = false; uncTokenConfig = appHost.GetConfigToken(); if (uncTokenConfig != IntPtr.Zero) { ictxConfig = new ImpersonationContext(uncTokenConfig); } try { // Did the custom loader fail to load? ExceptionDispatchInfo customLoaderException = ProcessHost.GetExistingCustomLoaderFailureAndClear(appId); if (customLoaderException != null) { customLoaderException.Throw(); } // DevDiv #392603 - disallow running applications when string hash code randomization is enabled if (EnvironmentInfo.IsStringHashCodeRandomizationEnabled) { throw new ConfigurationErrorsException(SR.GetString(SR.Require_stable_string_hash_codes)); } bool skipAdditionalConfigChecks = false; if (inClientBuildManager && hostingParameters.IISExpressVersion != null) { permissionSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = defaultPartialTrustVisibleAssemblies; appConfig = GetAppConfigIISExpress(siteID, appSegment, hostingParameters.IISExpressVersion); skipAdditionalConfigChecks = true; } else { //Hosted by IIS, we already have an IISMap. if (appHost is ISAPIApplicationHost) { string cacheKey = System.Web.Caching.CacheInternal.PrefixMapPath + siteID + virtualPath.VirtualPathString; MapPathCacheInfo cacheInfo = (MapPathCacheInfo)HttpRuntime.CacheInternal.Remove(cacheKey); appConfig = WebConfigurationManager.OpenWebConfiguration(appSegment, siteID); } // For non-IIS hosting scenarios, we need to get config map from application host in a generic way. else { appConfig = GetAppConfigGeneric(appHost, siteID, appSegment, virtualPath, physicalPath); } } HttpRuntimeSection httpRuntimeSection = (HttpRuntimeSection)appConfig.GetSection("system.web/httpRuntime"); if (httpRuntimeSection == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_section_not_present, "httpRuntime")); } // DevDiv #403846 - Change certain config defaults if <httpRuntime targetFramework="4.5" /> exists in config. // We store this information in the AppDomain data because certain configuration sections (like <compilation>) // are loaded before config is "baked" in the child AppDomain, and if we make <compilation> and other sections // dependent on <httpRuntime> which may not have been loaded yet, we risk introducing ----s. Putting this value // in the AppDomain data guarantees that it is available before the first call to the config system. FrameworkName targetFrameworkName = httpRuntimeSection.GetTargetFrameworkName(); if (targetFrameworkName != null) { appDomainAdditionalData[BinaryCompatibility.TargetFrameworkKey] = targetFrameworkName; } if (!skipAdditionalConfigChecks) { // DevDiv #71268 - Add <httpRuntime defaultRegexMatchTimeout="HH:MM:SS" /> configuration attribute if (httpRuntimeSection.DefaultRegexMatchTimeout != TimeSpan.Zero) { appDomainAdditionalData[_regexMatchTimeoutKey] = httpRuntimeSection.DefaultRegexMatchTimeout; } // DevDiv #258274 - Add support for CLR quirks mode to ASP.NET if (targetFrameworkName != null) { setup.TargetFrameworkName = targetFrameworkName.ToString(); } // DevDiv #286354 - Having a Task-friendly SynchronizationContext requires overriding the AppDomain's HostExecutionContextManager. // DevDiv #403846 - If we can't parse the <appSettings> switch, use the <httpRuntime/targetFramework> setting to determine the default. AppSettingsSection appSettingsSection = appConfig.AppSettings; KeyValueConfigurationElement useTaskFriendlySynchronizationContextElement = appSettingsSection.Settings["aspnet:UseTaskFriendlySynchronizationContext"]; if (!(useTaskFriendlySynchronizationContextElement != null && Boolean.TryParse(useTaskFriendlySynchronizationContextElement.Value, out requireHostExecutionContextManager))) { requireHostExecutionContextManager = new BinaryCompatibility(targetFrameworkName).TargetsAtLeastFramework45 ? true : false; } // DevDiv #248126 - Allow configuration of FileChangeMonitor behavior if (httpRuntimeSection.FcnMode != FcnMode.NotSet) { if (hostingParameters == null) { hostingParameters = new HostingEnvironmentParameters(); } hostingParameters.FcnMode = httpRuntimeSection.FcnMode; } // DevDiv #322858 - Allow FileChangesMonitor to skip reading DACLs as a perf improvement KeyValueConfigurationElement disableFcnDaclReadElement = appSettingsSection.Settings["aspnet:DisableFcnDaclRead"]; if (disableFcnDaclReadElement != null) { bool skipReadingAndCachingDacls; Boolean.TryParse(disableFcnDaclReadElement.Value, out skipReadingAndCachingDacls); if (skipReadingAndCachingDacls) { if (hostingParameters == null) { hostingParameters = new HostingEnvironmentParameters(); } hostingParameters.FcnSkipReadAndCacheDacls = true; } } // If we were launched from a development environment, we might want to enable the application to do things // it otherwise wouldn't normally allow, such as enabling an administrative control panel. For security reasons, // we only do this check if <deployment retail="false" /> [the default value] is specified, since the // <deployment> element can only be set at machine-level in a hosted environment. DeploymentSection deploymentSection = (DeploymentSection)appConfig.GetSection("system.web/deployment"); if (deploymentSection != null && !deploymentSection.Retail && EnvironmentInfo.WasLaunchedFromDevelopmentEnvironment) { appDomainAdditionalData[".devEnvironment"] = true; // DevDiv #275724 - Allow LocalDB support in partial trust scenarios // Normally LocalDB requires full trust since it's the equivalent of unmanaged code execution. If this is // a development environment and not a retail deployment, we can assume that the user developing the // application is actually in charge of the host, so we can trust him with LocalDB execution. // Technically this also means that the developer could have set <trust level="Full" /> in his application, // but he might want to deploy his application on a Medium-trust server and thus test how the rest of his // application works in a partial trust environment. (He would use SQL in production, whch is safe in // partial trust.) appDomainAdditionalData["ALLOW_LOCALDB_IN_PARTIAL_TRUST"] = true; } TrustSection trustSection = (TrustSection)appConfig.GetSection("system.web/trust"); if (trustSection == null || String.IsNullOrEmpty(trustSection.Level)) { throw new ConfigurationErrorsException(SR.GetString(SR.Config_section_not_present, "trust")); } switches.UseLegacyCas = trustSection.LegacyCasModel; if (inClientBuildManager) { permissionSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = defaultPartialTrustVisibleAssemblies; } else { if (!switches.UseLegacyCas) { if (trustSection.Level == "Full") { permissionSet = new PermissionSet(PermissionState.Unrestricted); setup.PartialTrustVisibleAssemblies = defaultPartialTrustVisibleAssemblies; } else { SecurityPolicySection securityPolicySection = (SecurityPolicySection)appConfig.GetSection("system.web/securityPolicy"); CompilationSection compilationSection = (CompilationSection)appConfig.GetSection("system.web/compilation"); FullTrustAssembliesSection fullTrustAssembliesSection = (FullTrustAssembliesSection)appConfig.GetSection("system.web/fullTrustAssemblies"); policyLevel = GetPartialTrustPolicyLevel(trustSection, securityPolicySection, compilationSection, physicalPath, virtualPath); permissionSet = policyLevel.GetNamedPermissionSet(trustSection.PermissionSetName); if (permissionSet == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Permission_set_not_found, trustSection.PermissionSetName)); } // read full trust assemblies and populate the strong name list if (fullTrustAssembliesSection != null) { FullTrustAssemblyCollection fullTrustAssembliesCollection = fullTrustAssembliesSection.FullTrustAssemblies; if (fullTrustAssembliesCollection != null) { fullTrustAssemblies.AddRange(from FullTrustAssembly fta in fullTrustAssembliesCollection select CreateStrongName(fta.AssemblyName, fta.Version, fta.PublicKey)); } } // DevDiv #27645 - We need to add future versions of Microsoft.Web.Infrastructure to <fullTrustAssemblies> so that ASP.NET // can version out-of-band releases. We should only do this if V1 of M.W.I is listed. if (fullTrustAssemblies.Contains(_mwiV1StrongName)) { fullTrustAssemblies.AddRange(CreateFutureMicrosoftWebInfrastructureStrongNames()); } // Partial-trust AppDomains using a non-legacy CAS model require our special HostSecurityManager requireHostSecurityManager = true; } } if (trustSection.Level != "Full") { PartialTrustVisibleAssembliesSection partialTrustVisibleAssembliesSection = (PartialTrustVisibleAssembliesSection)appConfig.GetSection("system.web/partialTrustVisibleAssemblies"); string[] partialTrustVisibleAssemblies = null; if (partialTrustVisibleAssembliesSection != null) { PartialTrustVisibleAssemblyCollection partialTrustVisibleAssembliesCollection = partialTrustVisibleAssembliesSection.PartialTrustVisibleAssemblies; if (partialTrustVisibleAssembliesCollection != null && partialTrustVisibleAssembliesCollection.Count != 0) { partialTrustVisibleAssemblies = new string[partialTrustVisibleAssembliesCollection.Count + defaultPartialTrustVisibleAssemblies.Length]; for (int i = 0; i < partialTrustVisibleAssembliesCollection.Count; i++) { partialTrustVisibleAssemblies[i] = partialTrustVisibleAssembliesCollection[i].AssemblyName + ", PublicKey=" + NormalizePublicKeyBlob(partialTrustVisibleAssembliesCollection[i].PublicKey); } defaultPartialTrustVisibleAssemblies.CopyTo(partialTrustVisibleAssemblies, partialTrustVisibleAssembliesCollection.Count); } } if (partialTrustVisibleAssemblies == null) { partialTrustVisibleAssemblies = defaultPartialTrustVisibleAssemblies; } setup.PartialTrustVisibleAssemblies = partialTrustVisibleAssemblies; } } } } catch (Exception e) { appDomainStartupConfigurationException = e; permissionSet = new PermissionSet(PermissionState.Unrestricted); } // Set the AppDomainManager if needed Type appDomainManagerType = AspNetAppDomainManager.GetAspNetAppDomainManagerType(requireHostExecutionContextManager, requireHostSecurityManager); if (appDomainManagerType != null) { setup.AppDomainManagerType = appDomainManagerType.FullName; setup.AppDomainManagerAssembly = appDomainManagerType.Assembly.FullName; } // Apply compatibility switches switches.Apply(setup); try { if (switches.UseLegacyCas) { appDomain = AppDomain.CreateDomain(domainId, #if FEATURE_PAL // FEATURE_PAL: hack to avoid non-supported hosting features null, #else // FEATURE_PAL GetDefaultDomainIdentity(), #endif // FEATURE_PAL setup); } else { appDomain = AppDomain.CreateDomain(domainId, #if FEATURE_PAL // FEATURE_PAL: hack to avoid non-supported hosting features null, #else // FEATURE_PAL GetDefaultDomainIdentity(), #endif // FEATURE_PAL setup, permissionSet, fullTrustAssemblies.ToArray() /* fully trusted assemblies list: empty list means only trust GAC assemblies */); } foreach (DictionaryEntry e in bindings) appDomain.SetData((String)e.Key, (String)e.Value); foreach (var entry in appDomainAdditionalData) appDomain.SetData(entry.Key, entry.Value); } catch (Exception e) { Debug.Trace("AppManager", "AppDomain.CreateDomain failed", e); appDomainCreationException = e; } } finally { if (ictxConfig != null) { ictxConfig.Undo(); ictxConfig = null; } if (uncTokenConfig != IntPtr.Zero) { UnsafeNativeMethods.CloseHandle(uncTokenConfig); uncTokenConfig = IntPtr.Zero; } } if (appDomain == null) { throw new SystemException(SR.GetString(SR.Cannot_create_AppDomain), appDomainCreationException); } // Create hosting environment in the new app domain Type hostType = typeof(HostingEnvironment); String module = hostType.Module.Assembly.FullName; String typeName = hostType.FullName; ObjectHandle h = null; // impersonate UNC identity, if any ImpersonationContext ictx = null; IntPtr uncToken = IntPtr.Zero; // // fetching config can fail due to a ---- with the // native config reader // if that has happened, force a flush // int maxRetries = 10; int numRetries = 0; while (numRetries < maxRetries) { try { uncToken = appHost.GetConfigToken(); // no throw, so break break; } catch (InvalidOperationException) { numRetries++; System.Threading.Thread.Sleep(250); } } if (uncToken != IntPtr.Zero) { try { ictx = new ImpersonationContext(uncToken); } catch { } finally { UnsafeNativeMethods.CloseHandle(uncToken); } } try { // Create the hosting environment in the app domain #if DBG try { h = Activator.CreateInstance(appDomain, module, typeName); } catch (Exception e) { Debug.Trace("AppManager", "appDomain.CreateInstance failed; identity=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name, e); throw; } #else h = Activator.CreateInstance(appDomain, module, typeName); #endif } finally { // revert impersonation if (ictx != null) ictx.Undo(); if (h == null) { AppDomain.Unload(appDomain); } } HostingEnvironment env = (h != null) ? h.Unwrap() as HostingEnvironment : null; if (env == null) throw new SystemException(SR.GetString(SR.Cannot_create_HostEnv)); // initialize the hosting environment IConfigMapPathFactory configMapPathFactory = appHost.GetConfigMapPathFactory(); if (appDomainStartupConfigurationException == null) { env.Initialize(this, appHost, configMapPathFactory, hostingParameters, policyLevel); } else { env.Initialize(this, appHost, configMapPathFactory, hostingParameters, policyLevel, appDomainStartupConfigurationException); } return env; } private static string NormalizePublicKeyBlob(string publicKey) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < publicKey.Length; i++) { if (!Char.IsWhiteSpace(publicKey[i])) { sb.Append(publicKey[i]); } } publicKey = sb.ToString(); return publicKey; } private static StrongName CreateStrongName(string assemblyName, string version, string publicKeyString) { byte[] publicKey = null; StrongName strongName = null; publicKeyString = NormalizePublicKeyBlob(publicKeyString); int publicKeySize = publicKeyString.Length / 2; publicKey = new byte[publicKeySize]; for (int i = 0; i < publicKeySize; i++) { publicKey[i] = Byte.Parse(publicKeyString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber, CultureInfo.InvariantCulture); } StrongNamePublicKeyBlob keyBlob = new StrongNamePublicKeyBlob(publicKey); strongName = new StrongName(keyBlob, assemblyName, new Version(version)); return strongName; } // For various reasons, we can't add any entries to the <fullTrustAssemblies> list until .NET 5, which at the time of this writing is a few // years out. But since ASP.NET releases projects out-of-band from the .NET Framework as a whole (using Microsoft.Web.Infrasturcture), we // need to be sure that future versions of M.W.I have the ability to assert full trust. This code works by seeing if M.W.I v1 is in the // <fullTrustAssemblies> list, and if it is then v2 - v10 are implicitly added. If v1 is not present in the <fTA> list, then we'll not // treat v2 - v10 as implicitly added. See DevDiv #27645 for more information. private static StrongName GetMicrosoftWebInfrastructureV1StrongName() { return CreateStrongName( assemblyName: "Microsoft.Web.Infrastructure", version: "1.0.0.0", publicKeyString: "0024000004800000940000000602000000240000525341310004000001000100B5FC90E7027F67871E773A8FDE8938C81DD402BA65B9201D60593E96C492651E889CC13F1415EBB53FAC1131AE0BD333C5EE6021672D9718EA31A8AEBD0DA0072F25D87DBA6FC90FFD598ED4DA35E44C398C454307E8E33B8426143DAEC9F596836F97C8F74750E5975C64E2189F45DEF46B2A2B1247ADC3652BF5C308055DA9"); } private static IEnumerable<StrongName> CreateFutureMicrosoftWebInfrastructureStrongNames() { string asmName = _mwiV1StrongName.Name; StrongNamePublicKeyBlob publicKey = _mwiV1StrongName.PublicKey; for (int i = 2; i <= 10; i++) { yield return new StrongName(publicKey, asmName, new Version(i, 0, 0, 0)); } } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "We carefully control this method's caller.")] private static PolicyLevel GetPartialTrustPolicyLevel( TrustSection trustSection, SecurityPolicySection securityPolicySection, CompilationSection compilationSection, string physicalPath, VirtualPath virtualPath) { if (securityPolicySection == null || securityPolicySection.TrustLevels[trustSection.Level] == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level), String.Empty, 0); } String configFile = (String)securityPolicySection.TrustLevels[trustSection.Level].PolicyFileExpanded; if (configFile == null || !FileUtil.FileExists(configFile)) { throw new HttpException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level)); } PolicyLevel policyLevel = null; String appDir = FileUtil.RemoveTrailingDirectoryBackSlash(physicalPath); String appDirUrl = HttpRuntime.MakeFileUrl(appDir); // setup $CodeGen$ replacement string tempDirectory = null; // These variables are used for error handling string tempDirAttribName = null; string configFileName = null; int configLineNumber = 0; if (compilationSection != null && !String.IsNullOrEmpty(compilationSection.TempDirectory)) { tempDirectory = compilationSection.TempDirectory; compilationSection.GetTempDirectoryErrorInfo(out tempDirAttribName, out configFileName, out configLineNumber); } if (tempDirectory != null) { tempDirectory = tempDirectory.Trim(); if (!Path.IsPathRooted(tempDirectory)) { // Make sure the path is not relative (VSWhidbey 260075) tempDirectory = null; } else { try { // Canonicalize it to avoid problems with spaces (VSWhidbey 229873) tempDirectory = new DirectoryInfo(tempDirectory).FullName; } catch { tempDirectory = null; } } if (tempDirectory == null) { throw new ConfigurationErrorsException( SR.GetString(SR.Invalid_temp_directory, tempDirAttribName), configFileName, configLineNumber); } // Create the config-specified directory if needed try { Directory.CreateDirectory(tempDirectory); } catch (Exception e) { throw new ConfigurationErrorsException( SR.GetString(SR.Invalid_temp_directory, tempDirAttribName), e, configFileName, configLineNumber); } } else { tempDirectory = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), HttpRuntime.codegenDirName); } // If we don't have write access to the codegen dir, use the TEMP dir instead. // This will allow non-admin users to work in hosting scenarios (e.g. Venus, aspnet_compiler) if (!System.Web.UI.Util.HasWriteAccessToDirectory(tempDirectory)) { // Don't do this if we're in a service (!UserInteractive), as TEMP // could point to unwanted places. if (!Environment.UserInteractive) { throw new HttpException(SR.GetString(SR.No_codegen_access, System.Web.UI.Util.GetCurrentAccountName(), tempDirectory)); } tempDirectory = Path.GetTempPath(); Debug.Assert(System.Web.UI.Util.HasWriteAccessToDirectory(tempDirectory)); tempDirectory = Path.Combine(tempDirectory, HttpRuntime.codegenDirName); } String simpleAppName = System.Web.Hosting.AppManagerAppDomainFactory.ConstructSimpleAppName( VirtualPath.GetVirtualPathStringNoTrailingSlash(virtualPath)); String binDir = Path.Combine(tempDirectory, simpleAppName); binDir = FileUtil.RemoveTrailingDirectoryBackSlash(binDir); String binDirUrl = HttpRuntime.MakeFileUrl(binDir); String originUrl = trustSection.OriginUrl; FileStream file = new FileStream(configFile, FileMode.Open, FileAccess.Read); StreamReader reader = new StreamReader(file, Encoding.UTF8); String strFileData = reader.ReadToEnd(); reader.Close(); strFileData = strFileData.Replace("$AppDir$", appDir); strFileData = strFileData.Replace("$AppDirUrl$", appDirUrl); strFileData = strFileData.Replace("$CodeGen$", binDirUrl); if (originUrl == null) originUrl = String.Empty; strFileData = strFileData.Replace("$OriginHost$", originUrl); String gacLocation = null; if (strFileData.IndexOf("$Gac$", StringComparison.Ordinal) != -1) { gacLocation = HttpRuntime.GetGacLocation(); if (gacLocation != null) gacLocation = HttpRuntime.MakeFileUrl(gacLocation); if (gacLocation == null) gacLocation = String.Empty; strFileData = strFileData.Replace("$Gac$", gacLocation); } #pragma warning disable 618 // ASP is reading their grant set out of legacy policy level files policyLevel = SecurityManager.LoadPolicyLevelFromString(strFileData, PolicyLevelType.AppDomain); if (policyLevel == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Unable_to_get_policy_file, trustSection.Level)); } // Found GAC Token if (gacLocation != null) { // walk the code groups at the app domain level and look for one that grants // access to the GAC with an UrlMembershipCondition. CodeGroup rootGroup = policyLevel.RootCodeGroup; bool foundGacCondition = false; foreach (CodeGroup childGroup in rootGroup.Children) { if (childGroup.MembershipCondition is GacMembershipCondition) { foundGacCondition = true; // if we found the GAC token and also have the GacMembershipCondition // the policy file needs to be upgraded to just include the GacMembershipCondition Debug.Assert(!foundGacCondition); break; } } // add one as a child of the toplevel group after // some sanity checking to make sure it's an ASP.NET policy file // which always begins with a FirstMatchCodeGroup granting nothing // this might not upgrade some custom policy files if (!foundGacCondition) { if (rootGroup is FirstMatchCodeGroup) { FirstMatchCodeGroup firstMatch = (FirstMatchCodeGroup)rootGroup; if (firstMatch.MembershipCondition is AllMembershipCondition && firstMatch.PermissionSetName == "Nothing") { PermissionSet fullTrust = new PermissionSet(PermissionState.Unrestricted); CodeGroup gacGroup = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(fullTrust)); // now, walk the current groups and insert our new group immediately before the old Gac group // we'll need to use heuristics for this: it will be an UrlMembershipCondition group with full trust CodeGroup newRoot = new FirstMatchCodeGroup(rootGroup.MembershipCondition, rootGroup.PolicyStatement); foreach (CodeGroup childGroup in rootGroup.Children) { // is this the target old $Gac$ group? // insert our new GacMembershipCondition group ahead of it if ((childGroup is UnionCodeGroup) && (childGroup.MembershipCondition is UrlMembershipCondition) && childGroup.PolicyStatement.PermissionSet.IsUnrestricted()) { if (null != gacGroup) { newRoot.AddChild(gacGroup); gacGroup = null; } } // append this group to the root group // AddChild itself does a deep Copy to get any // child groups so we don't need one here newRoot.AddChild(childGroup); } policyLevel.RootCodeGroup = newRoot; } } } } return policyLevel; #pragma warning restore 618 } private sealed class ApplicationResumeStateContainer { private static readonly WaitCallback _tpCallback = ResumeCallback; private readonly HostingEnvironment _hostEnv; private readonly IntPtr _resumeState; internal ApplicationResumeStateContainer(HostingEnvironment hostEnv, IntPtr resumeState) { _hostEnv = hostEnv; _resumeState = resumeState; } // schedules resume for execution on a new thread // unsafe since we don't care about impersonation, identity, etc. internal void Resume() { ThreadPool.UnsafeQueueUserWorkItem(_tpCallback, this); } private static void ResumeCallback(object state) { ApplicationResumeStateContainer container = (ApplicationResumeStateContainer)state; try { container._hostEnv.ResumeApplication(container._resumeState); } catch (AppDomainUnloadedException) { // AD unloads aren't considered a failure, ---- } } } [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] private static class AspNetAppDomainManager { internal static Type GetAspNetAppDomainManagerType(bool overrideHostExecutionContextManager, bool overrideHostSecurityManager) { if (!overrideHostExecutionContextManager && !overrideHostSecurityManager) { // A custom AppDomainManager isn't necessary for this AppDomain. return null; } else { // A custom AppDomainManager is necessary for this AppDomain. // See comment on the generic type for further information. Type openGenericType = typeof(AspNetAppDomainManagerImpl<,>); Type closedGenericType = openGenericType.MakeGenericType( (overrideHostExecutionContextManager) ? typeof(AspNetHostExecutionContextManager) : typeof(object), (overrideHostSecurityManager) ? typeof(AspNetHostSecurityManager) : typeof(object) ); return closedGenericType; } } // This AppDomainManager may have been set because we need it for Task support, because this is a partial-trust // AppDomain, or both. Normally we would store this data in the AppDomain's ambient data store (AppDomain.SetData), // but the AppDomainManager instance is initialized in the new AppDomain before the original AppDomain has a chance to // call SetData, so in this AppDomain the call to GetData is useless. However, we can use the AppDomainManager type // itself to carry the necessary information in the form of a generic type parameter. If a custom // HostExecutionContextManager or HostSecurityManager is necessary, the generic type parameters can tell us that. // A generic type parameter of "object" means that this particular sub-manager isn't necessary. private sealed class AspNetAppDomainManagerImpl<THostExecutionContextManager, THostSecurityManager> : AppDomainManager where THostExecutionContextManager : class, new() where THostSecurityManager : class, new() { private readonly HostExecutionContextManager _hostExecutionContextManager = CreateHostExecutionContextManager(); private readonly HostSecurityManager _hostSecurityManager = CreateHostSecurityManager(); public override HostExecutionContextManager HostExecutionContextManager { get { return _hostExecutionContextManager ?? base.HostExecutionContextManager; } } public override HostSecurityManager HostSecurityManager { get { return _hostSecurityManager ?? base.HostSecurityManager; } } private static HostExecutionContextManager CreateHostExecutionContextManager() { object hostExecutionContextManager = new THostExecutionContextManager(); Debug.Assert(hostExecutionContextManager is HostExecutionContextManager || hostExecutionContextManager.GetType() == typeof(object), "THostExecutionContextManager was an unexpected type!"); return hostExecutionContextManager as HostExecutionContextManager; } private static HostSecurityManager CreateHostSecurityManager() { object hostSecurityManager = new THostSecurityManager(); Debug.Assert(hostSecurityManager is HostSecurityManager || hostSecurityManager.GetType() == typeof(object), "THostSecurityManager was an unexpected type!"); return hostSecurityManager as HostSecurityManager; } } private sealed class AspNetHostSecurityManager : HostSecurityManager { private PermissionSet Nothing = new PermissionSet(PermissionState.None); private PermissionSet FullTrust = new PermissionSet(PermissionState.Unrestricted); private HostSecurityPolicyResolver hostSecurityPolicyResolver = null; public override HostSecurityManagerOptions Flags { get { return HostSecurityManagerOptions.HostResolvePolicy; } } [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)] public override PermissionSet ResolvePolicy(Evidence evidence) { if (base.ResolvePolicy(evidence).IsUnrestricted()) { return FullTrust; } if (!String.IsNullOrEmpty(HttpRuntime.HostSecurityPolicyResolverType) && hostSecurityPolicyResolver == null) { hostSecurityPolicyResolver = Activator.CreateInstance( Type.GetType(HttpRuntime.HostSecurityPolicyResolverType)) as HostSecurityPolicyResolver; } if (hostSecurityPolicyResolver != null) { switch (hostSecurityPolicyResolver.ResolvePolicy(evidence)) { case HostSecurityPolicyResults.FullTrust: return FullTrust; case HostSecurityPolicyResults.AppDomainTrust: return HttpRuntime.NamedPermissionSet; case HostSecurityPolicyResults.Nothing: return Nothing; case HostSecurityPolicyResults.DefaultPolicy: break; } } if (HttpRuntime.PolicyLevel == null || HttpRuntime.PolicyLevel.Resolve(evidence).PermissionSet.IsUnrestricted()) return FullTrust; else if (HttpRuntime.PolicyLevel.Resolve(evidence).PermissionSet.Equals(Nothing)) return Nothing; else return HttpRuntime.NamedPermissionSet; } } } private static void PopulateDomainBindings(String domainId, String appId, String appName, String appPath, VirtualPath appVPath, AppDomainSetup setup, IDictionary dict) { // assembly loading settings // We put both the old and new bin dir names on the private bin path setup.PrivateBinPathProbe = "*"; // disable loading from app base setup.ShadowCopyFiles = "true"; setup.ApplicationBase = appPath; setup.ApplicationName = appName; setup.ConfigurationFile = HttpConfigurationSystem.WebConfigFileName; // Disallow code download, since it's unreliable in services (ASURT 123836/127606) setup.DisallowCodeDownload = true; // internal settings dict.Add(".appDomain", "*"); dict.Add(".appId", appId); dict.Add(".appPath", appPath); dict.Add(".appVPath", appVPath.VirtualPathString); dict.Add(".domainId", domainId); } private static Evidence GetDefaultDomainIdentity() { Evidence evidence = AppDomain.CurrentDomain.Evidence; // CurrentDomain.Evidence returns a clone so we can modify it if we need bool hasZone = evidence.GetHostEvidence<Zone>() != null; bool hasUrl = evidence.GetHostEvidence<Url>() != null; if (!hasZone) evidence.AddHostEvidence(new Zone(SecurityZone.MyComputer)); if (!hasUrl) evidence.AddHostEvidence(new Url("ms-internal-microsoft-asp-net-webhost-20")); return evidence; } private static int s_domainCount = 0; private static Object s_domainCountLock = new Object(); private static String ConstructAppDomainId(String id) { int domainCount = 0; lock (s_domainCountLock) { domainCount = ++s_domainCount; } return id + "-" + domainCount.ToString(NumberFormatInfo.InvariantInfo) + "-" + DateTime.UtcNow.ToFileTime().ToString(); } internal LockableAppDomainContext GetLockableAppDomainContext (string appId) { lock (this) { LockableAppDomainContext ac; if (!_appDomains.TryGetValue(appId, out ac)) { ac = new LockableAppDomainContext(); _appDomains.Add (appId, ac); } return ac; } } // take a copy of _appDomains collection so that it can be used without locking on ApplicationManager private Dictionary<string, LockableAppDomainContext> CloneAppDomainsCollection() { lock (this) { return new Dictionary<string, LockableAppDomainContext>(_appDomains, StringComparer.OrdinalIgnoreCase); } } private static Configuration GetAppConfigCommon(IConfigMapPath configMapPath, string siteID, string appSegment) { WebConfigurationFileMap fileMap = new WebConfigurationFileMap(); string dir = null; string fileName = null; string subDir = "/"; // add root mapping configMapPath.GetPathConfigFilename(siteID, subDir, out dir, out fileName); if (dir != null) { fileMap.VirtualDirectories.Add(subDir, new VirtualDirectoryMapping(Path.GetFullPath(dir), true)); } // add subdir mappings string[] subDirs = appSegment.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in subDirs) { subDir = subDir + s; configMapPath.GetPathConfigFilename(siteID, subDir, out dir, out fileName); if (dir != null) { fileMap.VirtualDirectories.Add(subDir, new VirtualDirectoryMapping(Path.GetFullPath(dir), true)); } subDir = subDir + "/"; } // open mapped web config for application return WebConfigurationManager.OpenMappedWebConfiguration(fileMap, appSegment, siteID); } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Only ever called by the full-trust parent AppDomain.")] private static Configuration GetAppConfigGeneric(IApplicationHost appHost, string siteID, string appSegment, VirtualPath virtualPath, string physicalPath) { WebConfigurationFileMap fileMap = new WebConfigurationFileMap(); IConfigMapPathFactory configMapPathFactory2 = appHost.GetConfigMapPathFactory(); IConfigMapPath configMapPath = configMapPathFactory2.Create(virtualPath.VirtualPathString, physicalPath); return GetAppConfigCommon(configMapPath, siteID, appSegment); } private static Configuration GetAppConfigIISExpress(string siteID, string appSegment, string iisExpressVersion) { ExpressServerConfig serverConfig = (ExpressServerConfig)ServerConfig.GetDefaultDomainInstance(iisExpressVersion); return GetAppConfigCommon(serverConfig, siteID, appSegment); } private sealed class AppDomainSwitches { public bool UseLegacyCas; public void Apply(AppDomainSetup setup) { List<string> switches = new List<string>(); if (UseLegacyCas) { // Enables the AppDomain to use the legacy CAS model for compatibility <trust/legacyCasModel> switches.Add("NetFx40_LegacySecurityPolicy"); } if (switches.Count > 0) { setup.SetCompatibilitySwitches(switches); } } } // This class holds information about the environment that is hosting ASP.NET. The particular design of this class // is that the information is computed once and stored, and the methods which compute the information are private. // This prevents accidental misuse of this type via querying the environment after user code has had a chance to // run, which could potentially affect the environment itself. private static class EnvironmentInfo { public static readonly bool IsStringHashCodeRandomizationEnabled = GetIsStringHashCodeRandomizationEnabled(); public static readonly bool WasLaunchedFromDevelopmentEnvironment = GetWasLaunchedFromDevelopmentEnvironmentValue(); private static bool GetIsStringHashCodeRandomizationEnabled() { // known test vector return (StringComparer.InvariantCultureIgnoreCase.GetHashCode("The quick brown fox jumps over the lazy dog.") != 0x703e662e); } // Visual Studio / WebMatrix will set DEV_ENVIRONMENT=1 when launching an ASP.NET host in a development environment. private static bool GetWasLaunchedFromDevelopmentEnvironmentValue() { try { string envVar = Environment.GetEnvironmentVariable("DEV_ENVIRONMENT", EnvironmentVariableTarget.Process); return String.Equals(envVar, "1", StringComparison.Ordinal); } catch { // We don't care if we can't read the environment variable; just treat it as not present. return false; } } } } }
51.460237
435
0.585035
[ "Apache-2.0" ]
Distrotech/mono
external/referencesource/System.Web/Hosting/ApplicationManager.cs
91,239
C#
#region using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading.Tasks; using Convex.Base.Calculator; using Convex.Core; using Convex.Core.Net; using Convex.Event; using Convex.Plugin; using Convex.Plugin.Composition; using Convex.Plugin.Event; using Newtonsoft.Json.Linq; using SharpConfig; #endregion namespace Convex.Base { public class Base : IPlugin { #region MEMBERS public string Name => "Base"; public string Author => "Zavier Divelbiss"; public Version Version => new AssemblyName(GetType().GetTypeInfo().Assembly.FullName).Version; public string Id => Guid.NewGuid().ToString(); public PluginStatus Status { get; private set; } = PluginStatus.Stopped; private readonly InlineCalculator _Calculator = new InlineCalculator(); private readonly Regex _YoutubeRegex = new Regex(@"(?i)http(?:s?)://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be/)(?<ID>[\w\-]+)(&(amp;)?[\w\?=‌​]*)?", RegexOptions.Compiled); private bool MotdReplyEndSequenceEnacted { get; set; } private Configuration Configuration { get; set; } #endregion #region INTERFACE IMPLEMENTATION public event AsyncEventHandler<PluginActionEventArgs> Callback; public async Task Start(Configuration configuration) { //await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Join, args => InputEquals(args, "join"), new CompositionDescription(nameof(Join), "(< channel> *<message>) — joins specified channel."), Commands.PRIVMSG), Name)); //await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Part, args => InputEquals(args, "part"), new CompositionDescription(nameof(Part), "(< channel> *<message>) — parts from specified channel."), Commands.PRIVMSG), Name)); //await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Channels, args => InputEquals(args, "channels"), new CompositionDescription(nameof(Channels), "returns a list of connected channels."), Commands.PRIVMSG), Name)); //await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, YouTubeLinkResponse, args => _youtubeRegex.IsMatch(args.Message.Args), null, Commands.PRIVMSG), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(1, Default, null, null, Commands.PRIVMSG), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, MotdReplyEnd, null, null, Commands.RPL_ENDOFMOTD), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Quit, args => InputEquals(args, "quit"), new CompositionDescription(nameof(Quit), "terminates bot execution"), Commands.PRIVMSG), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Eval, args => InputEquals(args, "eval"), new CompositionDescription(nameof(Eval), "(<expression>) — evaluates given mathematical expression."), Commands.PRIVMSG), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Define, args => InputEquals(args, "define"), new CompositionDescription(nameof(Define), "(< word> *<part of speech>) — returns definition for given word."), Commands.PRIVMSG), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.RegisterMethod, new Composition<ServerMessagedEventArgs>(99, Lookup, args => InputEquals(args, "lookup"), new CompositionDescription(nameof(Lookup), "(<term/phrase>) — returns the wikipedia summary of given term or phrase."), Commands.PRIVMSG), Name)); } public async Task Stop() { if ((Status == PluginStatus.Running) || (Status == PluginStatus.Processing)) { await Log($"Stop called but process is running from: {Name}"); } else { await Log($"Plugin stopping: {Name}"); await CallDie(); } } public async Task CallDie() { Status = PluginStatus.Stopped; await Log($"Calling die, stopping process, sending unload —— plugin: {Name}"); } #endregion #region METHODS private async Task Log(params string[] args) { await DoCallback(this, new PluginActionEventArgs(PluginActionType.Log, string.Join(" ", args), Name)); } private async Task DoCallback(object source, PluginActionEventArgs args) { if (Callback == null) { return; } args.PluginName = Name; await Callback.Invoke(source, args); } private static bool InputEquals(ServerMessagedEventArgs args, string comparison) => args.Message.SplitArgs[0].Equals(comparison, StringComparison.OrdinalIgnoreCase); #endregion #region REGISTRARS private async Task Default(ServerMessagedEventArgs e) { if (Configuration[nameof(Core)]["IgnoreList"].StringValueArray.Contains(e.Message.RealName)) { return; } if (!e.Message.SplitArgs[0].Replace(",", string.Empty) .Equals(Configuration[nameof(Core)]["Nickname"].StringValue.ToLower())) { return; } if (e.Message.SplitArgs.Count < 2) { // typed only 'eve' await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {e.Message.Origin}", "Type 'eve help' to view my command list."), Name)); return; } // built-in 'help' command if (e.Message.SplitArgs[1].Equals("help", StringComparison.OrdinalIgnoreCase)) { if (e.Message.SplitArgs.Count.Equals(2)) { // in this case, 'help' is the only text in the string. List<CompositionDescription> entries = e.Caller.PluginCommands.Values.ToList(); string commandsReadable = string.Join(", ", entries.Where(entry => entry != null).Select(entry => entry.Command)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.PRIVMSG, entries.Count == 0 ? $"{e.Message.Origin} No commands currently active." : $"{e.Message.Origin} Active commands: {commandsReadable}"), Name)); return; } CompositionDescription queriedCommand = e.Caller.GetDescription(e.Message.SplitArgs[2]); string valueToSend = queriedCommand.Equals(null) ? "Command not found." : $"{queriedCommand.Command}: {queriedCommand.Description}"; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {e.Message.Origin}", valueToSend), Name)); return; } if (e.Caller.CommandExists(e.Message.SplitArgs[1].ToLower())) { return; } await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {e.Message.Origin}", "Invalid command. Type 'eve help' to view my command list."), Name)); } private async Task MotdReplyEnd(ServerMessagedEventArgs args) { if (MotdReplyEndSequenceEnacted) { return; } await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.PRIVMSG, $"NICKSERV IDENTIFY {Configuration[nameof(Core)]["Password"].StringValue}"), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.MODE, $"{Configuration[nameof(Core)]["Nickname"].StringValue} +B"), Name)); //args.Caller.Server.Channels.Add(new Channel("#testgrounds")); MotdReplyEndSequenceEnacted = true; } private async Task Quit(ServerMessagedEventArgs args) { if ((args.Message.SplitArgs.Count < 2) || !args.Message.SplitArgs[1].Equals("quit")) { return; } await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.QUIT, "Shutting down."), Name)); await DoCallback(this, new PluginActionEventArgs(PluginActionType.SignalTerminate, null, Name)); } private async Task Eval(ServerMessagedEventArgs e) { Status = PluginStatus.Processing; IrcCommandEventArgs command = new IrcCommandEventArgs($"{Commands.PRIVMSG} {e.Message.Origin}", string.Empty); if (e.Message.SplitArgs.Count < 3) { command.Arguments = "Not enough parameters."; } Status = PluginStatus.Running; if (string.IsNullOrEmpty(command.Arguments)) { Status = PluginStatus.Running; string evalArgs = e.Message.SplitArgs.Count > 3 ? e.Message.SplitArgs[2] + e.Message.SplitArgs[3] : e.Message.SplitArgs[2]; try { command.Arguments = _Calculator.Evaluate(evalArgs).ToString(CultureInfo.CurrentCulture); } catch (Exception ex) { command.Arguments = ex.Message; } } await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); Status = PluginStatus.Stopped; } //private async Task Join(ServerMessagedEventArgs args) { // Status = PluginStatus.Processing; // string message = string.Empty; // if (args.Message.SplitArgs.Count < 3) { // message = "Insufficient parameters. Type 'eve help join' to view command's help index."; // } else if (args.Message.SplitArgs.Count < 2 || !args.Message.SplitArgs[2].StartsWith("#")) { // message = "Channel name must start with '#'."; // } else if (args.Caller.Server.GetChannel(args.Message.SplitArgs[2].ToLower()) != null) { // message = "I'm already in that channel."; // } // Status = PluginStatus.Running; // if (string.IsNullOrEmpty(message)) { // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.JOIN, args.Message.SplitArgs[2]), Name)); // args.Caller.Server.Channels.Add(new Channel(args.Message.SplitArgs[2].ToLower())); // message = $"Successfully joined channel: {args.Message.SplitArgs[2]}."; // } // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", message), Name)); // Status = PluginStatus.Stopped; //} //private async Task Part(ServerMessagedEventArgs args) { // Status = PluginStatus.Processing; // IrcCommandEventArgs command = new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", string.Empty); // if (args.Message.SplitArgs.Count < 3) { // command.Arguments = "Insufficient parameters. Type 'eve help part' to view command's help index."; // } else if (args.Message.SplitArgs.Count < 2 || !args.Message.SplitArgs[2].StartsWith("#")) { // command.Arguments = "Channel parameter must be a proper name (starts with '#')."; // } else if (args.Message.SplitArgs.Count < 2 || args.Caller.Server.GetChannel(args.Message.SplitArgs[2]) == null) { // command.Arguments = "I'm not in that channel."; // } // Status = PluginStatus.Running; // if (!string.IsNullOrEmpty(command.Arguments)) { // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); // return; // } // string channel = args.Message.SplitArgs[2].ToLower(); // args.Caller.Server.RemoveChannel(channel); // command.Arguments = $"Successfully parted channel: {channel}"; // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs(Commands.PART, $"{channel} Channel part invoked by: {args.Message.Nickname}"), Name)); // Status = PluginStatus.Stopped; //} //private async Task Channels(ServerMessagedEventArgs args) { // Status = PluginStatus.Running; // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", string.Join(", ", args.Caller.Server.Channels.Where(channel => channel.Name.StartsWith("#")).Select(channel => channel.Name))), Name)); // Status = PluginStatus.Stopped; //} //private async Task YouTubeLinkResponse(ServerMessagedEventArgs args) { // Status = PluginStatus.Running; // const int maxDescriptionLength = 100; // string getResponse = await $"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={_youtubeRegex.Match(args.Message.Args).Groups["ID"]}&key={args.Caller.GetApiKey("YouTube")}".HttpGet(); // JToken video = JObject.Parse(getResponse)["items"][0]["snippet"]; // string channel = (string)video["channelTitle"]; // string title = (string)video["title"]; // string description = video["description"].ToString().Split('\n')[0]; // string[] descArray = description.Split(' '); // if (description.Length > maxDescriptionLength) { // description = string.Empty; // for (int i = 0; description.Length < maxDescriptionLength; i++) { // description += $" {descArray[i]}"; // } // if (!description.EndsWith(" ")) { // description.Remove(description.LastIndexOf(' ')); // } // description += "...."; // } // await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", $"{title} (by {channel}) — {description}"), Name)); // Status = PluginStatus.Stopped; //} private async Task Define(ServerMessagedEventArgs args) { Status = PluginStatus.Processing; IrcCommandEventArgs command = new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", string.Empty); if (args.Message.SplitArgs.Count < 3) { command.Arguments = "Insufficient parameters. Type 'eve help define' to view correct usage."; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); return; } Status = PluginStatus.Running; string partOfSpeech = args.Message.SplitArgs.Count > 3 ? $"&part_of_speech={args.Message.SplitArgs[3]}" : string.Empty; JObject entry = JObject.Parse( await $"http://api.pearson.com/v2/dictionaries/laad3/entries?headword={args.Message.SplitArgs[2]}{partOfSpeech}&limit=1" .HttpGet()); if ((int)entry.SelectToken("count") < 1) { command.Arguments = "Query returned no results."; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); return; } Dictionary<string, string> _out = new Dictionary<string, string> { { "word", (string)entry["results"][0]["headword"] }, { "pos", (string)entry["results"][0]["part_of_speech"] } }; // todo optimise if block // this 'if' block seems messy and unoptimised. // I'll likely change it in the future. if (entry["results"][0]["senses"][0]["subsenses"] != null) { _out.Add("definition", (string)entry["results"][0]["senses"][0]["subsenses"][0]["definition"]); if (entry["results"][0]["senses"][0]["subsenses"][0]["examples"] != null) { _out.Add("example", (string)entry["results"][0]["senses"][0]["subsenses"][0]["examples"][0]["text"]); } } else { _out.Add("definition", (string)entry["results"][0]["senses"][0]["definition"]); if (entry["results"][0]["senses"][0]["examples"] != null) { _out.Add("example", (string)entry["results"][0]["senses"][0]["examples"][0]["text"]); } } string returnMessage = $"{_out["word"]} [{_out["pos"]}] — {_out["definition"]}"; if (_out.ContainsKey("example")) { returnMessage += $" (ex. {_out["example"]})"; } command.Arguments = returnMessage; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); Status = PluginStatus.Stopped; } private async Task Lookup(ServerMessagedEventArgs args) { Status = PluginStatus.Processing; if ((args.Message.SplitArgs.Count < 2) || !args.Message.SplitArgs[1].Equals("lookup")) { return; } IrcCommandEventArgs command = new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", string.Empty); if (args.Message.SplitArgs.Count < 3) { command.Arguments = "Insufficient parameters. Type 'eve help lookup' to view correct usage."; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); return; } Status = PluginStatus.Running; string query = string.Join(" ", args.Message.SplitArgs.Skip(1)); string response = await $"https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles={query}" .HttpGet(); JToken pages = JObject.Parse(response)["query"]["pages"].Values().First(); if (string.IsNullOrEmpty((string)pages["extract"])) { command.Arguments = "Query failed to return results. Perhaps try a different term?"; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); return; } string fullReplyStr = $"\x02{(string)pages["title"]}\x0F — {Regex.Replace((string)pages["extract"], @"\n\n?|\n", " ")}"; command.Command = args.Message.Nickname; foreach (string splitMessage in fullReplyStr.LengthSplit(400)) { command.Arguments = splitMessage; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); } Status = PluginStatus.Stopped; } private async Task Set(ServerMessagedEventArgs args) { if ((args.Message.SplitArgs.Count < 2) || !args.Message.SplitArgs[1].Equals("set")) { return; } Status = PluginStatus.Processing; IrcCommandEventArgs command = new IrcCommandEventArgs($"{Commands.PRIVMSG} {args.Message.Origin}", string.Empty); if (args.Message.SplitArgs.Count < 5) { command.Arguments = "Insufficient parameters. Type 'eve help lookup' to view correct usage."; await DoCallback(this, new PluginActionEventArgs(PluginActionType.SendMessage, command, Name)); return; } Status = PluginStatus.Stopped; } } #endregion }
43.217726
309
0.575613
[ "MIT" ]
SemiViral/Convex
Convex.Base/Base.cs
22,456
C#
using System.Text; using Util.Datas.Matedatas; using Util.Datas.Sql.Queries.Builders.Abstractions; using Util.Datas.Sql.Queries.Builders.Core; namespace Util.Datas.Dapper.MySql { /// <summary> /// MySql Sql生成器 /// </summary> public class MySqlBuilder : SqlBuilderBase { /// <summary> /// 初始化Sql生成器 /// </summary> /// <param name="matedata">实体元数据解析器</param> /// <param name="parameterManager">参数管理器</param> public MySqlBuilder( IEntityMatedata matedata = null, IParameterManager parameterManager = null ) : base( matedata, parameterManager ) { } /// <summary> /// 获取Sql方言 /// </summary> protected override IDialect GetDialect() { return new MySqlDialect(); } /// <summary> /// 创建Sql生成器 /// </summary> public override ISqlBuilder New() { return new MySqlBuilder( EntityMatedata, ParameterManager ); } /// <summary> /// 创建From子句 /// </summary> protected override IFromClause CreateFromClause() { return new MySqlFromClause( GetDialect(), EntityResolver, AliasRegister ); } /// <summary> /// 创建Join子句 /// </summary> protected override IJoinClause CreateJoinClause() { return new MySqlJoinClause( GetDialect(), EntityResolver, AliasRegister ); } /// <summary> /// 创建分页Sql /// </summary> protected override void CreatePagerSql( StringBuilder result ) { AppendSelect( result ); AppendFrom( result ); AppendSql( result, GetJoin() ); AppendSql( result, GetWhere() ); AppendSql( result, GetGroupBy() ); AppendSql( result, GetOrderBy() ); result.Append( $"Limit {GetSkipCountParam()}, {GetPageSizeParam()}" ); } } }
31.983333
144
0.569567
[ "MIT" ]
VAllens/Util
src/Util.Datas/Dapper/MySql/MySqlBuilder.cs
2,007
C#
using System; using System.Collections.Generic; using System.Text; using MHUrho.Logic; using Urho; namespace MHUrho.PathFinding { public interface ITileNode : INode { ITile Tile { get; } /// <summary> /// Gets the position of the edge between this tile and the <paramref name="other"/> tile /// </summary> /// <param name="other">The other tile to which we want the edge</param> /// <returns>The position of the edge connecting the two tiles</returns> Vector3 GetEdgePosition(ITileNode other); } }
24.952381
91
0.704198
[ "MIT" ]
MK4H/MHUrho
MHUrho/MHUrho/PathFinding/ITileNode.cs
526
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 09.05.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.NullableDouble.NullableSingle{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Double>; using T_DATA2 =System.Nullable<System.Single>; //////////////////////////////////////////////////////////////////////////////// //class TestSet_504__param__04__NN public static class TestSet_504__param__04__NN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => ((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2)); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=null; T_DATA2 vv2=null; var recs=db.testTable.Where(r => !(((object)vv1) /*OP{*/ == /*}OP*/ ((object)vv2))); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_0")); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 };//class TestSet_504__param__04__NN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.Equal.Complete2__objs.NullableDouble.NullableSingle
26.70073
149
0.533898
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/Equal/Complete2__objs/NullableDouble/NullableSingle/TestSet_504__param__04__NN.cs
3,660
C#
using FilmWebAPI.Models; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FilmWebAPI.Requests.Get { public class GetBornTodayPersons : RequestBase<PersonBirthdate[]> { public GetBornTodayPersons() : base(Signature.Create("getBornTodayPersons", -1), FilmWebHttpMethod.Get) { } public override async Task<PersonBirthdate[]> Parse(HttpResponseMessage responseMessage) { var content = await responseMessage.Content.ReadAsStringAsync(); if (content.StartsWith("ok")) { var jsonBody = content.Remove(0, 3); var json = JArray.Parse(Regex.Replace(jsonBody, "t(s?):(\\d+)$", string.Empty)); return json.Skip(1).Select(token => { var array = token as JArray; if (array == null) return null; return new PersonBirthdate { Id = array[0].ToObject<int>(), Name = array[1].ToObject<string>(), Poster = array[2].ToObject<string>(), Birthdate = array[3].ToObject<DateTime>(), Deathdate = array[4].HasValues ? array[4].ToObject<DateTime>() : DateTime.MinValue, }; }).ToArray(); } throw new FilmWebException(FilmWebExceptionType.UnableToGetData); } } }
37.511628
112
0.536888
[ "MIT" ]
Sunnyline2/FilmWeb-API
src/FilmWebAPI/Requests/Get/GetBornTodayPersons.cs
1,615
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph { using System.Text.Json.Serialization; /// <summary> /// The enum WindowsInformationProtectionPinCharacterRequirements. /// </summary> [JsonConverter(typeof(JsonStringEnumConverter))] public enum WindowsInformationProtectionPinCharacterRequirements { /// <summary> /// Not Allow /// </summary> NotAllow = 0, /// <summary> /// Require At Least One /// </summary> RequireAtLeastOne = 1, /// <summary> /// Allow /// </summary> Allow = 2, } }
27.358974
153
0.522024
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/WindowsInformationProtectionPinCharacterRequirements.cs
1,067
C#
using System.Numerics; namespace _14_CornellBoxONBScatterFunction { public class Ray { private Vector3 orig; private Vector3 dir; private float tm; public Vector3 Origin => this.orig; public Vector3 Direction => this.dir; public float Time => this.tm; public Ray(Vector3 a, Vector3 b, float ti = 0.0f) { this.orig = a; this.dir = b; this.tm = ti; } public Vector3 At(float t) { return this.orig + t * this.dir; //P(t) = A + tb } } }
20.517241
60
0.517647
[ "MIT" ]
Jorgemagic/RaytracingTheRestOfYourLife
14-CornellBoxONBScatterFunction/Ray.cs
597
C#
// <auto-generated /> using System; using HealthPairDataAccess.DataModels; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace HealthPairDataAccess.Migrations { [DbContext(typeof(HealthPairContext))] [Migration("20200512180753_migrationname")] partial class migrationname { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn) .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 63); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Appointment", b => { b.Property<int>("AppointmentId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<DateTime>("AppointmentDate") .HasColumnType("timestamp without time zone"); b.Property<int>("PatientId") .HasColumnType("integer"); b.Property<int>("ProviderId") .HasColumnType("integer"); b.HasKey("AppointmentId"); b.HasIndex("PatientId"); b.HasIndex("ProviderId"); b.ToTable("Appointments"); b.HasData( new { AppointmentId = 1, AppointmentDate = new DateTime(2020, 4, 29, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientId = 3, ProviderId = 1 }, new { AppointmentId = 2, AppointmentDate = new DateTime(2020, 6, 29, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientId = 2, ProviderId = 3 }, new { AppointmentId = 3, AppointmentDate = new DateTime(2020, 5, 29, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientId = 1, ProviderId = 2 }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Facility", b => { b.Property<int>("FacilityId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("FacilityAddress1") .IsRequired() .HasColumnType("character varying(120)") .HasMaxLength(120); b.Property<string>("FacilityCity") .IsRequired() .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("FacilityName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<long>("FacilityPhoneNumber") .HasColumnType("bigint"); b.Property<string>("FacilityState") .IsRequired() .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<int>("FacilityZipcode") .HasColumnType("integer"); b.HasKey("FacilityId"); b.ToTable("Facilities"); b.HasData( new { FacilityId = 1, FacilityAddress1 = "1700 James Bowie Drive", FacilityCity = "Baytown", FacilityName = "Houston Methodist San Jacinto Hospital Alexander Campus", FacilityPhoneNumber = 2814208765L, FacilityState = "TX", FacilityZipcode = 77520 }, new { FacilityId = 2, FacilityAddress1 = "16750 Red Oak Drive", FacilityCity = "Houston", FacilityName = "Providence Hospital of North Houston LLC", FacilityPhoneNumber = 2814537110L, FacilityState = "TX", FacilityZipcode = 77090 }, new { FacilityId = 3, FacilityAddress1 = "301 West Expressway 83", FacilityCity = "McAllen", FacilityName = "McCallen Medical Center", FacilityPhoneNumber = 9566324000L, FacilityState = "TX", FacilityZipcode = 78590 }, new { FacilityId = 4, FacilityAddress1 = "215 Chisholm Trail", FacilityCity = "Jacksboro", FacilityName = "Faith Community Hospital", FacilityPhoneNumber = 9405676633L, FacilityState = "TX", FacilityZipcode = 76458 }, new { FacilityId = 5, FacilityAddress1 = "4000 24th Street", FacilityCity = "Lubbock", FacilityName = "Covenant Medical Center – Lakeside", FacilityPhoneNumber = 8067250536L, FacilityState = "TX", FacilityZipcode = 79410 }, new { FacilityId = 6, FacilityAddress1 = "25440 I 45 North", FacilityCity = "The Woodlands", FacilityName = "Woodlands Specialty Hospita", FacilityPhoneNumber = 2816028160L, FacilityState = "TX", FacilityZipcode = 77386 }, new { FacilityId = 7, FacilityAddress1 = "600 Elizabeth Street", FacilityCity = "Corpus Christi", FacilityName = "Christus Spohn Hospital Corpus Christi Shoreline", FacilityPhoneNumber = 3619024690L, FacilityState = "TX", FacilityZipcode = 78404 }, new { FacilityId = 8, FacilityAddress1 = "13725 Northwest Blvd", FacilityCity = "Corpus Christi", FacilityName = "The Corpus Christi Medical Center – Northwest", FacilityPhoneNumber = 3617674300L, FacilityState = "TX", FacilityZipcode = 78410 }, new { FacilityId = 9, FacilityAddress1 = "1300 N Main Ave", FacilityCity = "Big Lake", FacilityName = "Reagan Memorial Hospital", FacilityPhoneNumber = 3258842561L, FacilityState = "TX", FacilityZipcode = 76932 }, new { FacilityId = 10, FacilityAddress1 = "1975 Alpha, Suite 100", FacilityCity = "Rockwall", FacilityName = "Baylor Emergency Medical Center", FacilityPhoneNumber = 2142946200L, FacilityState = "TX", FacilityZipcode = 75087 }, new { FacilityId = 11, FacilityAddress1 = "620 South Main, Suite 100", FacilityCity = "Keller", FacilityName = "Baylor Emergency Medical Center", FacilityPhoneNumber = 2142946100L, FacilityState = "TX", FacilityZipcode = 76248 }, new { FacilityId = 12, FacilityAddress1 = "12500 South Freeway, Suite 100", FacilityCity = "Burleson", FacilityName = "Baylor Emergency Medical Center", FacilityPhoneNumber = 2142946250L, FacilityState = "TX", FacilityZipcode = 76028 }, new { FacilityId = 13, FacilityAddress1 = "1776 North Us 287, Suite 100", FacilityCity = "Mansfield", FacilityName = "Baylor Emergency Medical Center", FacilityPhoneNumber = 2142946300L, FacilityState = "TX", FacilityZipcode = 76063 }, new { FacilityId = 14, FacilityAddress1 = "5500 Colleyville Boulevard", FacilityCity = "Colleyville", FacilityName = "Baylor Emergency Medical Center", FacilityPhoneNumber = 2142946350L, FacilityState = "TX", FacilityZipcode = 76034 }, new { FacilityId = 15, FacilityAddress1 = "3101 North Tarrant Parkway", FacilityCity = "Fort Worth", FacilityName = "Medical Center of Alliance", FacilityPhoneNumber = 8176391100L, FacilityState = "TX", FacilityZipcode = 76177 }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Insurance", b => { b.Property<int>("InsuranceId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("InsuranceName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.HasKey("InsuranceId"); b.ToTable("Insurances"); b.HasData( new { InsuranceId = 1, InsuranceName = "Cigna" }, new { InsuranceId = 2, InsuranceName = "Humana" }, new { InsuranceId = 3, InsuranceName = "Community" }, new { InsuranceId = 4, InsuranceName = "Molina" }, new { InsuranceId = 5, InsuranceName = "FirstCare" }, new { InsuranceId = 6, InsuranceName = "Superior" }, new { InsuranceId = 7, InsuranceName = "Christus" }, new { InsuranceId = 8, InsuranceName = "Celtic" }, new { InsuranceId = 9, InsuranceName = "Sendero" }, new { InsuranceId = 10, InsuranceName = "EmblemHealth" }, new { InsuranceId = 11, InsuranceName = "Wellcare" }, new { InsuranceId = 12, InsuranceName = "CVS" }, new { InsuranceId = 13, InsuranceName = "Independence Health Group Inc." }, new { InsuranceId = 14, InsuranceName = "Highmark Group" }, new { InsuranceId = 15, InsuranceName = "None (Cash)" }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_InsuranceProvider", b => { b.Property<int>("IPId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("InsuranceId") .HasColumnType("integer"); b.Property<int>("ProviderId") .HasColumnType("integer"); b.HasKey("IPId"); b.HasIndex("InsuranceId"); b.HasIndex("ProviderId"); b.ToTable("InsuranceProviders"); b.HasData( new { IPId = 2, InsuranceId = 1, ProviderId = 2 }, new { IPId = 46, InsuranceId = 1, ProviderId = 4 }, new { IPId = 47, InsuranceId = 1, ProviderId = 5 }, new { IPId = 49, InsuranceId = 1, ProviderId = 7 }, new { IPId = 52, InsuranceId = 1, ProviderId = 10 }, new { IPId = 53, InsuranceId = 1, ProviderId = 11 }, new { IPId = 55, InsuranceId = 1, ProviderId = 13 }, new { IPId = 56, InsuranceId = 1, ProviderId = 14 }, new { IPId = 57, InsuranceId = 1, ProviderId = 15 }, new { IPId = 59, InsuranceId = 1, ProviderId = 17 }, new { IPId = 62, InsuranceId = 1, ProviderId = 20 }, new { IPId = 66, InsuranceId = 1, ProviderId = 24 }, new { IPId = 69, InsuranceId = 1, ProviderId = 27 }, new { IPId = 70, InsuranceId = 1, ProviderId = 28 }, new { IPId = 73, InsuranceId = 1, ProviderId = 31 }, new { IPId = 74, InsuranceId = 1, ProviderId = 32 }, new { IPId = 76, InsuranceId = 1, ProviderId = 34 }, new { IPId = 77, InsuranceId = 1, ProviderId = 35 }, new { IPId = 78, InsuranceId = 1, ProviderId = 36 }, new { IPId = 82, InsuranceId = 1, ProviderId = 40 }, new { IPId = 4, InsuranceId = 2, ProviderId = 1 }, new { IPId = 5, InsuranceId = 2, ProviderId = 2 }, new { IPId = 6, InsuranceId = 2, ProviderId = 3 }, new { IPId = 90, InsuranceId = 2, ProviderId = 8 }, new { IPId = 91, InsuranceId = 2, ProviderId = 9 }, new { IPId = 92, InsuranceId = 2, ProviderId = 10 }, new { IPId = 93, InsuranceId = 2, ProviderId = 11 }, new { IPId = 94, InsuranceId = 2, ProviderId = 12 }, new { IPId = 95, InsuranceId = 2, ProviderId = 13 }, new { IPId = 96, InsuranceId = 2, ProviderId = 14 }, new { IPId = 97, InsuranceId = 2, ProviderId = 15 }, new { IPId = 100, InsuranceId = 2, ProviderId = 18 }, new { IPId = 101, InsuranceId = 2, ProviderId = 19 }, new { IPId = 107, InsuranceId = 2, ProviderId = 25 }, new { IPId = 108, InsuranceId = 2, ProviderId = 26 }, new { IPId = 109, InsuranceId = 2, ProviderId = 27 }, new { IPId = 117, InsuranceId = 2, ProviderId = 35 }, new { IPId = 118, InsuranceId = 2, ProviderId = 36 }, new { IPId = 119, InsuranceId = 2, ProviderId = 37 }, new { IPId = 120, InsuranceId = 2, ProviderId = 38 }, new { IPId = 7, InsuranceId = 3, ProviderId = 1 }, new { IPId = 9, InsuranceId = 3, ProviderId = 3 }, new { IPId = 10, InsuranceId = 4, ProviderId = 1 }, new { IPId = 12, InsuranceId = 4, ProviderId = 3 }, new { IPId = 13, InsuranceId = 5, ProviderId = 1 }, new { IPId = 16, InsuranceId = 6, ProviderId = 1 }, new { IPId = 18, InsuranceId = 6, ProviderId = 3 }, new { IPId = 19, InsuranceId = 7, ProviderId = 1 }, new { IPId = 21, InsuranceId = 7, ProviderId = 3 }, new { IPId = 22, InsuranceId = 8, ProviderId = 1 }, new { IPId = 24, InsuranceId = 8, ProviderId = 3 }, new { IPId = 26, InsuranceId = 9, ProviderId = 2 }, new { IPId = 27, InsuranceId = 9, ProviderId = 3 }, new { IPId = 28, InsuranceId = 10, ProviderId = 1 }, new { IPId = 31, InsuranceId = 11, ProviderId = 1 }, new { IPId = 32, InsuranceId = 11, ProviderId = 2 }, new { IPId = 33, InsuranceId = 11, ProviderId = 3 }, new { IPId = 34, InsuranceId = 12, ProviderId = 1 }, new { IPId = 35, InsuranceId = 12, ProviderId = 2 }, new { IPId = 38, InsuranceId = 13, ProviderId = 2 }, new { IPId = 41, InsuranceId = 14, ProviderId = 2 }, new { IPId = 42, InsuranceId = 14, ProviderId = 3 }, new { IPId = 43, InsuranceId = 15, ProviderId = 1 }, new { IPId = 45, InsuranceId = 15, ProviderId = 3 }, new { IPId = 83, InsuranceId = 1, ProviderId = 41 }, new { IPId = 84, InsuranceId = 1, ProviderId = 42 }, new { IPId = 85, InsuranceId = 1, ProviderId = 43 }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Patient", b => { b.Property<int>("PatientId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("InsuranceId") .HasColumnType("integer"); b.Property<bool>("IsAdmin") .ValueGeneratedOnAdd() .HasColumnType("boolean") .HasDefaultValue(false); b.Property<string>("PatientAddress1") .IsRequired() .HasColumnType("character varying(120)") .HasMaxLength(120); b.Property<DateTime>("PatientBirthDay") .HasColumnType("timestamp without time zone"); b.Property<string>("PatientCity") .IsRequired() .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<string>("PatientEmail") .IsRequired() .HasColumnType("character varying(120)") .HasMaxLength(120); b.Property<string>("PatientFirstName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("PatientLastName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("PatientPassword") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<long>("PatientPhoneNumber") .HasColumnType("bigint"); b.Property<string>("PatientState") .IsRequired() .HasColumnType("character varying(40)") .HasMaxLength(40); b.Property<int>("PatientZipcode") .HasColumnType("integer"); b.HasKey("PatientId"); b.HasIndex("InsuranceId"); b.ToTable("Patients"); b.HasData( new { PatientId = 1, InsuranceId = 1, IsAdmin = true, PatientAddress1 = "8401 Ronnie St", PatientBirthDay = new DateTime(2000, 4, 12, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "White Settlement", PatientEmail = "ifawdry0@si.edu", PatientFirstName = "Josh", PatientLastName = "Kraus", PatientPassword = "Password1", PatientPhoneNumber = 7167787419L, PatientState = "TX", PatientZipcode = 76108 }, new { PatientId = 2, InsuranceId = 3, IsAdmin = true, PatientAddress1 = "2500 Victory Ave", PatientBirthDay = new DateTime(1988, 11, 30, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "Dallas", PatientEmail = "wotimony1@shop-pro.jp", PatientFirstName = "Devin", PatientLastName = "Holt", PatientPassword = "Password2", PatientPhoneNumber = 3619033062L, PatientState = "TX", PatientZipcode = 75201 }, new { PatientId = 3, InsuranceId = 5, IsAdmin = false, PatientAddress1 = "5919 Peg Street", PatientBirthDay = new DateTime(2002, 10, 31, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "Houston", PatientEmail = "lsiward2@cnbc.com", PatientFirstName = "Zach", PatientLastName = "Zellner", PatientPassword = "Password3", PatientPhoneNumber = 2452488647L, PatientState = "TX", PatientZipcode = 77092 }, new { PatientId = 4, InsuranceId = 7, IsAdmin = false, PatientAddress1 = "10810 Spring Cypress Rd.", PatientBirthDay = new DateTime(1999, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "Tomball", PatientEmail = "mindgs3@microsoft.com", PatientFirstName = "Don", PatientLastName = "Robbins", PatientPassword = "Password4", PatientPhoneNumber = 8823701130L, PatientState = "TX", PatientZipcode = 77375 }, new { PatientId = 5, InsuranceId = 7, IsAdmin = false, PatientAddress1 = "10810 Spring Cypress Rd.", PatientBirthDay = new DateTime(1999, 1, 9, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "Tomball", PatientEmail = "mindgs3@microsoft.com", PatientFirstName = "Don", PatientLastName = "Robbins", PatientPassword = "Password4", PatientPhoneNumber = 8823701130L, PatientState = "TX", PatientZipcode = 77375 }, new { PatientId = 6, InsuranceId = 1, IsAdmin = true, PatientAddress1 = "123 Test Street", PatientBirthDay = new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), PatientCity = "Test City", PatientEmail = "TestEmail@test.com", PatientFirstName = "TestPatientFirstName", PatientLastName = "TestPatientLastName", PatientPassword = "TestPassword", PatientPhoneNumber = 1234567890L, PatientState = "Test State", PatientZipcode = 12345 }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Provider", b => { b.Property<int>("ProviderId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<int>("FacilityId") .HasColumnType("integer"); b.Property<string>("ProviderFirstName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<string>("ProviderLastName") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.Property<long>("ProviderPhoneNumber") .HasColumnType("bigint"); b.Property<int>("SpecialtyId") .HasColumnType("integer"); b.HasKey("ProviderId"); b.HasIndex("FacilityId"); b.HasIndex("SpecialtyId"); b.ToTable("Providers"); b.HasData( new { ProviderId = 1, FacilityId = 1, ProviderFirstName = "Devin", ProviderLastName = "Kraus", ProviderPhoneNumber = 7167787419L, SpecialtyId = 6 }, new { ProviderId = 2, FacilityId = 2, ProviderFirstName = "Zach", ProviderLastName = "Holt", ProviderPhoneNumber = 3619033062L, SpecialtyId = 13 }, new { ProviderId = 3, FacilityId = 3, ProviderFirstName = "Josh", ProviderLastName = "Zellner", ProviderPhoneNumber = 2452488647L, SpecialtyId = 5 }, new { ProviderId = 4, FacilityId = 4, ProviderFirstName = "Josh", ProviderLastName = "Robins", ProviderPhoneNumber = 8823701130L, SpecialtyId = 8 }, new { ProviderId = 5, FacilityId = 5, ProviderFirstName = "Donald", ProviderLastName = "Mullen", ProviderPhoneNumber = 9016226625L, SpecialtyId = 11 }, new { ProviderId = 6, FacilityId = 6, ProviderFirstName = "Maury", ProviderLastName = "Chitter", ProviderPhoneNumber = 2577977019L, SpecialtyId = 4 }, new { ProviderId = 7, FacilityId = 7, ProviderFirstName = "Philomena", ProviderLastName = "Capon", ProviderPhoneNumber = 2834986226L, SpecialtyId = 8 }, new { ProviderId = 8, FacilityId = 8, ProviderFirstName = "Michail", ProviderLastName = "Minkin", ProviderPhoneNumber = 4487593448L, SpecialtyId = 4 }, new { ProviderId = 9, FacilityId = 9, ProviderFirstName = "Boothe", ProviderLastName = "Gurrado", ProviderPhoneNumber = 9373233203L, SpecialtyId = 2 }, new { ProviderId = 10, FacilityId = 10, ProviderFirstName = "Kendall", ProviderLastName = "Mulqueen", ProviderPhoneNumber = 9033544326L, SpecialtyId = 1 }, new { ProviderId = 11, FacilityId = 11, ProviderFirstName = "Onfre", ProviderLastName = "Grazier", ProviderPhoneNumber = 8503233858L, SpecialtyId = 14 }, new { ProviderId = 12, FacilityId = 12, ProviderFirstName = "Mauricio", ProviderLastName = "Rowes", ProviderPhoneNumber = 3259067361L, SpecialtyId = 8 }, new { ProviderId = 13, FacilityId = 13, ProviderFirstName = "Elana", ProviderLastName = "Dollman", ProviderPhoneNumber = 8696441600L, SpecialtyId = 6 }, new { ProviderId = 14, FacilityId = 14, ProviderFirstName = "Georg", ProviderLastName = "Yakunchikov", ProviderPhoneNumber = 3464020514L, SpecialtyId = 10 }, new { ProviderId = 15, FacilityId = 15, ProviderFirstName = "Nanny", ProviderLastName = "Stead", ProviderPhoneNumber = 7705745366L, SpecialtyId = 3 }, new { ProviderId = 16, FacilityId = 1, ProviderFirstName = "Jorie", ProviderLastName = "Atwool", ProviderPhoneNumber = 9363687510L, SpecialtyId = 8 }, new { ProviderId = 17, FacilityId = 2, ProviderFirstName = "Alfons", ProviderLastName = "Shee", ProviderPhoneNumber = 6445427083L, SpecialtyId = 11 }, new { ProviderId = 18, FacilityId = 3, ProviderFirstName = "Netta", ProviderLastName = "Fincken", ProviderPhoneNumber = 5252048919L, SpecialtyId = 7 }, new { ProviderId = 19, FacilityId = 4, ProviderFirstName = "Melli", ProviderLastName = "Hansford", ProviderPhoneNumber = 5024459183L, SpecialtyId = 14 }, new { ProviderId = 20, FacilityId = 5, ProviderFirstName = "Kathryne", ProviderLastName = "Pawlaczyk", ProviderPhoneNumber = 6981610466L, SpecialtyId = 14 }, new { ProviderId = 21, FacilityId = 6, ProviderFirstName = "Dex", ProviderLastName = "Rawstron", ProviderPhoneNumber = 5243227555L, SpecialtyId = 13 }, new { ProviderId = 22, FacilityId = 7, ProviderFirstName = "Dorie", ProviderLastName = "O'Dreain", ProviderPhoneNumber = 5123716488L, SpecialtyId = 4 }, new { ProviderId = 23, FacilityId = 8, ProviderFirstName = "Leonora", ProviderLastName = "Pitford", ProviderPhoneNumber = 2138363970L, SpecialtyId = 10 }, new { ProviderId = 24, FacilityId = 9, ProviderFirstName = "Whitney", ProviderLastName = "Sevior", ProviderPhoneNumber = 6174183997L, SpecialtyId = 1 }, new { ProviderId = 25, FacilityId = 10, ProviderFirstName = "Zora", ProviderLastName = "Paolucci", ProviderPhoneNumber = 1909364291L, SpecialtyId = 8 }, new { ProviderId = 26, FacilityId = 11, ProviderFirstName = "Jayson", ProviderLastName = "Wookey", ProviderPhoneNumber = 8982665744L, SpecialtyId = 10 }, new { ProviderId = 27, FacilityId = 12, ProviderFirstName = "Rock", ProviderLastName = "Sharville", ProviderPhoneNumber = 5864186454L, SpecialtyId = 8 }, new { ProviderId = 28, FacilityId = 13, ProviderFirstName = "Dani", ProviderLastName = "Broadwell", ProviderPhoneNumber = 4221047432L, SpecialtyId = 10 }, new { ProviderId = 29, FacilityId = 14, ProviderFirstName = "Virginia", ProviderLastName = "McAvinchey", ProviderPhoneNumber = 8769325946L, SpecialtyId = 2 }, new { ProviderId = 30, FacilityId = 15, ProviderFirstName = "Neala", ProviderLastName = "Cianelli", ProviderPhoneNumber = 4504879923L, SpecialtyId = 15 }, new { ProviderId = 31, FacilityId = 6, ProviderFirstName = "Pooh", ProviderLastName = "Florio", ProviderPhoneNumber = 3317751153L, SpecialtyId = 6 }, new { ProviderId = 32, FacilityId = 14, ProviderFirstName = "Portia", ProviderLastName = "Treadwell", ProviderPhoneNumber = 3609514708L, SpecialtyId = 14 }, new { ProviderId = 33, FacilityId = 4, ProviderFirstName = "Tucky", ProviderLastName = "Dreher", ProviderPhoneNumber = 1313561327L, SpecialtyId = 4 }, new { ProviderId = 34, FacilityId = 15, ProviderFirstName = "Gardie", ProviderLastName = "Drakes", ProviderPhoneNumber = 6921919943L, SpecialtyId = 15 }, new { ProviderId = 35, FacilityId = 7, ProviderFirstName = "Phillip", ProviderLastName = "Sharville", ProviderPhoneNumber = 9529171778L, SpecialtyId = 7 }, new { ProviderId = 36, FacilityId = 8, ProviderFirstName = "Byrle", ProviderLastName = "Shuttleworth", ProviderPhoneNumber = 2717398518L, SpecialtyId = 8 }, new { ProviderId = 37, FacilityId = 14, ProviderFirstName = "Hy", ProviderLastName = "Hamflett", ProviderPhoneNumber = 1206169437L, SpecialtyId = 14 }, new { ProviderId = 38, FacilityId = 12, ProviderFirstName = "Eadie", ProviderLastName = "Taill", ProviderPhoneNumber = 7997088826L, SpecialtyId = 12 }, new { ProviderId = 39, FacilityId = 2, ProviderFirstName = "Timi", ProviderLastName = "Kestian", ProviderPhoneNumber = 2894355254L, SpecialtyId = 2 }, new { ProviderId = 40, FacilityId = 11, ProviderFirstName = "Gearalt", ProviderLastName = "Dows", ProviderPhoneNumber = 7618424391L, SpecialtyId = 11 }, new { ProviderId = 41, FacilityId = 6, ProviderFirstName = "Lisa", ProviderLastName = "Simons", ProviderPhoneNumber = 5821908432L, SpecialtyId = 1 }, new { ProviderId = 42, FacilityId = 12, ProviderFirstName = "Leroy", ProviderLastName = "Gerkins", ProviderPhoneNumber = 2337452877L, SpecialtyId = 1 }, new { ProviderId = 43, FacilityId = 1, ProviderFirstName = "Ki'Nir", ProviderLastName = "Habadayah", ProviderPhoneNumber = 4997874451L, SpecialtyId = 1 }, new { ProviderId = 44, FacilityId = 12, ProviderFirstName = "James", ProviderLastName = "Comey", ProviderPhoneNumber = 3261558779L, SpecialtyId = 1 }, new { ProviderId = 45, FacilityId = 1, ProviderFirstName = "Karina", ProviderLastName = "Silkya", ProviderPhoneNumber = 6674219116L, SpecialtyId = 1 }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Specialty", b => { b.Property<int>("SpecialtyId") .ValueGeneratedOnAdd() .HasColumnType("integer") .HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn); b.Property<string>("Specialty") .IsRequired() .HasColumnType("character varying(80)") .HasMaxLength(80); b.HasKey("SpecialtyId"); b.ToTable("Specialties"); b.HasData( new { SpecialtyId = 1, Specialty = "Ophthalmologist" }, new { SpecialtyId = 2, Specialty = "Dermatologist" }, new { SpecialtyId = 3, Specialty = "Cardiologist" }, new { SpecialtyId = 4, Specialty = "Urologist" }, new { SpecialtyId = 5, Specialty = "Gastroenterologist" }, new { SpecialtyId = 6, Specialty = "Psychiatrist" }, new { SpecialtyId = 7, Specialty = "Internist" }, new { SpecialtyId = 8, Specialty = "Neurologist" }, new { SpecialtyId = 9, Specialty = "Endocrinologist" }, new { SpecialtyId = 10, Specialty = "Otolaryngologist" }, new { SpecialtyId = 11, Specialty = "Orthopedist" }, new { SpecialtyId = 12, Specialty = "Pediatrician" }, new { SpecialtyId = 13, Specialty = "Anesthesiologist" }, new { SpecialtyId = 14, Specialty = "Pulmonologist" }, new { SpecialtyId = 15, Specialty = "Proctologist" }); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Appointment", b => { b.HasOne("HealthPairDataAccess.DataModels.Data_Patient", "Patient") .WithMany("Appointments") .HasForeignKey("PatientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthPairDataAccess.DataModels.Data_Provider", "Provider") .WithMany("Appointments") .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_InsuranceProvider", b => { b.HasOne("HealthPairDataAccess.DataModels.Data_Insurance", "Insurance") .WithMany("InsuranceProviders") .HasForeignKey("InsuranceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthPairDataAccess.DataModels.Data_Provider", "Provider") .WithMany("InsuranceProviders") .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Patient", b => { b.HasOne("HealthPairDataAccess.DataModels.Data_Insurance", "Insurance") .WithMany("Patients") .HasForeignKey("InsuranceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("HealthPairDataAccess.DataModels.Data_Provider", b => { b.HasOne("HealthPairDataAccess.DataModels.Data_Facility", "Facility") .WithMany("Providers") .HasForeignKey("FacilityId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("HealthPairDataAccess.DataModels.Data_Specialty", "Specialty") .WithMany("Providers") .HasForeignKey("SpecialtyId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
40.94152
128
0.304353
[ "MIT" ]
2002-feb24-net/HealthPair-API
HealthPairService/HealthPairDataAccess/Migrations/20200512180753_migrationname.Designer.cs
63,015
C#
namespace Altairis.Services.Mailing.SendGrid { public class SendGridMailerServiceOptions : MailerServiceOptions { public string ApiKey { get; set; } } }
21.5
70
0.715116
[ "MIT" ]
ridercz/Altairis.Services.Mailing
Altairis.Services.Mailing.SendGrid/SendGridMailerServiceOptions.cs
174
C#
using System.Collections.Generic; using System.IO; using System.Net; using Arbor.KVConfiguration.Core; using Arbor.KVConfiguration.Microsoft.Extensions.Configuration.Urns; using Autofac; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Milou.Deployer.Web.Core.Application; using Milou.Deployer.Web.Core.Configuration; using Milou.Deployer.Web.Core.Extensions; using Serilog.Extensions.Logging; namespace Milou.Deployer.Web.IisHost.AspNetCore { public static class CustomWebHostBuilder { public static IWebHostBuilder GetWebHostBuilder( IKeyValueConfiguration configuration, Scope startupScope, Scope webHostScope, Serilog.ILogger logger, Scope scope) { var environmentConfiguration = startupScope.Deepest().Lifetime.ResolveOptional<EnvironmentConfiguration>(); string contentRoot = environmentConfiguration?.ContentBasePath ?? Directory.GetCurrentDirectory(); logger.Debug("Using content root {ContentRoot}", contentRoot); var kestrelServerOptions = new List<KestrelServerOptions>(); IWebHostBuilder webHostBuilder = new WebHostBuilder() .UseStartup<Startup>() .ConfigureLogging((context, builder) => { builder.AddProvider(new SerilogLoggerProvider(logger)); }) .ConfigureServices(services => { services.AddHttpClient(); services.AddTransient(provider => webHostScope.Lifetime.Resolve<Startup>()); }) .ConfigureAppConfiguration((hostingContext, config) => { config.AddKeyValueConfigurationSource(configuration); }) .UseKestrel(options => { if (kestrelServerOptions.Contains(options)) { return; } if (environmentConfiguration != null) { if (environmentConfiguration.HttpPort.HasValue) { logger.Information("Listening on http port {Port}", environmentConfiguration.HttpPort.Value); options.Listen(IPAddress.Loopback, environmentConfiguration.HttpPort.Value); } if (environmentConfiguration.HttpsPort.HasValue && environmentConfiguration.PfxFile.HasValue() && environmentConfiguration.PfxPassword.HasValue()) { logger.Information("Listening on https port {Port}", environmentConfiguration.HttpsPort.Value); options.Listen(IPAddress.Loopback, environmentConfiguration.HttpsPort.Value, listenOptions => { listenOptions.UseHttps(environmentConfiguration.PfxFile, environmentConfiguration.PfxPassword); }); } } kestrelServerOptions.Add(options); }) .UseContentRoot(contentRoot) .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(); }) .UseIISIntegration() .UseDefaultServiceProvider((context, options) => { options.ValidateScopes = context.HostingEnvironment.IsDevelopment(); }) .UseStartup<Startup>(); if (environmentConfiguration != null) { if (environmentConfiguration.EnvironmentName.HasValue()) { webHostBuilder = webHostBuilder.UseEnvironment(environmentConfiguration.EnvironmentName); } } return new WebHostBuilderWrapper(webHostBuilder, scope); } } }
42.087379
123
0.562399
[ "MIT" ]
milou-se/milou.deployer.web
src/Milou.Deployer.Web.IisHost/AspNetCore/CustomWebHostBuilder.cs
4,335
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FlyingObject : GravityBody { PlayerController player; bool hasInteracted = false; protected override void Start() { base.Start(); player = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerController>(); } void FixedUpdate() { float step = 8.5f * Time.deltaTime; if (hasInteracted) transform.position = Vector3.MoveTowards(transform.position, player.holdPoint.transform.position, step); } public void Interact() { rb.velocity = new Vector3(0, 0, 0); if (hasInteracted) rb.AddForce(player.camera.transform.forward * 12, ForceMode.Impulse); hasInteracted = !hasInteracted; } void OnCollisionEnter(Collision other) { if (hasInteracted && other.collider.tag != "Player" && other.collider.tag != "Portal") Interact(); } }
27.285714
131
0.662827
[ "MIT" ]
celinehsieh68/Non_Eclidian_Geometry
Assets/_Script/FlyingObject.cs
957
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.BitConverter; namespace Microsoft.Data.Encryption.Cryptography.Serializers { /// <inheritdoc/> public class DateTimeOffsetSerializer : Serializer<DateTimeOffset> { private static readonly DateTimeSerializer DateTimeSerializer = new DateTimeSerializer(); private static readonly TimeSpanSerializer TimeSpanSerializer = new TimeSpanSerializer(); /// <inheritdoc/> public override string Identifier => "DateTimeOffset"; /// <inheritdoc/> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="bytes"/> is null. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when the length of <paramref name="bytes"/> is less than 16. /// </exception> public override DateTimeOffset Deserialize(byte[] bytes) { const int DateTimeIndex = 0; const int TimeSpanIndex = sizeof(long); const int MinimumSize = sizeof(long) + sizeof(long); bytes.ValidateNotNull(nameof(bytes)); bytes.ValidateGreaterThanSize(MinimumSize, nameof(bytes)); byte[] dateTimePart = bytes.Skip(DateTimeIndex).Take(sizeof(long)).ToArray(); byte[] timeSpanPart = bytes.Skip(TimeSpanIndex).Take(sizeof(long)).ToArray(); DateTime dateTime = DateTimeSerializer.Deserialize(dateTimePart); TimeSpan timeSpan = TimeSpanSerializer.Deserialize(timeSpanPart); return new DateTimeOffset(dateTime, timeSpan); } /// <inheritdoc/> /// <returns> /// An array of bytes with length 16. /// </returns> public override byte[] Serialize(DateTimeOffset value) { IEnumerable<byte> dateTimePart = DateTimeSerializer.Serialize(value.DateTime); IEnumerable<byte> timeSpanPart = TimeSpanSerializer.Serialize(value.Offset); return dateTimePart.Concat(timeSpanPart).ToArray(); } } }
37.105263
97
0.652955
[ "MIT" ]
Xtrimmer/SqlClient
src/Microsoft.Data.Encryption/src/Microsoft/Data/Encryption/Cryptography/Serializers/StandardSerializers/DateTimeOffsetSerializer.cs
2,117
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.MSHTMLApi { ///<summary> /// DispatchInterface DispHTMLAreaElement /// SupportByVersion MSHTML, 4 ///</summary> [SupportByVersionAttribute("MSHTML", 4)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class DispHTMLAreaElement : COMObject { #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(DispHTMLAreaElement); 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 DispHTMLAreaElement(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 DispHTMLAreaElement(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 DispHTMLAreaElement(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 DispHTMLAreaElement(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 DispHTMLAreaElement(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTMLAreaElement() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public DispHTMLAreaElement(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string className { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "className", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "className", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string id { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "id", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "id", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string tagName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "tagName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElement parentElement { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "parentElement", paramsArray); NetOffice.MSHTMLApi.IHTMLElement newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElement; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.MSHTMLApi.IHTMLStyle style { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "style", paramsArray); NetOffice.MSHTMLApi.IHTMLStyle newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLStyle; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onhelp { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onhelp", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onhelp", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onclick { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onclick", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onclick", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondblclick { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondblclick", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondblclick", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onkeydown { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onkeydown", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onkeydown", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onkeyup { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onkeyup", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onkeyup", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onkeypress { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onkeypress", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onkeypress", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmouseout { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmouseout", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmouseout", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmouseover { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmouseover", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmouseover", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmousemove { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmousemove", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmousemove", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmousedown { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmousedown", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmousedown", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmouseup { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmouseup", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmouseup", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object document { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "document", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string title { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "title", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "title", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string language { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "language", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "language", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onselectstart { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onselectstart", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onselectstart", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 sourceIndex { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "sourceIndex", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object recordNumber { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "recordNumber", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string lang { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "lang", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "lang", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 offsetLeft { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "offsetLeft", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 offsetTop { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "offsetTop", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 offsetWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "offsetWidth", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 offsetHeight { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "offsetHeight", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElement offsetParent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "offsetParent", paramsArray); NetOffice.MSHTMLApi.IHTMLElement newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElement; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string innerHTML { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "innerHTML", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "innerHTML", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string innerText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "innerText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "innerText", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string outerHTML { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "outerHTML", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "outerHTML", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string outerText { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "outerText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "outerText", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElement parentTextEdit { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "parentTextEdit", paramsArray); NetOffice.MSHTMLApi.IHTMLElement newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElement; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool isTextEdit { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "isTextEdit", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLFiltersCollection filters { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "filters", paramsArray); NetOffice.MSHTMLApi.IHTMLFiltersCollection newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.MSHTMLApi.IHTMLFiltersCollection.LateBindingApiWrapperType) as NetOffice.MSHTMLApi.IHTMLFiltersCollection; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondragstart { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondragstart", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondragstart", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforeupdate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforeupdate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforeupdate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onafterupdate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onafterupdate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onafterupdate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onerrorupdate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onerrorupdate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onerrorupdate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onrowexit { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onrowexit", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onrowexit", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onrowenter { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onrowenter", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onrowenter", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondatasetchanged { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondatasetchanged", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondatasetchanged", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondataavailable { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondataavailable", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondataavailable", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondatasetcomplete { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondatasetcomplete", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondatasetcomplete", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onfilterchange { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onfilterchange", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onfilterchange", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object children { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "children", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object all { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "all", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string scopeName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "scopeName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onlosecapture { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onlosecapture", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onlosecapture", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onscroll { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onscroll", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onscroll", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondrag { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondrag", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondrag", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondragend { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondragend", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondragend", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondragenter { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondragenter", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondragenter", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondragover { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondragover", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondragover", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondragleave { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondragleave", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondragleave", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondrop { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondrop", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondrop", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforecut { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforecut", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforecut", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object oncut { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "oncut", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "oncut", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforecopy { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforecopy", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforecopy", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object oncopy { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "oncopy", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "oncopy", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforepaste { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforepaste", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforepaste", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onpaste { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onpaste", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onpaste", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.MSHTMLApi.IHTMLCurrentStyle currentStyle { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "currentStyle", paramsArray); NetOffice.MSHTMLApi.IHTMLCurrentStyle newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLCurrentStyle; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onpropertychange { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onpropertychange", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onpropertychange", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int16 tabIndex { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "tabIndex", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "tabIndex", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string accessKey { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "accessKey", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "accessKey", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onblur { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onblur", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onblur", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onfocus { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onfocus", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onfocus", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onresize { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onresize", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onresize", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 clientHeight { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "clientHeight", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 clientWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "clientWidth", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 clientTop { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "clientTop", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 clientLeft { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "clientLeft", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object readyState { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "readyState", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onreadystatechange { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onreadystatechange", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onreadystatechange", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onrowsdelete { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onrowsdelete", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onrowsdelete", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onrowsinserted { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onrowsinserted", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onrowsinserted", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object oncellchange { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "oncellchange", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "oncellchange", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string dir { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "dir", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "dir", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 scrollHeight { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "scrollHeight", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 scrollWidth { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "scrollWidth", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 scrollTop { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "scrollTop", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "scrollTop", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 scrollLeft { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "scrollLeft", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "scrollLeft", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object oncontextmenu { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "oncontextmenu", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "oncontextmenu", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool canHaveChildren { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "canHaveChildren", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public NetOffice.MSHTMLApi.IHTMLStyle runtimeStyle { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "runtimeStyle", paramsArray); NetOffice.MSHTMLApi.IHTMLStyle newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLStyle; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object behaviorUrns { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "behaviorUrns", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string tagUrn { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "tagUrn", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "tagUrn", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforeeditfocus { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforeeditfocus", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforeeditfocus", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int32 readyStateValue { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "readyStateValue", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool isMultiLine { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "isMultiLine", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool canHaveHTML { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "canHaveHTML", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onlayoutcomplete { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onlayoutcomplete", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onlayoutcomplete", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onpage { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onpage", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onpage", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool inflateBlock { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "inflateBlock", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "inflateBlock", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforedeactivate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforedeactivate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforedeactivate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string contentEditable { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "contentEditable", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "contentEditable", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool isContentEditable { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "isContentEditable", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool hideFocus { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "hideFocus", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "hideFocus", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool disabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "disabled", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "disabled", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool isDisabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "isDisabled", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmove { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmove", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmove", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object oncontrolselect { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "oncontrolselect", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "oncontrolselect", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onresizestart { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onresizestart", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onresizestart", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onresizeend { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onresizeend", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onresizeend", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmovestart { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmovestart", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmovestart", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmoveend { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmoveend", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmoveend", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmouseenter { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmouseenter", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmouseenter", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmouseleave { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmouseleave", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmouseleave", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onactivate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onactivate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onactivate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ondeactivate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ondeactivate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ondeactivate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int32 glyphMode { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "glyphMode", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onmousewheel { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onmousewheel", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onmousewheel", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onbeforeactivate { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onbeforeactivate", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onbeforeactivate", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onfocusin { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onfocusin", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onfocusin", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object onfocusout { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "onfocusout", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "onfocusout", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Int32 uniqueNumber { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "uniqueNumber", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public string uniqueID { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "uniqueID", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int32 nodeType { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "nodeType", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode parentNode { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "parentNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object childNodes { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "childNodes", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object attributes { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "attributes", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string nodeName { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "nodeName", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object nodeValue { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "nodeValue", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "nodeValue", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode firstChild { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "firstChild", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode lastChild { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "lastChild", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode previousSibling { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "previousSibling", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode nextSibling { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "nextSibling", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object ownerDocument { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ownerDocument", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string role { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "role", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "role", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaBusy { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaBusy", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaBusy", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaChecked { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaChecked", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaChecked", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaDisabled { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaDisabled", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaDisabled", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaExpanded { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaExpanded", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaExpanded", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaHaspopup { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaHaspopup", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaHaspopup", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaHidden { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaHidden", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaHidden", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaInvalid { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaInvalid", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaInvalid", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaMultiselectable { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaMultiselectable", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaMultiselectable", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaPressed { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaPressed", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaPressed", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaReadonly { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaReadonly", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaReadonly", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaRequired { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaRequired", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaRequired", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaSecret { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaSecret", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaSecret", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaSelected { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaSelected", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaSelected", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLAttributeCollection3 ie8_attributes { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ie8_attributes", paramsArray); NetOffice.MSHTMLApi.IHTMLAttributeCollection3 newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLAttributeCollection3; return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaValuenow { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaValuenow", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaValuenow", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int16 ariaPosinset { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaPosinset", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaPosinset", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int16 ariaSetsize { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaSetsize", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaSetsize", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public Int16 ariaLevel { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaLevel", paramsArray); return NetRuntimeSystem.Convert.ToInt16(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaLevel", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaValuemin { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaValuemin", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaValuemin", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaValuemax { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaValuemax", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaValuemax", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaControls { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaControls", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaControls", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaDescribedby { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaDescribedby", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaDescribedby", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaFlowto { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaFlowto", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaFlowto", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaLabelledby { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaLabelledby", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaLabelledby", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaActivedescendant { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaActivedescendant", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaActivedescendant", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaOwns { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaOwns", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaOwns", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaLive { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaLive", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaLive", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ariaRelevant { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ariaRelevant", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ariaRelevant", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("MSHTML", 4)] [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public object constructor { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "constructor", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string shape { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "shape", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "shape", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string coords { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "coords", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "coords", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string href { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "href", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "href", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string target { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "target", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "target", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string alt { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "alt", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "alt", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool noHref { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "noHref", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "noHref", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string host { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "host", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "host", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string hostname { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "hostname", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "hostname", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string pathname { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "pathname", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "pathname", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string port { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "port", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "port", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string protocol { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "protocol", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "protocol", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string search { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "search", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "search", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string hash { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "hash", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "hash", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ie8_shape { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ie8_shape", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ie8_shape", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ie8_coords { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ie8_coords", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ie8_coords", paramsArray); } } /// <summary> /// SupportByVersion MSHTML 4 /// Get/Set /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string ie8_href { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "ie8_href", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } set { object[] paramsArray = Invoker.ValidateParamsArray(value); Invoker.PropertySet(this, "ie8_href", paramsArray); } } #endregion #region Methods /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object AttributeValue</param> /// <param name="lFlags">optional Int32 lFlags = 1</param> [SupportByVersionAttribute("MSHTML", 4)] public void setAttribute(string strAttributeName, object attributeValue, object lFlags) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName, attributeValue, lFlags); Invoker.Method(this, "setAttribute", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object AttributeValue</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void setAttribute(string strAttributeName, object attributeValue) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName, attributeValue); Invoker.Method(this, "setAttribute", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="lFlags">optional Int32 lFlags = 0</param> [SupportByVersionAttribute("MSHTML", 4)] public object getAttribute(string strAttributeName, object lFlags) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName, lFlags); object returnItem = Invoker.MethodReturn(this, "getAttribute", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public object getAttribute(string strAttributeName) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName); object returnItem = Invoker.MethodReturn(this, "getAttribute", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="lFlags">optional Int32 lFlags = 1</param> [SupportByVersionAttribute("MSHTML", 4)] public bool removeAttribute(string strAttributeName, object lFlags) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName, lFlags); object returnItem = Invoker.MethodReturn(this, "removeAttribute", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public bool removeAttribute(string strAttributeName) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName); object returnItem = Invoker.MethodReturn(this, "removeAttribute", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="varargStart">optional object varargStart</param> [SupportByVersionAttribute("MSHTML", 4)] public void scrollIntoView(object varargStart) { object[] paramsArray = Invoker.ValidateParamsArray(varargStart); Invoker.Method(this, "scrollIntoView", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void scrollIntoView() { object[] paramsArray = null; Invoker.Method(this, "scrollIntoView", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pChild">NetOffice.MSHTMLApi.IHTMLElement pChild</param> [SupportByVersionAttribute("MSHTML", 4)] public bool contains(NetOffice.MSHTMLApi.IHTMLElement pChild) { object[] paramsArray = Invoker.ValidateParamsArray(pChild); object returnItem = Invoker.MethodReturn(this, "contains", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="where">string where</param> /// <param name="html">string html</param> [SupportByVersionAttribute("MSHTML", 4)] public void insertAdjacentHTML(string where, string html) { object[] paramsArray = Invoker.ValidateParamsArray(where, html); Invoker.Method(this, "insertAdjacentHTML", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="where">string where</param> /// <param name="text">string text</param> [SupportByVersionAttribute("MSHTML", 4)] public void insertAdjacentText(string where, string text) { object[] paramsArray = Invoker.ValidateParamsArray(where, text); Invoker.Method(this, "insertAdjacentText", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void click() { object[] paramsArray = null; Invoker.Method(this, "click", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public string toString() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "toString", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="containerCapture">optional bool containerCapture = true</param> [SupportByVersionAttribute("MSHTML", 4)] public void setCapture(object containerCapture) { object[] paramsArray = Invoker.ValidateParamsArray(containerCapture); Invoker.Method(this, "setCapture", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void setCapture() { object[] paramsArray = null; Invoker.Method(this, "setCapture", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void releaseCapture() { object[] paramsArray = null; Invoker.Method(this, "releaseCapture", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="x">Int32 x</param> /// <param name="y">Int32 y</param> [SupportByVersionAttribute("MSHTML", 4)] public string componentFromPoint(Int32 x, Int32 y) { object[] paramsArray = Invoker.ValidateParamsArray(x, y); object returnItem = Invoker.MethodReturn(this, "componentFromPoint", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="component">optional object component</param> [SupportByVersionAttribute("MSHTML", 4)] public void doScroll(object component) { object[] paramsArray = Invoker.ValidateParamsArray(component); Invoker.Method(this, "doScroll", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void doScroll() { object[] paramsArray = null; Invoker.Method(this, "doScroll", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLRectCollection getClientRects() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "getClientRects", paramsArray); NetOffice.MSHTMLApi.IHTMLRectCollection newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.MSHTMLApi.IHTMLRectCollection.LateBindingApiWrapperType) as NetOffice.MSHTMLApi.IHTMLRectCollection; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLRect getBoundingClientRect() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "getBoundingClientRect", paramsArray); NetOffice.MSHTMLApi.IHTMLRect newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.MSHTMLApi.IHTMLRect.LateBindingApiWrapperType) as NetOffice.MSHTMLApi.IHTMLRect; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="propname">string propname</param> /// <param name="expression">string expression</param> /// <param name="language">optional string language = </param> [SupportByVersionAttribute("MSHTML", 4)] public void setExpression(string propname, string expression, object language) { object[] paramsArray = Invoker.ValidateParamsArray(propname, expression, language); Invoker.Method(this, "setExpression", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="propname">string propname</param> /// <param name="expression">string expression</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void setExpression(string propname, string expression) { object[] paramsArray = Invoker.ValidateParamsArray(propname, expression); Invoker.Method(this, "setExpression", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="propname">string propname</param> [SupportByVersionAttribute("MSHTML", 4)] public object getExpression(string propname) { object[] paramsArray = Invoker.ValidateParamsArray(propname); object returnItem = Invoker.MethodReturn(this, "getExpression", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="propname">string propname</param> [SupportByVersionAttribute("MSHTML", 4)] public bool removeExpression(string propname) { object[] paramsArray = Invoker.ValidateParamsArray(propname); object returnItem = Invoker.MethodReturn(this, "removeExpression", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void focus() { object[] paramsArray = null; Invoker.Method(this, "focus", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void blur() { object[] paramsArray = null; Invoker.Method(this, "blur", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pUnk">object pUnk</param> [SupportByVersionAttribute("MSHTML", 4)] public void addFilter(object pUnk) { object[] paramsArray = Invoker.ValidateParamsArray(pUnk); Invoker.Method(this, "addFilter", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pUnk">object pUnk</param> [SupportByVersionAttribute("MSHTML", 4)] public void removeFilter(object pUnk) { object[] paramsArray = Invoker.ValidateParamsArray(pUnk); Invoker.Method(this, "removeFilter", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="_event">string event</param> /// <param name="pdisp">object pdisp</param> [SupportByVersionAttribute("MSHTML", 4)] public bool attachEvent(string _event, object pdisp) { object[] paramsArray = Invoker.ValidateParamsArray(_event, pdisp); object returnItem = Invoker.MethodReturn(this, "attachEvent", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="_event">string event</param> /// <param name="pdisp">object pdisp</param> [SupportByVersionAttribute("MSHTML", 4)] public void detachEvent(string _event, object pdisp) { object[] paramsArray = Invoker.ValidateParamsArray(_event, pdisp); Invoker.Method(this, "detachEvent", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public object createControlRange() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "createControlRange", paramsArray); object newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void clearAttributes() { object[] paramsArray = null; Invoker.Method(this, "clearAttributes", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="where">string where</param> /// <param name="insertedElement">NetOffice.MSHTMLApi.IHTMLElement insertedElement</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElement insertAdjacentElement(string where, NetOffice.MSHTMLApi.IHTMLElement insertedElement) { object[] paramsArray = Invoker.ValidateParamsArray(where, insertedElement); object returnItem = Invoker.MethodReturn(this, "insertAdjacentElement", paramsArray); NetOffice.MSHTMLApi.IHTMLElement newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElement; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="apply">NetOffice.MSHTMLApi.IHTMLElement apply</param> /// <param name="where">string where</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElement applyElement(NetOffice.MSHTMLApi.IHTMLElement apply, string where) { object[] paramsArray = Invoker.ValidateParamsArray(apply, where); object returnItem = Invoker.MethodReturn(this, "applyElement", paramsArray); NetOffice.MSHTMLApi.IHTMLElement newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElement; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="where">string where</param> [SupportByVersionAttribute("MSHTML", 4)] public string getAdjacentText(string where) { object[] paramsArray = Invoker.ValidateParamsArray(where); object returnItem = Invoker.MethodReturn(this, "getAdjacentText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="where">string where</param> /// <param name="newText">string newText</param> [SupportByVersionAttribute("MSHTML", 4)] public string replaceAdjacentText(string where, string newText) { object[] paramsArray = Invoker.ValidateParamsArray(where, newText); object returnItem = Invoker.MethodReturn(this, "replaceAdjacentText", paramsArray); return NetRuntimeSystem.Convert.ToString(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrUrl">string bstrUrl</param> /// <param name="pvarFactory">optional object pvarFactory</param> [SupportByVersionAttribute("MSHTML", 4)] public Int32 addBehavior(string bstrUrl, object pvarFactory) { object[] paramsArray = Invoker.ValidateParamsArray(bstrUrl, pvarFactory); object returnItem = Invoker.MethodReturn(this, "addBehavior", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrUrl">string bstrUrl</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public Int32 addBehavior(string bstrUrl) { object[] paramsArray = Invoker.ValidateParamsArray(bstrUrl); object returnItem = Invoker.MethodReturn(this, "addBehavior", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="cookie">Int32 cookie</param> [SupportByVersionAttribute("MSHTML", 4)] public bool removeBehavior(Int32 cookie) { object[] paramsArray = Invoker.ValidateParamsArray(cookie); object returnItem = Invoker.MethodReturn(this, "removeBehavior", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="v">string v</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLElementCollection getElementsByTagName(string v) { object[] paramsArray = Invoker.ValidateParamsArray(v); object returnItem = Invoker.MethodReturn(this, "getElementsByTagName", paramsArray); NetOffice.MSHTMLApi.IHTMLElementCollection newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLElementCollection; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param> /// <param name="pvarFlags">optional object pvarFlags</param> [SupportByVersionAttribute("MSHTML", 4)] public void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis, object pvarFlags) { object[] paramsArray = Invoker.ValidateParamsArray(mergeThis, pvarFlags); Invoker.Method(this, "mergeAttributes", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="mergeThis">NetOffice.MSHTMLApi.IHTMLElement mergeThis</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public void mergeAttributes(NetOffice.MSHTMLApi.IHTMLElement mergeThis) { object[] paramsArray = Invoker.ValidateParamsArray(mergeThis); Invoker.Method(this, "mergeAttributes", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void setActive() { object[] paramsArray = null; Invoker.Method(this, "setActive", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrEventName">string bstrEventName</param> /// <param name="pvarEventObject">optional object pvarEventObject</param> [SupportByVersionAttribute("MSHTML", 4)] public bool FireEvent(string bstrEventName, object pvarEventObject) { object[] paramsArray = Invoker.ValidateParamsArray(bstrEventName, pvarEventObject); object returnItem = Invoker.MethodReturn(this, "FireEvent", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrEventName">string bstrEventName</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public bool FireEvent(string bstrEventName) { object[] paramsArray = Invoker.ValidateParamsArray(bstrEventName); object returnItem = Invoker.MethodReturn(this, "FireEvent", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool dragDrop() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "dragDrop", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public void normalize() { object[] paramsArray = null; Invoker.Method(this, "normalize", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrName">string bstrName</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute getAttributeNode(string bstrName) { object[] paramsArray = Invoker.ValidateParamsArray(bstrName); object returnItem = Invoker.MethodReturn(this, "getAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr) { object[] paramsArray = Invoker.ValidateParamsArray(pattr); object returnItem = Invoker.MethodReturn(this, "setAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute pattr) { object[] paramsArray = Invoker.ValidateParamsArray(pattr); object returnItem = Invoker.MethodReturn(this, "removeAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool hasChildNodes() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "hasChildNodes", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> /// <param name="refChild">optional object refChild</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, object refChild) { object[] paramsArray = Invoker.ValidateParamsArray(newChild, refChild); object returnItem = Invoker.MethodReturn(this, "insertBefore", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode insertBefore(NetOffice.MSHTMLApi.IHTMLDOMNode newChild) { object[] paramsArray = Invoker.ValidateParamsArray(newChild); object returnItem = Invoker.MethodReturn(this, "insertBefore", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode removeChild(NetOffice.MSHTMLApi.IHTMLDOMNode oldChild) { object[] paramsArray = Invoker.ValidateParamsArray(oldChild); object returnItem = Invoker.MethodReturn(this, "removeChild", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> /// <param name="oldChild">NetOffice.MSHTMLApi.IHTMLDOMNode oldChild</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode replaceChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild, NetOffice.MSHTMLApi.IHTMLDOMNode oldChild) { object[] paramsArray = Invoker.ValidateParamsArray(newChild, oldChild); object returnItem = Invoker.MethodReturn(this, "replaceChild", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="fDeep">bool fDeep</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode cloneNode(bool fDeep) { object[] paramsArray = Invoker.ValidateParamsArray(fDeep); object returnItem = Invoker.MethodReturn(this, "cloneNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="fDeep">optional bool fDeep = false</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode removeNode(object fDeep) { object[] paramsArray = Invoker.ValidateParamsArray(fDeep); object returnItem = Invoker.MethodReturn(this, "removeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [CustomMethodAttribute] [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode removeNode() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "removeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="otherNode">NetOffice.MSHTMLApi.IHTMLDOMNode otherNode</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode swapNode(NetOffice.MSHTMLApi.IHTMLDOMNode otherNode) { object[] paramsArray = Invoker.ValidateParamsArray(otherNode); object returnItem = Invoker.MethodReturn(this, "swapNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="replacement">NetOffice.MSHTMLApi.IHTMLDOMNode replacement</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode replaceNode(NetOffice.MSHTMLApi.IHTMLDOMNode replacement) { object[] paramsArray = Invoker.ValidateParamsArray(replacement); object returnItem = Invoker.MethodReturn(this, "replaceNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="newChild">NetOffice.MSHTMLApi.IHTMLDOMNode newChild</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMNode appendChild(NetOffice.MSHTMLApi.IHTMLDOMNode newChild) { object[] paramsArray = Invoker.ValidateParamsArray(newChild); object returnItem = Invoker.MethodReturn(this, "appendChild", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMNode newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMNode; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="bstrName">string bstrName</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_getAttributeNode(string bstrName) { object[] paramsArray = Invoker.ValidateParamsArray(bstrName); object returnItem = Invoker.MethodReturn(this, "ie8_getAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute2 newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute2; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_setAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr) { object[] paramsArray = Invoker.ValidateParamsArray(pattr); object returnItem = Invoker.MethodReturn(this, "ie8_setAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute2 newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute2; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="pattr">NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr</param> [SupportByVersionAttribute("MSHTML", 4)] public NetOffice.MSHTMLApi.IHTMLDOMAttribute2 ie8_removeAttributeNode(NetOffice.MSHTMLApi.IHTMLDOMAttribute2 pattr) { object[] paramsArray = Invoker.ValidateParamsArray(pattr); object returnItem = Invoker.MethodReturn(this, "ie8_removeAttributeNode", paramsArray); NetOffice.MSHTMLApi.IHTMLDOMAttribute2 newObject = Factory.CreateObjectFromComProxy(this,returnItem) as NetOffice.MSHTMLApi.IHTMLDOMAttribute2; return newObject; } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="name">string name</param> [SupportByVersionAttribute("MSHTML", 4)] public bool hasAttribute(string name) { object[] paramsArray = Invoker.ValidateParamsArray(name); object returnItem = Invoker.MethodReturn(this, "hasAttribute", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [SupportByVersionAttribute("MSHTML", 4)] public object ie8_getAttribute(string strAttributeName) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName); object returnItem = Invoker.MethodReturn(this, "ie8_getAttribute", paramsArray); if((null != returnItem) && (returnItem is MarshalByRefObject)) { COMObject newObject = Factory.CreateObjectFromComProxy(this, returnItem); return newObject; } else { return returnItem; } } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> /// <param name="attributeValue">object AttributeValue</param> [SupportByVersionAttribute("MSHTML", 4)] public void ie8_setAttribute(string strAttributeName, object attributeValue) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName, attributeValue); Invoker.Method(this, "ie8_setAttribute", paramsArray); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> /// <param name="strAttributeName">string strAttributeName</param> [SupportByVersionAttribute("MSHTML", 4)] public bool ie8_removeAttribute(string strAttributeName) { object[] paramsArray = Invoker.ValidateParamsArray(strAttributeName); object returnItem = Invoker.MethodReturn(this, "ie8_removeAttribute", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } /// <summary> /// SupportByVersion MSHTML 4 /// /// </summary> [SupportByVersionAttribute("MSHTML", 4)] public bool hasAttributes() { object[] paramsArray = null; object returnItem = Invoker.MethodReturn(this, "hasAttributes", paramsArray); return NetRuntimeSystem.Convert.ToBoolean(returnItem); } #endregion #pragma warning restore } }
26.163458
229
0.676458
[ "MIT" ]
Engineerumair/NetOffice
Source/MSHTML/DispatchInterfaces/DispHTMLAreaElement.cs
127,730
C#
using System; #nullable disable namespace IdentityServer.Domain.DataTransferObjects { public partial class TblApplicationLog { public long Id { get; set; } public long? AppId { get; set; } public short? Severity { get; set; } public string Message { get; set; } public DateTime? CreatedOn { get; set; } public bool IsDeleted { get; set; } public string Initiator { get; set; } public virtual TblApplication App { get; set; } } }
25.45
55
0.618861
[ "MIT" ]
kaizendevsio/XFramework
XFramework/XFramework.Subsystems/XFramework.IdentityServer/Server/IdentityServer.Domain/DataTransferObjects/TblApplicationLog.cs
511
C#
using System; using System.Runtime.InteropServices; namespace ShellProgressBar { public static class TaskbarProgress { public enum TaskbarStates { NoProgress = 0, Indeterminate = 0x1, Normal = 0x2, Error = 0x4, Paused = 0x8 } [ComImport()] [Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ITaskbarList3 { // ITaskbarList [PreserveSig] void HrInit(); [PreserveSig] void AddTab(IntPtr hwnd); [PreserveSig] void DeleteTab(IntPtr hwnd); [PreserveSig] void ActivateTab(IntPtr hwnd); [PreserveSig] void SetActiveAlt(IntPtr hwnd); // ITaskbarList2 [PreserveSig] void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); // ITaskbarList3 [PreserveSig] void SetProgressValue(IntPtr hwnd, UInt64 ullCompleted, UInt64 ullTotal); [PreserveSig] void SetProgressState(IntPtr hwnd, TaskbarStates state); } [ComImport] [Guid("56fdf344-fd6d-11d0-958a-006097c9a090")] [ClassInterface(ClassInterfaceType.None)] private class TaskbarInstance {} [DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow(); private static readonly ITaskbarList3 _taskbarInstance = (ITaskbarList3) new TaskbarInstance(); private static readonly bool _taskbarSupported = !ProgressBar.IsLinux(); public static void SetState(TaskbarStates taskbarState) { if (_taskbarSupported) _taskbarInstance.SetProgressState(GetConsoleWindow(), taskbarState); } public static void SetValue(double progressValue, double progressMax) { if (_taskbarSupported) _taskbarInstance.SetProgressValue(GetConsoleWindow(), (ulong) progressValue, (ulong) progressMax); } } }
23.626667
102
0.73702
[ "MIT" ]
Skippeh/Oxide.GettingOverItMP
GettingOverItMP.Updater/ShellProgressBar/TaskbarProgress.cs
1,774
C#
using XFramework.Domain.Generic.BusinessObjects; namespace Records.Api.Options { public class JwtOptions : JwtOptionsBO { } }
15.555556
49
0.728571
[ "MIT" ]
kaizendevsio/XFramework
XFramework/XFramework.Subsystems/XFramework.Records/Records.Api/Options/JwtOptions.cs
142
C#
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("MyStoryboardApp.Droid.Resource", IsApplication=true)] namespace MyStoryboardApp.Droid { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int Icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050000 public const int myButton = 2131034112; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int Main = 2130903040; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f040001 public const int app_name = 2130968577; // aapt resource value: 0x7f040000 public const int hello = 2130968576; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
19.123894
115
0.606201
[ "MIT" ]
tiefenauer/MyStoryboardApp
MyStoryboardApp/MyStoryboardApp.Droid/Resources/Resource.designer.cs
2,161
C#
// Copyright (c) Edgardo Zoppi. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. using Backend.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Text; using Model.ThreeAddressCode.Instructions; using Model.ThreeAddressCode.Values; using Model; using Backend.Model; namespace Backend.Analyses { public class ReachingDefinitionsAnalysis : ForwardDataFlowAnalysis<Subset<DefinitionInstruction>> { private DefinitionInstruction[] definitions; private IDictionary<IVariable, Subset<DefinitionInstruction>> variable_definitions; private DataFlowAnalysisResult<Subset<DefinitionInstruction>>[] result; private MapList<DefinitionInstruction, IInstruction> def_use; private MapList<IInstruction, DefinitionInstruction> use_def; private Subset<DefinitionInstruction>[] GEN; private Subset<DefinitionInstruction>[] KILL; public ReachingDefinitionsAnalysis(ControlFlowGraph cfg) : base(cfg) { } public MapList<DefinitionInstruction, IInstruction> DefinitionUses { get { return def_use; } } public MapList<IInstruction, DefinitionInstruction> UseDefinitions { get { return use_def; } } public void ComputeDefUseAndUseDefChains() { if (this.result == null) throw new InvalidOperationException("Analysis result not available."); this.def_use = new MapList<DefinitionInstruction, IInstruction>(); this.use_def = new MapList<IInstruction, DefinitionInstruction>(); foreach (var node in this.cfg.Nodes) { var input = new HashSet<DefinitionInstruction>(); var node_result = this.result[node.Id]; if (node_result.Input != null) { node_result.Input.ToSet(input); } var definitions = input.ToMapSet(def => def.Result); foreach (var instruction in node.Instructions) { // use-def foreach (var variable in instruction.UsedVariables) { if (definitions.ContainsKey(variable)) { var var_defs = definitions[variable]; foreach (var definition in var_defs) { def_use.Add(definition, instruction); use_def.Add(instruction, definition); } } else { // Add all uses, even those with no reaching definitions. use_def.Add(instruction); } } // def-use if (instruction is DefinitionInstruction) { var definition = instruction as DefinitionInstruction; if (definition.HasResult) { var variable = definition.Result; definitions.Remove(variable); definitions.Add(variable, definition); // Add all definitions, even those with no uses. def_use.Add(definition); } } } } } public override DataFlowAnalysisResult<Subset<DefinitionInstruction>>[] Analyze() { this.ComputeDefinitions(); this.ComputeGen(); this.ComputeKill(); var result = base.Analyze(); this.result = result; this.definitions = null; this.variable_definitions = null; this.GEN = null; this.KILL = null; return result; } protected override Subset<DefinitionInstruction> InitialValue(CFGNode node) { return GEN[node.Id]; } protected override bool Compare(Subset<DefinitionInstruction> left, Subset<DefinitionInstruction> right) { return left.Equals(right); } protected override Subset<DefinitionInstruction> Join(Subset<DefinitionInstruction> left, Subset<DefinitionInstruction> right) { var result = left.Clone(); result.Union(right); return result; } protected override Subset<DefinitionInstruction> Flow(CFGNode node, Subset<DefinitionInstruction> input) { var output = input.Clone(); var kill = KILL[node.Id]; var gen = GEN[node.Id]; output.Except(kill); output.Union(gen); return output; } private void ComputeDefinitions() { var result = new List<DefinitionInstruction>(); foreach (var node in this.cfg.Nodes) { foreach (var instruction in node.Instructions) { if (instruction is DefinitionInstruction) { var definition = instruction as DefinitionInstruction; if (definition.HasResult) { result.Add(definition); } } } } this.definitions = result.ToArray(); this.variable_definitions = new Dictionary<IVariable, Subset<DefinitionInstruction>>(); for (var i = 0; i < this.definitions.Length; ++i) { var definition = this.definitions[i]; Subset<DefinitionInstruction> defs = null; if (variable_definitions.ContainsKey(definition.Result)) { defs = variable_definitions[definition.Result]; } else { defs = this.definitions.ToEmptySubset(); variable_definitions[definition.Result] = defs; } defs.Add(i); } } private void ComputeGen() { GEN = new Subset<DefinitionInstruction>[this.cfg.Nodes.Count]; var index = 0; foreach (var node in this.cfg.Nodes) { var defined = new Dictionary<IVariable, int>(); foreach (var instruction in node.Instructions) { if (instruction is DefinitionInstruction) { var definition = instruction as DefinitionInstruction; if (definition.HasResult) { defined[definition.Result] = index; index++; } } } // We only add to gen those definitions of node // that reach the end of the basic block var gen = this.definitions.ToEmptySubset(); foreach (var def in defined.Values) { gen.Add(def); } GEN[node.Id] = gen; } } private void ComputeKill() { KILL = new Subset<DefinitionInstruction>[this.cfg.Nodes.Count]; foreach (var node in this.cfg.Nodes) { // We add to kill all definitions of the variables defined at node var kill = this.definitions.ToEmptySubset(); foreach (var instruction in node.Instructions) { if (instruction is DefinitionInstruction) { var definition = instruction as DefinitionInstruction; if (definition.HasResult) { var defs = this.variable_definitions[definition.Result]; kill.Union(defs); } } } KILL[node.Id] = kill; } } } }
24.619048
149
0.680045
[ "MIT" ]
garbervetsky/analysis-net
Backend/Analyses/ReachingDefinitionsAnalysis.cs
6,206
C#
namespace MassTransit.Tests.Initializers { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using InitializerTestMessages; using MassTransit.Initializers; using Metadata; using NUnit.Framework; using TestFramework; using Util; [TestFixture] public class Creating_a_message_via_an_initializer : InMemoryTestFixture { [Test] public async Task Should_initialize_the_properties() { var client = CreateRequestClient<SimpleRequest>(); var response = await client.GetResponse<SimpleResponse>(new {Name = "Hello"}); Assert.That(response.Message.Name, Is.EqualTo("Hello")); Assert.That(response.Message.Value, Is.EqualTo("World")); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.Handler<SimpleRequest>(async context => { await context.RespondAsync<SimpleResponse>(new {Value = "World"}); }); } } [TestFixture] public class Creating_a_message_with_the_same_type_included : InMemoryTestFixture { [Test] public async Task Should_initialize_the_properties() { var context = await MessageInitializerCache<ExceptionInfo>.Initialize(new { Message = "Hello", ExceptionType = TypeMetadataCache<ArgumentException>.ShortName, }); var message = context.Message; Assert.That(message.Message, Is.EqualTo("Hello")); Assert.That(message.ExceptionType, Is.EqualTo(TypeMetadataCache<ArgumentException>.ShortName)); } } [TestFixture] public class Creating_a_message_via_an_initializer_with_missing_properties : InMemoryTestFixture { [Test] public async Task Should_initialize_the_properties() { var client = CreateRequestClient<SimpleRequest>(); var response = await client.GetResponse<SimpleResponse>(new {Name = "Hello"}); Assert.That(response.Message.Name, Is.EqualTo("Hello")); Assert.That(response.Message.Value, Is.Null); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.Handler<SimpleRequest>(async context => { await context.RespondAsync<SimpleResponse>(new { }); }); } } [TestFixture] public class Creating_a_complex_message : InMemoryTestFixture { [Test] public async Task Should_initialize_the_properties() { var client = CreateRequestClient<ComplexRequest>(); var response = await client.GetResponse<ComplexResponse>(new { Name = "Hello", IntValue = 27, NullableIntValue = 42 }); Assert.That(response.Message.Name, Is.EqualTo("Hello")); Assert.That(response.Message.IntValue.HasValue, Is.True); Assert.That(response.Message.IntValue.Value, Is.EqualTo(27)); Assert.That(response.Message.NullableIntValue, Is.EqualTo(42)); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.Handler<ComplexRequest>(async context => { await context.RespondAsync<ComplexResponse>(new { }); }); } } [TestFixture] public class Creating_a_super_complex_message : InMemoryTestFixture { DateTime _now; Response<SuperComplexResponse> _response; [OneTimeSetUp] public async Task Setup() { _now = DateTime.UtcNow; var client = CreateRequestClient<SuperComplexRequest>(); _response = await client.GetResponse<SuperComplexResponse>(new { InVar.CorrelationId, InVar.Id, InVar.Timestamp, StringId = InVar.Id, StringValue = "Hello", IntValue = 27, DateTimeValue = _now, NullableValue = 42, NotNullableValue = (int?)69, NullableDecimalValue = 123.45m, Numbers = new[] {12, 24, 36}, Names = new[] {"Curly", "Larry", "Moe"}, Exception = new IntentionalTestException("It Happens"), SubValue = new {Text = "Mary"}, SubValues = new object[] {new {Text = "Frank"}, new {Text = "Lola"},}, Amount = 867.53m, Amounts = Enumerable.Repeat(98.6m, 2), AsyncValue = GetIntResult().Select(x => x.Number), EngineStatus = Status.Started, NumberStatus = 12, StringStatus = "Started", ServiceAddress = new Uri("http://masstransit-project.com"), OtherAddress = "http://github.com", StringAddress = new Uri("loopback://localhost"), StringList = new[] {"Frank", "Estelle"}, NewProperty = new SubProperty {NewProperty = "Hello"}, Strings = new Dictionary<string, string> { {"Hello", "World"}, {"Thank You", "Next"} }, StringSubValues = new Dictionary<string, object> { {"A", new {Text = "Eh"}}, {"B", new {Text = "Bee"}} }, IntToStrings = new Dictionary<int, long> { {100, 1000}, {200, 2000}, } }); } [Test] public void Should_handle_string() { Assert.That(_response.Message.StringValue, Is.EqualTo("Hello")); } [Test] public void Should_handle_int() { Assert.That(_response.Message.IntValue, Is.EqualTo(27)); } [Test] public void Should_handle_datetime_utc() { Assert.That(_response.Message.DateTimeValue, Is.EqualTo(_now)); } [Test] public void Should_handle_nullable_long() { Assert.That(_response.Message.NullableValue, Is.EqualTo(42)); } [Test] public void Should_handle_long_from_nullable() { Assert.That(_response.Message.NotNullableValue, Is.EqualTo(69)); } [Test] public void Should_handle_nullable_decimal() { Assert.That(_response.Message.NullableDecimalValue, Is.EqualTo(123.45m)); } [Test] public void Should_handle_int_to_string_array() { Assert.That(_response.Message.Numbers, Is.Not.Null); Assert.That(_response.Message.Numbers.Length, Is.EqualTo(3)); Assert.That(_response.Message.Numbers[0], Is.EqualTo("12")); Assert.That(_response.Message.Numbers[1], Is.EqualTo("24")); Assert.That(_response.Message.Numbers[2], Is.EqualTo("36")); } [Test] public void Should_handle_enumerable_decimal() { Assert.That(_response.Message.Amounts, Is.Not.Null); Assert.That(_response.Message.Amounts.Count, Is.EqualTo(2)); Assert.That(_response.Message.Amounts[0], Is.EqualTo(98.6m)); Assert.That(_response.Message.Amounts[1], Is.EqualTo(98.6m)); } [Test] public void Should_handle_string_array() { Assert.That(_response.Message.Names, Is.Not.Null); Assert.That(_response.Message.Names.Length, Is.EqualTo(3)); Assert.That(_response.Message.Names[0], Is.EqualTo("Curly")); Assert.That(_response.Message.Names[1], Is.EqualTo("Larry")); Assert.That(_response.Message.Names[2], Is.EqualTo("Moe")); } [Test] public void Should_handle_exception() { Assert.That(_response.Message.Exception, Is.Not.Null); Assert.That(_response.Message.Exception.ExceptionType, Is.EqualTo(TypeMetadataCache<IntentionalTestException>.ShortName)); } [Test] public void Should_handle_interface_type() { Assert.That(_response.Message.SubValue, Is.Not.Null); Assert.That(_response.Message.SubValue.Text, Is.EqualTo("Mary")); } [Test] public void Should_handle_interface_type_array() { Assert.That(_response.Message.SubValues.Length, Is.EqualTo(2)); Assert.That(_response.Message.SubValues[0].Text, Is.EqualTo("Frank")); Assert.That(_response.Message.SubValues[1].Text, Is.EqualTo("Lola")); } [Test] public void Should_handle_timestamp_variable() { Assert.That(_response.Message.Timestamp.HasValue, Is.True); Assert.That(_response.Message.Timestamp, Is.GreaterThanOrEqualTo(_now)); } [Test] public void Should_handle_decimal() { Assert.That(_response.Message.Amount, Is.EqualTo(867.53m)); } [Test] public void Should_handle_task_of_task_of_int() { Assert.That(_response.Message.AsyncValue, Is.EqualTo(37)); } [Test] public void Should_handle_duplicate_input_property_names() { Assert.That(_response.Message.NewProperty, Is.Not.Null); Assert.That(_response.Message.NewProperty.NewProperty, Is.EqualTo("Hello")); } [Test] public void Should_handle_enums() { Assert.That(_response.Message.EngineStatus, Is.EqualTo(Status.Started)); Assert.That(_response.Message.NumberStatus, Is.EqualTo(Status.Stopped)); Assert.That(_response.Message.StringStatus, Is.EqualTo(Status.Started)); } [Test] public async Task Should_handle_id_variable() { Assert.That(_response.Message.CorrelationId, Is.EqualTo(_response.Message.Id)); Assert.That(_response.Message.StringId, Is.EqualTo(_response.Message.Id)); } [Test] public void Should_handle_uris() { Assert.That(_response.Message.ServiceAddress, Is.EqualTo(new Uri("http://masstransit-project.com"))); Assert.That(_response.Message.OtherAddress, Is.EqualTo(new Uri("http://github.com"))); Assert.That(_response.Message.StringAddress, Is.EqualTo("loopback://localhost/")); } [Test] public void Should_handle_lists() { Assert.That(_response.Message.StringList, Is.Not.Null); Assert.That(_response.Message.StringList.Count, Is.EqualTo(2)); Assert.That(_response.Message.StringList[0], Is.EqualTo("Frank")); Assert.That(_response.Message.StringList[1], Is.EqualTo("Estelle")); } [Test] public void Should_handle_basic_dictionary() { Assert.That(_response.Message.Strings, Is.Not.Null); Assert.That(_response.Message.Strings.Count, Is.EqualTo(2)); Assert.That(_response.Message.Strings["Hello"], Is.EqualTo("World")); Assert.That(_response.Message.Strings["Thank You"], Is.EqualTo("Next")); } [Test] public void Should_handle_object_dictionary() { Assert.That(_response.Message.StringSubValues, Is.Not.Null); Assert.That(_response.Message.StringSubValues.Count, Is.EqualTo(2)); Assert.That(_response.Message.StringSubValues["A"].Text, Is.EqualTo("Eh")); Assert.That(_response.Message.StringSubValues["B"].Text, Is.EqualTo("Bee")); } [Test] public void Should_handle_conversion_dictionary() { Assert.That(_response.Message.IntToStrings, Is.Not.Null); Assert.That(_response.Message.IntToStrings.Count, Is.EqualTo(2)); Assert.That(_response.Message.IntToStrings[100], Is.EqualTo("1000")); Assert.That(_response.Message.IntToStrings[200], Is.EqualTo("2000")); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { configurator.Handler<SuperComplexRequest>(async context => { Console.WriteLine(Encoding.UTF8.GetString(context.ReceiveContext.GetBody())); await context.RespondAsync<SuperComplexResponse>(new { }); }); } async Task<(Task<int> Number, string Text)> GetIntResult() { return (Task.FromResult(37), "Thirty Seven"); } } namespace InitializerTestMessages { using System; public interface SimpleRequest { string Name { get; } } public interface SimpleResponse { string Name { get; } string Value { get; } } public interface ComplexRequest { string Name { get; } int IntValue { get; } int? NullableIntValue { get; } } public interface ComplexResponse { string Name { get; } int? IntValue { get; } int NullableIntValue { get; } } public enum Status { Unknown = 0, Started = 1, Stopped = 12, } public interface SuperComplexRequest { Guid CorrelationId { get; } Guid Id { get; } string StringId { get; } string StringValue { get; } int IntValue { get; } DateTime DateTimeValue { get; } long? NullableValue { get; } long NotNullableValue { get; } decimal? NullableDecimalValue { get; } string[] Numbers { get; } string[] Names { get; } string[] Amounts { get; } ExceptionInfo Exception { get; } SubValue SubValue { get; } SubValue[] SubValues { get; } DateTime Timestamp { get; } string Amount { get; } long AsyncValue { get; } Status EngineStatus { get; } Status NumberStatus { get; } Status StringStatus { get; } Uri ServiceAddress { get; } Uri OtherAddress { get; } string StringAddress { get; } List<string> StringList { get; } AProperty NewProperty { get; } IDictionary<string, string> Strings { get; } IDictionary<string, SubValue> StringSubValues { get; } IDictionary<int, long> IntToStrings { get; } } public interface SuperComplexResponse { Guid CorrelationId { get; } Guid Id { get; } Guid StringId { get; } string StringValue { get; } int IntValue { get; } DateTime DateTimeValue { get; } long? NullableValue { get; } long NotNullableValue { get; } decimal? NullableDecimalValue { get; } string[] Numbers { get; } string[] Names { get; } IList<decimal> Amounts { get; } ExceptionInfo Exception { get; } SubValue SubValue { get; } SubValue[] SubValues { get; } DateTime? Timestamp { get; } decimal Amount { get; } long AsyncValue { get; } Status EngineStatus { get; } Status NumberStatus { get; } Status StringStatus { get; } Uri ServiceAddress { get; } Uri OtherAddress { get; } string StringAddress { get; } IList<string> StringList { get; } AProperty NewProperty { get; } IDictionary<string, string> Strings { get; } IDictionary<string, SubValue> StringSubValues { get; } IDictionary<long, string> IntToStrings { get; } } public interface SubValue { string Text { get; } } public interface AProperty { string NewProperty { get; } } class BaseProperty { public string NewProperty { get; set; } } class SubProperty : BaseProperty { public new string NewProperty { get; set; } } } }
33.316832
134
0.564636
[ "ECL-2.0", "Apache-2.0" ]
ArmyMedalMei/MassTransit
src/MassTransit.Tests/Initializers/MessageInitializer_Specs.cs
16,825
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RigidCharacterController : MonoBehaviour { [SerializeField] private float m_moveSpeed = 2; [SerializeField] private float m_turnSpeed = 200; [SerializeField] private float m_jumpForce = 4; [SerializeField] private Rigidbody m_rigidBody; private float m_currentV = 0; private float m_currentH = 0; private readonly float m_interpolation = 10; private readonly float m_walkScale = 0.33f; private readonly float m_backwardsWalkScale = 0.16f; private readonly float m_backwardRunScale = 0.66f; private bool m_wasGrounded; private Vector3 m_currentDirection = Vector3.zero; private float m_jumpTimeStamp = 0; private float m_minJumpInterval = 0.25f; private bool m_isGrounded; private List<Collider> m_collisions = new List<Collider>(); // Start is called before the first frame update void Start() { } void Update() { DirectUpdate(); m_wasGrounded = m_isGrounded; } private void OnCollisionEnter(Collision collision) { ContactPoint[] contactPoints = collision.contacts; for (int i = 0; i < contactPoints.Length; i++) { if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f) { if (!m_collisions.Contains(collision.collider)) { m_collisions.Add(collision.collider); } m_isGrounded = true; } } } private void OnCollisionStay(Collision collision) { ContactPoint[] contactPoints = collision.contacts; bool validSurfaceNormal = false; for (int i = 0; i < contactPoints.Length; i++) { if (Vector3.Dot(contactPoints[i].normal, Vector3.up) > 0.5f) { validSurfaceNormal = true; break; } } if (validSurfaceNormal) { m_isGrounded = true; if (!m_collisions.Contains(collision.collider)) { m_collisions.Add(collision.collider); } } else { if (m_collisions.Contains(collision.collider)) { m_collisions.Remove(collision.collider); } if (m_collisions.Count == 0) { m_isGrounded = false; } } } private void OnCollisionExit(Collision collision) { if (m_collisions.Contains(collision.collider)) { m_collisions.Remove(collision.collider); } if (m_collisions.Count == 0) { m_isGrounded = false; } } private void DirectUpdate() { float v = Input.GetAxis("Vertical"); float h = Input.GetAxis("Horizontal"); Transform camera = Camera.main.transform; if (Input.GetKey(KeyCode.LeftShift)) { v *= m_walkScale; h *= m_walkScale; } m_currentV = Mathf.Lerp(m_currentV, v, Time.deltaTime * m_interpolation); m_currentH = Mathf.Lerp(m_currentH, h, Time.deltaTime * m_interpolation); Vector3 direction = camera.forward * m_currentV + camera.right * m_currentH; float directionLength = direction.magnitude; direction.y = 0; direction = direction.normalized * directionLength; if (direction != Vector3.zero) { m_currentDirection = Vector3.Slerp(m_currentDirection, direction, Time.deltaTime * m_interpolation); transform.rotation = Quaternion.LookRotation(m_currentDirection); transform.position += m_currentDirection * m_moveSpeed * Time.deltaTime; } JumpingAndLanding(); } private void JumpingAndLanding() { if (Input.GetKey(KeyCode.Space)) { m_jumpTimeStamp = Time.time; //m_rigidBody.AddForce(Vector3.up * m_jumpForce, ForceMode.Impulse); Rigidbody arm = GameObject.Find("basic_rig UpperArm").GetComponent<Rigidbody>(); arm.AddForce(Vector3.up * m_jumpForce, ForceMode.Impulse); Debug.Log("Jump"); } } }
28.951724
112
0.602668
[ "MIT" ]
OGWChurchPuzzlers/OGWChurchPuzzler
Assets/Character/Scripts/RigidCharacterController.cs
4,200
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SoundPlayer : MonoBehaviour { public List<AudioClip> Audio1; public List<AudioClip> Audio2; void Start() { } // Update is called once per frame void Update() { } public void PlaySound1() { AudioSource.PlayClipAtPoint(Audio1[Random.Range(0, Audio1.Count)],transform.position); } public void PlaySound2() { AudioSource.PlayClipAtPoint(Audio2[Random.Range(0, Audio2.Count)],transform.position,0.5f); } }
18.78125
99
0.638935
[ "MIT" ]
popote1/LaJamDuLundi1
Assets/scripte/SoundPlayer.cs
601
C#
using AmbientSounds.Constants; using AmbientSounds.Models; using Microsoft.Toolkit.Diagnostics; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AmbientSounds.Services { /// <summary> /// Class for deciphering url and performing /// its actions. /// </summary> public class LinkProcessor : ILinkProcessor { private readonly ISoundMixService _soundMixService; private readonly IDialogService _dialogService; private readonly ITelemetry _telemetry; public LinkProcessor( ITelemetry telemetry, ISoundMixService soundMixService, IDialogService dialogService) { Guard.IsNotNull(soundMixService, nameof(soundMixService)); Guard.IsNotNull(dialogService, nameof(dialogService)); Guard.IsNotNull(telemetry, nameof(telemetry)); _telemetry = telemetry; _soundMixService = soundMixService; _dialogService = dialogService; } /// <inheritdoc/> public async void Process(Uri uri) { if (uri?.Query is null) { return; } var queryString = HttpUtility.ParseQueryString(uri.Query); var sounds = queryString["sounds"] ?? ""; if (string.IsNullOrWhiteSpace(sounds)) { return; } string[] list = sounds.Split(','); for (int x = 0; x < list.Length; x++) { list[x] = GuidEncoder.Decode(list[x]).ToString(); } Sound tempSoundMix = new() { SoundIds = list, IsMix = true }; var allLoaded = await _soundMixService.LoadMixAsync(tempSoundMix); bool manuallyPlayed = false; int tracksplayed = list.Length; if (!allLoaded) { // show the share result to the user and let them download missing sounds. IList<string> soundIdsToPlay = await _dialogService.OpenShareResultsAsync(list); if (soundIdsToPlay is not null && soundIdsToPlay.Count > 0) { manuallyPlayed = true; tempSoundMix.SoundIds = soundIdsToPlay.ToArray(); await _soundMixService.LoadMixAsync(tempSoundMix); } tracksplayed = soundIdsToPlay is not null ? soundIdsToPlay.Count : 0; } _telemetry.TrackEvent(TelemetryConstants.ShareReceived, new Dictionary<string, string>() { { "auto played", allLoaded.ToString() }, { "manually played", manuallyPlayed.ToString() }, { "tracks played count", tracksplayed.ToString() } }); } } }
32.177778
100
0.560773
[ "MIT" ]
JUV-Studios/ambie
src/AmbientSounds/Services/LinkProcessor.cs
2,898
C#
using System.Text; using System.Diagnostics; using UnityEngine; namespace CommandTerminal { public static class BuiltinCommands { [RegisterCommand(Help = "Does nothing")] static void CommandNoop(CommandArg[] args) { } [RegisterCommand(Help = "Clears the Command Console", MaxArgCount = 0)] static void CommandClear(CommandArg[] args) { Terminal.Buffer.Clear(); } [RegisterCommand(Help = "Lists all Commands or displays help documentation of a Command", MaxArgCount = 1)] static void CommandHelp(CommandArg[] args) { if (args.Length == 0) { foreach (var command in Terminal.Shell.Commands) { Terminal.Log("{0}: {1}", command.Key.PadRight(16), command.Value.help); } return; } string command_name = args[0].String.ToUpper(); if (!Terminal.Shell.Commands.ContainsKey(command_name)) { Terminal.Shell.IssueErrorMessage("Command {0} could not be found.", command_name); return; } string help = Terminal.Shell.Commands[command_name].help; if (help == null) { Terminal.Log("{0} does not provide any help documentation.", command_name); } else { Terminal.Log(help); } } [RegisterCommand(Help = "Times the execution of a Command", MinArgCount = 1)] static void CommandTime(CommandArg[] args) { var sw = new Stopwatch(); sw.Start(); Terminal.Shell.RunCommand(JoinArguments(args)); sw.Stop(); Terminal.Log("Time: {0}ms", (double)sw.ElapsedTicks / 10000); } [RegisterCommand(Help = "Outputs message")] static void CommandPrint(CommandArg[] args) { Terminal.Log(JoinArguments(args)); } #if DEBUG [RegisterCommand(Help = "Outputs the StackTrace of the previous message", MaxArgCount = 0)] static void CommandTrace(CommandArg[] args) { int log_count = Terminal.Buffer.Logs.Count; if (log_count - 2 < 0) { Terminal.Log("Nothing to trace."); return; } var log_item = Terminal.Buffer.Logs[log_count - 2]; if (log_item.stack_trace == "") { Terminal.Log("{0} (no trace)", log_item.message); } else { Terminal.Log(log_item.stack_trace); } } #endif [RegisterCommand(Help = "Quits running Application", MaxArgCount = 0)] static void CommandQuit(CommandArg[] args) { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying = false; #else Application.Quit(); #endif } static string JoinArguments(CommandArg[] args) { var sb = new StringBuilder(); int arg_length = args.Length; for (int i = 0; i < arg_length; i++) { sb.Append(args[i].String); if (i < arg_length - 1) { sb.Append(" "); } } return sb.ToString(); } } }
31.621359
115
0.538839
[ "Apache-2.0" ]
MafiaHub/MafiaUnity
Assets/Third Party Assets/command_terminal-master/CommandTerminal/BuiltinCommands.cs
3,257
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.AzureNative.Compute.V20150615.Outputs { [OutputType] public sealed class WinRMConfigurationResponse { /// <summary> /// The list of Windows Remote Management listeners /// </summary> public readonly ImmutableArray<Outputs.WinRMListenerResponse> Listeners; [OutputConstructor] private WinRMConfigurationResponse(ImmutableArray<Outputs.WinRMListenerResponse> listeners) { Listeners = listeners; } } }
28.892857
99
0.699629
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Compute/V20150615/Outputs/WinRMConfigurationResponse.cs
809
C#
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { #region Properties /// <summary> /// Référence au GameManager /// </summary> private static GameManager _instance; /// <summary> /// Permet d'accès à l'instance en cours du GameManager /// </summary> public static GameManager Instance { get { return _instance; } } /// <summary> /// Contient les données de jeu /// </summary> private PlayerData _playerData; public PlayerData PlayerData { get { return _playerData; } } private AudioManager _audioManager; public AudioManager AudioManager { get { return _audioManager; } } #endregion #region Methods private void Awake() { if (_instance != null) Destroy(this.gameObject); else { _instance = this; DontDestroyOnLoad(this.gameObject); // Initialisation des données de jeu LoadPlayerData(); _audioManager = this.GetComponent<AudioManager>(); } } private void Start() { SaveData(); SceneManager.activeSceneChanged += ChangementScene; ChangementScene(new Scene(), SceneManager.GetActiveScene()); //List<string> cl = new List<string>(); //cl.Add("test_1"); //cl.Add("test_2"); //cl.Add("test_3"); //cl.Add("test_4"); //PlayerData test = new PlayerData( // 15, 42, 2022, ChestList: cl // ); //string jdata = PlayerDataJson.WriteJson(test); //Debug.Log(jdata); //PlayerData read = PlayerDataJson.ReadJson(jdata); //Debug.Log(read.Vie); } public void SaveData() { StartCoroutine(SaveData(this.PlayerData)); } public IEnumerator SaveData(PlayerData data) { using (StreamWriter stream = new StreamWriter( Path.Combine(Application.persistentDataPath, "savedata_encrypt.json"), false, System.Text.Encoding.UTF8)) { //DataManipulator manipulator = new DataManipulator(); stream.Write(/*manipulator.Encrypt(*/PlayerDataJson.WriteJson(data)/*)*/); Debug.Log(Path.Combine(Application.persistentDataPath, "savedata_encrypt.json")); } yield return new WaitForEndOfFrame(); } private void LoadPlayerData() { string path = Path.Combine(Application.persistentDataPath, "savedata_encrypt.json"); if (File.Exists(path)) { using (StreamReader stream = new StreamReader(path, System.Text.Encoding.UTF8)) { /*DataManipulator manipulator = new DataManipulator();*/ this._playerData = PlayerDataJson.ReadJson(/*manipulator.Decrypt(*/stream.ReadToEnd())/*)*/; } //DataManipulator manipulator = new DataManipulator(); //this._playerData = manipulator.Decrypt(path); } else { this._playerData = new PlayerData(4, 2); SaveData(); } } private void Update() { Debug.Log($"Score : {this._playerData.Score}"); Debug.Log($"Vie : {this._playerData.Vie}, Énergie : {this._playerData.Energie}"); string msg = string.Empty; foreach (string chest in PlayerData.ListeCoffreOuvert) { msg += chest + ";"; } Debug.Log($"ChestList : {msg}"); Debug.Log($"Volume général : {_playerData.VolumeGeneral}, Volume musique : {_playerData.VolumeMusique}, Volume effets : {_playerData.VolumeEffet}"); } public void RechargerNiveau() { this.PlayerData.UIPerteEnergie = null; this.PlayerData.UIPerteVie = null; SceneManager.LoadScene(SceneManager.GetActiveScene().name, LoadSceneMode.Single); } private void OnApplicationQuit() { SaveData(); } public void ChangerScene(string nomScene) { _audioManager.StopAudio(0.3f); GameObject.Find("Fondu").SetActive(true); SceneManager.LoadScene(nomScene); } public GameObject fondu; public void ChangementScene(Scene current, Scene next) { fondu = GameObject.Find("Fondu"); Debug.Log(fondu); fondu.SetActive(false); } #endregion }
29.945946
156
0.602437
[ "MIT" ]
f1dhounk/Capitain-CVM-1
Assets/Scripts/GameManager.cs
4,443
C#
using FluentAssertions; using System; using Xunit; namespace Eris.Packets.Test.PacketReaderTests { public class ReadInt16Tests { private readonly byte[] _data = new byte[] { 1, 2, 3, 4 }; [Fact] public void Read_Int16_Should_Be_Of_Type_Short() { using (var reader = new PacketReader(_data)) { var result = reader.ReadInt16(); result.Should().BeOfType(typeof(short)); } } [Fact] public void Read_First_Int16() { using (var reader = new PacketReader(_data)) { var result = reader.ReadInt16(); result.Should().Be(0x0201); } } [Fact] public void Read_Second_Int16() { using (var reader = new PacketReader(_data)) { reader.ReadInt16(); var result = reader.ReadInt16(); result.Should().Be(0x0403); } } [Fact] public void Read_Int16_Exceeding_Data_Length() { using (var reader = new PacketReader(_data)) { reader.SkipBytes(4); Action action = () => reader.ReadInt16(); action.ShouldThrow<PacketReadException>(); } } } }
23.706897
66
0.488
[ "MIT" ]
wazowsk1/eris-packets
test/Eris.Packets.Test/PacketReaderTests/ReadInt16Tests.cs
1,377
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 lightsail-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Lightsail.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Lightsail.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteContainerImage operation /// </summary> public class DeleteContainerImageResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteContainerImageResponse response = new DeleteContainerImageResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidInputException")) { return InvalidInputExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return NotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceException")) { return ServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("UnauthenticatedException")) { return UnauthenticatedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonLightsailException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteContainerImageResponseUnmarshaller _instance = new DeleteContainerImageResponseUnmarshaller(); internal static DeleteContainerImageResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteContainerImageResponseUnmarshaller Instance { get { return _instance; } } } }
41
193
0.640297
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/Lightsail/Generated/Model/Internal/MarshallTransformations/DeleteContainerImageResponseUnmarshaller.cs
4,715
C#
using System; namespace MSFSTouchPortalPlugin.Attributes { internal class TouchPortalActionMappingAttribute : Attribute { public string ActionId; public string[] Values; public TouchPortalActionMappingAttribute(string actionId, string value) { ActionId = actionId; Values = new [] { value }; } public TouchPortalActionMappingAttribute(string actionId, string[] values = null) { ActionId = actionId; Values = values ?? new string [] { }; } } }
26.263158
87
0.689379
[ "MIT" ]
Touch-Portal-MSFS/MSFSTouchPortalPlugin
MSFSTouchPortalPlugin/Attributes/TouchPortalActionMappingAttribute.cs
501
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CStorySceneOutputBlock : CStorySceneGraphBlock { [Ordinal(1)] [RED("output")] public CPtr<CStorySceneOutput> Output { get; set;} public CStorySceneOutputBlock(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CStorySceneOutputBlock(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.2
134
0.742169
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CStorySceneOutputBlock.cs
830
C#