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
// ***************************************************************************** // BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE) // © Component Factory Pty Ltd, 2006 - 2016, All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 13 Swallows Close, // Mornington, Vic 3931, Australia and are supplied subject to license terms. // // Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.451) // Version 5.451.0.0 www.ComponentFactory.com // ***************************************************************************** using System.Drawing; using System.Windows.Forms; using ComponentFactory.Krypton.Navigator; namespace ComponentFactory.Krypton.Workspace { /// <summary> /// Target a transfer to the target workspace cell. /// </summary> public class DragTargetWorkspaceCellTransfer : DragTargetWorkspace { #region Instance Fields private KryptonWorkspaceCell _cell; private int _notDraggedPagesFromCell; #endregion #region Identity /// <summary> /// Initialize a new instance of the DragTargetWorkspaceCellTransfer class. /// </summary> /// <param name="screenRect">Rectangle for screen area.</param> /// <param name="hotRect">Rectangle for hot area.</param> /// <param name="drawRect">Rectangle for draw area.</param> /// <param name="workspace">Control instance for drop.</param> /// <param name="cell">Workspace cell as target for drop.</param> /// <param name="allowFlags">Only drop pages that have one of these flags defined.</param> public DragTargetWorkspaceCellTransfer(Rectangle screenRect, Rectangle hotRect, Rectangle drawRect, KryptonWorkspace workspace, KryptonWorkspaceCell cell, KryptonPageFlags allowFlags) : base(screenRect, hotRect, drawRect, DragTargetHint.Transfer, workspace, allowFlags) { _cell = cell; _notDraggedPagesFromCell = -1; } /// <summary> /// Release unmanaged and optionally managed resources. /// </summary> /// <param name="disposing">Called from Dispose method.</param> protected override void Dispose(bool disposing) { if (disposing) { _cell = null; } base.Dispose(disposing); } #endregion #region Public /// <summary> /// Is this target a match for the provided screen position. /// </summary> /// <param name="screenPt">Position in screen coordinates.</param> /// <param name="dragEndData">Data to be dropped at destination.</param> /// <returns>True if a match; otherwise false.</returns> public override bool IsMatch(Point screenPt, PageDragEndData dragEndData) { // First time around... if (_notDraggedPagesFromCell == -1) { // Search for any pages that are not from this cell _notDraggedPagesFromCell = 0; foreach (KryptonPage page in dragEndData.Pages) { if (!_cell.Pages.Contains(page)) { _notDraggedPagesFromCell = 1; break; } } } // If 1 or more pages are not from this cell then allow transfer into the target if (_notDraggedPagesFromCell > 0) { return base.IsMatch(screenPt, dragEndData); } else { return false; } } /// <summary> /// Perform the drop action associated with the target. /// </summary> /// <param name="screenPt">Position in screen coordinates.</param> /// <param name="data">Data to pass to the target to process drop.</param> /// <returns>Drop was performed and the source can perform any removal of pages as required.</returns> public override bool PerformDrop(Point screenPt, PageDragEndData data) { // Transfer the dragged pages into the existing cell KryptonPage page = ProcessDragEndData(Workspace, _cell, data); // Make the last page transfer the newly selected page of the cell if (page != null) { // Does the cell allow the selection of tabs? if (_cell.AllowTabSelect) { _cell.SelectedPage = page; } if (!_cell.IsDisposed) { // Without this DoEvents() call the dropping of multiple pages in a complex arrangement causes an exception for // a complex reason that is hard to work out (i.e. I'm not entirely sure). Something to do with using select to // change activation is causing the source workspace control to dispose to earlier. Application.DoEvents(); _cell.Select(); } } return true; } #endregion } }
41.651852
157
0.546683
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.451
Source/Krypton Components/ComponentFactory.Krypton.Workspace/Dragging/DragTargetWorkspaceCellTransfer.cs
5,626
C#
using System.Linq; namespace Prism.Modularity { /// <summary> /// <see cref="IModuleCatalog"/> extensions. /// </summary> public static class IModuleCatalogExtensions { /// <summary> /// Adds the module. /// </summary> /// <returns>The module.</returns> /// <param name="catalog">Catalog</param> /// <param name="mode"><see cref="InitializationMode"/></param> /// <typeparam name="T">The <see cref="IModule"/> type parameter.</typeparam> public static IModuleCatalog AddModule<T>(this IModuleCatalog catalog, InitializationMode mode = InitializationMode.WhenAvailable) where T : IModule => catalog.AddModule<T>(typeof(T).Name, mode); /// <summary> /// Adds the module. /// </summary> /// <returns>The module.</returns> /// <param name="catalog">Catalog.</param> /// <param name="name">Name.</param> /// <param name="mode"><see cref="IModule"/>.</param> /// <typeparam name="T">The <see cref="IModule"/> type parameter.</typeparam> public static IModuleCatalog AddModule<T>(this IModuleCatalog catalog, string name, InitializationMode mode = InitializationMode.WhenAvailable) where T : IModule => catalog.AddModule(new ModuleInfo(typeof(T), name, mode)); /// <summary> /// Checks to see if the <see cref="IModule"/> exists in the <see cref="IModuleCatalog.Modules"/> /// </summary> /// <returns><c>true</c> if the Module exists.</returns> /// <param name="catalog">Catalog.</param> /// <typeparam name="T">The <see cref="IModule"/> to check for.</typeparam> public static bool Exists<T>(this IModuleCatalog catalog) where T : IModule => catalog.Modules.Any(mi => mi.ModuleType == typeof(T).AssemblyQualifiedName); /// <summary> /// Exists the specified catalog and name. /// </summary> /// <returns><c>true</c> if the Module exists.</returns> /// <param name="catalog">Catalog.</param> /// <param name="name">Name.</param> public static bool Exists(this IModuleCatalog catalog, string name) => catalog.Modules.Any(module => module.ModuleName == name); /// <summary> /// Checks to see if the <see cref="IModule"/> is already initialized. /// </summary> /// <returns><c>true</c>, if initialized, <c>false</c> otherwise.</returns> /// <param name="catalog">Catalog.</param> /// <typeparam name="T">The <see cref="IModule"/> to check.</typeparam> public static bool IsInitialized<T>(this IModuleCatalog catalog) where T : IModule => catalog.Modules.FirstOrDefault(mi => mi.ModuleType == typeof(T).AssemblyQualifiedName)?.State == ModuleState.Initialized; /// <summary> /// Checks to see if the <see cref="IModule"/> is already initialized. /// </summary> /// <returns><c>true</c>, if initialized, <c>false</c> otherwise.</returns> /// <param name="catalog">Catalog.</param> /// <param name="name">Name.</param> public static bool IsInitialized(this IModuleCatalog catalog, string name) => catalog.Modules.FirstOrDefault(module => module.ModuleName == name)?.State == ModuleState.Initialized; } }
47.319444
151
0.597593
[ "Apache-2.0" ]
TaviTruman/Prism
Source/Xamarin/Prism.Forms/Modularity/IModuleCatalogExtensions.cs
3,409
C#
using System; using System.Reflection; namespace Orleans.Runtime.Scheduler { internal class ClosureWorkItem : WorkItemBase { private readonly Action continuation; private readonly Func<string> nameGetter; public override string Name { get { return nameGetter==null ? "" : nameGetter(); } } public ClosureWorkItem(Action closure) { continuation = closure; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) { SchedulerStatisticsGroup.OnClosureWorkItemsCreated(); } #endif } public ClosureWorkItem(Action closure, Func<string> getName) { continuation = closure; nameGetter = getName; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) { SchedulerStatisticsGroup.OnClosureWorkItemsCreated(); } #endif } #region IWorkItem Members public override void Execute() { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) { SchedulerStatisticsGroup.OnClosureWorkItemsExecuted(); } #endif continuation(); } public override WorkItemType ItemType { get { return WorkItemType.Closure; } } #endregion public override string ToString() { var detailedName = string.Empty; if (nameGetter == null) // if NameGetter != null, base.ToString() will print its name. { var continuationMethodInfo = continuation.GetMethodInfo(); detailedName = string.Format(": {0}->{1}", (continuation.Target == null) ? "" : continuation.Target.ToString(), (continuationMethodInfo == null) ? "" : continuationMethodInfo.ToString()); } return string.Format("{0}{1}", base.ToString(), detailedName); } } }
29.782609
98
0.587348
[ "MIT" ]
Drawaes/orleans
src/OrleansRuntime/Scheduler/ClosureWorkItem.cs
2,055
C#
using System; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Core.Common.Models; using Orchard.Core.Common.Utilities; using Orchard.Core.Common.ViewModels; using Orchard.Localization; using Orchard.Localization.Services; namespace Orchard.Core.Common.DateEditor { public class DateEditorDriver : ContentPartDriver<CommonPart> { private readonly IDateLocalizationServices _dateLocalizationServices; public DateEditorDriver( IOrchardServices services, IDateLocalizationServices dateLocalizationServices) { _dateLocalizationServices = dateLocalizationServices; T = NullLocalizer.Instance; Services = services; } public Localizer T { get; set; } public IOrchardServices Services { get; set; } protected override string Prefix { get { return ""; } } protected override DriverResult Editor(CommonPart part, dynamic shapeHelper) { return Editor(part, null, shapeHelper); } protected override DriverResult Editor(CommonPart part, IUpdateModel updater, dynamic shapeHelper) { var settings = part.TypePartDefinition.Settings.GetModel<DateEditorSettings>(); if (!settings.ShowDateEditor) { return null; } return ContentShape( "Parts_Common_Date_Edit", () => { DateEditorViewModel model = shapeHelper.Parts_Common_Date_Edit(typeof(DateEditorViewModel)); model.Editor = new DateTimeEditor() { ShowDate = true, ShowTime = true }; if (part.CreatedUtc != null) { // show CreatedUtc only if is has been "touched", // i.e. it has been published once, or CreatedUtc has been set var itemHasNeverBeenPublished = part.PublishedUtc == null; var thisIsTheInitialVersionRecord = part.ContentItem.Version < 2; // Dates are assumed the same if the millisecond part is the only difference. // This is because SqlCe doesn't support high precision times (Datetime2) and the infoset does // implying some discrepancies between values read from different storage mechanism. var theDatesHaveNotBeenModified = DateUtils.DatesAreEquivalent(part.CreatedUtc, part.VersionCreatedUtc); var theEditorShouldBeBlank = itemHasNeverBeenPublished && thisIsTheInitialVersionRecord && theDatesHaveNotBeenModified; if (!theEditorShouldBeBlank) { model.Editor.Date = _dateLocalizationServices.ConvertToLocalizedDateString(part.CreatedUtc); model.Editor.Time = _dateLocalizationServices.ConvertToLocalizedTimeString(part.CreatedUtc); } } if (updater != null) { updater.TryUpdateModel(model, Prefix, null, null); if (!String.IsNullOrWhiteSpace(model.Editor.Date) && !String.IsNullOrWhiteSpace(model.Editor.Time)) { try { var utcDateTime = _dateLocalizationServices.ConvertFromLocalizedString(model.Editor.Date, model.Editor.Time); part.CreatedUtc = utcDateTime; } catch (FormatException) { updater.AddModelError(Prefix, T("'{0} {1}' could not be parsed as a valid date and time.", model.Editor.Date, model.Editor.Time)); } } else if (!String.IsNullOrWhiteSpace(model.Editor.Date) || !String.IsNullOrWhiteSpace(model.Editor.Time)) { updater.AddModelError(Prefix, T("Both the date and time need to be specified.")); } // Neither date/time part is specified => do nothing. } return model; }); } } }
46.0625
162
0.560606
[ "BSD-3-Clause" ]
1996dylanriley/Orchard
src/Orchard.Web/Core/Common/DateEditor/DateEditorDriver.cs
4,424
C#
using Akka.Actor; namespace Akka.ClusterPingPong.Actors { public class EchoActor : UntypedActor { protected override void OnReceive(object message) { Sender.Tell(message); } public static Props EchoProps {get;} = Props.Create(() => new EchoActor()); } }
22.285714
83
0.615385
[ "Apache-2.0" ]
Aaronontheweb/akka.net-integration-tests
src/ClusterPingPong/src/Akka.ClusterPingPong/Actors/EchoActor.cs
314
C#
// Copyright 2017 Secure Decisions, a division of Applied Visions, Inc. // 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. // // This material is based on research sponsored by the Department of Homeland // Security (DHS) Science and Technology Directorate, Cyber Security Division // (DHS S&T/CSD) via contract number HHSP233201600058C. using System.Collections.Generic; namespace CodePulse.Client.Instrumentation.Id { public class ClassIdentifier { private int _nextClassId; private readonly Dictionary<string, ClassInformation> _classes = new Dictionary<string, ClassInformation>(); public int Record(string className, string classSourceFile) { if (_classes.TryGetValue(className, out var classInformation)) { return classInformation.Id; } var classId = _nextClassId++; _classes[className] = new ClassInformation(classId, className, classSourceFile); return classId; } } }
43.723404
116
0.723601
[ "Apache-2.0" ]
alextudu/codepulse
dotnet-tracer/main/CodePulse.Client/Instrumentation/Id/ClassIdentifier.cs
2,057
C#
using ILRuntime.CLR.Method; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ILRuntime.Runtime.Stack { class IntegerReference { public int Value { get; set; } } unsafe struct StackFrame { public ILMethod Method; public StackObject* LocalVarPointer; public StackObject* BasePointer; public StackObject* ValueTypeBasePointer; public IntegerReference Address; public int ManagedStackBase; } }
22.565217
49
0.687861
[ "MIT" ]
RedAWM/GDNet
GameDesigner/ILRuntime/Runtime/Stack/StackFrame.cs
521
C#
/******************************************************************** License: https://github.com/chengderen/Smartflow/blob/master/LICENSE Home page: http://www.smartflow-sharp.com Github : https://github.com/chengderen/Smartflow-Sharp ******************************************************************** */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace Smartflow.Core { public class WorkflowConfiguration { public virtual long ID { get; set; } /// <summary> /// 配置名称 /// </summary> public virtual string Name { get; set; } /// <summary> /// 连接字符串 /// </summary> public virtual string ConnectionString { get; set; } /// <summary> /// 提供访问者 /// </summary> public virtual string ProviderName { get; set; } } }
20.862745
70
0.432331
[ "MIT" ]
Lu-Lucifer/Smartflow-Sharp
src/Smartflow.Core/WorkflowConfiguration.cs
1,094
C#
// WARNING // // This file has been generated automatically by Visual Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace MakeMeMove.iOS.ViewControllers { [Register ("MyExercisesController")] partial class MyExercisesController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIButton AddExerciseButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITableView ExerciseList { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UIBarButtonItem MenuButton { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UINavigationBar NavBar { get; set; } void ReleaseDesignerOutlets () { if (AddExerciseButton != null) { AddExerciseButton.Dispose (); AddExerciseButton = null; } if (ExerciseList != null) { ExerciseList.Dispose (); ExerciseList = null; } if (MenuButton != null) { MenuButton.Dispose (); MenuButton = null; } if (NavBar != null) { NavBar.Dispose (); NavBar = null; } } } }
27.303571
84
0.52845
[ "MIT" ]
HofmaDresu/MakeMeMove
MakeMeMove/MakeMeMove.iOS/ViewControllers/MyExercisesController.designer.cs
1,529
C#
using Jbe.NewsReader.Applications.Services; using System.Composition; using System.Threading.Tasks; using System.IO; namespace Test.NewsReader.Applications.Services { [Export(typeof(IWebStorageService)), Export, Shared] public class MockWebStorageService : IWebStorageService { public Task<string> DownloadFileAsync(string fileName, Stream destination, string token, string eTag) { return Task.FromResult("DummyETag"); } public Task<string> UploadFileAsync(Stream source, string fileName, string token) { return Task.FromResult("DummyETag"); } } }
30
110
0.672727
[ "MIT" ]
pskpatil/waf
src/NewsReader/NewsReader.Applications.Test/Services/MockWebStorageService.cs
662
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.Collections.Generic; using System.Linq; using Xunit; using Microsoft.ML.Probabilistic.Distributions; using Microsoft.ML.Probabilistic.Factors; using Microsoft.ML.Probabilistic.Math; namespace Microsoft.ML.Probabilistic.Tests { using System.Diagnostics; using System.Threading.Tasks; using Utilities; using Assert = Microsoft.ML.Probabilistic.Tests.AssertHelper; using GaussianArray = DistributionStructArray<Gaussian, double>; using GaussianArray2D = DistributionStructArray2D<Gaussian, double>; public class OperatorTests { [Fact] public void AverageTest() { foreach(var a in Doubles()) { foreach(var b in Doubles()) { if (double.IsNaN(a+b)) continue; double midpoint = MMath.Average(a, b); Assert.True(midpoint >= System.Math.Min(a,b)); Assert.True(midpoint <= System.Math.Max(a,b)); } } } [Fact] public void AverageLongTest() { foreach (var a in Longs()) { foreach (var b in Longs()) { double midpoint = MMath.Average(a, b); Assert.True(midpoint >= System.Math.Min(a, b)); Assert.True(midpoint <= System.Math.Max(a, b)); } } } /// <summary> /// Tests an edge case involving subnormal numbers. /// </summary> [Fact] public void LargestDoubleProductTest2() { MMath.LargestDoubleProduct(0.00115249439895759, 4.9187693503017E-319); MMath.LargestDoubleProduct(0.00115249439895759, -4.9187693503017E-319); } [Fact] public void LargestDoubleProductTest() { foreach (var denominator in DoublesGreaterThanZero()) { if (double.IsPositiveInfinity(denominator)) continue; foreach (var ratio in Doubles()) { AssertLargestDoubleProduct(denominator, ratio); } } } private void AssertLargestDoubleProduct(double denominator, double ratio) { double numerator = MMath.LargestDoubleProduct(denominator, ratio); Assert.True((double)(numerator / denominator) <= ratio); Assert.True(double.IsPositiveInfinity(numerator) || (double)(MMath.NextDouble(numerator) / denominator) > ratio); } [Fact] public void LargestDoubleSumTest() { MMath.LargestDoubleSum(1, -1); foreach (var b in Doubles()) { if (double.IsNegativeInfinity(b)) continue; if (double.IsPositiveInfinity(b)) continue; foreach (var sum in Doubles()) { AssertLargestDoubleSum(b, sum); } } } private void AssertLargestDoubleSum(double b, double sum) { double a = MMath.LargestDoubleSum(b, sum); Assert.True(a - b <= sum); Assert.True(double.IsPositiveInfinity(a) || MMath.NextDouble(a) - b > sum); } // Test inference on a model where precision is scaled. internal void GammaProductTest() { for (int i = 0; i <= 20; i++) { double minutesPlayed = System.Math.Pow(0.1, i); if (i == 20) minutesPlayed = 0; var EventCountMean_F = Gaussian.PointMass(0); var EventCountPrecision_F = GammaRatioOp.RatioAverageConditional(Gamma.PointMass(1), minutesPlayed); var realCount_F = GaussianOp_PointPrecision.SampleAverageConditional(EventCountMean_F, EventCountPrecision_F); var realCount_use_B = MaxGaussianOp.BAverageConditional(0.0, 0.0, realCount_F); var EventCountPrecision_B = GaussianOp_PointPrecision.PrecisionAverageConditional(realCount_use_B, EventCountMean_F, EventCountPrecision_F); var EventsPerMinutePrecision_B = GammaRatioOp.AAverageConditional(EventCountPrecision_B, minutesPlayed); Console.WriteLine($"realCount_use_B = {realCount_use_B}, EventCountPrecision_B = {EventCountPrecision_B}, EventsPerMinutePrecision_B = {EventsPerMinutePrecision_B}"); } } [Fact] public void VariablePointOp_RpropGammaTest() { using (TestUtils.TemporarilyUseMeanPointGamma) { var buffer = VariablePointOp_RpropGamma.Buffer0Init(); Gamma g = Gamma.FromShapeAndRate(0.6, 1); Gamma to_marginal = Gamma.PointMass(1); for (int i = 0; i < 1000; i++) { buffer = VariablePointOp_RpropGamma.Buffer0(g, g, to_marginal, buffer); //Console.WriteLine(buffer.nextPoint); to_marginal = Gamma.Uniform(); } } } [Fact] public void ArrayFromVectorOpTest() { bool verbose = false; PositiveDefiniteMatrix A = new PositiveDefiniteMatrix(new double[,] { { 4.008640513161180, 1.303104352135630, - 2.696380025254830, - 2.728465435435790 }, { 1.303104352135630, 4.024136989099960, - 2.681070246787840, - 2.713155656968810 }, { -2.696380025254830, - 2.681070246787840, 4.136120496920130, 1.403451295855420 }, { -2.728465435435790, - 2.713155656968810, 1.403451295855420, 4.063123100392480 } }); Vector arrayVariance = Vector.FromArray(1, 0, 3, 4); Vector arrayMean = Vector.FromArray(1, 2, 3, 4); VectorGaussianMoments vg = new VectorGaussianMoments(Vector.FromArray(6, 5, 4, 3), A); Gaussian[] array = Util.ArrayInit(arrayMean.Count, i => new Gaussian(arrayMean[i], arrayVariance[i])); var result = ArrayFromVectorOp.ArrayAverageConditional(array, vg, new Gaussian[array.Length]); Vector varianceExpected = Vector.FromArray(0.699231932932321, 0, 0.946948669226297, 0.926496676481940); Vector varianceActual = Vector.FromArray(Util.ArrayInit(result.Length, i => (result[i] * array[i]).GetVariance())); if (verbose) Console.WriteLine($"variance = {varianceActual} should be {varianceExpected}"); Assert.True(varianceExpected.MaxDiff(varianceActual) < 1e-4); Vector meanExpected = Vector.FromArray(2.640276200841019, 2.000000014880260, 6.527941507328482, 6.908179339051594); Vector meanActual = Vector.FromArray(Util.ArrayInit(result.Length, i => (result[i] * array[i]).GetMean())); if (verbose) Console.WriteLine($"mean = {meanActual} should be {meanExpected}"); Assert.True(meanExpected.MaxDiff(meanActual) < 1e-4); arrayVariance.SetTo(Vector.FromArray(1, double.PositiveInfinity, 3, 4)); array = Util.ArrayInit(arrayMean.Count, i => new Gaussian(arrayMean[i], arrayVariance[i])); result = ArrayFromVectorOp.ArrayAverageConditional(array, vg, new Gaussian[array.Length]); varianceExpected = Vector.FromArray(0.703202829692760, 2.371534574978036, 1.416576208767429, 1.566923316764467); varianceActual = Vector.FromArray(Util.ArrayInit(result.Length, i => (result[i] * array[i]).GetVariance())); if (verbose) Console.WriteLine($"variance = {varianceActual} should be {varianceExpected}"); Assert.True(varianceExpected.MaxDiff(varianceActual) < 1e-4); meanExpected = Vector.FromArray(2.495869677904531, 5.528904975989440, 4.957577684071078, 5.074347889058121); meanActual = Vector.FromArray(Util.ArrayInit(result.Length, i => (result[i] * array[i]).GetMean())); if (verbose) Console.WriteLine($"mean = {meanActual} should be {meanExpected}"); Assert.True(meanExpected.MaxDiff(meanActual) < 1e-4); bool testImproper = false; if (testImproper) { array = new Gaussian[] { new Gaussian(0.5069, 27.43), new Gaussian(0.649, 38.94), Gaussian.FromNatural(-0.5753, 0), new Gaussian(0.1064, 10.15) }; PositiveDefiniteMatrix B = new PositiveDefiniteMatrix(new double[,] { { 0.7158, -0.1356, -0.2979, -0.2993 }, { -0.1356, 0.7294, -0.2975, -0.2989 }, { -0.2979, -0.2975, 0.7625, -0.1337 }, { -0.2993, -0.2989, -0.1337, 0.7203 }, }); vg = new VectorGaussianMoments(Vector.FromArray(0.3042, 0.4795, -0.2114, -0.5748), B); result = ArrayFromVectorOp.ArrayAverageConditional(array, vg, new Gaussian[array.Length]); Gaussian[] resultExpected = new Gaussian[] { new Gaussian(0.4589, 0.707), new Gaussian(0.6338, 0.7204), new Gaussian(-0.2236, 0.7553), new Gaussian(-0.4982, 0.7148), }; if (verbose) Console.WriteLine(StringUtil.ArrayToString(result)); for (int i = 0; i < result.Length; i++) { Assert.True(resultExpected[i].MaxDiff(result[i]) < 1e-4); } } } internal void VectorFromArrayOp_SpeedTest() { int dim = 20; int n = 100000; VectorGaussian vector = new VectorGaussian(dim); Matrix random = new Matrix(dim, dim); for (int i = 0; i < dim; i++) { vector.MeanTimesPrecision[i] = Rand.Double(); for (int j = 0; j < dim; j++) { random[i, j] = Rand.Double(); } } vector.Precision.SetToOuter(random); Gaussian[] array = Util.ArrayInit(dim, i => Gaussian.FromMeanAndVariance(i, i)); Gaussian[] result = new Gaussian[dim]; for (int i = 0; i < n; i++) { VectorFromArrayOp.ArrayAverageConditional(vector, array, result); } } [Fact] public void VectorFromArrayOp_PointMassTest() { vectorFromArrayOp_PointMassTest(false); vectorFromArrayOp_PointMassTest(true); } private void vectorFromArrayOp_PointMassTest(bool partial) { int dim = 2; VectorGaussian to_vector = new VectorGaussian(dim); VectorGaussian vector = VectorGaussian.FromNatural(Vector.FromArray(2.0, 3.0), new PositiveDefiniteMatrix(new double[,] { { 5.0, 1.0 }, { 1.0, 6.0 } })); GaussianArray expected = null; double lastError = double.PositiveInfinity; for (int i = 0; i < 10; i++) { double variance = System.Math.Exp(-i); if (i == 0) variance = 0; Gaussian[] array = Util.ArrayInit(dim, j => new Gaussian(j, (j > 0 && partial) ? j : variance)); to_vector = VectorFromArrayOp.VectorAverageConditional(array, to_vector); var to_array = new GaussianArray(dim); to_array = VectorFromArrayOp.ArrayAverageConditional(vector, array, to_array); if (i == 0) expected = to_array; else { double error = expected.MaxDiff(to_array); Assert.True(error < lastError); lastError = error; } ////Console.WriteLine(to_array); } } [Fact] public void GammaRatioOpTest() { Gamma ratio = new Gamma(2, 3); double shape = 4; Gamma A = new Gamma(shape, 1); Gamma B = new Gamma(5, 6); Gamma q = GammaFromShapeAndRateOp_Laplace.Q(ratio, shape, B); Gamma bExpected = GammaFromShapeAndRateOp_Laplace.RateAverageConditional(ratio, shape, B, q); Gamma rExpected = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(ratio, shape, B, q); q = GammaRatioOp_Laplace.Q(ratio, A, B); Gamma bActual = GammaRatioOp_Laplace.BAverageConditional(ratio, A, B, q); Gamma rActual = GammaRatioOp_Laplace.RatioAverageConditional(ratio, A, B); Console.WriteLine("b = {0} should be {1}", bActual, bExpected); Console.WriteLine("ratio = {0} should be {1}", rActual, rExpected); Assert.True(bExpected.MaxDiff(bActual) < 1e-4); Assert.True(rExpected.MaxDiff(rActual) < 1e-4); } // Test that the operator behaves correctly for arguments with small variance [Fact] public void GammaFromShapeAndRateOpTest() { Gamma sample, rate, result; double prevDiff; double shape = 3; rate = Gamma.FromShapeAndRate(4, 5); sample = Gamma.PointMass(2); result = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); Console.WriteLine("{0}: {1}", sample, result); prevDiff = double.PositiveInfinity; for (int i = 10; i < 50; i++) { double v = System.Math.Pow(0.1, i); sample = Gamma.FromMeanAndVariance(2, v); Gamma result2 = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); double diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} (diff={2})", sample, result2, diff.ToString("g4")); Assert.True(diff <= prevDiff || diff < 1e-10); prevDiff = diff; } } [Fact] public void GammaFromShapeAndRateOpTest2() { Gamma sample, rate, result; double prevDiff; double shape = 3; sample = Gamma.FromShapeAndRate(4, 5); shape = 0.1; rate = Gamma.FromShapeAndRate(0.1, 0.1); result = GammaFromShapeAndRateOp_Slow.RateAverageConditional(sample, shape, rate); Console.WriteLine(result); shape = 3; rate = Gamma.PointMass(2); result = GammaFromShapeAndRateOp_Slow.RateAverageConditional(sample, shape, rate); Console.WriteLine("{0}: {1}", rate, result); prevDiff = double.PositiveInfinity; for (int i = 10; i < 50; i++) { double v = System.Math.Pow(0.1, i); rate = Gamma.FromMeanAndVariance(2, v); Gamma result2 = GammaFromShapeAndRateOp_Slow.RateAverageConditional(sample, shape, rate); double diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} (diff={2})", rate, result2, diff.ToString("g4")); Assert.True(diff <= prevDiff || diff < 1e-10); prevDiff = diff; } } [Fact] public void GammaFromShapeAndRateOpTest3() { Console.WriteLine(GammaFromShapeAndRateOp_Slow.RateAverageConditional(Gamma.FromShapeAndRate(2, 1), 1, Gamma.FromShapeAndRate(1.5, 0.5))); Gamma sample = Gamma.FromShapeAndRate(2, 0); Gamma rate = Gamma.FromShapeAndRate(4, 1); double shape = 1; Gamma to_sample2 = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); double evExpected = GammaFromShapeAndRateOp_Slow.LogEvidenceRatio(sample, shape, rate, to_sample2); Console.WriteLine("sample = {0} to_sample = {1} evidence = {2}", sample, to_sample2, evExpected); for (int i = 40; i < 41; i++) { sample.Rate = System.Math.Pow(0.1, i); Gamma to_sample = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); double evActual = GammaFromShapeAndRateOp_Slow.LogEvidenceRatio(sample, shape, rate, to_sample); Console.WriteLine("sample = {0} to_sample = {1} evidence = {2}", sample, to_sample, evActual); Assert.True(to_sample2.MaxDiff(to_sample2) < 1e-4); Assert.True(MMath.AbsDiff(evExpected, evActual) < 1e-4); } } [Fact] public void GammaFromShapeAndRateOpTest4() { Gamma sample = Gamma.FromShapeAndRate(2, 0); Gamma rate = Gamma.FromShapeAndRate(4, 1); double shape = 1; Gamma rateExpected = GammaFromShapeAndRateOp_Slow.RateAverageConditional(sample, shape, rate); Gamma q = GammaFromShapeAndRateOp_Laplace.Q(sample, shape, rate); Gamma rateActual = GammaFromShapeAndRateOp_Laplace.RateAverageConditional(sample, shape, rate, q); Assert.True(rateExpected.MaxDiff(rateActual) < 1e-4); Gamma to_sample2 = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(sample, shape, rate, q); double evExpected = GammaFromShapeAndRateOp_Laplace.LogEvidenceRatio(sample, shape, rate, to_sample2, q); Console.WriteLine("sample = {0} to_sample = {1} evidence = {2}", sample, to_sample2, evExpected); for (int i = 40; i < 41; i++) { sample.Rate = System.Math.Pow(0.1, i); q = GammaFromShapeAndRateOp_Laplace.Q(sample, shape, rate); Gamma to_sample = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(sample, shape, rate, q); double evActual = GammaFromShapeAndRateOp_Laplace.LogEvidenceRatio(sample, shape, rate, to_sample, q); Console.WriteLine("sample = {0} to_sample = {1} evidence = {2}", sample, to_sample, evActual); Assert.True(to_sample2.MaxDiff(to_sample2) < 1e-4); Assert.True(MMath.AbsDiff(evExpected, evActual) < 1e-4); } } [Fact] [Trait("Category", "OpenBug")] public void GammaFromShapeAndRateOpTest5() { Gamma sample; Gamma rate; double shape = 1; Gamma q, sampleExpected, sampleActual; sample = Gamma.FromShapeAndRate(101, 6.7234079315458819E-154); rate = Gamma.FromShapeAndRate(1, 1); q = GammaFromShapeAndRateOp_Laplace.Q(sample, shape, rate); Console.WriteLine(q); Assert.True(!double.IsNaN(q.Rate)); sampleExpected = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); sampleActual = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(sample, shape, rate, q); Console.WriteLine("sample = {0} should be {1}", sampleActual, sampleExpected); Assert.True(sampleExpected.MaxDiff(sampleActual) < 1e-4); sample = Gamma.FromShapeAndRate(1.4616957536444839, 6.2203585601953317E+36); rate = Gamma.FromShapeAndRate(2.5, 0.99222007168007165); sampleExpected = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); q = Gamma.FromShapeAndRate(3.5, 0.99222007168007154); sampleActual = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(sample, shape, rate, q); Console.WriteLine("sample = {0} should be {1}", sampleActual, sampleExpected); Assert.True(sampleExpected.MaxDiff(sampleActual) < 1e-4); sample = Gamma.FromShapeAndRate(1.9692446124520258, 1.0717828357423075E+77); rate = Gamma.FromShapeAndRate(101.0, 2.1709591889324445E-80); sampleExpected = GammaFromShapeAndRateOp_Slow.SampleAverageConditional(sample, shape, rate); q = GammaFromShapeAndRateOp_Laplace.Q(sample, shape, rate); sampleActual = GammaFromShapeAndRateOp_Laplace.SampleAverageConditional(sample, shape, rate, q); Console.WriteLine("sample = {0} should be {1}", sampleActual, sampleExpected); Assert.True(sampleExpected.MaxDiff(sampleActual) < 1e-4); Assert.Equal(0.0, GammaFromShapeAndRateOp_Laplace.LogEvidenceRatio(Gamma.Uniform(), 4.0, Gamma.PointMass(0.01), Gamma.FromShapeAndRate(4, 0.01), Gamma.PointMass(0.01))); } [Fact] public void MatrixTimesVectorOpTest() { Matrix[] ms = new Matrix[3]; ms[0] = new Matrix(new double[,] { { 0.036, -0.036, 0 }, { 0.036, 0, -0.036 } }); ms[1] = new Matrix(new double[,] { { -0.036, 0.036, 0 }, { 0, 0.036, -0.036 } }); ms[2] = new Matrix(new double[,] { { -0.036, 0, 0.036 }, { 0, -0.036, 0.036 } }); VectorGaussian product = new VectorGaussian(Vector.FromArray(new double[] { 1, 1 }), PositiveDefiniteMatrix.IdentityScaledBy(2, 0.01)); Matrix A = ms[0]; VectorGaussian result = MatrixVectorProductOp.BAverageConditional(product, A, new VectorGaussian(3)); Assert.False(result.Precision.IsPositiveDefinite()); Vector BMean = Vector.FromArray(1, 2, 3); PositiveDefiniteMatrix BVariance = new PositiveDefiniteMatrix(new double[,] { { 3,2,1 }, { 2,3,2 }, { 1,2,3 } }); GaussianArray2D to_A = new GaussianArray2D(A.Rows, A.Cols); MatrixVectorProductOp.AAverageConditional(product, GaussianArray2D.PointMass(A.ToArray()), BMean, BVariance, to_A); double[,] dExpected = new double[,] { { 542.014350893474, -34.0730521080406, -261.179402050882 }, { 449.735198014871, -31.4263853641523, -215.272881589687 }, }; for (int i = 0; i < to_A.GetLength(0); i++) { for (int j = 0; j < to_A.GetLength(1); j++) { Gaussian dist = to_A[i, j]; double dlogp, ddlogp; dist.GetDerivatives(A[i, j], out dlogp, out ddlogp); Assert.True(System.Math.Abs(dExpected[i, j] - dlogp) < 1e-8); } } } [Fact] public void SumOpTest() { Gaussian sum_F = new Gaussian(0, 1); Gaussian sum_B = Gaussian.FromMeanAndPrecision(0, 1e-310); GaussianArray array = new GaussianArray(2, i => new Gaussian(0, 1)); var result = FastSumOp.ArrayAverageConditional(sum_B, sum_F, array, new GaussianArray(array.Count)); Console.WriteLine(result); Assert.True(!double.IsNaN(result[0].MeanTimesPrecision)); sum_B = new Gaussian(0, 1); array[0] = Gaussian.FromMeanAndPrecision(0, 1e-310); result = FastSumOp.ArrayAverageConditional(sum_B, sum_F, array, new GaussianArray(array.Count)); Console.WriteLine(result); Assert.True(!double.IsNaN(result[0].MeanTimesPrecision)); Assert.True(result[0].MaxDiff(new Gaussian(0, 2)) < 1e-10); } [Fact] public void ExpOpTest2() { ExpOp.QuadratureNodeCount = 50; for (int i = 1; i < 10; i++) { double ve = System.Math.Pow(10, -i); Gamma exp = Gamma.FromMeanAndVariance(1, ve); Gaussian d = Gaussian.FromMeanAndVariance(0, 1); Gaussian to_d = ExpOp.DAverageConditional(exp, d, Gaussian.Uniform()); var importanceSampler = new ImportanceSampler(100000, d.Sample, x => System.Math.Exp(exp.GetLogProb(System.Math.Exp(x)))); double mean = importanceSampler.GetExpectation(x => x); double Ex2 = importanceSampler.GetExpectation(x => x * x); Gaussian to_d_is = new Gaussian(mean, Ex2 - mean * mean) / d; var exp2 = Gamma.FromShapeAndRate(exp.Shape - 1, exp.Rate); importanceSampler = new ImportanceSampler(100000, exp2.Sample, x => System.Math.Exp(d.GetLogProb(System.Math.Log(x)))); mean = importanceSampler.GetExpectation(x => System.Math.Log(x)); Ex2 = importanceSampler.GetExpectation(x => System.Math.Log(x) * System.Math.Log(x)); Gaussian to_d_is2 = new Gaussian(mean, Ex2 - mean * mean) / d; Console.WriteLine("{3}\t{0}\t{1}\t{2}", to_d.GetMean(), to_d_is.GetMean(), to_d_is2.GetMean(), ve); Gamma to_exp = ExpOp.ExpAverageConditional(exp, d, Gaussian.Uniform()); importanceSampler = new ImportanceSampler(100000, d.Sample, x => System.Math.Exp(exp.GetLogProb(System.Math.Exp(x)))); double Ey = importanceSampler.GetExpectation(x => System.Math.Exp(x)); double Elogy = importanceSampler.GetExpectation(x => x); var to_exp_is1 = Gamma.FromMeanAndMeanLog(Ey, Elogy) / exp; importanceSampler = new ImportanceSampler(100000, exp2.Sample, x => System.Math.Exp(d.GetLogProb(System.Math.Log(x)))); Ey = importanceSampler.GetExpectation(x => x); Elogy = importanceSampler.GetExpectation(x => System.Math.Log(x)); var to_exp_is2 = Gamma.FromMeanAndMeanLog(Ey, Elogy) / exp; //Console.WriteLine("to_d: Quad {0} IS1: {1} IS2: {2}", to_exp.GetMean(), to_exp_is1.GetMean(), to_exp_is2.GetMean()); } } [Fact] public void ExpOpTest() { ExpOp.QuadratureNodeCount = 50; double vd = 1e-4; vd = 1e-3; double ve = 2e-3; //ve = 1; for (int i = 0; i < 10; i++) { ve = System.Math.Pow(10, -i); Gamma exp = Gamma.FromMeanAndVariance(1, ve); Gamma to_exp = ExpOp.ExpAverageConditional(exp, new Gaussian(0, vd), Gaussian.Uniform()); Gaussian to_d = ExpOp.DAverageConditional(exp, new Gaussian(0, vd), Gaussian.Uniform()); Console.WriteLine("ve={0}: to_exp={1} to_d={2}", ve, to_exp, to_d); // TODO: add assertions here } Console.WriteLine(ExpOp.ExpAverageConditional(Gamma.PointMass(1), new Gaussian(0, vd), Gaussian.Uniform())); Console.WriteLine(ExpOp.DAverageConditional(Gamma.FromMeanAndVariance(1, ve), new Gaussian(0, vd), Gaussian.Uniform())); ExpOp.QuadratureShift = true; Console.WriteLine(ExpOp.DAverageConditional(Gamma.FromMeanAndVariance(1, ve), new Gaussian(0, vd), Gaussian.Uniform())); } [Fact] public void LogisticOpTest() { for (int trial = 0; trial < 2; trial++) { double xMean = (trial == 0) ? -1 : 1; Gaussian x = Gaussian.FromMeanAndVariance(xMean, 0); Gaussian result2 = BernoulliFromLogOddsOp.LogOddsAverageConditional(true, x); Console.WriteLine("{0}: {1}", x, result2); for (int i = 8; i < 30; i++) { double v = System.Math.Pow(0.1, i); x = Gaussian.FromMeanAndVariance(xMean, v); Gaussian result = BernoulliFromLogOddsOp.LogOddsAverageConditional(true, x); Console.WriteLine("{0}: {1} maxDiff={2}", x, result, result2.MaxDiff(result)); Assert.True(result2.MaxDiff(result) < 1e-6); } } for (int i = 0; i < 10; i++) { Gaussian falseMsg = LogisticOp.FalseMsg(new Beta(0.2, 1.8), new Gaussian(0, 97.0 * (i + 1)), new Gaussian()); Console.WriteLine(falseMsg); } Gaussian toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, new Gaussian(-4662, 1314)); Console.WriteLine(toLogOdds); toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, new Gaussian(2249, 2.5)); Console.WriteLine(toLogOdds); Gaussian logOdds = new Gaussian(100, 100); toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, logOdds); Console.WriteLine(toLogOdds * logOdds); // test m =approx 1.5*v for increasing v for (int i = 0; i < 10; i++) { double v = System.Math.Pow(2, i + 5); Gaussian g = new Gaussian(37 + 1.5 * v, v); toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, g); Console.WriteLine("{0}: {1}", g, toLogOdds); Gaussian actualPost = toLogOdds * g; Gaussian expectedPost = new Gaussian(0, 1); if (i == 0) { // for Gaussian(85,32) expectedPost = new Gaussian(53, 32); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } else if (i == 1) { // for Gaussian(133,64) expectedPost = new Gaussian(69, 64); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } else if (i == 4) { // for Gaussian(805,512) the posterior should be (293, 511.81) expectedPost = new Gaussian(293, 511.81); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } else if (i == 5) { // for Gaussian(1573,1024) expectedPost = new Gaussian(549, 1023.9); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } } // test m =approx v for increasing v for (int i = 0; i < 10; i++) { double v = System.Math.Pow(2, i + 5); Gaussian g = new Gaussian(v - 1, v); toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, g); Console.WriteLine("{0}: {1}", g, toLogOdds); Gaussian actualPost = toLogOdds * g; Gaussian expectedPost = new Gaussian(0, 1); if (i == 0) { // for Gaussian(31,32) expectedPost = new Gaussian(3.8979, 12.4725); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } else if (i == 6) { // for Gaussian(2047,2048) expectedPost = new Gaussian(35.7156, 736.2395); Assert.True(expectedPost.MaxDiff(actualPost) < 1e-3); } } for (int i = 0; i < 10; i++) { toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, new Gaussian(54.65 / 10 * (i + 1), 8.964)); Console.WriteLine(toLogOdds); } toLogOdds = BernoulliFromLogOddsOp.LogOddsAverageConditional(false, new Gaussian(9900, 10000) ^ 0.1); Console.WriteLine(toLogOdds); Gaussian falseMsg2 = LogisticOp.FalseMsg(new Beta(0.9, 0.1), Gaussian.FromNatural(-10.097766458353044, 0.000011644704327819733), Gaussian.FromNatural(-0.0010832099815010626, 0.000010092906656322242)); Console.WriteLine(falseMsg2); } [Fact] public void BernoulliFromLogOddsTest() { double tolerance = 1e-8; Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(0, 2)), System.Math.Log(0.5)) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(2, 0)), MMath.LogisticLn(2)) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(1, 1)), System.Math.Log(1 - 0.5 * System.Math.Exp(-0.5))) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(10, 10)), System.Math.Log(1 - 0.5 * System.Math.Exp(-5))) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(-1, 1)), System.Math.Log(0.303265329856008)) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(-5, 3)), System.Math.Log(0.023962216989475)) < tolerance); Assert.True(MMath.AbsDiff(BernoulliFromLogOddsOp.LogAverageFactor(true, new Gaussian(-5, 10)), System.Math.Log(0.084396512538678)) < tolerance); } [Fact] public void MaxTest() { Gaussian actual, expected; actual = MaxGaussianOp.MaxAverageConditional(Gaussian.Uniform(), Gaussian.PointMass(0), new Gaussian(-7.357e+09, 9.75)); expected = Gaussian.PointMass(0); Assert.True(expected.MaxDiff(actual) < 1e-4); Gaussian max; max = new Gaussian(4, 5); actual = MaxGaussianOp.MaxAverageConditional(max, new Gaussian(0, 1), new Gaussian(2, 3)); actual *= max; expected = new Gaussian(2.720481395499785, 1.781481142817509); //expected = MaxPosterior(max, new Gaussian(0, 1), new Gaussian(2, 3)); Assert.True(expected.MaxDiff(actual) < 1e-4); max = new Gaussian(); max.MeanTimesPrecision = 0.2; max.Precision = 1e-10; actual = MaxGaussianOp.MaxAverageConditional(max, new Gaussian(0, 1), new Gaussian(0, 1)); actual *= max; expected = new Gaussian(0.702106815765215, 0.697676918460236); Assert.True(expected.MaxDiff(actual) < 1e-4); } [Fact] public void MaxTest2() { double max = 0; double oldm = 0; double oldv = 0; for (int i = 0; i < 100; i++) { Gaussian a = new Gaussian(System.Math.Pow(10, i), 177); Gaussian to_a = MaxGaussianOp.AAverageConditional(max, a, max); Gaussian to_a2 = IsPositiveOp.XAverageConditional(false, a); double error = to_a.MaxDiff(to_a2) / to_a.Precision; //Console.WriteLine($"{a} {to_a} {to_a2} {error}"); Assert.True(error < 1e-8); double m, v; to_a.GetMeanAndVariance(out m, out v); if (i > 0) { Assert.True(v <= oldv); double olddiff = System.Math.Abs(max - oldm); double diff = System.Math.Abs(max - m); Assert.True(diff <= olddiff); } oldm = m; oldv = v; } // check that this doesn't throw MaxGaussianOp.AAverageConditional(0, Gaussian.FromNatural(537836855.52522063, 23.535214584839739), 0); } [Fact] public void Max_MaxPointMassTest() { Gaussian a = new Gaussian(1, 2); Gaussian b = new Gaussian(4, 5); max_MaxPointMassTest(a, b); max_MaxPointMassTest(a, Gaussian.PointMass(2)); max_MaxPointMassTest(a, Gaussian.PointMass(3)); max_MaxPointMassTest(Gaussian.PointMass(2), b); max_MaxPointMassTest(Gaussian.PointMass(3), b); max_MaxPointMassTest(Gaussian.PointMass(3), Gaussian.PointMass(2)); max_MaxPointMassTest(Gaussian.PointMass(2), Gaussian.PointMass(3)); } private void max_MaxPointMassTest(Gaussian a, Gaussian b) { double point = 3; Gaussian toPoint = MaxGaussianOp.MaxAverageConditional(Gaussian.PointMass(point), a, b); //Console.WriteLine($"{point} {toPoint} {toPoint.MeanTimesPrecision} {toPoint.Precision}"); double oldDiff = double.PositiveInfinity; for (int i = 5; i < 100; i++) { Gaussian max = Gaussian.FromMeanAndPrecision(point, System.Math.Pow(10, i)); Gaussian to_max = MaxGaussianOp.MaxAverageConditional(max, a, b); double diff = toPoint.MaxDiff(to_max); //Console.WriteLine($"{max} {to_max} {to_max.MeanTimesPrecision} {to_max.Precision} {diff}"); if (diff < 1e-14) diff = 0; Assert.True(diff <= oldDiff); oldDiff = diff; } } [Fact] public void Max_APointMassTest() { //MaxGaussianOp.ForceProper = false; Gaussian max = new Gaussian(4, 5); Gaussian b = new Gaussian(1, 2); max_APointMassTest(new Gaussian(4, 1e-0), Gaussian.PointMass(0)); max_APointMassTest(Gaussian.PointMass(11), Gaussian.PointMass(0)); max_APointMassTest(max, b); max_APointMassTest(max, Gaussian.PointMass(2)); max_APointMassTest(max, Gaussian.PointMass(3)); max_APointMassTest(max, Gaussian.PointMass(4)); max_APointMassTest(Gaussian.PointMass(3), b); max_APointMassTest(Gaussian.PointMass(4), b); max_APointMassTest(Gaussian.PointMass(3), Gaussian.PointMass(3)); } private void max_APointMassTest(Gaussian max, Gaussian b) { double point = 3; Gaussian toPoint = MaxGaussianOp.AAverageConditional(max, Gaussian.PointMass(point), b); //Console.WriteLine($"{point} {toPoint} {toPoint.MeanTimesPrecision:r} {toPoint.Precision:r}"); if (max.IsPointMass && b.IsPointMass) { Gaussian toUniform = MaxGaussianOp.AAverageConditional(max, Gaussian.Uniform(), b); if (max.Point > b.Point) { Assert.Equal(toUniform, max); } else { Assert.Equal(toUniform, Gaussian.Uniform()); } } double oldDiff = double.PositiveInfinity; for (int i = 3; i < 100; i++) { Gaussian a = Gaussian.FromMeanAndPrecision(point, System.Math.Pow(10, i)); Gaussian to_a = MaxGaussianOp.AAverageConditional(max, a, b); //Console.WriteLine($"{a} {to_a} {to_a.MeanTimesPrecision:r} {to_a.Precision:r}"); double diff = toPoint.MaxDiff(to_a); if (diff < 1e-14) diff = 0; Assert.True(diff <= oldDiff); oldDiff = diff; } } public static Gaussian MaxAPosterior(Gaussian max, Gaussian a, Gaussian b) { int n = 10000000; GaussianEstimator est = new GaussianEstimator(); for (int i = 0; i < n; i++) { double aSample = a.Sample(); double bSample = b.Sample(); double logProb = max.GetLogProb(System.Math.Max(aSample, bSample)); double weight = System.Math.Exp(logProb); est.Add(aSample, weight); } return est.GetDistribution(new Gaussian()); } public static Gaussian MaxPosterior(Gaussian max, Gaussian a, Gaussian b) { int n = 10000000; GaussianEstimator est = new GaussianEstimator(); for (int i = 0; i < n; i++) { double aSample = a.Sample(); double bSample = b.Sample(); double maxSample = System.Math.Max(aSample, bSample); double logProb = max.GetLogProb(maxSample); double weight = System.Math.Exp(logProb); est.Add(maxSample, weight); } return est.GetDistribution(new Gaussian()); } [Fact] public void OrTest() { Assert.Equal(1.0, BooleanOrOp.AAverageConditional(true, false).GetProbTrue()); Assert.Equal(1.0, BooleanOrOp.OrAverageConditional(Bernoulli.PointMass(true), false).GetProbTrue()); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(Bernoulli.PointMass(false), Bernoulli.PointMass(false)).LogOdds); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(false, Bernoulli.PointMass(false)).LogOdds); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(Bernoulli.PointMass(false), false).LogOdds); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(false, false).LogOdds); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(Bernoulli.PointMass(false), Bernoulli.PointMass(true)).GetProbTrue()); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(false, Bernoulli.PointMass(true)).GetProbTrue()); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(Bernoulli.PointMass(false), true).GetProbTrue()); Assert.Equal(0.0, BooleanAndOp.AAverageConditional(false, true).GetProbTrue()); try { BooleanAndOp.AAverageConditional(true, false); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { BooleanAndOp.AAverageConditional(Bernoulli.PointMass(true), false); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { BooleanAndOp.AAverageConditional(true, Bernoulli.PointMass(false)); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { BooleanAndOp.AAverageConditional(Bernoulli.PointMass(true), Bernoulli.PointMass(false)); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } } [Fact] public void BernoulliFromDiscreteTest() { double[] probTrue = { 0.4, 0.7 }; Discrete indexDist = new Discrete(0.8, 0.2); Bernoulli sampleDist = new Bernoulli(0.8 * 0.4 + 0.2 * 0.7); Assert.True(sampleDist.MaxDiff(BernoulliFromDiscreteOp.SampleAverageConditional(indexDist, probTrue)) < 1e-4); sampleDist.SetProbTrue(0.2); double p = (0.8 * 0.3 + 0.2 * 0.7) / (0.8 * 0.3 + 0.2 * 0.7 + 0.8 * 0.6 + 0.2 * 0.4); Vector probs = indexDist.GetWorkspace(); probs[0] = 1 - p; probs[1] = p; indexDist.SetProbs(probs); Assert.True(indexDist.MaxDiff(BernoulliFromDiscreteOp.IndexAverageConditional(sampleDist, probTrue, Discrete.Uniform(indexDist.Dimension))) < 1e-4); } [Fact] public void BernoulliFromBooleanTest() { double[] probTrue = { 0.4, 0.7 }; Bernoulli choiceDist = new Bernoulli(0.2); Bernoulli sampleDist = new Bernoulli(0.8 * 0.4 + 0.2 * 0.7); Assert.True(sampleDist.MaxDiff(BernoulliFromBooleanArray.SampleAverageConditional(choiceDist, probTrue)) < 1e-4); sampleDist.SetProbTrue(0.2); choiceDist.SetProbTrue((0.8 * 0.3 + 0.2 * 0.7) / (0.8 * 0.3 + 0.2 * 0.7 + 0.8 * 0.6 + 0.2 * 0.4)); Assert.True(choiceDist.MaxDiff(BernoulliFromBooleanArray.ChoiceAverageConditional(sampleDist, probTrue)) < 1e-4); } [Fact] [Trait("Category", "ModifiesGlobals")] public void BernoulliFromBetaOpTest() { Assert.True(System.Math.Abs(BernoulliFromBetaOp.LogEvidenceRatio(new Bernoulli(3e-5), Beta.PointMass(1)) - 0) < 1e-10); using (TestUtils.TemporarilyAllowBetaImproperSums) { Beta probTrueDist = new Beta(3, 2); Bernoulli sampleDist = new Bernoulli(); Assert.True(new Beta(1, 1).MaxDiff(BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist)) < 1e-4); sampleDist = Bernoulli.PointMass(true); Assert.True(new Beta(2, 1).MaxDiff(BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist)) < 1e-4); sampleDist = Bernoulli.PointMass(false); Assert.True(new Beta(1, 2).MaxDiff(BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist)) < 1e-4); sampleDist = new Bernoulli(0.9); Assert.True(new Beta(1.724, 0.9598).MaxDiff(BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist)) < 1e-3); try { BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, new Beta(1, -2)); Assert.True(false, "Did not throw exception"); } catch (ImproperMessageException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } } } [Fact] [Trait("Category", "ModifiesGlobals")] public void BernoulliFromBetaOpTest2() { Bernoulli sampleDist = new Bernoulli(2.0 / 3); using (TestUtils.TemporarilyAllowBetaImproperSums) { for (int i = 10; i <= 10; i++) { double s = System.Math.Exp(i); Beta probTrueDist = new Beta(s, 2 * s); Beta expected = BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist); if (i == 10) probTrueDist.Point = probTrueDist.GetMean(); Beta actual = BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist); Console.WriteLine("{0} {1}", probTrueDist, actual); Assert.True(expected.MaxDiff(actual) < 1e-4); } } for (int i = 10; i <= 10; i++) { Beta probTrueDist = new Beta(System.Math.Exp(i), 1); Beta expected = BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist); if (i == 10) probTrueDist.Point = 1; Beta actual = BernoulliFromBetaOp.ProbTrueAverageConditional(sampleDist, probTrueDist); Console.WriteLine("{0} {1}", probTrueDist, actual); Assert.True(expected.MaxDiff(actual) < 1e-4); } } [Trait("Category", "ModifiesGlobals")] internal void DiscreteFromDirichletOpTest2() { Discrete sample = new Discrete(1.0 / 3, 2.0 / 3); Vector sampleProbs = sample.GetProbs(); Dirichlet result = Dirichlet.Uniform(2); using (TestUtils.TemporarilyAllowDirichletImproperSums) { for (int i = 1; i <= 10; i++) { double s = System.Math.Exp(i); Dirichlet probsDist = new Dirichlet(s, 2 * s); if (i == 10) probsDist.Point = probsDist.GetMean(); Console.WriteLine("{0} {1}", probsDist, DiscreteFromDirichletOp.ProbsAverageConditional(sample, probsDist, result)); Dirichlet post = probsDist * result; Vector postMean = post.GetMean(); Vector priorMean = probsDist.GetMean(); Vector postMeanSquare = post.GetMeanSquare(); DenseVector delta2 = DenseVector.Zero(postMean.Count); for (int j = 0; j < delta2.Count; j++) { delta2[j] = postMeanSquare[j] - (probsDist.PseudoCount[j] + 1) / (probsDist.TotalCount + 1) * postMean[j]; } delta2.Scale(probsDist.TotalCount + 1); Vector delta1 = (postMean - priorMean) * probsDist.TotalCount; DenseVector delta1Approx = DenseVector.Zero(postMean.Count); //delta.SetToFunction(sampleProbs, priorMean, (sampleProb, prob) => ( double Z = sampleProbs.Inner(priorMean); delta1Approx[0] = priorMean[0] * priorMean[1] * (sampleProbs[0] - sampleProbs[1]) / Z; DenseVector delta2Approx = DenseVector.Zero(postMean.Count); delta2Approx[0] = priorMean[0] * priorMean[0] * priorMean[1] * (sampleProbs[0] - sampleProbs[1]) / Z; //Console.WriteLine("delta = {0} {1} {2} {3}", delta1, delta1Approx, delta2, delta2Approx); } } for (int i = 1; i <= 10; i++) { double s = System.Math.Exp(i); Dirichlet probsDist = new Dirichlet(s * 4, s * 5); if (i == 10) probsDist.Point = probsDist.GetMean(); Console.WriteLine("{0} {1}", probsDist, DiscreteFromDirichletOp.ProbsAverageConditional(sample, probsDist, result)); } } [Trait("Category", "ModifiesGlobals")] internal void DiscreteFromDirichletOpTest3() { Discrete sample = new Discrete(3.0 / 6, 2.0 / 6, 1.0 / 6); Vector sampleProbs = sample.GetProbs(); Dirichlet result = Dirichlet.Uniform(3); using (TestUtils.TemporarilyAllowDirichletImproperSums) { for (int i = 1; i <= 10; i++) { double s = System.Math.Exp(i); Dirichlet probsDist = new Dirichlet(s * 2, s * 1, s * 3); if (i == 10) probsDist.Point = probsDist.GetMean(); Console.WriteLine("{0} {1}", probsDist, DiscreteFromDirichletOp.ProbsAverageConditional(sample, probsDist, result)); Dirichlet post = probsDist * result; Vector postMean = post.GetMean(); Vector postMeanSquare = post.GetMeanSquare(); Vector priorMean = probsDist.GetMean(); Vector delta1 = (postMean - priorMean) * probsDist.TotalCount; DenseVector delta2 = DenseVector.Zero(postMean.Count); for (int j = 0; j < delta2.Count; j++) { delta2[j] = postMeanSquare[j] - (probsDist.PseudoCount[j] + 1) / (probsDist.TotalCount + 1) * postMean[j]; } delta2.Scale(probsDist.TotalCount + 1); double Z = sampleProbs.Inner(priorMean); DenseVector delta1Approx = DenseVector.Zero(postMean.Count); //delta.SetToFunction(sampleProbs, priorMean, (sampleProb, prob) => ( //delta1Approx[0] = priorMean[0] * priorMean[2] * (sampleProbs[0] - sampleProbs[2])/Z; delta1Approx[0] = probsDist.PseudoCount[1] * postMean[0] - probsDist.PseudoCount[0] * postMean[1] + priorMean[0] * priorMean[2] * (sampleProbs[0] - sampleProbs[2]) / Z; delta1Approx[0] = (probsDist.PseudoCount[1] + probsDist.PseudoCount[2]) / probsDist.PseudoCount[2] * priorMean[0] * priorMean[2] * (sampleProbs[0] - sampleProbs[2]) / Z - probsDist.PseudoCount[0] / probsDist.PseudoCount[2] * priorMean[1] * priorMean[2] * (sampleProbs[1] - sampleProbs[2]) / Z; delta1Approx[1] = probsDist.PseudoCount[0] * postMean[1] - probsDist.PseudoCount[1] * postMean[0] + priorMean[1] * priorMean[2] * (sampleProbs[1] - sampleProbs[2]) / Z; delta1Approx[2] = -priorMean[0] * priorMean[2] * (sampleProbs[0] - sampleProbs[2]) / Z - priorMean[1] * priorMean[2] * (sampleProbs[1] - sampleProbs[2]) / Z; DenseVector delta2Approx = DenseVector.Zero(postMean.Count); delta2Approx[0] = priorMean[0] * priorMean[0] * priorMean[1] * (sampleProbs[0] - sampleProbs[1]) / Z; //Console.WriteLine("delta = {0} {1} {2} {3}", delta1, delta1Approx, delta2, delta2Approx); } } for (int i = 1; i <= 10; i++) { double s = System.Math.Exp(i); Dirichlet probsDist = new Dirichlet(s * 4, s * 5, s * 6); if (i == 10) probsDist.Point = probsDist.GetMean(); Console.WriteLine("{0} {1}", probsDist, DiscreteFromDirichletOp.ProbsAverageConditional(sample, probsDist, result)); } } [Fact] public void DiscreteFromDirichletOpMomentMatchTest() { bool save = Dirichlet.AllowImproperSum; Dirichlet.AllowImproperSum = true; Dirichlet probsDist = new Dirichlet(1, 2, 3, 4); Discrete sampleDist = Discrete.Uniform(4); Assert.True(Dirichlet.Uniform(4).MaxDiff(DiscreteFromDirichletOp.ProbsAverageConditional(sampleDist, probsDist, Dirichlet.Uniform(4))) < 1e-4); sampleDist = Discrete.PointMass(1, 4); Assert.True(new Dirichlet(1, 2, 1, 1).MaxDiff(DiscreteFromDirichletOp.ProbsAverageConditional(sampleDist, probsDist, Dirichlet.Uniform(4))) < 1e-4); sampleDist = new Discrete(0, 1, 1, 0); Assert.True(new Dirichlet(0.9364, 1.247, 1.371, 0.7456).MaxDiff(DiscreteFromDirichletOp.ProbsAverageConditional(sampleDist, probsDist, Dirichlet.Uniform(4))) < 1e-3); Dirichlet.AllowImproperSum = false; } [Fact] public void DiscreteFromDirichletOpTest() { Dirichlet probs4 = new Dirichlet(1.0, 2, 3, 4); Discrete sample4 = Discrete.Uniform(4); sample4 = new Discrete(0.4, 0.6, 0, 0); Dirichlet result4 = (Dirichlet)DiscreteFromDirichletOp.ProbsAverageConditional(sample4, probs4, Dirichlet.Uniform(4)); Console.WriteLine(result4); Dirichlet probs3 = new Dirichlet(1.0, 2, 7); Discrete sample3 = Discrete.Uniform(3); sample3 = new Discrete(0.4, 0.6, 0); Dirichlet result3 = (Dirichlet)DiscreteFromDirichletOp.ProbsAverageConditional(sample3, probs3, Dirichlet.Uniform(3)); Console.WriteLine(result3); for (int i = 0; i < 3; i++) { Assert.True(MMath.AbsDiff(result4.PseudoCount[i], result3.PseudoCount[i], 1e-6) < 1e-10); } // test handling of small alphas Discrete sample = DiscreteFromDirichletOp.SampleAverageLogarithm(Dirichlet.Symmetric(2, 1e-8), Discrete.Uniform(2)); Console.WriteLine(sample); Assert.True(sample.IsUniform()); } // test the limit of an incoming message with small precision [Fact] public void GaussianIsPositiveTest2() { for (int trial = 0; trial < 2; trial++) { bool isPositive = (trial == 0); Gaussian x = Gaussian.FromNatural(isPositive ? -2 : 2, 0); Gaussian result = IsPositiveOp.XAverageConditional(isPositive, x); for (int i = 10; i < 20; i++) { x.Precision = System.Math.Pow(0.1, i); Gaussian result2 = IsPositiveOp.XAverageConditional(isPositive, x); //Console.WriteLine("{0}: {1} maxDiff={2}", x, result2, result.MaxDiff(result2)); Assert.True(result.MaxDiff(result2) < 1e-6); } } } [Fact] public void GaussianIsPositiveTest() { for (int trial = 0; trial < 2; trial++) { double xMean = (trial == 0) ? -1 : 1; Gaussian x = Gaussian.FromMeanAndVariance(xMean, 0); Gaussian result2 = IsPositiveOp.XAverageConditional(true, x); //Console.WriteLine("{0}: {1}", x, result2); if (trial == 0) Assert.True(result2.IsPointMass && result2.Point == 0.0); else Assert.True(result2.IsUniform()); for (int i = 8; i < 30; i++) { double v = System.Math.Pow(0.1, i); x = Gaussian.FromMeanAndVariance(xMean, v); Gaussian result = IsPositiveOp.XAverageConditional(true, x); //Console.WriteLine("{0}: {1} maxDiff={2}", x, result, result2.MaxDiff(result)); if (trial == 0) { Assert.True(MMath.AbsDiff(result2.GetMean(), result.GetMean()) < 1e-6); } else Assert.True(result2.MaxDiff(result) < 1e-6); } } for (int i = 0; i < 20; i++) { Assert.True(IsPositiveOp.XAverageConditional(true, Gaussian.FromNatural(-System.Math.Pow(10, i), 0.1)).IsProper()); } Assert.True(IsPositiveOp.XAverageConditional(true, Gaussian.FromNatural(-2.3287253734154412E+107, 0.090258824802119691)).IsProper()); Assert.True(IsPositiveOp.XAverageConditional(false, Gaussian.FromNatural(2.3287253734154412E+107, 0.090258824802119691)).IsProper()); //Assert.True(IsPositiveOp.XAverageConditional(Bernoulli.FromLogOdds(-4e-16), new Gaussian(490, 1.488e+06)).IsProper()); Assert.True(IsPositiveOp.XAverageConditional(true, new Gaussian(-2.03e+09, 5.348e+09)).IsProper()); Gaussian uniform = new Gaussian(); Assert.Equal(0.0, IsPositiveOp.IsPositiveAverageConditional(Gaussian.FromMeanAndVariance(0, 1)).LogOdds); Assert.True(MMath.AbsDiff(MMath.NormalCdfLogit(2.0 / System.Math.Sqrt(3)), IsPositiveOp.IsPositiveAverageConditional(Gaussian.FromMeanAndVariance(2, 3)).LogOdds, 1e-10) < 1e-10); Assert.Equal(0.0, IsPositiveOp.IsPositiveAverageConditional(uniform).LogOdds); Assert.Equal(0.0, IsPositiveOp.IsPositiveAverageConditional(Gaussian.PointMass(0.0)).GetProbTrue()); Bernoulli isPositiveDist = new Bernoulli(); Gaussian xDist = new Gaussian(0, 1); Gaussian xMsg = new Gaussian(); Assert.True(IsPositiveOp.XAverageConditional(isPositiveDist, xDist).Equals(uniform)); isPositiveDist = new Bernoulli(0); Gaussian xBelief = new Gaussian(); xMsg = IsPositiveOp.XAverageConditional(isPositiveDist, xDist); xBelief.SetToProduct(xMsg, xDist); Assert.True(xBelief.MaxDiff(Gaussian.FromMeanAndVariance(-0.7979, 0.3634)) < 1e-1); isPositiveDist = new Bernoulli(1); xMsg = IsPositiveOp.XAverageConditional(isPositiveDist, xDist); xBelief.SetToProduct(xMsg, xDist); Assert.True(xBelief.MaxDiff(Gaussian.FromMeanAndVariance(0.7979, 0.3634)) < 1e-1); isPositiveDist = new Bernoulli(0.6); xMsg = IsPositiveOp.XAverageConditional(isPositiveDist, xDist); xBelief.SetToProduct(xMsg, xDist); Assert.True(xBelief.MaxDiff(Gaussian.FromMeanAndVariance(0.15958, 0.97454)) < 1e-1); Assert.True(IsPositiveOp.XAverageConditional(isPositiveDist, uniform).Equals(uniform)); Assert.True(IsPositiveOp.XAverageConditional(true, new Gaussian(127, 11)).Equals(uniform)); Assert.True(IsPositiveOp.XAverageConditional(false, new Gaussian(-127, 11)).Equals(uniform)); Assert.True(IsPositiveOp.XAverageConditional(true, new Gaussian(-1e5, 10)).IsProper()); Assert.True(IsPositiveOp.XAverageConditional(false, new Gaussian(1e5, 10)).IsProper()); try { IsPositiveOp.XAverageConditional(true, Gaussian.FromNatural(1, 0)); Assert.True(false, "Did not throw exception"); } catch (ImproperMessageException) { Console.WriteLine("Correctly threw ImproperMessageException"); } try { IsPositiveOp.XAverageConditional(false, Gaussian.FromNatural(-1, 0)); Assert.True(false, "Did not throw exception"); } catch (ImproperMessageException) { Console.WriteLine("Correctly threw ImproperMessageException"); } } [Fact] public void ExpMinus1_IsIncreasing() { IsIncreasing(MMath.ExpMinus1); } [Fact] public void ExpMinus1RatioMinus1RatioMinusHalf_IsIncreasing() { IsIncreasingForAtLeastZero(MMath.ExpMinus1RatioMinus1RatioMinusHalf); } [Fact] public void Log1MinusExp_IsDecreasing() { IsIncreasingForAtLeastZero(x => MMath.Log1MinusExp(-x)); } [Fact] public void NormalCdfLn_IsIncreasing() { IsIncreasing(MMath.NormalCdfLn); } [Fact] public void NormalCdfRatio_IsIncreasing() { IsIncreasing(MMath.NormalCdfRatio); } [Fact] public void NormalCdfRatioDiff_Converges() { foreach (var x in DoublesAtLeastZero().Select(y => -y)) { if (double.IsInfinity(x)) continue; foreach (var delta in Doubles().Select(y => y + System.Math.Abs(x))) { if (System.Math.Abs(delta) <= System.Math.Abs(x) * 0.7 || System.Math.Abs(delta) <= 9.9) { double f = MMath.NormalCdfRatioDiff(x, delta); Assert.False(double.IsInfinity(f)); } } } } [Fact] public void NormalCdfMomentRatio_IsIncreasing() { for (int i = 1; i < 10; i++) { IsIncreasing(x => MMath.NormalCdfMomentRatio(i, x)); } } [Fact] public void LogExpMinus1_IsIncreasing() { IsIncreasingForAtLeastZero(MMath.LogExpMinus1); } [Fact] public void Log1Plus_IsIncreasing() { IsIncreasingForAtLeastZero(x => MMath.Log1Plus(x - 1)); IsIncreasingForAtLeastZero(MMath.Log1Plus); } [Fact] public void OneMinusSqrtOneMinus_IsIncreasing() { IsIncreasingForAtLeastZero(x => MMath.OneMinusSqrtOneMinus(1 / (1 + 1 / x))); } [Fact] public void GammaLower_IsIncreasingInX() { foreach (double a in DoublesGreaterThanZero()) { IsIncreasingForAtLeastZero(x => MMath.GammaLower(a, x)); } } [Fact] [Trait("Category", "OpenBug")] public void GammaUpper_IsDecreasingInX() { foreach (double a in DoublesGreaterThanZero()) { IsIncreasingForAtLeastZero(x => -MMath.GammaUpper(a, x)); } } [Fact] public void GammaLower_IsDecreasingInA() { foreach (double x in DoublesAtLeastZero()) { IsIncreasingForAtLeastZero(a => -MMath.GammaLower(a + double.Epsilon, x)); } } [Fact] [Trait("Category", "OpenBug")] public void GammaUpper_IsIncreasingInA() { foreach (double x in DoublesAtLeastZero()) { IsIncreasingForAtLeastZero(a => MMath.GammaUpper(a + double.Epsilon, x)); } } [Fact] public void GammaLn_IsIncreasingAbove2() { IsIncreasingForAtLeastZero(x => MMath.GammaLn(2 + x)); } [Fact] public void GammaLn_IsDecreasingBelow1() { IsIncreasingForAtLeastZero(x => MMath.GammaLn(1 / (1 + x))); } [Fact] public void Digamma_IsIncreasing() { IsIncreasingForAtLeastZero(x => MMath.Digamma(x)); } [Fact] public void Trigamma_IsDecreasing() { IsIncreasingForAtLeastZero(x => -MMath.Trigamma(x)); } [Fact] public void Tetragamma_IsIncreasing() { IsIncreasingForAtLeastZero(x => MMath.Tetragamma(x)); } [Fact] public void ReciprocalFactorialMinus1_IsDecreasingAbove1() { IsIncreasingForAtLeastZero(x => -MMath.ReciprocalFactorialMinus1(1 + x)); } /// <summary> /// Asserts that a function is increasing over the entire domain of reals. /// </summary> /// <param name="func"></param> /// <returns></returns> public bool IsIncreasing(Func<double, double> func) { foreach (var x in Doubles()) { double fx = func(x); foreach (var delta in DoublesGreaterThanZero()) { double x2 = x + delta; if (double.IsPositiveInfinity(delta)) x2 = delta; double fx2 = func(x2); // The cast here is important when running in 32-bit, Release mode. Assert.True((double)fx2 >= fx); } } return true; } /// <summary> /// Asserts that a function is increasing over the non-negative reals. /// </summary> /// <param name="func"></param> /// <returns></returns> public bool IsIncreasingForAtLeastZero(Func<double, double> func) { foreach (var x in DoublesAtLeastZero()) { double fx = func(x); foreach (var delta in DoublesGreaterThanZero()) { double x2 = x + delta; if (double.IsPositiveInfinity(delta)) x2 = delta; double fx2 = func(x2); // The cast here is important when running in 32-bit, Release mode. Assert.True((double)fx2 >= fx); } } return true; } // Used to debug IsBetweenOp internal static void GaussianIsBetween_Experiments() { double lowerBound = -10000.0; double upperBound = -9999.9999999999982; double mx = 0.5; //mx = 2 * 0.5 - mx; Gaussian X = new Gaussian(mx, 1 / 10.1); X = Gaussian.FromNatural(0.010000100000000001, 0.00010000100000000002); //X = Gaussian.FromNatural(0.010000000000000002, 0.00010000000000000002); X = Gaussian.FromNatural(10, 1); lowerBound = 9999.9999999999982; upperBound = 10000.0; X = Gaussian.FromNatural(1.0000000000000001E+73, 1E+69); bool largeDelta = false; if (largeDelta) { lowerBound = -990000; upperBound = 10000.0; X = Gaussian.FromNatural(0.00010000000000000002, 1.0000000000000014E-25); X = Gaussian.FromNatural(0.00010000000000000002, 1.0000000000000028E-49); // tests accuracy of drU X = Gaussian.FromNatural(0.00010000000000000002, 1.0000000000000006E-12); //upperBound = 990000; //lowerBound = -10000.0; //X = Gaussian.FromNatural(-0.00010000000000000002, 1.0000000000000014E-25); } bool zeroDelta = false; if (zeroDelta) { lowerBound = 9999.99999999999; upperBound = 10000.0; X = Gaussian.FromNatural(0.00010000000000000002, 1.0000000000000005E-08); // center and mx are not equal, have significant errors // upperBound*X.Precision has same error // instead of (mx>center), check (-zU-zL) > 0 or (zU+zL) < 0 } /* from mpmath import * mp.dps = 100; mp.pretty = True tau=mpf('-0.00010000000000000002'); prec=mpf('1.0000000000000005E-08'); L=mpf('-10000.0'); U = mpf('-9999.99999999999'); mx = tau/prec; center = (L+U)/2; mx (tau - prec*center) zU = (U - mx)*sqrt(prec) zL = (L - mx)*sqrt(prec) */ bool largezU = false; if (largezU) { lowerBound = 0; upperBound = 1e54; X = Gaussian.FromNatural(1.0000000000000013E-23, 1.0000000000000043E-77); mx = X.GetMean(); X.SetMeanAndPrecision(mx, 1e-80); } bool smallzU = false; if (smallzU) { lowerBound = 0; upperBound = 2e-69; X = Gaussian.FromNatural(10000000000000, 1.0000000000000056E-100); } bool smallDiffs = false; if (smallDiffs) { lowerBound = 0; upperBound = 2e-69; X = Gaussian.FromNatural(1.0000000000000052E-93, 1.0000000000000014E-24); } mx = X.GetMean(); bool showNeighborhood = true; if (showNeighborhood) { for (int i = 0; i < 100; i++) { //XAverageConditional_Debug(X, lowerBound, upperBound); //X = Gaussian.FromMeanAndPrecision(mx, X.Precision + 1.0000000000000011E-19); Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional(Bernoulli.PointMass(true), X, lowerBound, upperBound); Gaussian xPost = X * toX2; Console.WriteLine($"mx = {X.GetMean():r} mp = {xPost.GetMean():r} vp = {xPost.GetVariance():r} toX = {toX2}"); //X.Precision *= 100; //X.MeanTimesPrecision *= 0.999999; //X.SetMeanAndPrecision(mx, X.Precision * 2); X.SetMeanAndPrecision(mx, MMath.NextDouble(X.Precision)); } } else { var mva = new MeanVarianceAccumulator(); Rand.Restart(0); for (int i = 0; i < 10000000; i++) { double sample = X.Sample(); if (sample > lowerBound && sample < upperBound) mva.Add(sample); } Gaussian toX = DoubleIsBetweenOp.XAverageConditional(Bernoulli.PointMass(true), X, lowerBound, upperBound); Console.WriteLine($"expected mp = {mva.Mean}, vp = {mva.Variance}, {X * toX}"); XAverageConditional_Debug(X, lowerBound, upperBound); } } private static void XAverageConditional_Debug(Gaussian X, double lowerBound, double upperBound) { double mx = X.GetMean(); double sqrtPrec = System.Math.Sqrt(X.Precision); double zL = (lowerBound - mx) * sqrtPrec; double zU = (upperBound - mx) * sqrtPrec; double logZ = DoubleIsBetweenOp.LogProbBetween(X, lowerBound, upperBound); double logPhiL = X.GetLogProb(lowerBound); double ZR = System.Math.Exp(logZ - logPhiL); // Z/X.Prob(U)*sqrtPrec = NormalCdfRatio(zU) - NormalCdfRatio(zL)*X.Prob(L)/X.Prob(U) // Z/X.Prob(L)*sqrtPrec = NormalCdfRatio(zU)*X.Prob(U)/X.Prob(L) - NormalCdfRatio(zL) // = NormalCdfRatio(zU)*exp(delta) - NormalCdfRatio(zL) double diff = upperBound - lowerBound; double diffs = zU - zL; diffs = diff * sqrtPrec; double center = (upperBound + lowerBound) / 2; double delta = diff * (X.MeanTimesPrecision - X.Precision * center); // -(zL+zU)/2 = delta/diffs double deltaOverDiffs = (-zL - zU) / 2; // This is more accurate than checking mx<center if (deltaOverDiffs < 0) throw new Exception("deltaOverDiffs < 0"); delta = diffs * deltaOverDiffs; double rL = MMath.NormalCdfRatio(zL); double rU = MMath.NormalCdfRatio(zU); double r1L = MMath.NormalCdfMomentRatio(1, zL); double r1U = MMath.NormalCdfMomentRatio(1, zU); double r2U = MMath.NormalCdfMomentRatio(2, zU) * 2; double r2L = MMath.NormalCdfMomentRatio(2, zL) * 2; double r3L = MMath.NormalCdfMomentRatio(3, zL) * 6; double r3U = MMath.NormalCdfMomentRatio(3, zU) * 6; double r4L = MMath.NormalCdfMomentRatio(4, zL) * 24; double drU, drU2, drU3, drU4, dr1U, dr1U2, dr1U3, dr1U4, dr2U, dr2U2, dr2U3; if (diffs < 0.5 || true) { // drU is noisy - why? //drU = MMath.NormalCdfRatioDiff(zL, diffs); //drU2 = MMath.NormalCdfRatioDiff(zL, diffs, 2); //drU3 = MMath.NormalCdfRatioDiff(zL, diffs, 3); drU4 = MMath.NormalCdfRatioDiff(zL, diffs, 4); drU3 = diffs * (r3L / 6 + drU4); drU2 = diffs * (r2L / 2 + drU3); drU = diffs * (r1L + drU2); dr1U = MMath.NormalCdfMomentRatioDiff(1, zL, diffs); dr1U2 = MMath.NormalCdfMomentRatioDiff(1, zL, diffs, 2); dr1U3 = MMath.NormalCdfMomentRatioDiff(1, zL, diffs, 3); dr1U4 = MMath.NormalCdfMomentRatioDiff(1, zL, diffs, 4); dr2U = MMath.NormalCdfMomentRatioDiff(2, zL, diffs); dr2U2 = MMath.NormalCdfMomentRatioDiff(2, zL, diffs, 2); dr2U3 = MMath.NormalCdfMomentRatioDiff(2, zL, diffs, 3); } else { // drU = diffs*(r1L + drU2) drU = rU - rL; // drU2 = diffs*(r2L/2 + drU3) drU2 = drU / diffs - r1L; // drU3 = diffs*(r3L/6 + drU4) drU3 = drU2 / diffs - r2L / 2; drU4 = drU3 / diffs - r3L / 6; // dr1U = diffs*(r2L + dr1U2) dr1U = r1U - r1L; // dr1U2 = dr1U / diffs - r2L // dr1U2 = diffs*r3L/2 + diffs^2*r4L/6 + ... // dr1U2 = diffs*(r3L/2 + dr1U3) dr1U2 = dr1U / diffs - r2L; // dr1U3 = diffs*(r4L/6 + dr1U4) dr1U3 = dr1U2 / diffs - r3L / 2; dr1U4 = dr1U3 / diffs - r4L / 6; // dr2U = diffs*(r3L + dr2U2) dr2U = r2U - r2L; // dr2U2 = diffs*(r4L/2 + dr2U3) dr2U2 = dr2U / diffs - r3L; dr2U3 = dr2U2 / diffs - r4L / 2; } double expMinus1 = MMath.ExpMinus1(delta); double ZR2 = (rU * System.Math.Exp(delta) - rL) / sqrtPrec; double ZR2b = (drU + rU * expMinus1) / sqrtPrec; double ZR2c = (drU + rU * diffs * (-zL - zU) / 2 + rU * (expMinus1 - delta)) / sqrtPrec; List<double> ZRs = new List<double>() { ZR, ZR2, ZR2b, ZR2c }; double ZR4 = (0.5 * diffs * diffs * (-zL) + diffs) / sqrtPrec; // delta = 0.0004 diffs = 0.0002: ZR6 is exact, but not ZR5 // delta = 0.0002 diffs = 0.0002: ZR6 is exact, but not ZR5 // delta = 0.0001 diffs = 0.0002: ZR6 is exact, but not ZR5 // delta = 2.5E-05 diffs = 0.0001: ZR6 is exact, but not ZR5 // delta = 1E-05 diffs = 6.32455532033676E-05: ZR6 is exact, but not ZR5 // delta = 2.5E-06 diffs = 0.0001: ZR6 is exact, but not ZR5 // delta = 6.25E-06 diffs = 5E-05: ZR5 is exact // delta = 6.25E-07 diffs = 5E-05: ZR5 is exact // delta = 0.02 diffs = 2E-05 diffs*zL = -0.0200000002: neither ZR5 nor ZR6 are exact // seems we need diffs and diffs*zL (or delta) to be small // delta = 0.0002 diffs = 2E-05 diffs*zL = -0.0002000002: ZR6 is exact, but not ZR5 // delta = 2E-05 diffs = 2E-05 diffs*zL = -2.00002E-05: ZR5 is exact // delta = 2E-08 diffs = 2E-05 diffs*zL = -2.02E-08: ZR5 is exact // all we need is a good approx for (ZR/diff - 1) double ZR5 = (1.0 / 6 * diffs * diffs * diffs * (-1 + zL * zL) + 0.5 * diffs * diffs * (-zL) + diffs) / sqrtPrec; double ZR6 = (1.0 / 24 * diffs * diffs * diffs * diffs * (zL - zL * zL * zL + 2 * zL) + 1.0 / 6 * diffs * diffs * diffs * (-1 + zL * zL) + 0.5 * diffs * diffs * (-zL) + diffs) / sqrtPrec; //Console.WriteLine($"zL = {zL:r} delta = {delta:r} (-zL-zU)/2*diffs={(-zL - zU) / 2 * diffs:r} diffs = {diffs:r} diffs*zL = {diffs * zL}"); //Console.WriteLine($"Z/N = {ZR} {ZR2} {ZR2b} {ZR2c} asympt:{ZRasympt} {ZR4} {ZR5} {ZR6}"); // want to compute Z/X.Prob(L)/diffs + (exp(delta)-1)/delta double expMinus1RatioMinus1RatioMinusHalf = MMath.ExpMinus1RatioMinus1RatioMinusHalf(delta); // expMinus1RatioMinus1 = expMinus1Ratio - 1; double expMinus1RatioMinus1 = delta * (0.5 + expMinus1RatioMinus1RatioMinusHalf); double expMinus1Ratio = 1 + expMinus1RatioMinus1; //double expMinus1Ratio = expMinus1 / delta; double numer = ZR2b / diff - expMinus1Ratio; //WriteLast(new[] { diffs * (r1L + drU2), drU, rU, diffs, numer }); // when delta < 254 and zU < -1e61, we can assume drU =approx 0 // (drU + rU * expMinus1) / diffs - expMinus1Ratio // drU/diffs + rU*expMinus1Ratio*delta/diffs - expMinus1Ratio // = (r1L + drU2) + expMinus1Ratio*(rU*(-zU-zL)/2 - 1) // r1L = r1U - dr1U // zL = zU - diffs // drU = diffs*(r1U-dr1U+drU2) double numerSmallzU = drU2 - dr1U + r1U + expMinus1Ratio * (rU * (-zU + diffs / 2) - 1); // rU = (r1U-1)/zU double numerSmallzU2 = drU2 - dr1U + r1U + expMinus1Ratio * (rU * diffs / 2 - r1U); // when delta is small: // expMinus1Ratio = 1 + expMinus1RatioMinus1 double numerSmallzU3 = drU2 - dr1U + rU * diffs / 2 + expMinus1RatioMinus1 * (rU * diffs / 2 - r1U); // expMinus1RatioMinus1 = delta * (0.5 + expMinus1RatioMinus1RatioMinusHalf) // delta = diffs*(-zL-zU)/2 // zL = zU - diffs // r1U = (r2U - rU)/zU = r2U/zU - r1U/zU^2 + 1/zU^2 double numerSmallzU4 = drU2 - dr1U + diffs / 2 * (r2U - diffs / 2 * r1U) + expMinus1RatioMinus1 * rU * diffs / 2 - delta * expMinus1RatioMinus1RatioMinusHalf * r1U; List<double> numerSmallzUs = new List<double>() { numerSmallzU, numerSmallzU2, numerSmallzU3, numerSmallzU4 }; double numer1SmallzL = -(-rL * zL) + drU2 + rU * expMinus1RatioMinus1 * delta / diffs + rU * delta / diffs - expMinus1RatioMinus1; // rU*delta/diffs = rU*(-zL-zU)/2 = rU*(-zL)/2 - (r1U-1)/2 - rL*(-zL)/2 + rL*(-zL)/2 = drU*(-zL)/2 - (r1U-1)/2 - (r1L-1)/2 double numerLargezL = drU2 + rU * expMinus1RatioMinus1 * delta / diffs + drU * (-zL) / 2 - r1U / 2 + r1L / 2 - expMinus1RatioMinus1; // drU2 - dr1U/2 = diffs^2*r3L*(1/6 - 1/4) + ... = diffs^2*r3L*(-1/12) + ... double numerLargezL2 = (drU2 - dr1U / 2) + rU * expMinus1RatioMinus1 * delta / diffs + drU * (-zL) / 2 - expMinus1RatioMinus1; // now substitute rU*delta/diffs again double numerLargezL3 = (drU2 - dr1U / 2) + (drU * (-zL) / 2 - r1U / 2 - r1L / 2) * expMinus1RatioMinus1 + drU * (-zL) / 2; // drU*zL = diffs*(r1L*zL + drU2*zL) = diffs*(r2L-rL + drU2*zL) // expMinus1RatioMinus1 =approx delta/2 = 0.5*diffs*(-zL-zU)/2 // replace r1L = drU/diffs - drU2 // replace r1U = dr1U + r1L double numerLargezL4 = (drU2 - dr1U / 2) + (drU * (-zL) / 2 - dr1U / 2 + drU2) * expMinus1RatioMinus1 - drU / diffs * expMinus1RatioMinus1 + drU * (-zL) / 2; double numerLargezL5 = (drU2 - dr1U / 2) * expMinus1Ratio + drU * (-zL) / 2 * expMinus1RatioMinus1 - drU / diffs * (expMinus1RatioMinus1 - delta / 2) - drU / diffs * delta / 2 + drU * (-zL) / 2; // delta/diffs + zL = -diffs/2 // cancellation in (drU2 - dr1U / 2) // drU2 = diffs*(r2L/2 + drU3) // dr1U = diffs*(r2L + dr1U2) double numerLargezL6 = (drU2 - dr1U / 2) * expMinus1Ratio + drU * ( (-zL) / 2 * expMinus1RatioMinus1 - deltaOverDiffs * expMinus1RatioMinus1RatioMinusHalf + diffs / 4); // divide by diffs double numerLargezL7 = (drU3 - dr1U2 / 2) * expMinus1Ratio + (r1L + drU2) * ( (-zL) / 2 * expMinus1RatioMinus1 - deltaOverDiffs * expMinus1RatioMinus1RatioMinusHalf + diffs / 4); List<double> numerLargezLs = new List<double>() { numerLargezL, numerLargezL2, numerLargezL3, numerLargezL4, numerLargezL4, numerLargezL5, numerLargezL6, numerLargezL7 * diffs }; //WriteLast(numerLargezLs); double numer1e = drU2 + (drU * (-zL) / 2 - r1U / 2 - r1L / 2) * expMinus1RatioMinus1 + (-rL * (zU - zL) / 2 + drU * (-zL - zU) / 2); double numer2 = (0.5 * diffs * (-zL) + 1.0 / 6 * diffs * diffs * (-1 + zL * zL) + 1.0 / 24 * diffs * diffs * diffs * (zL - zL * zL * zL + 2 * zL)) - expMinus1RatioMinus1; double numer3 = (0.5 * diffs * (-zL) - delta * 0.5) + 1.0 / 6 * (-diffs * diffs + (diffs * diffs * zL * zL - delta * delta)) - 1.0 / 24 * delta * delta * delta - 1.0 / 120 * delta * delta * delta * delta; // diffs*(-zL) - delta = diffs*(-zL + (zL+zU)/2) = diffs*diffs/2 // (diffs*(-zL))^2 = (delta + diffs^2/2)^2 = delta^2 + delta*diffs^2 + diffs^4/4 double numer4 = 0.5 * diffs * ((-zL) - (-zL - zU) * 0.5) + 1.0 / 6 * (-diffs * diffs + (diffs * diffs * zL * zL - delta * delta)) - 1.0 / 24 * delta * delta * delta - 1.0 / 120 * delta * delta * delta * delta; // delta = 0.2 diffs = 0.14142135623731: bad // delta = 0.02 diffs = 0.014142135623731: bad // delta = 0.002 diffs = 0.0014142135623731: bad // delta = 0.0002 diffs = 0.00014142135623731: bad // delta = 2E-08 diffs = 1.4142135623731E-08: good double numer5 = delta * diffs * diffs / 6 + diffs * diffs * diffs * diffs / 24 - 1.0 / 24 * delta * delta * delta - 1.0 / 120 * delta * delta * delta * delta + diffs * diffs / 12; //Console.WriteLine($"numer = {numer} smallzL:{numer1SmallzL} largezL:{numerLargezL} {numerLargezL2} {numerLargezL3} {numerLargezL4:r} {numerLargezL5:r} {numerLargezL6:r} {numerLargezL7:r} {numerLargezL8:r} {numer1e} asympt:{numerAsympt} {numerAsympt2} {numer2} {numer3} {numer4} {numer5}"); double mp = mx - System.Math.Exp(logPhiL - logZ) * expMinus1 / X.Precision; double mp2 = center + (delta / diff - System.Math.Exp(logPhiL - logZ) * expMinus1) / X.Precision; double mp3 = center + (delta / diff * ZR2b - expMinus1) * System.Math.Exp(logPhiL - logZ) / X.Precision; double alphaXcLprecDiffs = diffs / (ZR2b * X.Precision); //Console.WriteLine($"alpha = {alphaXcLprec}"); double mpLargezL4 = center + numerLargezL4 * delta / (ZR2b * X.Precision); double mpLargezL5 = center + numerLargezL5 * delta / (ZR2b * X.Precision); double mpLargezL6 = center + numerLargezL6 * delta / diffs * alphaXcLprecDiffs; double mpLargezL7 = center + numerLargezL7 * delta * alphaXcLprecDiffs; // center = lowerBound + diff/2 = upperBound - diff/2 // try adding -diffs/delta/2*(rU * deltaOverDiffs * expMinus1Ratio + r1L + drU2) to numer // -rU/2*expMinus1Ratio - (r1L+drU2)/2/deltaOverDiffs // when the first term dominates (large delta), this is -rU/2*expMinus1Ratio // -rU / 2 * expMinus1Ratio + r1L * (-zL) / 2 * expMinus1RatioMinus1 // r1L = (r2L - rL)/zL // should not be used for delta<1e-2 // same as above for delta=10 double numerLargezL8 = (drU3 - dr1U2 / 2 - drU / 2 - r2L / 2 + drU2 * (-zL) / 2) * expMinus1Ratio + (r1L + drU2) * (zL / 2 - deltaOverDiffs * expMinus1RatioMinus1RatioMinusHalf - 0.5 / deltaOverDiffs + diffs / 4); double mpLargezL8 = upperBound + numerLargezL8 * delta * alphaXcLprecDiffs; List<double> mpLargezLs = new List<double>() { mpLargezL4, mpLargezL5, mpLargezL6, mpLargezL7, mpLargezL8 }; WriteLast(mpLargezLs); double alphaXcLprecSmallzU = 1 / (rU * expMinus1 * sqrtPrec); double mpSmallzU4 = center + numerSmallzU4 * delta * alphaXcLprecSmallzU; double mpSmallzU4b = center + ((drU2 - dr1U) / rU + diffs / 2 * (r2U / rU - diffs / 2 * r1U / rU) + expMinus1RatioMinus1 * diffs / 2 - delta * expMinus1RatioMinus1RatioMinusHalf * r1U / rU) * delta / (expMinus1 * sqrtPrec); // r1U/rU = (r2U/rU - 1)/zU =approx -1/zU //double mpSmallzU2b = center + (expMinus1RatioMinus1 * diffs / 2 - delta * expMinus1RatioMinus1RatioMinusHalf /(-zU)) * delta / (expMinus1 * sqrtPrec); List<double> mpSmallzUs = new List<double>() { mpSmallzU4, mpSmallzU4b }; //WriteLast(mpSmallzUs); double mp5 = center + numer5 * delta / diffs * alphaXcLprecDiffs; //double mpBrute = Util.ArrayInit(10000000, i => X.Sample()).Where(sample => (sample > lowerBound) && (sample < upperBound)).Average(); //Console.WriteLine($"mp = {mp} {mp2} {mp3} {mpLargezL4:r} {mpLargezL5:r} {mpLargezL6:r} {mpLargezL7:r} {mpLargezL8:r} asympt:{mpAsympt} {mpAsympt2} {mp5}"); double cL = -1 / expMinus1; // rU*diffs = rU*zU - rU*zL = r1U - 1 - rU*zL + rL*zL - rL*zL = r1U - 1 - drU*zL - (r1L-1) = dr1U - drU*zL // zL = -diffs/2 - delta/diffs // zU = diffs/2 - delta/diffs // rU = r2U - zU*r1U //if (zL != -diffs / 2 - delta / diffs) throw new Exception(); //if (zU != diffs / 2 - delta / diffs) throw new Exception(); double q = ((rU - drU * cL) * (rU - drU * cL) - r1U * (1 - cL) - r1L * cL + (1 - cL) * cL * diffs * drU) / cL / cL; double q2 = (-rU * expMinus1 - drU) * (-rU * expMinus1 - drU) - r1U * (expMinus1 + 1) * expMinus1 + r1L * expMinus1 - (expMinus1 + 1) * diffs * drU; double q3 = (rU * expMinus1 + drU) * (rU * expMinus1 + drU) + (r1L - r1U * (expMinus1 + 1)) * expMinus1 - (expMinus1 + 1) * diffs * drU; // r1L = r1U - dr1U double q4 = (rU * expMinus1) * (rU * expMinus1) + 2 * rU * expMinus1 * drU + drU * drU + (-dr1U - r1U * expMinus1) * expMinus1 - (expMinus1 + 1) * diffs * drU; double q5 = (rU * expMinus1) * (rU * expMinus1) + 2 * rU * expMinus1 * drU + drU * diffs * (r1L + drU2 - 1 - expMinus1) + (-dr1U - r1U * expMinus1) * expMinus1; double q6 = (rU * expMinus1) * (rU * expMinus1) + 2 * rU * expMinus1 * drU + drU * diffs * (zL * rL + drU2 - expMinus1) - dr1U * expMinus1 - r1U * expMinus1 * expMinus1; // replace drU and r1L // want to relate rU*drU with dr1U // rU*drU = approx r2U*diffs // rU = r2U - zU*r1U // drU = diffs*(r1L + drU2) // dr1U = diffs*(r2L + dr1U2) double q7 = rU * expMinus1 * rU * expMinus1 + rU * expMinus1 * drU + rU * diffs * (zL * rL + drU2) * expMinus1 + (dr2U - zU * r1U - dr1U2) * diffs * expMinus1 + drU * diffs * (zL * rL + drU2 - expMinus1) - r1U * expMinus1 * expMinus1; // replace zL double q8 = rU * expMinus1 * rU * expMinus1 + drU * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (-diffs / 2 * rL + drU2 - expMinus1)) + rU * diffs * (zL * rL + drU2) * expMinus1 + (dr2U - zU * r1U - dr1U2) * diffs * expMinus1 - r1U * expMinus1 * expMinus1; // replace zU double q9 = rU * expMinus1 * rU * expMinus1 + drU * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (-diffs / 2 * rL + drU2 - expMinus1)) + rU * diffs * (zL * rL + drU2) * expMinus1 + (dr2U - dr1U2) * diffs * expMinus1 - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1; // replace zL // rU * diffs * (zL * rL + drU2) * expMinus1 => rU*expMinus1 *diffs*((-diffs/2-delta/diffs)*rL + drU2) double q10 = rU * expMinus1 * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (-diffs / 2 * rL + drU2)) + drU * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (-diffs / 2 * rL + drU2 - expMinus1)) + (dr2U - dr1U2) * diffs * expMinus1 - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1; // drU = diffs*(r1L + drU2) // drU2 = diffs*(r2L/2 + drU3) // -diffs/2 *rL + drU2 = diffs/2*(r2L-rL) + diffs*drU3 = diffs/2*r1L*zL + diffs*drU3 = diffs/2*(1+zL*rL)*zL + diffs*drU3 double q11 = rU * expMinus1 * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (diffs / 2 * r1L * zL + diffs * drU3)) + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + drU * diffs * diffs / 2 * zL - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * delta + (dr2U - dr1U2) * diffs * expMinus1 - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1RatioMinus1 * delta; // combine terms 3 and 4 double q12 = rU * expMinus1 * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (diffs / 2 * r1L * zL + diffs * drU3)) + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + diffs * diffs / 2 * (diffs * (r1L + drU2) * zL - r1U * delta) + (dr2U - dr1U2) * diffs * delta + (dr2U - dr1U2) * diffs * expMinus1RatioMinus1 * delta - expMinus1RatioMinus1 * delta * r1U * delta - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1RatioMinus1 * delta; // combine terms 3 and 4 // replace zL // dr2U = diffs*(r3L + dr2U2) // dr1U2 = diffs*(r3L/2 + dr1U3) double q13 = rU * expMinus1 * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (diffs / 2 * r1L * zL + diffs * drU3)) + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + diffs * diffs / 2 * (-diffs * (r1L + drU2) * diffs / 2 + delta * (r3L - r1U - r1L - drU2 + 2 * dr2U2 - 2 * dr1U3)) + (dr2U - dr1U2) * diffs * expMinus1RatioMinus1 * delta - expMinus1RatioMinus1 * delta * r1U * delta - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1RatioMinus1 * delta; // 3rd term: // r3L = zL*r2L + 2*r1L double q14 = rU * expMinus1 * (rU * expMinus1RatioMinus1 * delta + drU * delta + diffs * (diffs / 2 * r1L * zL + diffs * drU3)) + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + diffs * diffs / 2 * (-diffs * (r1L + drU2) * diffs / 2 + delta * (zL * r2L - dr1U - drU2 + 2 * dr2U2 - 2 * dr1U3)) + (dr2U - dr1U2) * diffs * expMinus1RatioMinus1 * delta - expMinus1RatioMinus1 * delta * r1U * delta - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1RatioMinus1 * delta; // combine terms 1,3,5 // drU*delta = diffs*(r1L + drU2)*delta = diffs*diffs/2*(r1L+drU2)*(-zL-zU) // rU*delta/2*delta = rU*diffs*diffs/2*(-zL-zU)/2*(-zL-zU)/2 = diffs*diffs/2*(-rU*zL-rU*zU)/2*(-zL-zU)/2 = diffs*diffs/2*(rU*(diffs-zU) + 1-r1U)/2*(-zL-zU)/2 // = diffs*diffs/2*(rU*diffs + 2-2*r1U)/2*(-zL-zU)/2 // diffs*diffs/2*r1L*(-zU) = diffs*diffs/2*r1L*(-diffs/2+delta/diffs) = -diffs*diffs/2*r1L*diffs/2 + diffs/2*r1L*delta // drU = diffs*(r1L + drU2) // dr1U = diffs*(r2L + dr1U2) double q15 = rU * expMinus1 * (rU * expMinus1RatioMinus1RatioMinusHalf * delta * delta - (rU / 2 + (r1L + drU2) * zL) * diffs * diffs / 2 * delta - diffs * diffs / 2 * r1L * diffs / 2 + diffs * diffs / 2 * drU2 * (-zL - zU) + diffs * diffs * drU3) + rU * expMinus1RatioMinus1 * delta * diffs / 2 * delta //+ delta*delta*((rU-r2L) * diffs / 2 - delta/2*r1U - expMinus1RatioMinus1RatioMinusHalf * delta * r1U) + delta * delta * ((dr2U - diffs * r1U / 2) * diffs / 2 - expMinus1RatioMinus1RatioMinusHalf * delta * r1U) - diffs * diffs / 2 * delta * diffs / 2 * r2L + diffs * diffs / 2 * (delta * (-dr1U - drU2 + 2 * dr2U2 - 2 * dr1U3) - diffs * (r1L + drU2) * diffs / 2) + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + (dr2U - dr1U2) * diffs * expMinus1RatioMinus1 * delta - (diffs / 2 * diffs + expMinus1RatioMinus1 * delta) * r1U * expMinus1RatioMinus1 * delta; // combine terms 1,2,3 and 8 // zU = diffs/2 - delta/diffs // rU = r2U -r1U*zU = r2U - r1U*(diffs/2 - delta/diffs) double drU2r1U = DoubleIsBetweenOp.NormalCdfRatioSqrMinusDerivative(zU, rU, r1U, r3U); double q16 = delta * delta * (drU2r1U * expMinus1 * expMinus1RatioMinus1RatioMinusHalf + (r2U - r1U * diffs / 2) * expMinus1RatioMinus1 * diffs / 2) + rU * expMinus1 * (-(rU / 2 + (r1L + drU2) * zL) * diffs * diffs / 2 * delta - diffs * diffs / 2 * r1L * diffs / 2 + diffs * diffs / 2 * drU2 * (-zL - zU) + diffs * diffs * drU3) - delta * diffs / 2 * diffs * r1U * expMinus1RatioMinus1 + delta * delta * (dr2U - diffs * r1U / 2) * diffs / 2 - delta * diffs * diffs / 2 * diffs / 2 * r2L + diffs * diffs / 2 * (delta * (-dr1U - drU2 + 2 * dr2U2 - 2 * dr1U3) - diffs * (r1L + drU2) * diffs / 2) // cancellation inside + drU * (rU * expMinus1RatioMinus1 * delta + diffs * ((rL * zL + drU2) * delta + diffs / 2 * rL * zL * zL + diffs * drU3 - expMinus1RatioMinus1 * delta)) + delta * (dr2U - dr1U2) * diffs * expMinus1RatioMinus1; double q17 = delta * delta * (drU2r1U * expMinus1 * expMinus1RatioMinus1RatioMinusHalf + (r2U - r1U * diffs / 2) * expMinus1RatioMinus1 * diffs / 2) + rU * expMinus1 * (-(rU / 2 + (r1L + drU2) * zL) * diffs * diffs / 2 * delta - diffs * diffs / 2 * r1L * diffs / 2 + diffs * diffs / 2 * drU2 * (-zL - zU) + diffs * diffs * drU3) - delta * diffs / 2 * diffs * r1U * expMinus1RatioMinus1 + delta * delta * (dr2U - diffs * r1U / 2) * diffs / 2 - delta * diffs * diffs / 2 * diffs / 2 * r2L + delta * (dr2U - dr1U2) * diffs * expMinus1RatioMinus1 + diffs * diffs / 2 * (delta * (-dr1U - drU2 + 2 * dr2U2 - 2 * dr1U3) - diffs * (r1L + drU2) * diffs / 2) // cancellation inside // drU = diffs*(r1L + drU2) // drU2 = diffs*(r2L/2 + drU3) // r2L = zL*r1L + rL // zL = -diffs/2 - delta/diffs + drU * (rU * expMinus1RatioMinus1RatioMinusHalf * delta * delta - rL * delta * delta * delta / 2 + diffs * diffs * drU3 + r2L / 2 * diffs * diffs * delta + diffs * diffs * drU3 * delta - diffs * expMinus1RatioMinus1RatioMinusHalf * delta * delta + diffs * drU2 * delta * delta / 2 + rL * diffs * diffs / 2 * diffs / 2 * diffs / 2 - rL * diffs * diffs / 2 * delta * delta / 2); double q18 = delta * delta * (drU2r1U / diffs * expMinus1Ratio * deltaOverDiffs * expMinus1RatioMinus1RatioMinusHalf + (r2U / diffs - r1U / 2) * expMinus1RatioMinus1 / 2) // r3L = zL*r2L + 2*r1L + rU * expMinus1 * (-(rU / 2 + (r1L + drU2) * zL) / 2 * delta + diffs * (r3L / 6 + drU4 - r1L / 4) + drU2 / diffs * delta) + delta * expMinus1RatioMinus1 * (dr2U / diffs - dr1U2 / diffs - r1U / 2) + delta * delta / 2 * (dr2U / diffs - r1U / 2) // cancellation inside // dr1U = diffs*(r2L + dr1U2) // dr2U2 = diffs*(r4L/2 + dr2U3) // dr1U3 = diffs*(r4L/6 + dr1U4) // r4L = zL*r3L + 3*r2L + delta * diffs / 2 * (2 * zL * r3L / 3 + 2 * dr2U3 - 2 * dr1U4 - drU3 - dr1U2) + (r1L + drU2) * (delta * deltaOverDiffs * rU * expMinus1RatioMinus1RatioMinusHalf - delta * delta * expMinus1RatioMinus1RatioMinusHalf + delta * delta * drU2 / 2 - delta * delta * deltaOverDiffs / 2 * rL + delta * diffs * r2L / 2 + delta * diffs * drU3 // drU3 = diffs*(r3L/6 + drU4) + diffs * (drU3 - diffs / 4 + diffs * diffs * rL / 8) - delta * delta / 2 * diffs / 2 * rL); List<double> qs = new List<double>() { q, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18 }; //WriteLast(qs); // from q4: // (rU*rU - r1U) = drU2r1U = O(1/zU^4) double qSmallzU = drU2r1U * expMinus1 * expMinus1 + drU * drU + drU * (2 * rU * expMinus1 - (expMinus1 + 1) * diffs) - dr1U * expMinus1; // drU = diffs*(r1U-dr1U+drU2) = O(1/zU^3) // dr1U = diffs*(r2U - dr2U + dr1U2) double qSmallzU2 = drU2r1U * expMinus1 * expMinus1 - drU * diffs + ((r1U - dr1U + drU2) * 2 * rU - r2U + dr2U - dr1U2) * diffs * expMinus1 - drU * diffs * expMinus1 + drU * drU; // rU = (r1U-1)/zU // r2U = (r3U - 2r1U)/zU // expMinus1 = delta*(1 + expMinus1RatioMinus1) double qSmallzU3 = drU2r1U * expMinus1 * expMinus1 - drU * diffs + (2 * r1U * r1U - r3U) / zU * diffs * expMinus1 + ((-dr1U + drU2) * 2 * rU + dr2U - dr1U2) * diffs * expMinus1 - drU * diffs * expMinus1 + drU * drU; double qSmallzU4 = drU2r1U * delta * (1 + expMinus1RatioMinus1) * delta * (1 + expMinus1RatioMinus1) - diffs * (r1U - dr1U + drU2) * diffs + (2 * r1U * r1U - r3U) / zU * diffs * expMinus1 + ((-dr1U + drU2) * 2 * rU + dr2U - dr1U2) * diffs * expMinus1 - drU * diffs * expMinus1 + drU * drU; // every term is O(1/zU^4) double qSmallzU5 = delta * delta * (drU2r1U * expMinus1 * expMinus1RatioMinus1RatioMinusHalf + (r2U - r1U * diffs / 2) * expMinus1RatioMinus1 * diffs / 2) + delta * diffs * diffs / 2 * rU * rU / 2 * expMinus1 - delta * diffs * diffs / 2 * r1U * (expMinus1RatioMinus1 + delta / 2) + drU * (delta * delta * (rU - diffs) * expMinus1RatioMinus1RatioMinusHalf - delta * delta * delta / 2 * rL); List<double> qSmallzUs = new List<double>() { q4, qSmallzU, qSmallzU2, qSmallzU3, qSmallzU4, qSmallzU5 }; //WriteLast(qSmallzUs); double vp15 = q15 / diffs / diffs * alphaXcLprecDiffs * alphaXcLprecDiffs; double vp16 = q16 / diffs / diffs * alphaXcLprecDiffs * alphaXcLprecDiffs; double vp17 = q17 / diffs / diffs * alphaXcLprecDiffs * alphaXcLprecDiffs; double vp18 = q18 * alphaXcLprecDiffs * alphaXcLprecDiffs; double vpSmallzU = (r1U * expMinus1 * expMinus1RatioMinus1RatioMinusHalf + (2 * rU - diffs / 2) * expMinus1RatioMinus1 * diffs / 2 + diffs * diffs / 2 / 2 * expMinus1Ratio - diffs / 2 * rU * (expMinus1RatioMinus1 + delta / 2) + diffs * rU * ((1 - delta) * expMinus1RatioMinus1RatioMinusHalf - delta / 2)) / (expMinus1Ratio * expMinus1Ratio * X.Precision); List<double> vps = new List<double>() { vp15, vp16, vp17, vp18, vpSmallzU }; //WriteLast(vps); } private static void WriteLast(ICollection<double> doubles) { int maxCount = 5; foreach (var item in doubles.Skip(System.Math.Max(0, doubles.Count - maxCount))) { Console.Write(item.ToString("r").PadRight(24)); } Console.WriteLine(); } [Fact] public void GaussianIsBetweenTest() { Assert.True(DoubleIsBetweenOp.LogProbBetween(Gaussian.FromNatural(3172.868479466179, 1.5806459147637875E-06), -0.18914271233981969, 0.18914271233981969) < 0); Assert.True(DoubleIsBetweenOp.LogProbBetween(new Gaussian(-49.13, 1.081), new Gaussian(47, 1.25), new Gaussian(48, 1.25)) < -10); Assert.True(!double.IsNaN(DoubleIsBetweenOp.LogZ(Bernoulli.PointMass(true), new Gaussian(-49.13, 1.081), new Gaussian(47, 1.25), new Gaussian(48, 1.25)))); DoubleIsBetweenOp.LogProbBetween(Gaussian.FromNatural(-1.9421168441678062E-32, 3.0824440518369444E-35), Gaussian.FromNatural(-9.4928010569516363, 0.0084055128328109872), Gaussian.FromNatural(0.67290512665940949, 0.0042043926136280212)); double actual, expected; Gaussian x = new Gaussian(0, 1); double lp = DoubleIsBetweenOp.LogProbBetween(x, 100, 100.1); double lp2 = DoubleIsBetweenOp.LogProbBetween(x, -100.1, -100); Assert.True(MMath.AbsDiff(lp, lp2, 1e-8) < 1e-8); Console.WriteLine("{0} {1}", lp, lp2); Gaussian lowerBound = Gaussian.PointMass(0); Gaussian upperBound = Gaussian.PointMass(1); Assert.True(System.Math.Abs(DoubleIsBetweenOp.LogProbBetween(new Gaussian(1, 3e-5), 0.5, 1.1)) < 1e-10); Assert.True( System.Math.Abs(DoubleIsBetweenOp.LogProbBetween(new Gaussian(1, 1e-6), Gaussian.FromMeanAndVariance(0.5, 1e-10), Gaussian.FromMeanAndVariance(1.1, 1e-10))) < 1e-10); // test in matlab: x=randn(1e7,1); [mean(0<x & x<1) normcdf(1)-normcdf(0)] actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound, upperBound).GetProbTrue(); expected = MMath.NormalCdf(1) - MMath.NormalCdf(0); Assert.True(System.Math.Abs(expected - actual) < 1e-10); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound.Point, upperBound.Point).GetProbTrue(); expected = MMath.NormalCdf(1) - MMath.NormalCdf(0); Assert.True(System.Math.Abs(expected - actual) < 1e-10); try { Assert.Equal(1.0, DoubleIsBetweenOp.IsBetweenAverageConditional(Gaussian.PointMass(0.5), 1, 0).GetProbTrue()); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } try { Assert.Equal(1.0, DoubleIsBetweenOp.IsBetweenAverageConditional(new Gaussian(0, 1), 1, 0).GetProbTrue()); Assert.True(false, "Did not throw exception"); } catch (AllZeroException ex) { Console.WriteLine("Correctly failed with exception: " + ex); } Assert.Equal(1.0, DoubleIsBetweenOp.IsBetweenAverageConditional(Gaussian.PointMass(0), 0, 1).GetProbTrue()); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(Gaussian.PointMass(-1), Gaussian.PointMass(0), Gaussian.FromMeanAndVariance(1, 1)).GetProbTrue()); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(Gaussian.PointMass(1), 0, 1).GetProbTrue()); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(Gaussian.PointMass(1), Gaussian.FromMeanAndVariance(0, 1), Gaussian.PointMass(1)).GetProbTrue()); Assert.Equal(1.0, DoubleIsBetweenOp.IsBetweenAverageConditional(new Gaussian(0, 1), Double.NegativeInfinity, Double.PositiveInfinity).GetProbTrue()); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(new Gaussian(0, 1), 0.0, Double.PositiveInfinity).LogOdds); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(new Gaussian(0, 1), Double.NegativeInfinity, 0.0).LogOdds); Assert.Equal(0.0, DoubleIsBetweenOp.IsBetweenAverageConditional(new Gaussian(0, 1), Gaussian.PointMass(Double.NegativeInfinity), new Gaussian()).LogOdds); lowerBound = new Gaussian(); upperBound = Gaussian.PointMass(1); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound, upperBound).GetProbTrue(); expected = MMath.NormalCdf(1) * 0.5; Assert.True(System.Math.Abs(expected - actual) < 1e-10); lowerBound = Gaussian.PointMass(0); upperBound = new Gaussian(); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound, upperBound).GetProbTrue(); expected = MMath.NormalCdf(0) * 0.5; Assert.True(System.Math.Abs(expected - actual) < 1e-10); lowerBound = new Gaussian(1, 8); upperBound = new Gaussian(3, 3); // test in matlab: x=randn(1e7,1); mean(randnorm(1e7,1,[],8)'<x & x<randnorm(1e7,3,[],3)') // bvnl(-1/3,3/2,-1/2/3) = 0.33632 actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound, upperBound).GetProbTrue(); expected = MMath.NormalCdf(-1.0 / 3, 3.0 / 2, -1.0 / 2 / 3); Assert.True(System.Math.Abs(expected - actual) < 1e-10); // uniform x x.SetToUniform(); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, lowerBound, upperBound).GetProbTrue(); expected = 0; Assert.True(System.Math.Abs(expected - actual) < 1e-10); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, 0, 1).GetProbTrue(); expected = 0; Assert.True(System.Math.Abs(expected - actual) < 1e-10); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, new Gaussian(), upperBound).GetProbTrue(); expected = 0.25; Assert.True(System.Math.Abs(expected - actual) < 1e-10); actual = DoubleIsBetweenOp.IsBetweenAverageConditional(x, new Gaussian(), new Gaussian()).GetProbTrue(); expected = 0.25; Assert.True(System.Math.Abs(expected - actual) < 1e-10); } // Test that the operator behaves correctly for arguments with small variance [Fact] public void GaussianIsBetween_PointLowerBound() { Bernoulli isBetween = Bernoulli.PointMass(true); Gaussian x = new Gaussian(0, 1); Gaussian upperBound; for (int trial = 0; trial < 2; trial++) { if (trial == 0) upperBound = Gaussian.PointMass(1); else upperBound = new Gaussian(1, 1); Console.WriteLine("upperBound = {0}", upperBound); Gaussian lowerBound = Gaussian.PointMass(-1); Gaussian result2 = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Console.WriteLine("{0}: {1}", lowerBound, result2); for (int i = 8; i < 30; i++) { double v = System.Math.Pow(0.1, i); lowerBound = Gaussian.FromMeanAndVariance(-1, v); Gaussian result = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); double error = result.MaxDiff(result2); Console.WriteLine("{0}: {1} {2}", lowerBound, result, error); Assert.True(error < 1e-6); } } } // Test that the operator behaves correctly for arguments with small variance [Fact] public void GaussianIsBetween_PointUpperBound() { Bernoulli isBetween = Bernoulli.PointMass(true); Gaussian x = new Gaussian(0, 1); Gaussian lowerBound; for (int trial = 0; trial < 2; trial++) { if (trial == 1) lowerBound = Gaussian.PointMass(-1); else lowerBound = new Gaussian(-1, 1); Gaussian upperBound = Gaussian.PointMass(1); Gaussian result2 = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Console.WriteLine("{0}: {1}", upperBound, result2); for (int i = 8; i < 30; i++) { double v = System.Math.Pow(0.1, i); upperBound = Gaussian.FromMeanAndVariance(1, v); Gaussian result = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); double error = result.MaxDiff(result2); Console.WriteLine("{0}: {1} {2}", lowerBound, result, error); Assert.True(error < 1e-6); } } } public static double UlpDiff(double a, double b) { if (a == b) return 0; // avoid infinity-infinity double diff = System.Math.Abs(a - b); if (diff == 0) return diff; // avoid 0/0 return diff / System.Math.Max(MMath.Ulp(a), MMath.Ulp(b)); } public static double MaxUlpDiff(Gaussian a, Gaussian b) { return System.Math.Max(UlpDiff(a.MeanTimesPrecision, b.MeanTimesPrecision), UlpDiff(a.Precision, b.Precision)); } /// <summary> /// Generates a representative set of int64 numbers for testing purposes. /// </summary> /// <returns></returns> public static IEnumerable<long> Longs() { yield return long.MaxValue; yield return 0L; yield return long.MinValue; for (int i = 0; i < 64; i++) { double bigValue = System.Math.Pow(2, i); yield return -(long)bigValue; yield return (long)bigValue; } } /// <summary> /// Generates a representative set of double-precision numbers for testing purposes. /// </summary> /// <returns></returns> public static IEnumerable<double> Doubles() { yield return double.NegativeInfinity; yield return MMath.NextDouble(double.NegativeInfinity); yield return MMath.PreviousDouble(0); yield return 0.0; yield return MMath.NextDouble(0); yield return MMath.PreviousDouble(double.PositiveInfinity); yield return double.PositiveInfinity; for (int i = 0; i <= 100; i++) { double bigValue = System.Math.Pow(10, i); yield return -bigValue; yield return bigValue; if (i != 0) { double smallValue = System.Math.Pow(0.1, i); yield return -smallValue; yield return smallValue; } } } public static IEnumerable<double> DoublesGreaterThanZero() { return Doubles().Where(value => value > 0); } public static IEnumerable<double> DoublesAtLeastZero() { return Doubles().Where(value => value >= 0); } public static IEnumerable<Bernoulli> Bernoullis() { foreach (var logOdds in Doubles()) { yield return Bernoulli.FromLogOdds(logOdds); } } /// <summary> /// Generates a representative set of proper Gaussian distributions. /// </summary> /// <returns></returns> public static IEnumerable<Gaussian> Gaussians() { foreach (var tau in Doubles()) { foreach (var precision in DoublesGreaterThanZero()) { yield return Gaussian.FromNatural(tau, precision); } } } public static IEnumerable<double> UpperBounds(double lowerBound) { HashSet<double> set = new HashSet<double>(); foreach (var diff in DoublesGreaterThanZero()) { double upperBound = lowerBound + diff; if (double.IsPositiveInfinity(diff)) upperBound = diff; if (!set.Contains(upperBound)) { set.Add(upperBound); yield return upperBound; } } } [Fact] public void GaussianIsBetweenCRCC_IsSymmetricInXMean() { double meanMaxUlpError = 0; double meanMaxUlpErrorLowerBound = 0; double meanMaxUlpErrorUpperBound = 0; Bernoulli meanMaxUlpErrorIsBetween = new Bernoulli(); double precMaxUlpError = 0; double precMaxUlpErrorLowerBound = 0; double precMaxUlpErrorUpperBound = 0; Bernoulli precMaxUlpErrorIsBetween = new Bernoulli(); foreach (var isBetween in new[] { Bernoulli.PointMass(true), Bernoulli.PointMass(false), new Bernoulli(0.1) }) { foreach (var lowerBound in Doubles()) { if (lowerBound >= 0) continue; //Console.WriteLine($"isBetween = {isBetween}, lowerBound = {lowerBound:r}"); foreach (var upperBound in new[] { -lowerBound })// UpperBounds(lowerBound)) { //Console.WriteLine($"lowerBound = {lowerBound:r}, upperBound = {upperBound:r}"); double center = MMath.Average(lowerBound, upperBound); if (double.IsNegativeInfinity(lowerBound) && double.IsPositiveInfinity(upperBound)) center = 0; if (double.IsInfinity(center)) continue; foreach (var x in Gaussians()) { double mx = x.GetMean(); if (double.IsInfinity(mx)) continue; Gaussian toX = DoubleIsBetweenOp.XAverageConditional(isBetween, x, lowerBound, upperBound); //Gaussian x2 = Gaussian.FromMeanAndPrecision(2 * center - mx, x.Precision); Gaussian x2 = Gaussian.FromNatural(-x.MeanTimesPrecision, x.Precision); Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional(isBetween, x2, lowerBound, upperBound); double precUlpDiff = UlpDiff(toX2.Precision, toX.Precision); Assert.Equal(0, precUlpDiff); if (precUlpDiff > precMaxUlpError) { precMaxUlpError = precUlpDiff; precMaxUlpErrorLowerBound = lowerBound; precMaxUlpErrorUpperBound = upperBound; precMaxUlpErrorIsBetween = isBetween; } Gaussian xPost = toX.IsPointMass ? toX : toX * x; Gaussian xPost2 = toX2.IsPointMass ? toX2 : toX2 * x2; double mean = xPost.GetMean(); double mean2 = 2 * center - xPost2.GetMean(); double meanUlpDiff = UlpDiff(mean, mean2); Assert.Equal(0, meanUlpDiff); if (meanUlpDiff > meanMaxUlpError) { meanMaxUlpError = meanUlpDiff; meanMaxUlpErrorLowerBound = lowerBound; meanMaxUlpErrorUpperBound = upperBound; meanMaxUlpErrorIsBetween = isBetween; } } } } } Console.WriteLine($"meanMaxUlpError = {meanMaxUlpError}, lowerBound = {meanMaxUlpErrorLowerBound:r}, upperBound = {meanMaxUlpErrorUpperBound:r}, isBetween = {meanMaxUlpErrorIsBetween}"); Console.WriteLine($"precMaxUlpError = {precMaxUlpError}, lowerBound = {precMaxUlpErrorLowerBound:r}, upperBound = {precMaxUlpErrorUpperBound:r}, isBetween = {precMaxUlpErrorIsBetween}"); Assert.True(meanMaxUlpError == 0); Assert.True(precMaxUlpError == 0); } /// <summary> /// Used to debug LogProbBetween /// </summary> internal void LogProbBetweenCRCC_Experiments() { double lowerBound = -0.010000000000000002; double upperBound = -0.01; Gaussian x = Gaussian.FromNatural(-1E+34, 1E+36); for (int i = 0; i < 1000; i++) { double logProb = DoubleIsBetweenOp.LogProbBetween(x, lowerBound, upperBound); Console.WriteLine($"{x.Precision:r} {logProb:r}"); x = Gaussian.FromMeanAndPrecision(x.GetMean(), x.Precision + 1000000000000 * MMath.Ulp(x.Precision)); } } [Fact] public void LogProbBetweenCRCC_IsMonotonicInXPrecision() { double maxUlpError = 0; double maxUlpErrorLowerBound = 0; double maxUlpErrorUpperBound = 0; IEnumerable<double> lowerBounds = Doubles(); // maxUlpError = 22906784576, lowerBound = -0.010000000000000002, upperBound = -0.01 lowerBounds = new double[] { 0 }; foreach (double lowerBound in lowerBounds) { foreach (double upperBound in new double[] { 1 }) //Parallel.ForEach(UpperBounds(lowerBound), upperBound => { Trace.WriteLine($"lowerBound = {lowerBound:r}, upperBound = {upperBound:r}"); foreach (var x in Gaussians()) { if (x.IsPointMass) continue; double mx = x.GetMean(); bool isBetween = Factor.IsBetween(mx, lowerBound, upperBound); if (!isBetween) { // If mx is too close, LogProbBetween is not monotonic. double distance; if (mx < lowerBound) distance = System.Math.Abs(mx - lowerBound); else distance = System.Math.Abs(mx - upperBound); if (distance < 1 / System.Math.Sqrt(x.Precision)) continue; } double logProbBetween = DoubleIsBetweenOp.LogProbBetween(x, lowerBound, upperBound); foreach (var precisionDelta in DoublesGreaterThanZero()) { Gaussian x2 = Gaussian.FromMeanAndPrecision(mx, x.Precision + precisionDelta); if (x2.Equals(x)) continue; if (x2.GetMean() != mx) continue; double logProbBetween2 = DoubleIsBetweenOp.LogProbBetween(x2, lowerBound, upperBound); if ((isBetween && logProbBetween2 < logProbBetween) || (!isBetween && logProbBetween2 > logProbBetween)) { double ulpDiff = UlpDiff(logProbBetween2, logProbBetween); if (ulpDiff > maxUlpError) { maxUlpError = ulpDiff; maxUlpErrorLowerBound = lowerBound; maxUlpErrorUpperBound = upperBound; Assert.True(maxUlpError < 1e10); } } } } Trace.WriteLine($"maxUlpError = {maxUlpError}, lowerBound = {maxUlpErrorLowerBound:r}, upperBound = {maxUlpErrorUpperBound:r}"); }//); } Assert.True(maxUlpError < 1e3); } [Fact] public void GaussianIsBetweenCRCC_IsMonotonicInXPrecision() { double meanMaxUlpError = 0; double meanMaxUlpErrorLowerBound = 0; double meanMaxUlpErrorUpperBound = 0; double precMaxUlpError = 0; double precMaxUlpErrorLowerBound = 0; double precMaxUlpErrorUpperBound = 0; Bernoulli isBetween = new Bernoulli(1.0); foreach (double lowerBound in new[] { -10000.0 })// Doubles()) //foreach (double lowerBound in Doubles()) { foreach (double upperBound in new[] { -9999.9999999999982 }) //foreach (double upperBound in UpperBounds(lowerBound)) //Parallel.ForEach(UpperBounds(lowerBound), upperBound => { Trace.WriteLine($"lowerBound = {lowerBound:r}, upperBound = {upperBound:r}"); //foreach (var x in new[] { Gaussian.FromNatural(-0.1, 0.010000000000000002) })// Gaussians()) foreach (var x in Gaussians()) { if (x.IsPointMass) continue; double mx = x.GetMean(); Gaussian toX = DoubleIsBetweenOp.XAverageConditional(isBetween, x, lowerBound, upperBound); Gaussian xPost; double meanError; if (toX.IsPointMass) { xPost = toX; meanError = 0; } else { xPost = toX * x; meanError = GetProductMeanError(toX, x); } double mean = xPost.GetMean(); double variance = xPost.GetVariance(); double precError = MMath.Ulp(xPost.Precision); double varianceError = 2 * precError * variance * variance; foreach (var precisionDelta in DoublesGreaterThanZero()) { Gaussian x2 = Gaussian.FromMeanAndPrecision(mx, x.Precision + precisionDelta); if (x2.Equals(x)) continue; if (x2.GetMean() != mx) continue; Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional(isBetween, x2, lowerBound, upperBound); Gaussian xPost2; double meanError2; if (toX2.IsPointMass) { xPost2 = toX2; meanError2 = 0; } else { xPost2 = toX2 * x2; meanError2 = GetProductMeanError(toX2, x2); } double mean2 = xPost2.GetMean(); double meanUlpDiff = 0; if (mean > mx) { // Since mx < mean, increasing the prior precision should decrease the posterior mean. if (mean2 > mean) { meanUlpDiff = (mean2 - mean) / System.Math.Max(meanError, meanError2); } } else { if (mean2 < mean) { meanUlpDiff = (mean - mean2) / System.Math.Max(meanError, meanError2); } } if (meanUlpDiff > meanMaxUlpError) { meanMaxUlpError = meanUlpDiff; meanMaxUlpErrorLowerBound = lowerBound; meanMaxUlpErrorUpperBound = upperBound; //Assert.True(meanUlpDiff < 1e16); } double variance2 = xPost2.GetVariance(); double precError2 = MMath.Ulp(xPost2.Precision); // 1 / (xPost.Precision - precError) - 1 / (xPost.Precision + precError) =approx 2*precError*variance*variance double varianceError2 = 2 * precError2 * variance2 * variance2; // Increasing prior precision should increase posterior precision. if (xPost2.Precision < xPost.Precision) { double ulpDiff = UlpDiff(xPost2.Precision, xPost.Precision); if (ulpDiff > precMaxUlpError) { precMaxUlpError = ulpDiff; precMaxUlpErrorLowerBound = lowerBound; precMaxUlpErrorUpperBound = upperBound; //Assert.True(precMaxUlpError < 1e15); } } } } }//); Trace.WriteLine($"meanMaxUlpError = {meanMaxUlpError}, lowerBound = {meanMaxUlpErrorLowerBound:r}, upperBound = {meanMaxUlpErrorUpperBound:r}"); Trace.WriteLine($"precMaxUlpError = {precMaxUlpError}, lowerBound = {precMaxUlpErrorLowerBound:r}, upperBound = {precMaxUlpErrorUpperBound:r}"); } // meanMaxUlpError = 4271.53318407361, lowerBound = -1.0000000000000006E-12, upperBound = inf // precMaxUlpError = 5008, lowerBound = 1E+40, upperBound = 1.00000001E+40 Assert.True(meanMaxUlpError < 1e4); Assert.True(precMaxUlpError < 1e4); } [Fact] public void GaussianIsBetweenCRCC_IsMonotonicInXMean() { double meanMaxUlpError = 0; double meanMaxUlpErrorLowerBound = 0; double meanMaxUlpErrorUpperBound = 0; double precMaxUlpError = 0; double precMaxUlpErrorLowerBound = 0; double precMaxUlpErrorUpperBound = 0; Bernoulli isBetween = new Bernoulli(1.0); foreach (double lowerBound in new[] { -1000.0 })// Doubles()) //foreach (double lowerBound in Doubles()) { foreach (double upperBound in new[] { 0.0 }) //foreach (double upperBound in UpperBounds(lowerBound)) //Parallel.ForEach(UpperBounds(lowerBound), upperBound => { Console.WriteLine($"lowerBound = {lowerBound:r}, upperBound = {upperBound:r}"); double center = (lowerBound + upperBound) / 2; if (double.IsNegativeInfinity(lowerBound) && double.IsPositiveInfinity(upperBound)) center = 0; //foreach (var x in new[] { Gaussian.FromNatural(0, 1e55) })// Gaussians()) foreach (var x in Gaussians()) { double mx = x.GetMean(); Gaussian toX = DoubleIsBetweenOp.XAverageConditional(isBetween, x, lowerBound, upperBound); Gaussian xPost; double meanError; if (toX.IsPointMass) { xPost = toX; meanError = 0; } else { xPost = toX * x; meanError = GetProductMeanError(toX, x); } double mean = xPost.GetMean(); foreach (var meanDelta in DoublesGreaterThanZero()) { double mx2 = mx + meanDelta; if (double.IsPositiveInfinity(meanDelta)) mx2 = meanDelta; if (mx2 == mx) continue; Gaussian x2 = Gaussian.FromMeanAndPrecision(mx2, x.Precision); Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional(isBetween, x2, lowerBound, upperBound); Gaussian xPost2; double meanError2; if (toX2.IsPointMass) { xPost2 = toX2; meanError2 = 0; } else { xPost2 = toX2 * x2; meanError2 = GetProductMeanError(toX2, x2); } double mean2 = xPost2.GetMean(); // Increasing the prior mean should increase the posterior mean. if (mean2 < mean) { double meanUlpDiff = (mean - mean2) / System.Math.Max(meanError, meanError2); if (meanUlpDiff > meanMaxUlpError) { meanMaxUlpError = meanUlpDiff; meanMaxUlpErrorLowerBound = lowerBound; meanMaxUlpErrorUpperBound = upperBound; Assert.True(meanUlpDiff < 1e5); } } // When mx > center, increasing prior mean should increase posterior precision. if (mx > center && xPost2.Precision < xPost.Precision) { double ulpDiff = UlpDiff(xPost2.Precision, xPost.Precision); if (ulpDiff > precMaxUlpError) { precMaxUlpError = ulpDiff; precMaxUlpErrorLowerBound = lowerBound; precMaxUlpErrorUpperBound = upperBound; Assert.True(precMaxUlpError < 1e6); } } } } }//); Console.WriteLine($"meanMaxUlpError = {meanMaxUlpError}, lowerBound = {meanMaxUlpErrorLowerBound:r}, upperBound = {meanMaxUlpErrorUpperBound:r}"); Console.WriteLine($"precMaxUlpError = {precMaxUlpError}, lowerBound = {precMaxUlpErrorLowerBound:r}, upperBound = {precMaxUlpErrorUpperBound:r}"); } // meanMaxUlpError = 104.001435643838, lowerBound = -1.0000000000000022E-37, upperBound = 9.9000000000000191E-36 // precMaxUlpError = 4960, lowerBound = -1.0000000000000026E-47, upperBound = -9.9999999000000263E-48 Assert.True(meanMaxUlpError < 1e3); Assert.True(precMaxUlpError < 1e4); } [Fact] public void GaussianIsBetweenCRCC_IsMonotonicInUpperBound() { // Test the symmetric version of a corner case that is tested below. DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(-1.7976931348623157E+308, 4.94065645841247E-324), double.NegativeInfinity, 0); double meanMaxUlpError = 0; double meanMaxUlpErrorLowerBound = 0; double meanMaxUlpErrorUpperBound = 0; double precMaxUlpError = 0; double precMaxUlpErrorLowerBound = 0; double precMaxUlpErrorUpperBound = 0; foreach (double lowerBound in new[] { 0 }) //foreach (double lowerBound in Doubles()) { foreach (double upperBound in new[] { 1 })// DoublesGreaterThanZero()) //Parallel.ForEach(UpperBounds(lowerBound), upperBound => { Console.WriteLine($"lowerBound = {lowerBound:r}, upperBound = {upperBound:r}"); foreach (Gaussian x in Gaussians()) { Gaussian toX = DoubleIsBetweenOp.XAverageConditional(true, x, lowerBound, upperBound); Gaussian xPost; double meanError; if (toX.IsPointMass) { xPost = toX; meanError = 0; } else { xPost = toX * x; meanError = GetProductMeanError(toX, x); } double mean = xPost.GetMean(); foreach (double delta in DoublesGreaterThanZero()) { double upperBound2 = upperBound + delta; if (delta > double.MaxValue) upperBound2 = delta; if (upperBound2 == upperBound) continue; Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional(true, x, lowerBound, upperBound2); Gaussian xPost2; double meanError2; if (toX2.IsPointMass) { xPost2 = toX2; meanError2 = 0; } else { xPost2 = toX2 * x; meanError2 = GetProductMeanError(toX2, x); } if (toX2.IsUniform()) meanError2 = 0; double mean2 = xPost2.GetMean(); // When adding a new point x to a population, the mean increases iff x is greater than the old mean. // Increasing the upper bound adds new points that are larger than all existing points, so it must increase the mean. if (mean > mean2) { double ulpDiff = (mean - mean2) / System.Math.Max(meanError, meanError2); Assert.True(ulpDiff < 1e15); if (ulpDiff > meanMaxUlpError) { meanMaxUlpError = ulpDiff; meanMaxUlpErrorLowerBound = lowerBound; meanMaxUlpErrorUpperBound = upperBound; } } if (toX2.Precision > toX.Precision) { double ulpDiff = UlpDiff(toX.Precision, toX2.Precision); Assert.True(ulpDiff < 1e15); if (ulpDiff > precMaxUlpError) { precMaxUlpError = ulpDiff; precMaxUlpErrorLowerBound = lowerBound; precMaxUlpErrorUpperBound = upperBound; } } } } }//); Console.WriteLine($"meanMaxUlpError = {meanMaxUlpError}, lowerBound = {meanMaxUlpErrorLowerBound:r}, upperBound = {meanMaxUlpErrorUpperBound:r}"); Console.WriteLine($"precMaxUlpError = {precMaxUlpError}, lowerBound = {precMaxUlpErrorLowerBound:r}, upperBound = {precMaxUlpErrorUpperBound:r}"); } // meanMaxUlpError = 33584, lowerBound = -1E+30, upperBound = 9.9E+31 // precMaxUlpError = 256, lowerBound = -1, upperBound = 0 Assert.True(meanMaxUlpError < 1e5); Assert.True(precMaxUlpError < 1e3); } [Fact] public void NormalCdfRatioSqrMinusDerivative_IsIncreasing() { double maxUlpError = 0; foreach (var z in Doubles()) { if (z > 20) continue; double vp = NormalCdfRatioSqrMinusDerivativeRatio(z); //Console.WriteLine($"z = {z}: vp = {vp}"); foreach (var zDelta in DoublesGreaterThanZero()) { double zU2 = z - zDelta; double vp2 = NormalCdfRatioSqrMinusDerivativeRatio(zU2); if (vp2 > vp) { double ulpDiff = UlpDiff(vp2, vp); if (ulpDiff > maxUlpError) { maxUlpError = ulpDiff; } } } } //Console.WriteLine($"maxUlpError = {maxUlpError}"); Assert.True(maxUlpError <= 3); } [Fact] public void NormalCdfRatioSqrMinusDerivative_EqualsExact() { Assert.Equal(0.0855952047653234157436344334434, NormalCdfRatioSqrMinusDerivative(-1), 1e-15); Assert.Equal(0.0000000000009609728081846573866852515941776879, NormalCdfRatioSqrMinusDerivative(-1009.9999999999991), 1e-27); } private static double NormalCdfRatioSqrMinusDerivative(double z) { double r = MMath.NormalCdfRatio(z); double r1 = MMath.NormalCdfMomentRatio(1, z); double r3 = MMath.NormalCdfMomentRatio(3, z) * 6; double vp = DoubleIsBetweenOp.NormalCdfRatioSqrMinusDerivative(z, r, r1, r3); return vp; } private static double NormalCdfRatioSqrMinusDerivativeRatio(double z) { double vp = NormalCdfRatioSqrMinusDerivative(z); if (vp != 0) { double r = MMath.NormalCdfRatio(z); vp /= (r * r); } return vp; } public static double GetPrecisionError(Gaussian gaussian) { if (double.IsInfinity(gaussian.Precision)) return 0; else return MMath.Ulp(gaussian.Precision); } public static double GetMeanError(Gaussian gaussian) { if (gaussian.IsPointMass) return 0; else if (double.IsInfinity(gaussian.MeanTimesPrecision)) return 0; else return MMath.Ulp(gaussian.MeanTimesPrecision) / (gaussian.Precision - GetPrecisionError(gaussian)); } public static double GetSumError(double a, double b) { return MMath.Ulp(a) + MMath.Ulp(b); } public static double GetProductMeanError(Gaussian a, Gaussian b) { if (a.IsPointMass || b.IsPointMass) return 0; return GetSumError(a.MeanTimesPrecision, b.MeanTimesPrecision) / (a.Precision + b.Precision - GetSumError(a.Precision, b.Precision)); } // Test that the operator behaves correctly for arguments with small variance [Fact] public void GaussianIsBetween_PointX_Test() { foreach (Gaussian lowerBound in new[] { Gaussian.PointMass(1), Gaussian.FromMeanAndVariance(1, 1) }) { foreach (Gaussian upperBound in new[] { Gaussian.PointMass(3), Gaussian.FromMeanAndVariance(3, 1) }) { GaussianIsBetween_PointX(lowerBound, upperBound); } } } internal void GaussianIsBetween_PointX(Gaussian lowerBound, Gaussian upperBound) { Gaussian x = Gaussian.PointMass(-1000); Gaussian Xpost = new Gaussian(); Bernoulli isBetween = Bernoulli.PointMass(true); Gaussian toXExpected = DoubleIsBetweenOp.XAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toLowerExpected = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toUpperExpected = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); if (double.IsNaN(toXExpected.Precision)) throw new Exception(); Console.WriteLine($"expected toX={toXExpected} toLower={toLowerExpected} toUpper={toUpperExpected}"); Gaussian previousXpost = new Gaussian(); Gaussian previousToLower = new Gaussian(); Gaussian previousToUpper = new Gaussian(); for (int i = -10; i < 30; i++) { x.SetMeanAndVariance(1, System.Math.Pow(0.1, i)); Gaussian toX = DoubleIsBetweenOp.XAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toLower = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toUpper = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Assert.True(toX.Precision >= 0); Xpost.SetToProduct(x, toX); Console.WriteLine($"{x}: {toX} {Xpost} toLower={toLower} toUpper={toUpper}"); if (i > 0) { Assert.True(Xpost.GetVariance() < previousXpost.GetVariance()); Assert.True(Xpost.GetMean() <= previousXpost.GetMean() + 1e-20); } previousXpost = Xpost; if (i > 0) { Assert.True(toLower.GetMean() <= previousToLower.GetMean() || toLower.GetVariance() <= previousToLower.GetVariance()); } previousToLower = toLower; if (i > 0) { Assert.True(toUpper.GetVariance() >= previousToUpper.GetVariance() - 1e-20); Assert.True(toUpper.GetMean() <= previousToUpper.GetMean()); } previousToUpper = toUpper; // check making diffs smaller if (lowerBound.Precision == upperBound.Precision && lowerBound.MeanTimesPrecision == -upperBound.MeanTimesPrecision) { // check the flipped case x.SetMeanAndVariance(-x.GetMean(), System.Math.Pow(0.1, i)); Gaussian toX2 = DoubleIsBetweenOp.XAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toLower2 = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Gaussian toUpper2 = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound); Assert.True(toX.Precision == toX2.Precision); Assert.True(toX.MeanTimesPrecision == -toX2.MeanTimesPrecision); Assert.True(toLower2.Precision == toUpper.Precision); Assert.True(toLower2.MeanTimesPrecision == -toUpper.MeanTimesPrecision); Assert.True(toUpper2.Precision == toLower.Precision); Assert.True(toUpper2.MeanTimesPrecision == -toLower.MeanTimesPrecision); } } } /// <summary> /// Test that the operator behaves correctly for contexts far outside of the bounds /// </summary> [Fact] public void GaussianIsBetween_EqualsExact() { /* Anaconda Python script to generate a true value (must not be indented): from mpmath import * mp.dps = 100; mp.pretty = True prec=mpf('1.00001E+36'); tau = mpf('1.0000099999999998E+34'); mx = tau/prec; l=mpf('0.010000000000000002'); u=mpf('0.010000000000000004'); p0=mpf('0'); qu = (u-mx)*sqrt(prec); ql = (l-mx)*sqrt(prec); Z = (1-2*p0)*(ncdf(qu) - ncdf(ql))+p0; #Z = ncdf(-ql) - ncdf(-qu); alphaU = (1-2*p0)*npdf(qu)/Z*sqrt(prec); alphaL = (1-2*p0)*npdf(ql)/Z*sqrt(prec); alphaX = alphaL - alphaU; betaX = alphaX*alphaX + qu*alphaU*sqrt(prec) - ql*alphaL*sqrt(prec); mx + alphaX/prec 1/prec - betaX/prec/prec weight = betaX / (prec - betaX); prec * weight weight * (tau + alphaX) + alphaX */ //Assert.Equal(DoubleIsBetweenOp.LogProbBetween(Gaussian.FromNatural(1.0000099999999998E+34, 1.00001E+36), 0.010000000000000002, 0.010000000000000004), -10.360132636204013435798441, 1e-3); Gaussian expected; Gaussian result2; result2 = DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(100, 0.6), -0.0025, 0.0025); expected = Gaussian.FromNatural(0.83382446386897639746, 486015.0838217901083); Assert.True(MaxUlpDiff(expected, result2) < 1e5); result2 = DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(1000, 0.6), -0.0025, 0.0025); // exact posterior mean = 0.00153391785173542665 // exact posterior variance = 0.0000008292583427621911323272374 expected = Gaussian.FromNatural(849.7466623321181468, 1205896.221814396816657); Assert.True(MaxUlpDiff(expected, result2) < 1e6); result2 = DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(10000, 0.6), -0.0025, 0.0025); expected = Gaussian.FromNatural(229999.9352600054688757876, 99999973.0000021996482); Assert.True(MaxUlpDiff(expected, result2) < 1e2); Gaussian result = DoubleIsBetweenOp.XAverageConditional_Slow(Bernoulli.PointMass(true), new Gaussian(-48.26, 1.537), new Gaussian(-12.22, 0.4529), new Gaussian(-17.54, 0.3086)); result2 = DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(1, 1e-19), -10, 0); // exact posterior mean = -0.99954598008990312211948 // exact posterior variance = 0.99545959476495245821845 expected = Gaussian.FromNatural(-2.00410502379648622469036, 1.0045611145433980376101655346945); Assert.True(MaxUlpDiff(expected, result2) < 2); result2 = DoubleIsBetweenOp.XAverageConditional(true, Gaussian.FromNatural(1, 1e19), -10, 0); // exact posterior mean = -0.00000000025231325216567798206492 // exact posterior variance = 0.00000000000000000003633802275634766987678763433333 expected = Gaussian.FromNatural(-6943505261.522269414985891, 17519383944062174805.8794215); Assert.True(MaxUlpDiff(expected, result2) <= 5); } [Fact] public void GaussianIsBetweenTest2() { Assert.True(!double.IsNaN(DoubleIsBetweenOp.XAverageConditional(Bernoulli.PointMass(true), new Gaussian(1, 2), double.PositiveInfinity, double.PositiveInfinity).MeanTimesPrecision)); Bernoulli isBetween = new Bernoulli(1); Gaussian x = new Gaussian(0, 1); Gaussian lowerBound = new Gaussian(1, 8); Gaussian upperBound = new Gaussian(3, 3); Assert.True(DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, Gaussian.PointMass(0), Gaussian.PointMass(-1), Gaussian.PointMass(1)).IsUniform()); Assert.True(DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, Gaussian.PointMass(double.NegativeInfinity), upperBound).IsUniform()); Assert.True(DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, Gaussian.PointMass(double.PositiveInfinity)).IsUniform()); // test in matlab: x=randn(1e7,1); l=randnorm(1e7,1,[],8)'; u=randnorm(1e7,3,[],3)'; // ok=(l<x & x<u); [mean(l(ok)) var(l(ok)); mean(u(ok)) var(u(ok)); mean(x(ok)) var(x(ok))] Gaussian LpostTrue = new Gaussian(-1.7784, 2.934); Gaussian UpostTrue = new Gaussian(3.2694, 2.3796); Gaussian XpostTrue = new Gaussian(0.25745, 0.8625); Gaussian Lpost = new Gaussian(); Gaussian Upost = new Gaussian(); Gaussian Xpost = new Gaussian(); Lpost.SetToProduct(lowerBound, DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(LpostTrue.MaxDiff(Lpost) < 1e-4); Upost.SetToProduct(upperBound, DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(UpostTrue.MaxDiff(Upost) < 1e-4); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(XpostTrue.MaxDiff(Xpost) < 1e-4); // special case for uniform X x = new Gaussian(); LpostTrue.SetMeanAndVariance(-1.2741, 5.3392); UpostTrue.SetMeanAndVariance(3.8528, 2.6258); XpostTrue.SetMeanAndVariance(1.2894, 5.1780); Lpost.SetToProduct(lowerBound, DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(LpostTrue.MaxDiff(Lpost) < 1e-4); Upost.SetToProduct(upperBound, DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(UpostTrue.MaxDiff(Upost) < 1e-4); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional_Slow(isBetween, x, lowerBound, upperBound)); Assert.True(XpostTrue.MaxDiff(Xpost) < 1e-4); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(new Bernoulli(0), Gaussian.PointMass(1.0), Gaussian.PointMass(0.0), new Gaussian()); Assert.True(new Gaussian(0.5, 1.0 / 12).MaxDiff(Upost) < 1e-4); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(new Bernoulli(0), new Gaussian(1.0, 0.5), Gaussian.PointMass(0.0), new Gaussian()); UpostTrue = DoubleIsBetweenOp.XAverageConditional_Slow(Bernoulli.PointMass(true), new Gaussian(), Gaussian.PointMass(0.0), new Gaussian(1.0, 0.5)); Assert.True(UpostTrue.MaxDiff(Upost) < 1e-4); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(new Bernoulli(0.1), Gaussian.PointMass(1.0), Gaussian.PointMass(0.0), new Gaussian()); Assert.True(new Gaussian().MaxDiff(Upost) < 1e-10); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(new Bernoulli(1), Gaussian.PointMass(1.0), Gaussian.PointMass(0.0), new Gaussian()); Assert.True(new Gaussian().MaxDiff(Upost) < 1e-10); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(new Bernoulli(0), Gaussian.PointMass(0.0), new Gaussian(), Gaussian.PointMass(1.0)); Assert.True(new Gaussian(0.5, 1.0 / 12).MaxDiff(Lpost) < 1e-4); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(new Bernoulli(0), new Gaussian(0.0, 0.5), new Gaussian(), Gaussian.PointMass(1.0)); LpostTrue = DoubleIsBetweenOp.XAverageConditional_Slow(Bernoulli.PointMass(true), new Gaussian(), new Gaussian(0.0, 0.5), Gaussian.PointMass(1.0)); Assert.True(LpostTrue.MaxDiff(Lpost) < 1e-4); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(new Bernoulli(0.1), Gaussian.PointMass(0.0), new Gaussian(), Gaussian.PointMass(1.0)); Assert.True(new Gaussian().MaxDiff(Lpost) < 1e-10); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(new Bernoulli(1), Gaussian.PointMass(0.0), new Gaussian(), Gaussian.PointMass(1.0)); Assert.True(new Gaussian().MaxDiff(Lpost) < 1e-10); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional(Bernoulli.PointMass(true), new Gaussian(-2.839e+10, 39.75), Gaussian.PointMass(0.05692), Gaussian.PointMass(double.PositiveInfinity), -1.0138308906207461E+19); Assert.True(!double.IsNaN(Lpost.MeanTimesPrecision)); /* test in matlab: s = [0 0 0]; for iter = 1:100 x=randn(1e7,1); l=1; u=3; ok=(l<x & x<u); s = s + [sum(ok) sum(x(ok)) sum(x(ok).^2)]; end m = s(2)/s(1); v = s(3)/s(1) - m*m; [m v] */ x = new Gaussian(0, 1); Assert.True(DoubleIsBetweenOp.XAverageConditional_Slow(new Bernoulli(0.5), x, Gaussian.PointMass(Double.NegativeInfinity), Gaussian.Uniform()).IsUniform()); Assert.True(DoubleIsBetweenOp.XAverageConditional_Slow(Bernoulli.PointMass(true), x, Gaussian.PointMass(Double.NegativeInfinity), Gaussian.Uniform()).IsUniform()); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, 1, 3)); Assert.True(Xpost.MaxDiff(Gaussian.FromMeanAndVariance(1.5101, 0.17345)) < 1e-3); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(false, x, 1, 3)); Assert.True(Xpost.MaxDiff(Gaussian.FromMeanAndVariance(-0.28189, 0.64921)) < 1e-3); Assert.True(IsPositiveOp.XAverageConditional(true, x).MaxDiff( DoubleIsBetweenOp.XAverageConditional(true, x, 0.0, Double.PositiveInfinity)) < 1e-8); Assert.True(IsPositiveOp.XAverageConditional(false, x).MaxDiff( DoubleIsBetweenOp.XAverageConditional(true, x, Double.NegativeInfinity, 0)) < 1e-8); /* test in matlab: z=0;s1=0;s2=0; for iter = 1:100 x=randn(1e7,1); l=1; u=3; ok=(l<x & x<u); z=z + 0.6*sum(ok)+0.4*sum(~ok); s1=s1 + 0.6*sum(x(ok))+0.4*sum(x(~ok)); s2=s2 + 0.6*sum(x(ok).^2)+0.4*sum(x(~ok).^2); end m=s1/z; v=s2/z - m*m; [m v] */ Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(new Bernoulli(0.6), x, 1, 3)); if (DoubleIsBetweenOp.ForceProper) Assert.True(Xpost.MaxDiff(Gaussian.FromMeanAndVariance(0.1101, 1.0)) < 1e-3); else Assert.True(Xpost.MaxDiff(Gaussian.FromMeanAndVariance(0.11027, 1.0936)) < 1e-3); // special case for uniform X x = new Gaussian(); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, 1, 3)); Assert.True(Xpost.MaxDiff(Gaussian.FromMeanAndVariance(2, 4.0 / 12)) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(false, x, 1, 3)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(new Bernoulli(0.6), x, 1, 3)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, 1, Double.PositiveInfinity)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(false, x, 1, Double.PositiveInfinity)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, Double.NegativeInfinity, 1)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(false, x, Double.NegativeInfinity, 1)); Assert.True(Xpost.MaxDiff(new Gaussian()) < 1e-10); x = new Gaussian(0, 1); double[] lowerBounds = { 2, 10, 100, 1000 }; for (int i = 0; i < lowerBounds.Length; i++) { double m, v; Gaussian x2 = new Gaussian(-lowerBounds[i], 1); Xpost.SetToProduct(x2, IsPositiveOp.XAverageConditional(true, x2)); Console.WriteLine(Xpost); Xpost.GetMeanAndVariance(out m, out v); Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, lowerBounds[i], Double.PositiveInfinity)); Assert.True(Xpost.MaxDiff(new Gaussian(m + lowerBounds[i], v)) < 1e-5 / v); //Xpost.SetToProduct(x, DoubleIsBetweenOp.XAverageConditional(true, x, new Gaussian(lowerBounds[i], 1e-80), Double.PositiveInfinity)); //Assert.True(Xpost.MaxDiff(new Gaussian(m+lowerBounds[i], v)) < 1e-8); } //Gaussian upperBound = new Gaussian(3,4); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(Bernoulli.PointMass(true), Gaussian.PointMass(0.0), lowerBound, Gaussian.PointMass(0.0)); Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional_Slow(Bernoulli.PointMass(true), Gaussian.PointMass(0.0), lowerBound, Gaussian.PointMass(1.0)); Assert.True(Lpost.MaxDiff(IsPositiveOp.XAverageConditional(false, lowerBound)) < 1e-10); //Lpost = DoubleIsBetweenOp.LowerBoundAverageConditional(true,Gaussian.Uniform(),lowerBound,0); //Assert.True(Lpost.MaxDiff(IsPositiveOp.XAverageConditional(false,lowerBound)) < 1e-3); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(Bernoulli.PointMass(true), Gaussian.PointMass(-1), Gaussian.PointMass(0.0), upperBound); Upost = DoubleIsBetweenOp.UpperBoundAverageConditional_Slow(Bernoulli.PointMass(true), Gaussian.PointMass(0.0), Gaussian.PointMass(0.0), upperBound); Assert.True(Upost.MaxDiff(IsPositiveOp.XAverageConditional(true, upperBound)) < 1e-10); //Upost = DoubleIsBetweenOp.UpperBoundAverageConditional(true,Gaussian.Uniform(),0,upperBound); //Assert.True(Upost.MaxDiff(IsPositiveOp.XAverageConditional(true,upperBound)) < 1e-3); } internal void ProductGaussianGammaVmpOpTest() { double prec = 1; double a = 2; Gamma B = Gamma.FromShapeAndRate(1e-3, 1e-3); //Gamma B = Gamma.FromShapeAndRate(1, 1); for (int i = 0; i < 10; i++) { prec = (i + 1) * 4.0e-15; Gamma result = ProductGaussianGammaVmpOp.BAverageLogarithm(Gaussian.FromNatural(0.5, prec), Gaussian.PointMass(a), B, Gamma.Uniform()); Gamma result2 = ProductGaussianGammaVmpOp.BAverageLogarithm(Gaussian.FromNatural(0.5, prec), Gaussian.PointMass(a), B, Gamma.Uniform()); Console.WriteLine("{0} {1}", result, result2); //Console.WriteLine("rate = {0}", result.Rate); // rate = -0.5*A } } [Fact] public void ProductOpTest() { Assert.True(GaussianProductVmpOp.ProductAverageLogarithm( 2.0, Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional( 2.0, Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional(new Gaussian(0, 1), Gaussian.PointMass(2.0), Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5)) < 1e-8); Assert.True(GaussianProductVmpOp.ProductAverageLogarithm( 0.0, Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.PointMass(0.0)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional( 0.0, Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.PointMass(0.0)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional(new Gaussian(0, 1), Gaussian.PointMass(0.0), Gaussian.FromMeanAndVariance(3.0, 5.0)).MaxDiff(Gaussian.PointMass(0.0)) < 1e-8); Assert.True(GaussianProductVmpOp.ProductAverageLogarithm( Gaussian.FromMeanAndVariance(2, 4), Gaussian.FromMeanAndVariance(3, 5)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5 + 3 * 3 * 4 + 2 * 2 * 5)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional(Gaussian.Uniform(), Gaussian.FromMeanAndVariance(2, 4), Gaussian.FromMeanAndVariance(3, 5)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5 + 3 * 3 * 4 + 2 * 2 * 5)) < 1e-8); Assert.True(GaussianProductOp.ProductAverageConditional(Gaussian.FromMeanAndVariance(0, 1e16), Gaussian.FromMeanAndVariance(2, 4), Gaussian.FromMeanAndVariance(3, 5)).MaxDiff(Gaussian.FromMeanAndVariance(2 * 3, 4 * 5 + 3 * 3 * 4 + 2 * 2 * 5)) < 1e-4); Assert.True(GaussianProductOp.AAverageConditional(6.0, 2.0) .MaxDiff(Gaussian.PointMass(6.0 / 2.0)) < 1e-8); Assert.True(GaussianProductOp.AAverageConditional(6.0, new Gaussian(1, 3), Gaussian.PointMass(2.0)) .MaxDiff(Gaussian.PointMass(6.0 / 2.0)) < 1e-8); Assert.True(GaussianProductOp.AAverageConditional(0.0, 0.0).IsUniform()); Assert.True(GaussianProductOp.AAverageConditional(Gaussian.Uniform(), 2.0).IsUniform()); Assert.True(GaussianProductOp.AAverageConditional(Gaussian.Uniform(), new Gaussian(1, 3), Gaussian.PointMass(2.0)).IsUniform()); Assert.True(GaussianProductOp.AAverageConditional(Gaussian.Uniform(), new Gaussian(1, 3), new Gaussian(2, 4)).IsUniform()); Gaussian aPrior = Gaussian.FromMeanAndVariance(0.0, 1000.0); Assert.True((GaussianProductOp.AAverageConditional( Gaussian.FromMeanAndVariance(10.0, 1.0), aPrior, Gaussian.FromMeanAndVariance(5.0, 1.0)) * aPrior).MaxDiff( Gaussian.FromMeanAndVariance(2.208041421368822, 0.424566765678152)) < 1e-4); Gaussian g = new Gaussian(0, 1); Assert.True(GaussianProductOp.AAverageConditional(g, 0.0).IsUniform()); Assert.True(GaussianProductOp.AAverageConditional(0.0, 0.0).IsUniform()); Assert.True(GaussianProductVmpOp.AAverageLogarithm(g, 0.0).IsUniform()); Assert.True(Gaussian.PointMass(3.0).MaxDiff(GaussianProductVmpOp.AAverageLogarithm(6.0, 2.0)) < 1e-10); Assert.True(GaussianProductVmpOp.AAverageLogarithm(0.0, 0.0).IsUniform()); try { Assert.True(GaussianProductVmpOp.AAverageLogarithm(6.0, g).IsUniform()); Assert.True(false, "Did not throw NotSupportedException"); } catch (NotSupportedException) { } try { g = GaussianProductOp.AAverageConditional(12.0, 0.0); Assert.True(false, "Did not throw AllZeroException"); } catch (AllZeroException) { } try { g = GaussianProductVmpOp.AAverageLogarithm(12.0, 0.0); Assert.True(false, "Did not throw AllZeroException"); } catch (AllZeroException) { } } [Fact] [Trait("Category", "ModifiesGlobals")] public void GaussianProductOp_APointMassTest() { using (TestUtils.TemporarilyAllowGaussianImproperMessages) { Gaussian Product = Gaussian.FromMeanAndVariance(1.3, 0.1); Gaussian B = Gaussian.FromMeanAndVariance(1.24, 0.04); gaussianProductOp_APointMassTest(1, Product, B); Product = Gaussian.FromMeanAndVariance(10, 1); B = Gaussian.FromMeanAndVariance(5, 1); gaussianProductOp_APointMassTest(2, Product, B); Product = Gaussian.FromNatural(1, 0); gaussianProductOp_APointMassTest(2, Product, B); } } private void gaussianProductOp_APointMassTest(double aMean, Gaussian Product, Gaussian B) { bool isProper = Product.IsProper(); Gaussian A = Gaussian.PointMass(aMean); Gaussian result = GaussianProductOp.AAverageConditional(Product, A, B); Console.WriteLine("{0}: {1}", A, result); Gaussian result2 = isProper ? GaussianProductOp_Slow.AAverageConditional(Product, A, B) : result; Console.WriteLine("{0}: {1}", A, result2); Assert.True(result.MaxDiff(result2) < 1e-6); var Amsg = InnerProductOp_PointB.BAverageConditional(Product, DenseVector.FromArray(B.GetMean()), new PositiveDefiniteMatrix(new double[,] { { B.GetVariance() } }), VectorGaussian.PointMass(aMean), VectorGaussian.Uniform(1)); //Console.WriteLine("{0}: {1}", A, Amsg); Assert.True(result.MaxDiff(Amsg.GetMarginal(0)) < 1e-6); double prevDiff = double.PositiveInfinity; for (int i = 3; i < 40; i++) { double v = System.Math.Pow(0.1, i); A = Gaussian.FromMeanAndVariance(aMean, v); result2 = isProper ? GaussianProductOp.AAverageConditional(Product, A, B) : result; double diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} diff={2}", A, result2, diff.ToString("g4")); //Assert.True(diff <= prevDiff || diff < 1e-6); result2 = isProper ? GaussianProductOp_Slow.AAverageConditional(Product, A, B) : result; diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} diff={2}", A, result2, diff.ToString("g4")); Assert.True(diff <= prevDiff || diff < 1e-6); prevDiff = diff; } } [Fact] [Trait("Category", "OpenBug")] public void GaussianProductOp_ProductPointMassTest() { Gaussian A = new Gaussian(1, 2); Gaussian B = new Gaussian(3, 4); Gaussian pointMass = Gaussian.PointMass(4); Gaussian to_pointMass = GaussianProductOp.ProductAverageConditional(pointMass, A, B); double prevDiff = double.PositiveInfinity; for (int i = 0; i < 100; i++) { Gaussian Product = Gaussian.FromMeanAndVariance(4, System.Math.Pow(10, -i)); Gaussian to_product = GaussianProductOp.ProductAverageConditional(Product, A, B); double evidence = GaussianProductOp.LogEvidenceRatio(Product, A, B, to_product); Console.WriteLine($"{Product} {to_product} {evidence}"); double diff = to_product.MaxDiff(to_pointMass); Assert.True(diff <= prevDiff || diff < 1e-6); prevDiff = diff; } } [Fact] public void ProductOpTest3() { Gaussian Product = new Gaussian(3.207, 2.222e-06); Gaussian A = new Gaussian(2.854e-06, 1.879e-05); Gaussian B = new Gaussian(0, 1); Gaussian result = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); Console.WriteLine(result); Assert.False(double.IsNaN(result.Precision)); Product = Gaussian.FromNatural(2, 1); A = Gaussian.FromNatural(0, 3); B = Gaussian.FromNatural(0, 1); result = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); Console.WriteLine("{0}: {1}", Product, result); Product = Gaussian.FromNatural(129146.60457039363, 320623.20967711863); A = Gaussian.FromNatural(-0.900376203577801, 0.00000001); B = Gaussian.FromNatural(0, 1); result = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); Console.WriteLine("{0}: {1}", Product, result); Assert.True(GaussianProductOp_Slow.ProductAverageConditional( Gaussian.FromMeanAndVariance(0.0, 1000.0), Gaussian.FromMeanAndVariance(2.0, 3.0), Gaussian.FromMeanAndVariance(5.0, 1.0)).MaxDiff( Gaussian.FromMeanAndVariance(9.911, 79.2) // Gaussian.FromMeanAndVariance(12.110396063215639,3.191559311624262e+002) ) < 1e-4); A = new Gaussian(2, 3); B = new Gaussian(4, 5); Product = Gaussian.PointMass(2); result = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); Console.WriteLine("{0}: {1}", Product, result); double prevDiff = double.PositiveInfinity; for (int i = 3; i < 40; i++) { double v = System.Math.Pow(0.1, i); Product = Gaussian.FromMeanAndVariance(2, v); Gaussian result2 = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); double diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} diff={2}", Product, result2, diff.ToString("g4")); Assert.True(diff <= prevDiff || diff < 1e-6); prevDiff = diff; } Product = Gaussian.Uniform(); result = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); Console.WriteLine("{0}: {1}", Product, result); prevDiff = double.PositiveInfinity; for (int i = 3; i < 40; i++) { double v = System.Math.Pow(10, i); Product = Gaussian.FromMeanAndVariance(2, v); Gaussian result2 = GaussianProductOp_Slow.ProductAverageConditional(Product, A, B); double diff = result.MaxDiff(result2); Console.WriteLine("{0}: {1} diff={2}", Product, result2, diff.ToString("g4")); Assert.True(diff <= prevDiff || diff < 1e-6); prevDiff = diff; } } [Fact] public void LogisticProposalDistribution() { double[] TrueCounts = { 2, 20, 200, 2000, 20000, 2, 20, 200, 2000, 20000 }; double[] FalseCounts = { 2, 200, 20000, 200, 20, 200, 2000, 2, 2000, 20 }; double[] Means = { .5, 1, 2, 4, 8, 16, 32, 0, -2, -20 }; double[] Variances = { 1, 2, 4, 8, .1, .0001, .01, .000001, 0.000001, 0.001 }; for (int i = 0; i < 10; i++) { Beta b = new Beta(); b.TrueCount = TrueCounts[i]; b.FalseCount = FalseCounts[i]; Gaussian g = Gaussian.FromMeanAndVariance(Means[i], Variances[i]); Gaussian gProposal = GaussianBetaProductOp.LogisticProposalDistribution(b, g); } } /// <summary> /// Tests for the message operators for <see cref="Factor.CountTrue"/>. /// </summary> [Fact] public void CountTrueOpTest() { const double Tolerance = 1e-10; // Test forward message { var array = new[] { new Bernoulli(0.0), new Bernoulli(0.1), new Bernoulli(0.3), new Bernoulli(0.5), new Bernoulli(1.0) }; double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(array); Discrete count = CountTrueOp.CountAverageConditional(forwardPassBuffer); Assert.Equal(6, count.Dimension); Assert.Equal(0, count[0], Tolerance); Assert.Equal(0.9 * 0.7 * 0.5, count[1], Tolerance); Assert.Equal((0.1 * 0.7 * 0.5) + (0.9 * 0.3 * 0.5) + (0.9 * 0.7 * 0.5), count[2], Tolerance); Assert.Equal((0.1 * 0.3 * 0.5) + (0.1 * 0.7 * 0.5) + (0.9 * 0.3 * 0.5), count[3], Tolerance); Assert.Equal(0.1 * 0.3 * 0.5, count[4], Tolerance); Assert.Equal(0, count[5], Tolerance); } // Test backward message { var array = new[] { new Bernoulli(1.0 / 3.0), new Bernoulli(1.0 / 2.0), new Bernoulli(0.0) }; var count = new Discrete(1.0 / 9.0, 1.0 / 3.0, 1.0 / 3.0, 1.0 / 9.0); var resultArray = new Bernoulli[3]; double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(array); CountTrueOp.ArrayAverageConditional(array, count, forwardPassBuffer, resultArray); Assert.Equal(3.0 / 5.0, resultArray[0].GetProbTrue(), Tolerance); Assert.Equal(9.0 / 14.0, resultArray[1].GetProbTrue(), Tolerance); Assert.Equal(8.0 / 15.0, resultArray[2].GetProbTrue(), Tolerance); } // Test corner cases for forward message { const double Prob = 0.666; double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(new[] { new Bernoulli(Prob) }); Discrete count = CountTrueOp.CountAverageConditional(forwardPassBuffer); Assert.Equal(2, count.Dimension); Assert.Equal(1.0 - Prob, count[0], Tolerance); Assert.Equal(Prob, count[1], Tolerance); } { double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(new Bernoulli[] { }); Discrete count = CountTrueOp.CountAverageConditional(forwardPassBuffer); Assert.Equal(1, count.Dimension); Assert.Equal(1.0, count[0]); } // Test corner cases for backward message { const double Prob = 0.666, OtherProb = 0.777; var array = new[] { new Bernoulli(OtherProb) }; var resultArray = new Bernoulli[1]; double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(array); CountTrueOp.ArrayAverageConditional(array, new Discrete(1 - Prob, Prob), forwardPassBuffer, resultArray); Assert.Equal(Prob, resultArray[0].GetProbTrue(), Tolerance); } { var array = new Bernoulli[] { }; var resultArray = new Bernoulli[] { }; double[,] forwardPassBuffer = CountTrueOp.PoissonBinomialTable(array); CountTrueOp.ArrayAverageConditional(array, new Discrete(1.0), forwardPassBuffer, resultArray); } } } public class ImportanceSampler { public delegate double Sampler(); private Vector samples, weights; public ImportanceSampler(int N, Sampler sampler, Converter<double, double> weightFunction) { samples = Vector.Zero(N); weights = Vector.Zero(N); for (int i = 0; i < N; i++) { samples[i] = sampler(); weights[i] = weightFunction(samples[i]); } } public double GetExpectation(Converter<double, double> h) { var temp = Vector.Zero(samples.Count); temp.SetToFunction(samples, h); temp.SetToProduct(temp, weights); return temp.Sum() / weights.Sum(); } } }
54.456442
313
0.548347
[ "MIT" ]
a-sklyarov/infer
test/Tests/Operators/OperatorTests.cs
177,528
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ECS.MemberManager.Core.EF.Domain { public class CategoryOfOrganization : EntityBase { [Required, MaxLength(35)] public string Category { get; set; } public int DisplayOrder { get; set; } public IList<Organization> Organizations { get; set; } } }
31
70
0.706989
[ "MIT" ]
edmathias/ECS.MemberManager.Core
ECS.MemberManager.Core.EF.Domain/CategoryOfOrganization.cs
374
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TestMachineFrontend1.Helpers; namespace TestMachineFrontend1.Model { public class MultiplexerModel : ObservableObject { private double x; /// <summary> /// Value for x /// </summary> public double ValueX { get { return x; } set { x = value; OnPropertyChanged("ValueX"); } } private double y; /// <summary> /// Value for y /// </summary> public double ValueY { get { return y; } set { y = value; OnPropertyChanged("ValueY"); } } private UInt16 pinID; public UInt16 PinID { get { return pinID; } set { pinID = value; OnPropertyChanged("PinID"); } } } }
21.019608
52
0.449627
[ "Apache-2.0" ]
CytheY/amos-ss17-projSivantos
UserAgent/ProductionFrontend/Model/MultiplexerModel.cs
1,074
C#
using System; using Markify.Services.Rendering.T4.Tests.Attributes; using NFluent; using Xunit; namespace Markify.Services.Rendering.T4.Tests { public sealed class T4TemplateProviderTests { [Theory] [TemplateProviderData(new[] { typeof(string)}, typeof(string))] [TemplateProviderData(new[] { typeof(string), typeof(int), typeof(DateTime) }, typeof(DateTime))] public void GetTemplate_ShouldReturnTemplateInstance_WhenTypeIsRegistered(object content, T4TemplateProvider sut) { Check.That(sut.GetTemplate(content).HasValue).IsTrue(); } [Theory] [TemplateProviderData(new Type[0], typeof(int))] [TemplateProviderData(new[] { typeof(string), typeof(int), typeof(DateTime) }, typeof(float))] public void GetTemplate_ShouldReturnNone_WhenTypeIsNotRegistered(object content, T4TemplateProvider sut) { Check.That(sut.GetTemplate(content).HasValue).IsFalse(); } [Theory] [TemplateProviderData(new Type[0], null)] public void GetTemplate_ShouldReturnNone_WhenContentIsNull(object content, T4TemplateProvider sut) { Check.That(sut.GetTemplate(content).HasValue).IsFalse(); } } }
38.060606
121
0.683917
[ "MIT" ]
Julien-Pires/Markify
src/Services/Rendering/Markify.Services.Rendering.T4.Tests/T4TemplateProvider/T4TemplateProvider.GetTemplate.Tests.cs
1,258
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using LanguageExt; using SJP.Schematic.Core; using SJP.Schematic.Core.Comments; namespace SJP.Schematic.Oracle.Comments { /// <summary> /// A view comment provider for Oracle. /// </summary> /// <seealso cref="IDatabaseViewCommentProvider" /> public class OracleViewCommentProvider : IDatabaseViewCommentProvider { /// <summary> /// Initializes a new instance of the <see cref="OracleViewCommentProvider"/> class. /// </summary> /// <param name="connection">A database connection factory.</param> /// <param name="identifierDefaults">Database identifier defaults.</param> /// <param name="identifierResolver">An identifier resolver.</param> /// <exception cref="ArgumentNullException"><paramref name="connection"/> or <paramref name="identifierDefaults"/> or <paramref name="identifierResolver"/> are <c>null</c>.</exception> public OracleViewCommentProvider(IDbConnectionFactory connection, IIdentifierDefaults identifierDefaults, IIdentifierResolutionStrategy identifierResolver) { if (connection == null) throw new ArgumentNullException(nameof(connection)); if (identifierDefaults == null) throw new ArgumentNullException(nameof(identifierDefaults)); if (identifierResolver == null) throw new ArgumentNullException(nameof(identifierResolver)); QueryViewCommentProvider = new OracleQueryViewCommentProvider(connection, identifierDefaults, identifierResolver); MaterializedViewCommentProvider = new OracleMaterializedViewCommentProvider(connection, identifierDefaults, identifierResolver); } /// <summary> /// Gets a query view comment provider that does not return any materialized view comments. /// </summary> /// <value>A query view comment provider.</value> protected IDatabaseViewCommentProvider QueryViewCommentProvider { get; } /// <summary> /// Gets a materialized view comment provider, that does not return any simple query view comments. /// </summary> /// <value>A materialized view comment provider.</value> protected IDatabaseViewCommentProvider MaterializedViewCommentProvider { get; } /// <summary> /// Retrieves all database view comments defined within a database. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A collection of view comments.</returns> public async IAsyncEnumerable<IDatabaseViewComments> GetAllViewComments([EnumeratorCancellation] CancellationToken cancellationToken = default) { var queryViewCommentsTask = QueryViewCommentProvider.GetAllViewComments(cancellationToken).ToListAsync(cancellationToken).AsTask(); var materializedViewCommentsTask = MaterializedViewCommentProvider.GetAllViewComments(cancellationToken).ToListAsync(cancellationToken).AsTask(); await Task.WhenAll(queryViewCommentsTask, materializedViewCommentsTask).ConfigureAwait(false); var queryViewComments = await queryViewCommentsTask.ConfigureAwait(false); var materializedViewComments = await materializedViewCommentsTask.ConfigureAwait(false); var comments = queryViewComments .Concat(materializedViewComments) .OrderBy(static v => v.ViewName.Schema) .ThenBy(static v => v.ViewName.LocalName); foreach (var comment in comments) yield return comment; } /// <summary> /// Retrieves comments for a particular database view. /// </summary> /// <param name="viewName">The name of a database view.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>An <see cref="T:LanguageExt.OptionAsync`1" /> instance which holds the value of the view's comments, if available.</returns> /// <exception cref="ArgumentNullException"><paramref name="viewName"/> is <c>null</c>.</exception> public OptionAsync<IDatabaseViewComments> GetViewComments(Identifier viewName, CancellationToken cancellationToken = default) { if (viewName == null) throw new ArgumentNullException(nameof(viewName)); return QueryViewCommentProvider.GetViewComments(viewName, cancellationToken) | MaterializedViewCommentProvider.GetViewComments(viewName, cancellationToken); } } }
52.597826
193
0.680099
[ "MIT" ]
sjp/Schematic
src/SJP.Schematic.Oracle/Comments/OracleViewCommentProvider.cs
4,841
C#
// <auto-generated /> // Built from: hl7.fhir.r4.core version: 4.0.1 using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; using Fhir.R4.Serialization; namespace Fhir.R4.Models { /// <summary> /// Actor participating in the resource. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioActor>))] public class ExampleScenarioActor : BackboneElement, IFhirJsonSerializable { /// <summary> /// should this be called ID or acronym? /// </summary> public string ActorId { get; set; } /// <summary> /// Extension container element for ActorId /// </summary> public Element _ActorId { get; set; } /// <summary> /// Cardinality: is name and description 1..1? /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// Cardinality: is name and description 1..1? /// </summary> public string Name { get; set; } /// <summary> /// Extension container element for Name /// </summary> public Element _Name { get; set; } /// <summary> /// The type of actor - person or system. /// </summary> public string Type { get; set; } /// <summary> /// Extension container element for Type /// </summary> public Element _Type { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(ActorId)) { writer.WriteString("actorId", (string)ActorId!); } if (_ActorId != null) { writer.WritePropertyName("_actorId"); _ActorId.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Type)) { writer.WriteString("type", (string)Type!); } if (_Type != null) { writer.WritePropertyName("_type"); _Type.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Name)) { writer.WriteString("name", (string)Name!); } if (_Name != null) { writer.WritePropertyName("_name"); _Name.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "actorId": ActorId = reader.GetString(); break; case "_actorId": _ActorId = new Fhir.R4.Models.Element(); _ActorId.DeserializeJson(ref reader, options); break; case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "name": Name = reader.GetString(); break; case "_name": _Name = new Fhir.R4.Models.Element(); _Name.DeserializeJson(ref reader, options); break; case "type": Type = reader.GetString(); break; case "_type": _Type = new Fhir.R4.Models.Element(); _Type.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// A specific version of the resource. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioInstanceVersion>))] public class ExampleScenarioInstanceVersion : BackboneElement, IFhirJsonSerializable { /// <summary> /// The description of the resource version. /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// The identifier of a specific version of a resource. /// </summary> public string VersionId { get; set; } /// <summary> /// Extension container element for VersionId /// </summary> public Element _VersionId { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(VersionId)) { writer.WriteString("versionId", (string)VersionId!); } if (_VersionId != null) { writer.WritePropertyName("_versionId"); _VersionId.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "versionId": VersionId = reader.GetString(); break; case "_versionId": _VersionId = new Fhir.R4.Models.Element(); _VersionId.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Resources contained in the instance (e.g. the observations contained in a bundle). /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioInstanceContainedInstance>))] public class ExampleScenarioInstanceContainedInstance : BackboneElement, IFhirJsonSerializable { /// <summary> /// Each resource contained in the instance. /// </summary> public string ResourceId { get; set; } /// <summary> /// Extension container element for ResourceId /// </summary> public Element _ResourceId { get; set; } /// <summary> /// A specific version of a resource contained in the instance. /// </summary> public string VersionId { get; set; } /// <summary> /// Extension container element for VersionId /// </summary> public Element _VersionId { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(ResourceId)) { writer.WriteString("resourceId", (string)ResourceId!); } if (_ResourceId != null) { writer.WritePropertyName("_resourceId"); _ResourceId.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(VersionId)) { writer.WriteString("versionId", (string)VersionId!); } if (_VersionId != null) { writer.WritePropertyName("_versionId"); _VersionId.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "resourceId": ResourceId = reader.GetString(); break; case "_resourceId": _ResourceId = new Fhir.R4.Models.Element(); _ResourceId.DeserializeJson(ref reader, options); break; case "versionId": VersionId = reader.GetString(); break; case "_versionId": _VersionId = new Fhir.R4.Models.Element(); _VersionId.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Each resource and each version that is present in the workflow. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioInstance>))] public class ExampleScenarioInstance : BackboneElement, IFhirJsonSerializable { /// <summary> /// Resources contained in the instance (e.g. the observations contained in a bundle). /// </summary> public List<ExampleScenarioInstanceContainedInstance> ContainedInstance { get; set; } /// <summary> /// Human-friendly description of the resource instance. /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// A short name for the resource instance. /// </summary> public string Name { get; set; } /// <summary> /// Extension container element for Name /// </summary> public Element _Name { get; set; } /// <summary> /// The id of the resource for referencing. /// </summary> public string ResourceId { get; set; } /// <summary> /// Extension container element for ResourceId /// </summary> public Element _ResourceId { get; set; } /// <summary> /// The type of the resource. /// </summary> public string ResourceType { get; set; } /// <summary> /// Extension container element for ResourceType /// </summary> public Element _ResourceType { get; set; } /// <summary> /// A specific version of the resource. /// </summary> public List<ExampleScenarioInstanceVersion> Version { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(ResourceId)) { writer.WriteString("resourceId", (string)ResourceId!); } if (_ResourceId != null) { writer.WritePropertyName("_resourceId"); _ResourceId.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(ResourceType)) { writer.WriteString("resourceType", (string)ResourceType!); } if (_ResourceType != null) { writer.WritePropertyName("_resourceType"); _ResourceType.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Name)) { writer.WriteString("name", (string)Name!); } if (_Name != null) { writer.WritePropertyName("_name"); _Name.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if ((Version != null) && (Version.Count != 0)) { writer.WritePropertyName("version"); writer.WriteStartArray(); foreach (ExampleScenarioInstanceVersion valVersion in Version) { valVersion.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((ContainedInstance != null) && (ContainedInstance.Count != 0)) { writer.WritePropertyName("containedInstance"); writer.WriteStartArray(); foreach (ExampleScenarioInstanceContainedInstance valContainedInstance in ContainedInstance) { valContainedInstance.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "containedInstance": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } ContainedInstance = new List<ExampleScenarioInstanceContainedInstance>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioInstanceContainedInstance objContainedInstance = new Fhir.R4.Models.ExampleScenarioInstanceContainedInstance(); objContainedInstance.DeserializeJson(ref reader, options); ContainedInstance.Add(objContainedInstance); if (!reader.Read()) { throw new JsonException(); } } if (ContainedInstance.Count == 0) { ContainedInstance = null; } break; case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "name": Name = reader.GetString(); break; case "_name": _Name = new Fhir.R4.Models.Element(); _Name.DeserializeJson(ref reader, options); break; case "resourceId": ResourceId = reader.GetString(); break; case "_resourceId": _ResourceId = new Fhir.R4.Models.Element(); _ResourceId.DeserializeJson(ref reader, options); break; case "resourceType": ResourceType = reader.GetString(); break; case "_resourceType": _ResourceType = new Fhir.R4.Models.Element(); _ResourceType.DeserializeJson(ref reader, options); break; case "version": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Version = new List<ExampleScenarioInstanceVersion>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioInstanceVersion objVersion = new Fhir.R4.Models.ExampleScenarioInstanceVersion(); objVersion.DeserializeJson(ref reader, options); Version.Add(objVersion); if (!reader.Read()) { throw new JsonException(); } } if (Version.Count == 0) { Version = null; } break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Each interaction or action. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioProcessStepOperation>))] public class ExampleScenarioProcessStepOperation : BackboneElement, IFhirJsonSerializable { /// <summary> /// A comment to be inserted in the diagram. /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// Who starts the transaction. /// </summary> public string Initiator { get; set; } /// <summary> /// Extension container element for Initiator /// </summary> public Element _Initiator { get; set; } /// <summary> /// Whether the initiator is deactivated right after the transaction. /// </summary> public bool? InitiatorActive { get; set; } /// <summary> /// The human-friendly name of the interaction. /// </summary> public string Name { get; set; } /// <summary> /// Extension container element for Name /// </summary> public Element _Name { get; set; } /// <summary> /// The sequential number of the interaction, e.g. 1.2.5. /// </summary> public string Number { get; set; } /// <summary> /// Extension container element for Number /// </summary> public Element _Number { get; set; } /// <summary> /// Who receives the transaction. /// </summary> public string Receiver { get; set; } /// <summary> /// Extension container element for Receiver /// </summary> public Element _Receiver { get; set; } /// <summary> /// Whether the receiver is deactivated right after the transaction. /// </summary> public bool? ReceiverActive { get; set; } /// <summary> /// Each resource instance used by the initiator. /// </summary> public ExampleScenarioInstanceContainedInstance Request { get; set; } /// <summary> /// Each resource instance used by the responder. /// </summary> public ExampleScenarioInstanceContainedInstance Response { get; set; } /// <summary> /// The type of operation - CRUD. /// </summary> public string Type { get; set; } /// <summary> /// Extension container element for Type /// </summary> public Element _Type { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(Number)) { writer.WriteString("number", (string)Number!); } if (_Number != null) { writer.WritePropertyName("_number"); _Number.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Type)) { writer.WriteString("type", (string)Type!); } if (_Type != null) { writer.WritePropertyName("_type"); _Type.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Name)) { writer.WriteString("name", (string)Name!); } if (_Name != null) { writer.WritePropertyName("_name"); _Name.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Initiator)) { writer.WriteString("initiator", (string)Initiator!); } if (_Initiator != null) { writer.WritePropertyName("_initiator"); _Initiator.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Receiver)) { writer.WriteString("receiver", (string)Receiver!); } if (_Receiver != null) { writer.WritePropertyName("_receiver"); _Receiver.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if (InitiatorActive != null) { writer.WriteBoolean("initiatorActive", (bool)InitiatorActive!); } if (ReceiverActive != null) { writer.WriteBoolean("receiverActive", (bool)ReceiverActive!); } if (Request != null) { writer.WritePropertyName("request"); Request.SerializeJson(writer, options); } if (Response != null) { writer.WritePropertyName("response"); Response.SerializeJson(writer, options); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "initiator": Initiator = reader.GetString(); break; case "_initiator": _Initiator = new Fhir.R4.Models.Element(); _Initiator.DeserializeJson(ref reader, options); break; case "initiatorActive": InitiatorActive = reader.GetBoolean(); break; case "name": Name = reader.GetString(); break; case "_name": _Name = new Fhir.R4.Models.Element(); _Name.DeserializeJson(ref reader, options); break; case "number": Number = reader.GetString(); break; case "_number": _Number = new Fhir.R4.Models.Element(); _Number.DeserializeJson(ref reader, options); break; case "receiver": Receiver = reader.GetString(); break; case "_receiver": _Receiver = new Fhir.R4.Models.Element(); _Receiver.DeserializeJson(ref reader, options); break; case "receiverActive": ReceiverActive = reader.GetBoolean(); break; case "request": Request = new Fhir.R4.Models.ExampleScenarioInstanceContainedInstance(); Request.DeserializeJson(ref reader, options); break; case "response": Response = new Fhir.R4.Models.ExampleScenarioInstanceContainedInstance(); Response.DeserializeJson(ref reader, options); break; case "type": Type = reader.GetString(); break; case "_type": _Type = new Fhir.R4.Models.Element(); _Type.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Indicates an alternative step that can be taken instead of the operations on the base step in exceptional/atypical circumstances. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioProcessStepAlternative>))] public class ExampleScenarioProcessStepAlternative : BackboneElement, IFhirJsonSerializable { /// <summary> /// A human-readable description of the alternative explaining when the alternative should occur rather than the base step. /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// What happens in each alternative option. /// </summary> public List<ExampleScenarioProcessStep> Step { get; set; } /// <summary> /// The label to display for the alternative that gives a sense of the circumstance in which the alternative should be invoked. /// </summary> public string Title { get; set; } /// <summary> /// Extension container element for Title /// </summary> public Element _Title { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(Title)) { writer.WriteString("title", (string)Title!); } if (_Title != null) { writer.WritePropertyName("_title"); _Title.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if ((Step != null) && (Step.Count != 0)) { writer.WritePropertyName("step"); writer.WriteStartArray(); foreach (ExampleScenarioProcessStep valStep in Step) { valStep.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "step": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Step = new List<ExampleScenarioProcessStep>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioProcessStep objStep = new Fhir.R4.Models.ExampleScenarioProcessStep(); objStep.DeserializeJson(ref reader, options); Step.Add(objStep); if (!reader.Read()) { throw new JsonException(); } } if (Step.Count == 0) { Step = null; } break; case "title": Title = reader.GetString(); break; case "_title": _Title = new Fhir.R4.Models.Element(); _Title.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Each step of the process. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioProcessStep>))] public class ExampleScenarioProcessStep : BackboneElement, IFhirJsonSerializable { /// <summary> /// Indicates an alternative step that can be taken instead of the operations on the base step in exceptional/atypical circumstances. /// </summary> public List<ExampleScenarioProcessStepAlternative> Alternative { get; set; } /// <summary> /// Each interaction or action. /// </summary> public ExampleScenarioProcessStepOperation Operation { get; set; } /// <summary> /// If there is a pause in the flow. /// </summary> public bool? Pause { get; set; } /// <summary> /// Nested process. /// </summary> public List<ExampleScenarioProcess> Process { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if ((Process != null) && (Process.Count != 0)) { writer.WritePropertyName("process"); writer.WriteStartArray(); foreach (ExampleScenarioProcess valProcess in Process) { valProcess.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (Pause != null) { writer.WriteBoolean("pause", (bool)Pause!); } if (Operation != null) { writer.WritePropertyName("operation"); Operation.SerializeJson(writer, options); } if ((Alternative != null) && (Alternative.Count != 0)) { writer.WritePropertyName("alternative"); writer.WriteStartArray(); foreach (ExampleScenarioProcessStepAlternative valAlternative in Alternative) { valAlternative.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "alternative": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Alternative = new List<ExampleScenarioProcessStepAlternative>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioProcessStepAlternative objAlternative = new Fhir.R4.Models.ExampleScenarioProcessStepAlternative(); objAlternative.DeserializeJson(ref reader, options); Alternative.Add(objAlternative); if (!reader.Read()) { throw new JsonException(); } } if (Alternative.Count == 0) { Alternative = null; } break; case "operation": Operation = new Fhir.R4.Models.ExampleScenarioProcessStepOperation(); Operation.DeserializeJson(ref reader, options); break; case "pause": Pause = reader.GetBoolean(); break; case "process": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Process = new List<ExampleScenarioProcess>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioProcess objProcess = new Fhir.R4.Models.ExampleScenarioProcess(); objProcess.DeserializeJson(ref reader, options); Process.Add(objProcess); if (!reader.Read()) { throw new JsonException(); } } if (Process.Count == 0) { Process = null; } break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Each major process - a group of operations. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenarioProcess>))] public class ExampleScenarioProcess : BackboneElement, IFhirJsonSerializable { /// <summary> /// A longer description of the group of operations. /// </summary> public string Description { get; set; } /// <summary> /// Extension container element for Description /// </summary> public Element _Description { get; set; } /// <summary> /// Description of final status after the process ends. /// </summary> public string PostConditions { get; set; } /// <summary> /// Extension container element for PostConditions /// </summary> public Element _PostConditions { get; set; } /// <summary> /// Description of initial status before the process starts. /// </summary> public string PreConditions { get; set; } /// <summary> /// Extension container element for PreConditions /// </summary> public Element _PreConditions { get; set; } /// <summary> /// Each step of the process. /// </summary> public List<ExampleScenarioProcessStep> Step { get; set; } /// <summary> /// The diagram title of the group of operations. /// </summary> public string Title { get; set; } /// <summary> /// Extension container element for Title /// </summary> public Element _Title { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } ((Fhir.R4.Models.BackboneElement)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(Title)) { writer.WriteString("title", (string)Title!); } if (_Title != null) { writer.WritePropertyName("_title"); _Title.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Description)) { writer.WriteString("description", (string)Description!); } if (_Description != null) { writer.WritePropertyName("_description"); _Description.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(PreConditions)) { writer.WriteString("preConditions", (string)PreConditions!); } if (_PreConditions != null) { writer.WritePropertyName("_preConditions"); _PreConditions.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(PostConditions)) { writer.WriteString("postConditions", (string)PostConditions!); } if (_PostConditions != null) { writer.WritePropertyName("_postConditions"); _PostConditions.SerializeJson(writer, options); } if ((Step != null) && (Step.Count != 0)) { writer.WritePropertyName("step"); writer.WriteStartArray(); foreach (ExampleScenarioProcessStep valStep in Step) { valStep.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "description": Description = reader.GetString(); break; case "_description": _Description = new Fhir.R4.Models.Element(); _Description.DeserializeJson(ref reader, options); break; case "postConditions": PostConditions = reader.GetString(); break; case "_postConditions": _PostConditions = new Fhir.R4.Models.Element(); _PostConditions.DeserializeJson(ref reader, options); break; case "preConditions": PreConditions = reader.GetString(); break; case "_preConditions": _PreConditions = new Fhir.R4.Models.Element(); _PreConditions.DeserializeJson(ref reader, options); break; case "step": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Step = new List<ExampleScenarioProcessStep>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioProcessStep objStep = new Fhir.R4.Models.ExampleScenarioProcessStep(); objStep.DeserializeJson(ref reader, options); Step.Add(objStep); if (!reader.Read()) { throw new JsonException(); } } if (Step.Count == 0) { Step = null; } break; case "title": Title = reader.GetString(); break; case "_title": _Title = new Fhir.R4.Models.Element(); _Title.DeserializeJson(ref reader, options); break; default: ((Fhir.R4.Models.BackboneElement)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } /// <summary> /// Example of workflow instance. /// </summary> [JsonConverter(typeof(Fhir.R4.Serialization.JsonStreamComponentConverter<ExampleScenario>))] public class ExampleScenario : DomainResource, IFhirJsonSerializable { /// <summary> /// Resource Type Name /// </summary> public string ResourceType => "ExampleScenario"; /// <summary> /// Actor participating in the resource. /// </summary> public List<ExampleScenarioActor> Actor { get; set; } /// <summary> /// May be a web site, an email address, a telephone number, etc. /// </summary> public List<ContactDetail> Contact { get; set; } /// <summary> /// nullFrequently, the copyright differs between the value set and the codes that are included. The copyright statement should clearly differentiate between these when required. /// </summary> public string Copyright { get; set; } /// <summary> /// Extension container element for Copyright /// </summary> public Element _Copyright { get; set; } /// <summary> /// Note that this is not the same as the resource last-modified-date, since the resource may be a secondary representation of the example scenario. Additional specific dates may be added as extensions or be found by consulting Provenances associated with past versions of the resource. /// </summary> public string Date { get; set; } /// <summary> /// Extension container element for Date /// </summary> public Element _Date { get; set; } /// <summary> /// Allows filtering of example scenarios that are appropriate for use versus not. /// </summary> public bool? Experimental { get; set; } /// <summary> /// Typically, this is used for identifiers that can go in an HL7 V3 II (instance identifier) data type, and can then identify this example scenario outside of FHIR, where it is not possible to use the logical URI. /// </summary> public List<Identifier> Identifier { get; set; } /// <summary> /// Each resource and each version that is present in the workflow. /// </summary> public List<ExampleScenarioInstance> Instance { get; set; } /// <summary> /// It may be possible for the example scenario to be used in jurisdictions other than those for which it was originally designed or intended. /// </summary> public List<CodeableConcept> Jurisdiction { get; set; } /// <summary> /// The name is not expected to be globally unique. The name should be a simple alphanumeric type name to ensure that it is machine-processing friendly. /// </summary> public string Name { get; set; } /// <summary> /// Extension container element for Name /// </summary> public Element _Name { get; set; } /// <summary> /// Each major process - a group of operations. /// </summary> public List<ExampleScenarioProcess> Process { get; set; } /// <summary> /// Usually an organization but may be an individual. The publisher (or steward) of the example scenario is the organization or individual primarily responsible for the maintenance and upkeep of the example scenario. This is not necessarily the same individual or organization that developed and initially authored the content. The publisher is the primary point of contact for questions or issues with the example scenario. This item SHOULD be populated unless the information is available from context. /// </summary> public string Publisher { get; set; } /// <summary> /// Extension container element for Publisher /// </summary> public Element _Publisher { get; set; } /// <summary> /// This element does not describe the usage of the example scenario. Instead, it provides traceability of ''why'' the resource is either needed or ''why'' it is defined as it is. This may be used to point to source materials or specifications that drove the structure of this example scenario. /// </summary> public string Purpose { get; set; } /// <summary> /// Extension container element for Purpose /// </summary> public Element _Purpose { get; set; } /// <summary> /// Allows filtering of example scenarios that are appropriate for use versus not. /// </summary> public string Status { get; set; } /// <summary> /// Extension container element for Status /// </summary> public Element _Status { get; set; } /// <summary> /// Can be a urn:uuid: or a urn:oid: but real http: addresses are preferred. Multiple instances may share the same URL if they have a distinct version. /// The determination of when to create a new version of a resource (same url, new version) vs. defining a new artifact is up to the author. Considerations for making this decision are found in [Technical and Business Versions](resource.html#versions). /// In some cases, the resource can no longer be found at the stated url, but the url itself cannot change. Implementations can use the [meta.source](resource.html#meta) element to indicate where the current master source of the resource can be found. /// </summary> public string Url { get; set; } /// <summary> /// Extension container element for Url /// </summary> public Element _Url { get; set; } /// <summary> /// When multiple useContexts are specified, there is no expectation that all or any of the contexts apply. /// </summary> public List<UsageContext> UseContext { get; set; } /// <summary> /// There may be different example scenario instances that have the same identifier but different versions. The version can be appended to the url in a reference to allow a reference to a particular business version of the example scenario with the format [url]|[version]. /// </summary> public string Version { get; set; } /// <summary> /// Extension container element for Version /// </summary> public Element _Version { get; set; } /// <summary> /// Another nested workflow. /// </summary> public List<string> Workflow { get; set; } /// <summary> /// Extension container element for Workflow /// </summary> public List<Element> _Workflow { get; set; } /// <summary> /// Serialize to a JSON object /// </summary> public new void SerializeJson(Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } if (!string.IsNullOrEmpty(ResourceType)) { writer.WriteString("resourceType", (string)ResourceType!); } ((Fhir.R4.Models.DomainResource)this).SerializeJson(writer, options, false); if (!string.IsNullOrEmpty(Url)) { writer.WriteString("url", (string)Url!); } if (_Url != null) { writer.WritePropertyName("_url"); _Url.SerializeJson(writer, options); } if ((Identifier != null) && (Identifier.Count != 0)) { writer.WritePropertyName("identifier"); writer.WriteStartArray(); foreach (Identifier valIdentifier in Identifier) { valIdentifier.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Version)) { writer.WriteString("version", (string)Version!); } if (_Version != null) { writer.WritePropertyName("_version"); _Version.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Name)) { writer.WriteString("name", (string)Name!); } if (_Name != null) { writer.WritePropertyName("_name"); _Name.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Status)) { writer.WriteString("status", (string)Status!); } if (_Status != null) { writer.WritePropertyName("_status"); _Status.SerializeJson(writer, options); } if (Experimental != null) { writer.WriteBoolean("experimental", (bool)Experimental!); } if (!string.IsNullOrEmpty(Date)) { writer.WriteString("date", (string)Date!); } if (_Date != null) { writer.WritePropertyName("_date"); _Date.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Publisher)) { writer.WriteString("publisher", (string)Publisher!); } if (_Publisher != null) { writer.WritePropertyName("_publisher"); _Publisher.SerializeJson(writer, options); } if ((Contact != null) && (Contact.Count != 0)) { writer.WritePropertyName("contact"); writer.WriteStartArray(); foreach (ContactDetail valContact in Contact) { valContact.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((UseContext != null) && (UseContext.Count != 0)) { writer.WritePropertyName("useContext"); writer.WriteStartArray(); foreach (UsageContext valUseContext in UseContext) { valUseContext.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Jurisdiction != null) && (Jurisdiction.Count != 0)) { writer.WritePropertyName("jurisdiction"); writer.WriteStartArray(); foreach (CodeableConcept valJurisdiction in Jurisdiction) { valJurisdiction.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (!string.IsNullOrEmpty(Copyright)) { writer.WriteString("copyright", (string)Copyright!); } if (_Copyright != null) { writer.WritePropertyName("_copyright"); _Copyright.SerializeJson(writer, options); } if (!string.IsNullOrEmpty(Purpose)) { writer.WriteString("purpose", (string)Purpose!); } if (_Purpose != null) { writer.WritePropertyName("_purpose"); _Purpose.SerializeJson(writer, options); } if ((Actor != null) && (Actor.Count != 0)) { writer.WritePropertyName("actor"); writer.WriteStartArray(); foreach (ExampleScenarioActor valActor in Actor) { valActor.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Instance != null) && (Instance.Count != 0)) { writer.WritePropertyName("instance"); writer.WriteStartArray(); foreach (ExampleScenarioInstance valInstance in Instance) { valInstance.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Process != null) && (Process.Count != 0)) { writer.WritePropertyName("process"); writer.WriteStartArray(); foreach (ExampleScenarioProcess valProcess in Process) { valProcess.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if ((Workflow != null) && (Workflow.Count != 0)) { writer.WritePropertyName("workflow"); writer.WriteStartArray(); foreach (string valWorkflow in Workflow) { writer.WriteStringValue(valWorkflow); } writer.WriteEndArray(); } if ((_Workflow != null) && (_Workflow.Count != 0)) { writer.WritePropertyName("_workflow"); writer.WriteStartArray(); foreach (Element val_Workflow in _Workflow) { val_Workflow.SerializeJson(writer, options, true); } writer.WriteEndArray(); } if (includeStartObject) { writer.WriteEndObject(); } } /// <summary> /// Deserialize a JSON property /// </summary> public new void DeserializeJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "actor": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Actor = new List<ExampleScenarioActor>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioActor objActor = new Fhir.R4.Models.ExampleScenarioActor(); objActor.DeserializeJson(ref reader, options); Actor.Add(objActor); if (!reader.Read()) { throw new JsonException(); } } if (Actor.Count == 0) { Actor = null; } break; case "contact": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Contact = new List<ContactDetail>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ContactDetail objContact = new Fhir.R4.Models.ContactDetail(); objContact.DeserializeJson(ref reader, options); Contact.Add(objContact); if (!reader.Read()) { throw new JsonException(); } } if (Contact.Count == 0) { Contact = null; } break; case "copyright": Copyright = reader.GetString(); break; case "_copyright": _Copyright = new Fhir.R4.Models.Element(); _Copyright.DeserializeJson(ref reader, options); break; case "date": Date = reader.GetString(); break; case "_date": _Date = new Fhir.R4.Models.Element(); _Date.DeserializeJson(ref reader, options); break; case "experimental": Experimental = reader.GetBoolean(); break; case "identifier": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Identifier = new List<Identifier>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.Identifier objIdentifier = new Fhir.R4.Models.Identifier(); objIdentifier.DeserializeJson(ref reader, options); Identifier.Add(objIdentifier); if (!reader.Read()) { throw new JsonException(); } } if (Identifier.Count == 0) { Identifier = null; } break; case "instance": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Instance = new List<ExampleScenarioInstance>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioInstance objInstance = new Fhir.R4.Models.ExampleScenarioInstance(); objInstance.DeserializeJson(ref reader, options); Instance.Add(objInstance); if (!reader.Read()) { throw new JsonException(); } } if (Instance.Count == 0) { Instance = null; } break; case "jurisdiction": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Jurisdiction = new List<CodeableConcept>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.CodeableConcept objJurisdiction = new Fhir.R4.Models.CodeableConcept(); objJurisdiction.DeserializeJson(ref reader, options); Jurisdiction.Add(objJurisdiction); if (!reader.Read()) { throw new JsonException(); } } if (Jurisdiction.Count == 0) { Jurisdiction = null; } break; case "name": Name = reader.GetString(); break; case "_name": _Name = new Fhir.R4.Models.Element(); _Name.DeserializeJson(ref reader, options); break; case "process": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Process = new List<ExampleScenarioProcess>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.ExampleScenarioProcess objProcess = new Fhir.R4.Models.ExampleScenarioProcess(); objProcess.DeserializeJson(ref reader, options); Process.Add(objProcess); if (!reader.Read()) { throw new JsonException(); } } if (Process.Count == 0) { Process = null; } break; case "publisher": Publisher = reader.GetString(); break; case "_publisher": _Publisher = new Fhir.R4.Models.Element(); _Publisher.DeserializeJson(ref reader, options); break; case "purpose": Purpose = reader.GetString(); break; case "_purpose": _Purpose = new Fhir.R4.Models.Element(); _Purpose.DeserializeJson(ref reader, options); break; case "status": Status = reader.GetString(); break; case "_status": _Status = new Fhir.R4.Models.Element(); _Status.DeserializeJson(ref reader, options); break; case "url": Url = reader.GetString(); break; case "_url": _Url = new Fhir.R4.Models.Element(); _Url.DeserializeJson(ref reader, options); break; case "useContext": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } UseContext = new List<UsageContext>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.UsageContext objUseContext = new Fhir.R4.Models.UsageContext(); objUseContext.DeserializeJson(ref reader, options); UseContext.Add(objUseContext); if (!reader.Read()) { throw new JsonException(); } } if (UseContext.Count == 0) { UseContext = null; } break; case "version": Version = reader.GetString(); break; case "_version": _Version = new Fhir.R4.Models.Element(); _Version.DeserializeJson(ref reader, options); break; case "workflow": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } Workflow = new List<string>(); while (reader.TokenType != JsonTokenType.EndArray) { Workflow.Add(reader.GetString()); if (!reader.Read()) { throw new JsonException(); } } if (Workflow.Count == 0) { Workflow = null; } break; case "_workflow": if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read())) { throw new JsonException(); } _Workflow = new List<Element>(); while (reader.TokenType != JsonTokenType.EndArray) { Fhir.R4.Models.Element obj_Workflow = new Fhir.R4.Models.Element(); obj_Workflow.DeserializeJson(ref reader, options); _Workflow.Add(obj_Workflow); if (!reader.Read()) { throw new JsonException(); } } if (_Workflow.Count == 0) { _Workflow = null; } break; default: ((Fhir.R4.Models.DomainResource)this).DeserializeJsonProperty(ref reader, options, propertyName); break; } } /// <summary> /// Deserialize a JSON object /// </summary> public new void DeserializeJson(ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); reader.Read(); this.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException(); } } }
28.852888
508
0.589055
[ "MIT" ]
QPC-database/fhir-codegen
test/perfTestCS/R4/Models/ExampleScenario.cs
63,938
C#
using Cysharp.Threading.Tasks; namespace Millennium.InGame.Entity.Bullet { public class PlayerBullet : BulletBase { private void Start() { var token = this.GetCancellationTokenOnDestroy(); Move(token); DestroyWhenFrameOut(token); DamageWhenEnter(token); DestroyWhenEnter(token); } } }
21.277778
61
0.592689
[ "MIT" ]
andanteyk/Millennium
Assets/Millennium/Scripts/InGame/Entity/Bullet/PlayerBullet.cs
383
C#
using IronHook.EntityFrameworkCore.Extensions; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddIronHook(opts => { opts.UseNpgsql( builder.Configuration.GetConnectionString("Default"), opts =>opts.UseIronHookNpgsqlMigrations() ); }); var app = builder.Build(); app.MigrateIronHook(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
21.230769
88
0.748792
[ "MIT" ]
FowApps/IronHook
samples/dotnet6/IronHook.Web/Program.cs
828
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="RevisionsModificationResponse.cs"> // Copyright (c) 2021 Aspose.Words for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Aspose.Words.Cloud.Sdk.Model { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Converters; /// <summary> /// The REST response with a result of the modification operations for the revisions collection (now these are acceptAll and rejectAll). /// </summary> public class RevisionsModificationResponse : WordsResponse { /// <summary> /// Gets or sets the result of the modification operations for the revisions collection. /// </summary> public ModificationOperationResult Result { 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 RevisionsModificationResponse {\n"); sb.Append(" Result: ").Append(this.Result).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
45.766667
141
0.612163
[ "MIT" ]
aspose-words-cloud/aspose-words-cloud-dotne
Aspose.Words.Cloud.Sdk/Model/RevisionsModificationResponse.cs
2,687
C#
using System.Collections.Generic; using BethanysPieShop.Models; namespace BethanysPieShop.ViewModel { public class HomeViewModel { public IEnumerable<Pie> PiesOfWeek { get; set; } } }
20.4
56
0.72549
[ "MIT" ]
makampos/BethanysPieShop
BethanysPieShop/ViewModel/HomeViewModel.cs
204
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/ntsecapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="KERB_TRANSFER_CRED_REQUEST" /> struct.</summary> public static unsafe partial class KERB_TRANSFER_CRED_REQUESTTests { /// <summary>Validates that the <see cref="KERB_TRANSFER_CRED_REQUEST" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<KERB_TRANSFER_CRED_REQUEST>(), Is.EqualTo(sizeof(KERB_TRANSFER_CRED_REQUEST))); } /// <summary>Validates that the <see cref="KERB_TRANSFER_CRED_REQUEST" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(KERB_TRANSFER_CRED_REQUEST).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="KERB_TRANSFER_CRED_REQUEST" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(KERB_TRANSFER_CRED_REQUEST), Is.EqualTo(24)); } }
39.914286
145
0.735863
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ntsecapi/KERB_TRANSFER_CRED_REQUESTTests.cs
1,399
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace movie_db_app.Application.Common.Models { public class PaginatedList<T> { public List<T> Items { get; } public int PageIndex { get; } public int TotalPages { get; } public int TotalCount { get; } public PaginatedList(List<T> items, int count, int pageIndex, int pageSize) { PageIndex = pageIndex; TotalPages = (int)Math.Ceiling(count / (double)pageSize); TotalCount = count; Items = items; } public bool HasPreviousPage => PageIndex > 1; public bool HasNextPage => PageIndex < TotalPages; public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize) { var count = await source.CountAsync(); var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); return new PaginatedList<T>(items, count, pageIndex, pageSize); } } }
30.72973
113
0.629727
[ "MIT" ]
skvlive/movie-db-app
src/Application/Common/Models/PaginatedList.cs
1,139
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Concurrent; namespace Squidex.Infrastructure { public static class Singletons<T> { private static readonly ConcurrentDictionary<string, T> Instances = new ConcurrentDictionary<string, T>(StringComparer.OrdinalIgnoreCase); public static T GetOrAdd(string key, Func<string, T> factory) { return Instances.GetOrAdd(key, factory); } public static Lazy<T> GetOrAddLazy(string key, Func<string, T> factory) { return new Lazy<T>(() => Instances.GetOrAdd(key, factory)); } } }
34.678571
146
0.509784
[ "MIT" ]
BtrJay/squidex
src/Squidex.Infrastructure/Singletons.cs
974
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. // ---------------------------------------------------------------------------------- namespace DurableTask.Core { using System; /// <summary> /// Contains retry policies that can be passed as parameters to various operations /// </summary> public class RetryOptions { /// <summary> /// Creates a new instance RetryOptions with the supplied first retry and max attempts /// </summary> /// <param name="firstRetryInterval">Timespan to wait for the first retry</param> /// <param name="maxNumberOfAttempts">Max number of attempts to retry</param> /// <exception cref="ArgumentException"></exception> public RetryOptions(TimeSpan firstRetryInterval, int maxNumberOfAttempts) { if (firstRetryInterval <= TimeSpan.Zero) { throw new ArgumentException("Invalid interval. Specify a TimeSpan value greater then TimeSpan.Zero.", nameof(firstRetryInterval)); } FirstRetryInterval = firstRetryInterval; MaxNumberOfAttempts = maxNumberOfAttempts; // Defaults MaxRetryInterval = TimeSpan.MaxValue; BackoffCoefficient = 1; RetryTimeout = TimeSpan.MaxValue; Handle = e => true; } /// <summary> /// Gets or sets the first retry interval /// </summary> public TimeSpan FirstRetryInterval { get; set; } /// <summary> /// Gets or sets the max retry interval /// defaults to TimeSpan.MaxValue /// </summary> public TimeSpan MaxRetryInterval { get; set; } /// <summary> /// Gets or sets the back-off coefficient /// defaults to 1, used to determine rate of increase of back-off /// </summary> public double BackoffCoefficient { get; set; } /// <summary> /// Gets or sets the timeout for retries /// defaults to TimeSpan.MaxValue /// </summary> public TimeSpan RetryTimeout { get; set; } /// <summary> /// Gets or sets the max number of attempts /// </summary> public int MaxNumberOfAttempts { get; set; } /// <summary> /// Gets or sets a Func to call on exception to determine if retries should proceed /// </summary> public Func<Exception, bool> Handle { get; set; } } }
39.417722
118
0.584457
[ "Apache-2.0" ]
gfrancomsft/durabletask
src/DurableTask.Core/RetryOptions.cs
3,116
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using MyGUIPlugin; using Anomalous.GuiFramework; namespace Medical.GUI { public class NotesDialog : PinableMDIDialog { private MedicalStateController stateController; private EditBox stateNameTextBox; private EditBox datePicker; private EditBox distortionWizard; private EditBox notes; private MedicalState currentState; public NotesDialog(MedicalStateController stateController) : base("DentalSim.GUI.Notes.NotesDialog.layout") { window.Visible = false; stateNameTextBox = window.findWidget("Notes/DistortionName") as EditBox; datePicker = window.findWidget("Notes/DateCreated") as EditBox; distortionWizard = window.findWidget("Notes/DistortionWizard") as EditBox; notes = window.findWidget("Notes/NotesText") as EditBox; Button save = window.findWidget("Save") as Button; save.MouseButtonClick += new MyGUIEvent(save_MouseButtonClick); this.stateController = stateController; stateController.StateChanged += new MedicalStateStatusUpdate(stateController_StateChanged); stateController.StatesCleared += new MedicalStateEvent(stateController_StatesCleared); } void stateController_StatesCleared(MedicalStateController controller) { currentState = null; stateNameTextBox.Caption = ""; datePicker.Caption = ""; distortionWizard.Caption = ""; notes.OnlyText = ""; } void stateController_StateChanged(MedicalState state) { this.currentState = state; stateNameTextBox.Caption = state.Name; datePicker.Caption = state.Notes.ProcedureDate.ToString(); distortionWizard.Caption = state.Notes.DataSource; notes.OnlyText = state.Notes.Notes; } void save_MouseButtonClick(Widget source, EventArgs e) { if (currentState != null) { currentState.Name = stateNameTextBox.Caption; currentState.Notes.Notes = notes.OnlyText; stateController.alertStateUpdated(currentState); } } } }
35.101449
104
0.627581
[ "MIT" ]
AnomalousMedical/Medical
DentalSim/GUI/Notes/NotesDialog.cs
2,424
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ using System.Fabric; using Microsoft.Extensions.Configuration; namespace DeliveryService { public static class ConfigurationExtensions { public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, ServiceContext serviceContext, string settingsJson) { // Get the Config package directory var configFolderPath = serviceContext.CodePackageActivationContext.GetConfigurationPackageObject("Config").Path; // Combine it with appsettings.json file name var appSettingsFilePath = System.IO.Path.Combine(configFolderPath, settingsJson); // Add to the builder, making sure it will be reloaded every time the file changes, e.g. during Config-only deployment builder.AddJsonFile(appSettingsFilePath, optional: false, reloadOnChange: true); // Return the builder to allow for call chaining return builder; } } }
41.766667
143
0.644054
[ "MIT" ]
MichaelEdward/microservices-reference-implementation-servicefabric
src/DeliveryService/DeliveryService/ConfigurationExtensions.cs
1,255
C#
#region copyright // Copyright (c) rubicon IT GmbH // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage ("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")]
68
158
0.781176
[ "MIT" ]
RandomEngy/LicenseHeaderManager
LicenseHeaderManager/GlobalSuppressions.cs
1,700
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 ec2-2016-11-15.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.EC2.Model { /// <summary> /// Container for the parameters to the AssociateVpcCidrBlock operation. /// Associates a CIDR block with your VPC. You can associate a secondary IPv4 CIDR block, /// an Amazon-provided IPv6 CIDR block, or an IPv6 CIDR block from an IPv6 address pool /// that you provisioned through bring your own IP addresses (<a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html">BYOIP</a>). /// The IPv6 CIDR block size is fixed at /56. /// /// /// <para> /// For more information about associating CIDR blocks with your VPC and applicable restrictions, /// see <a href="https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html#VPC_Sizing">VPC /// and Subnet Sizing</a> in the <i>Amazon Virtual Private Cloud User Guide</i>. /// </para> /// </summary> public partial class AssociateVpcCidrBlockRequest : AmazonEC2Request { private bool? _amazonProvidedIpv6CidrBlock; private string _cidrBlock; private string _ipv6CidrBlock; private string _ipv6CidrBlockNetworkBorderGroup; private string _ipv6Pool; private string _vpcId; /// <summary> /// Gets and sets the property AmazonProvidedIpv6CidrBlock. /// <para> /// Requests an Amazon-provided IPv6 CIDR block with a /56 prefix length for the VPC. /// You cannot specify the range of IPv6 addresses, or the size of the CIDR block. /// </para> /// </summary> public bool AmazonProvidedIpv6CidrBlock { get { return this._amazonProvidedIpv6CidrBlock.GetValueOrDefault(); } set { this._amazonProvidedIpv6CidrBlock = value; } } // Check to see if AmazonProvidedIpv6CidrBlock property is set internal bool IsSetAmazonProvidedIpv6CidrBlock() { return this._amazonProvidedIpv6CidrBlock.HasValue; } /// <summary> /// Gets and sets the property CidrBlock. /// <para> /// An IPv4 CIDR block to associate with the VPC. /// </para> /// </summary> public string CidrBlock { get { return this._cidrBlock; } set { this._cidrBlock = value; } } // Check to see if CidrBlock property is set internal bool IsSetCidrBlock() { return this._cidrBlock != null; } /// <summary> /// Gets and sets the property Ipv6CidrBlock. /// <para> /// An IPv6 CIDR block from the IPv6 address pool. You must also specify <code>Ipv6Pool</code> /// in the request. /// </para> /// /// <para> /// To let Amazon choose the IPv6 CIDR block for you, omit this parameter. /// </para> /// </summary> public string Ipv6CidrBlock { get { return this._ipv6CidrBlock; } set { this._ipv6CidrBlock = value; } } // Check to see if Ipv6CidrBlock property is set internal bool IsSetIpv6CidrBlock() { return this._ipv6CidrBlock != null; } /// <summary> /// Gets and sets the property Ipv6CidrBlockNetworkBorderGroup. /// <para> /// The name of the location from which we advertise the IPV6 CIDR block. Use this parameter /// to limit the CiDR block to this location. /// </para> /// /// <para> /// You must set <code>AmazonProvidedIpv6CidrBlock</code> to <code>true</code> to use /// this parameter. /// </para> /// /// <para> /// You can have one IPv6 CIDR block association per network border group. /// </para> /// </summary> public string Ipv6CidrBlockNetworkBorderGroup { get { return this._ipv6CidrBlockNetworkBorderGroup; } set { this._ipv6CidrBlockNetworkBorderGroup = value; } } // Check to see if Ipv6CidrBlockNetworkBorderGroup property is set internal bool IsSetIpv6CidrBlockNetworkBorderGroup() { return this._ipv6CidrBlockNetworkBorderGroup != null; } /// <summary> /// Gets and sets the property Ipv6Pool. /// <para> /// The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. /// </para> /// </summary> public string Ipv6Pool { get { return this._ipv6Pool; } set { this._ipv6Pool = value; } } // Check to see if Ipv6Pool property is set internal bool IsSetIpv6Pool() { return this._ipv6Pool != null; } /// <summary> /// Gets and sets the property VpcId. /// <para> /// The ID of the VPC. /// </para> /// </summary> [AWSProperty(Required=true)] public string VpcId { get { return this._vpcId; } set { this._vpcId = value; } } // Check to see if VpcId property is set internal bool IsSetVpcId() { return this._vpcId != null; } } }
34.122905
154
0.597741
[ "Apache-2.0" ]
UpendoVentures/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/AssociateVpcCidrBlockRequest.cs
6,108
C#
using System; using System.Collections.Generic; using Moq; using SB014.API.BAL; using SB014.API.DAL; using SB014.API.Domain; using SB014.API.Domain.Enums; using Xunit; namespace SB014.UnitTests.Api { public class TournamentLogic_AddBellShould { [Fact] public void SetTournamentBellCounter() { // Arrange var tournamentRepositoryFake = new Mock<ITournamentRepository>(); var mapper = Helper.SetupMapper(); var gameLogicFake = new Mock<IGameLogic>(); ITournamentLogic tournamentLogic = new TournamentLogic(tournamentRepositoryFake.Object, gameLogicFake.Object); Tournament tournament = new Tournament{ BellCounter = 0, BellStateLookupMatrix = new List<BellStateLookup> { new BellStateLookup { BellCounter = 1, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 2, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 3, State = TournamentState.InPlay } }}; // Act tournamentLogic.AddBell(tournament); // Assert Assert.NotEqual(0,tournament.BellCounter); } [Fact] public void DetermineNewTournamentState_WhenBellStateMatrixAvailable() { // Arrange var tournamentRepositoryFake = new Mock<ITournamentRepository>(); var mapper = Helper.SetupMapper(); var gameLogicFake = new Mock<IGameLogic>(); ITournamentLogic tournamentLogic = new TournamentLogic(tournamentRepositoryFake.Object, gameLogicFake.Object); Tournament tournament = new Tournament{ BellCounter = 0, BellStateLookupMatrix = new List<BellStateLookup> { new BellStateLookup { BellCounter = 1, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 2, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 3, State = TournamentState.InPlay } } }; // Act var newState = tournamentLogic.AddBell(tournament); // Assert Assert.Equal( TournamentState.PrePlay, newState.State); } [Fact] public void ResetBellCounterToInitialState_WhenNoBellStateDefinedForBellCounter() { // Arrange var tournamentRepositoryFake = new Mock<ITournamentRepository>(); var mapper = Helper.SetupMapper(); var gameLogicFake = new Mock<IGameLogic>(); ITournamentLogic tournamentLogic = new TournamentLogic(tournamentRepositoryFake.Object, gameLogicFake.Object); Tournament tournament = new Tournament{ BellCounter = 100, BellStateLookupMatrix = new List<BellStateLookup> { new BellStateLookup { BellCounter = 1, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 2, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 3, State = TournamentState.InPlay } } }; // Act var newState = tournamentLogic.AddBell(tournament); // Assert //Assert.Equal( TournamentState.PrePlay, newState.State); Assert.Equal( 1, tournament.BellCounter); } [Fact] public void ReturnInitialState_WhenNoBellStateDefinedForBellCounter() { // Arrange var tournamentRepositoryFake = new Mock<ITournamentRepository>(); var mapper = Helper.SetupMapper(); var gameLogicFake = new Mock<IGameLogic>(); ITournamentLogic tournamentLogic = new TournamentLogic(tournamentRepositoryFake.Object, gameLogicFake.Object); Tournament tournament = new Tournament{ BellCounter = 100, BellStateLookupMatrix = new List<BellStateLookup> { new BellStateLookup { BellCounter = 1, State = TournamentState.PrePlay }, new BellStateLookup { BellCounter = 2, State = TournamentState.InPlay }, new BellStateLookup { BellCounter = 3, State = TournamentState.InPlay } } }; // Act var newState = tournamentLogic.AddBell(tournament); // Assert Assert.Equal( TournamentState.PrePlay, newState.State); } } }
36.0125
122
0.481083
[ "MIT" ]
sbarrettGitHub/SB014
SB014.Tests/TournamnetLogic_AddBellShould.cs
5,762
C#
using Net.Torrent.Tracker.Common.Http; using System; using System.Globalization; using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Xunit; namespace Net.Torrent.Tracker.Common.Test { public class TrackerTests { private const string HashString = "42015d75a42af5a1b20e1118bd0b71cddbafd5e8"; private static readonly byte[] Hash = HexStringToBytes(HashString); private static readonly Uri Tracker = new Uri("http://bt2.t-ru.org/ann"); [Fact] public void ConversionCorrect() { var convertedBack = BitConverter.ToString(Hash).Replace("-", string.Empty).ToLowerInvariant(); Assert.Equal(HashString, convertedBack); } [Fact] public async Task PerformsRequest() { var peerId = GeneratePeerId(); var announcement = new AnnounceRequest(Hash, Encoding.ASCII.GetBytes(peerId), 6882, new State(0, 0, 0)); using (var httpClient = new HttpClient()) { var helper = new DefaultHttpSerializer(false); var req = new HttpRequestMessage(); req.Headers.Clear(); req.Headers.Add("User-Agent", "something"); req.RequestUri = helper.Serialize(Tracker, announcement); var response = await httpClient.SendAsync(req); Assert.True(response.IsSuccessStatusCode); var bytes = await response.Content.ReadAsByteArrayAsync(); var resp = helper.Deserialize(bytes); Assert.True(resp.Peers.Count > 0); } } private string GeneratePeerId() { using (var sha1 = SHA1.Create()) { return Encoding.ASCII.GetString(sha1.ComputeHash(Guid.NewGuid().ToByteArray())); } } private static byte[] HexStringToBytes(string s) { var span = HashString.AsSpan(); var idx = 0; var bytes = new byte[s.Length / 2]; for (var i = 0; i < span.Length - 1; i += 2) { var slice = span.Slice(i, 2); bytes[idx] = byte.Parse(slice, NumberStyles.AllowHexSpecifier); idx++; } return bytes; } } }
34.823529
116
0.572213
[ "MIT" ]
l0nley/Net.Torrent.Tracker.Common
Net.Torrent.Tracker.Common.Test/TrackerTests.cs
2,368
C#
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; namespace Blumind.Controls { public class UIStatusImage { public UIStatusImage() { SlicesLocation = new Dictionary<UIControlStatus, Point>(); } public UIStatusImage(Image image) :this() { Image = image; } public Size SliceSize { get; set; } public Image Image { get; set; } public Dictionary<UIControlStatus, Point> SlicesLocation { get; private set; } public static UIStatusImage FromHorizontal(Image image, UIControlStatus[] status) { if (image != null && status != null && status.Length > 0) return FromHorizontal(image, image.Width / status.Length, status); else return FromHorizontal(image, 0, status); } public static UIStatusImage FromHorizontal(Image image, int sliceSize, UIControlStatus[] status) { var img = new UIStatusImage(image); img.SliceSize = new Size(sliceSize, 0); if (status != null) { int p = 0; foreach (var s in status) { img.SlicesLocation[s] = new Point(p, 0); p += sliceSize; } } return img; } public static UIStatusImage FromVertical(Image image, UIControlStatus[] status) { if (image != null && status != null && status.Length > 0) return FromVertical(image, image.Height / status.Length, status); else return FromVertical(image, 0, status); } public static UIStatusImage FromVertical(Image image, int sliceSize, UIControlStatus[] status) { var img = new UIStatusImage(image); img.SliceSize = new Size(0, sliceSize); if (status != null) { int p = 0; foreach (var s in status) { img.SlicesLocation[s] = new Point(0, p); p += sliceSize; } } return img; } public Rectangle GetBounds(UIControlStatus status) { Rectangle rect; if (SlicesLocation.ContainsKey(status)) { var location = SlicesLocation[status]; rect = new Rectangle(location, SliceSize); } else { rect = Rectangle.Empty; } if (rect.Width == 0 && Image != null) rect.Width = Image.Width; if (rect.Height == 0 && Image != null) rect.Height = Image.Height; return rect; } public bool Draw(Graphics graphics, UIControlStatus status, Rectangle targetRectangle) { if (this.Image == null) return false; var rectSource = GetBounds(status); if (rectSource.Width <= 0 || rectSource.Height <= 0) return false; return PaintHelper.DrawImageInRange(graphics, Image, targetRectangle, rectSource); } public bool DrawExpand(Graphics graphics, UIControlStatus status, Rectangle targetRectangle, int padding) { return DrawExpand(graphics, status, targetRectangle, new Padding(padding)); } public bool DrawExpand(Graphics graphics, UIControlStatus status, Rectangle targetRectangle, Padding padding) { if (this.Image == null) return false; var rectSource = GetBounds(status); if (rectSource.Width <= 0 || rectSource.Height <= 0) return false; return PaintHelper.ExpandImage(graphics, Image, padding, targetRectangle, rectSource); } } }
30.310606
117
0.530117
[ "MIT" ]
Darkxiete/Blumind
Code/Blumind/Controls/Paint/UIStatusImage.cs
4,003
C#
using System; using System.Collections.Generic; using System.Text; namespace Energy.Core.Interfaces.Entities { public interface IUser { } }
14
41
0.727273
[ "MIT" ]
zsra/energy
src/Energy.Core/Interfaces/Entities/IUser.cs
156
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Grave : Frezzeble, IInteractive { [SerializeField] SpriteRenderer face; [SerializeField] Sprite[] states; [SerializeField] AudioClip soundSource; private void Start() { GameControllor.singelton.objects.Add(transform.position, this.gameObject); frozen = mainFrozen; SaveFrezze(); Invoke("springFace0", 0.05f); } void IInteractive.Interact(GameObject interactor) { if (!frozen) { if (MetaData.runnorType == MetaData.RunnorType.Respawn) { Runner cb = interactor.GetComponent<Runner>(); if (cb != null) { if (cb.respawnPoint != (Vector2)this.transform.position) { AudioSource.PlayClipAtPoint(soundSource, transform.position); cb.respawnPoint = this.transform.position; } } } } } bool upGo = true; int nState = 0; private void springFace0() { if (upGo) { nState++; if (nState == states.Length-1) { upGo = false; } } else { nState--; if (nState == 0) { upGo = true; } } face.sprite = states[nState]; float time = Random.Range(0.4f , 0.8f); Invoke("springFace0", time); } }
25.460317
85
0.485661
[ "Apache-2.0" ]
LifeLich/LudumDare46
Assets/Items/Grave.cs
1,606
C#
using ICSharpCode.AvalonEdit.Highlighting.Xshd; using MyBase; using MyBase.Logging; using MyPad.Properties; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using Unity; namespace MyPad.Models { public sealed class SyntaxService { #region インジェクション [Dependency] public ILoggerFacade Logger { get; set; } [Dependency] public IProductInfo ProductInfo { get; set; } #endregion #region プロパティ private static readonly Encoding FILE_ENCODING = new UTF8Encoding(true); public string DirectoryPath => Path.Combine(this.ProductInfo.Roaming, "xshd"); private IDictionary<string, XshdSyntaxDefinition> _definitions; public IDictionary<string, XshdSyntaxDefinition> Definitions => this._definitions ??= this.Enumerate().Distinct(d => d.Name).ToDictionary(d => d.Name, d => d); #endregion public bool Initialize(bool force) { try { if (force == false && Directory.Exists(this.DirectoryPath)) return true; Directory.CreateDirectory(this.DirectoryPath); typeof(Resources).GetProperties().Where(p => p.PropertyType == typeof(byte[])) .ForEach(p => { using var stream = new FileStream(Path.Combine(this.DirectoryPath, $"{p.Name}.xshd"), FileMode.Create, FileAccess.ReadWrite, FileShare.Read); using var writer = new BinaryWriter(stream, FILE_ENCODING); writer.Write((byte[])p.GetValue(null)); }); this.Logger.Debug($"シンタックス定義ファイルを初期化しました。: Path={this.DirectoryPath}"); return true; } catch (Exception e) { this.Logger.Log($"シンタックス定義ファイルの初期化に失敗しました。: Path={this.DirectoryPath}", Category.Warn, e); return false; } } public IEnumerable<XshdSyntaxDefinition> Enumerate() { if (Directory.Exists(this.DirectoryPath) == false) yield break; foreach (var path in Directory.EnumerateFiles(this.DirectoryPath)) { XshdSyntaxDefinition definition; try { using var reader = new XmlTextReader(path); definition = HighlightingLoader.LoadXshd(reader); } catch { continue; } yield return definition; } } } }
31.55814
165
0.555269
[ "MIT" ]
kawasawa/MyPad
MyPad/Models/SyntaxService.cs
2,832
C#
using Xunit; namespace Day9.Tests { public class UnitTest1 { [Fact] public void Task1Example() { var res = new XMASencryption("input_example.txt").invalidVal(5); Assert.Equal(127, res.val); } [Fact] public void Task1Real() { var res = new XMASencryption("input.txt").invalidVal(25); Assert.Equal(14144619, res.val); } [Fact] public void Task2Example() { var res = new XMASencryption("input_example.txt").extremesInWindowSum(127); Assert.Equal(62, res); } [Fact] public void Task2Real() { var res = new XMASencryption("input.txt").extremesInWindowSum(14144619); Assert.Equal(1766397, res); } } }
23.194444
87
0.526946
[ "MIT" ]
joelbygger/adventofcode20
c_sharp/src/Day9.Tests/unitTest1.cs
835
C#
using System.Linq; using System.Runtime.CompilerServices; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Extensions; using MicroBenchmarks; namespace System.Buffers.Tests { [BenchmarkCategory(Categories.Libraries)] [GenericTypeArguments(typeof(byte))] [GenericTypeArguments(typeof(char))] public class ReadOnlySequenceTests<T> { private const int Size = 10_000; private readonly T[] _array = ValuesGenerator.Array<T>(Size); private BufferSegment<T> _startSegment, _endSegment; private ReadOnlyMemory<T> _memory; [Benchmark] public int IterateTryGetArray() => IterateTryGet(new ReadOnlySequence<T>(_array)); [Benchmark] public int IterateForEachArray() => IterateForEach(new ReadOnlySequence<T>(_array)); [Benchmark] public int IterateGetPositionArray() => IterateGetPosition(new ReadOnlySequence<T>(_array)); [Benchmark(OperationsPerInvoke = 16)] public int FirstArray() => First(new ReadOnlySequence<T>(_array)); #if !NETFRAMEWORK && !NETCOREAPP2_1 [Benchmark(OperationsPerInvoke = 16)] public int FirstSpanArray() => FirstSpan(new ReadOnlySequence<T>(_array)); [Benchmark(OperationsPerInvoke = 16)] public int FirstSpanMemory() => FirstSpan(new ReadOnlySequence<T>(_memory)); [Benchmark(OperationsPerInvoke = 16)] public int FirstSpanSingleSegment() => FirstSpan(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [Benchmark(OperationsPerInvoke = 16)] public int FirstSpanTenSegments() => FirstSpan(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [MethodImpl(MethodImplOptions.NoInlining)] private int FirstSpan(ReadOnlySequence<T> sequence) { int consume = 0; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; consume += sequence.FirstSpan.Length; return consume; } [GlobalSetup(Targets = new [] { nameof(FirstSpanSingleSegment) })] public void SetupFirstSpanSingleSegment() => SetupSingleSegment(); [GlobalSetup(Targets = new [] { nameof(FirstSpanMemory) })] public void MemoryFirstSpanMemory() => MemorySegment(); [GlobalSetup(Targets = new [] { nameof(FirstSpanTenSegments) })] public void SetupFirstSpanTenSegments() => SetupTenSegments(); #endif [Benchmark(OperationsPerInvoke = 10)] public long SliceArray() => Slice(new ReadOnlySequence<T>(_array)); [Benchmark] public int IterateTryGetMemory() => IterateTryGet(new ReadOnlySequence<T>(_memory)); [Benchmark] public int IterateForEachMemory() => IterateForEach(new ReadOnlySequence<T>(_memory)); [Benchmark] public int IterateGetPositionMemory() => IterateGetPosition(new ReadOnlySequence<T>(_memory)); [Benchmark(OperationsPerInvoke = 16)] public int FirstMemory() => First(new ReadOnlySequence<T>(_memory)); [Benchmark(OperationsPerInvoke = 10)] public long SliceMemory() => Slice(new ReadOnlySequence<T>(_memory)); [GlobalSetup(Targets = new [] { nameof(IterateTryGetSingleSegment), nameof(IterateForEachSingleSegment), nameof(IterateGetPositionSingleSegment), nameof(FirstSingleSegment), nameof(SliceSingleSegment) })] public void SetupSingleSegment() => _startSegment = _endSegment = new BufferSegment<T>(new ReadOnlyMemory<T>(_array)); [GlobalSetup(Targets = new [] { nameof(FirstMemory), nameof(SliceMemory), nameof(IterateTryGetMemory), nameof(IterateForEachMemory), nameof(IterateGetPositionMemory) })] public void MemorySegment() => _memory = new ReadOnlyMemory<T>(_array); [Benchmark] public int IterateTryGetSingleSegment() => IterateTryGet(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [Benchmark] public int IterateForEachSingleSegment() => IterateForEach(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [Benchmark] public int IterateGetPositionSingleSegment() => IterateGetPosition(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [Benchmark(OperationsPerInvoke = 16)] public int FirstSingleSegment() => First(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [Benchmark(OperationsPerInvoke = 10)] public long SliceSingleSegment() => Slice(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size)); [GlobalSetup(Targets = new [] { nameof(IterateTryGetTenSegments), nameof(IterateForEachTenSegments), nameof(IterateGetPositionTenSegments), nameof(FirstTenSegments), nameof(SliceTenSegments) })] public void SetupTenSegments() { const int segmentsCount = 10; const int segmentSize = Size / segmentsCount; _startSegment = new BufferSegment<T>(new ReadOnlyMemory<T>(_array.Take(segmentSize).ToArray())); _endSegment = _startSegment; for (int i = 1; i < segmentsCount; i++) { _endSegment = _endSegment.Append(new ReadOnlyMemory<T>(_array.Skip(i * segmentSize).Take(Size / segmentsCount).ToArray())); } } [Benchmark] public int IterateTryGetTenSegments() => IterateTryGet(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [Benchmark] public int IterateForEachTenSegments() => IterateForEach(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [Benchmark] public int IterateGetPositionTenSegments() => IterateGetPosition(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [Benchmark(OperationsPerInvoke = 16)] public int FirstTenSegments() => First(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [Benchmark(OperationsPerInvoke = 10)] public long SliceTenSegments() => Slice(new ReadOnlySequence<T>(startSegment: _startSegment, startIndex: 0, endSegment: _endSegment, endIndex: Size / 10)); [MethodImpl(MethodImplOptions.NoInlining)] // make sure that the method does not get inlined for any of the benchmarks and we compare apples to apples private int IterateTryGet(ReadOnlySequence<T> sequence) { int consume = 0; SequencePosition position = sequence.Start; while (sequence.TryGet(ref position, out var memory)) consume += memory.Length; return consume; } [MethodImpl(MethodImplOptions.NoInlining)] private int IterateForEach(ReadOnlySequence<T> sequence) { int consume = 0; foreach (ReadOnlyMemory<T> memory in sequence) consume += memory.Length; return consume; } [MethodImpl(MethodImplOptions.NoInlining)] private int IterateGetPosition(ReadOnlySequence<T> sequence) { int consume = 0; SequencePosition position = sequence.Start; int offset = (int)(sequence.Length / 10); SequencePosition end = sequence.GetPosition(0, sequence.End); while (!position.Equals(end)) { position = sequence.GetPosition(offset, position); consume += position.GetInteger(); } return consume; } [MethodImpl(MethodImplOptions.NoInlining)] private int First(ReadOnlySequence<T> sequence) { int consume = 0; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; consume += sequence.First.Length; return consume; } [MethodImpl(MethodImplOptions.NoInlining)] private long Slice(ReadOnlySequence<T> sequence) { long consume = 0; consume += sequence.Slice(Size / 10 * 0, Size / 10).Length; // 1 consume += sequence.Slice(Size / 10 * 1, Size / 10).Length; // 2 consume += sequence.Slice(Size / 10 * 2, Size / 10).Length; // 3 consume += sequence.Slice(Size / 10 * 3, Size / 10).Length; // 4 consume += sequence.Slice(Size / 10 * 4, Size / 10).Length; // 5 consume += sequence.Slice(Size / 10 * 5, Size / 10).Length; // 6 consume += sequence.Slice(Size / 10 * 6, Size / 10).Length; // 7 consume += sequence.Slice(Size / 10 * 7, Size / 10).Length; // 8 consume += sequence.Slice(Size / 10 * 8, Size / 10).Length; // 9 consume += sequence.Slice(Size / 10 * 9, Size / 10).Length; // 10 return consume; } } internal class BufferSegment<T> : ReadOnlySequenceSegment<T> { public BufferSegment(ReadOnlyMemory<T> memory) => Memory = memory; public BufferSegment<T> Append(ReadOnlyMemory<T> memory) { var segment = new BufferSegment<T>(memory) { RunningIndex = RunningIndex + Memory.Length }; Next = segment; return segment; } } }
44.620408
212
0.649744
[ "MIT" ]
333fred/performance
src/benchmarks/micro/libraries/System.Buffers/ReadOnlySequenceTests.cs
10,932
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Net; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace System.DirectoryServices.Protocols { internal delegate DirectoryResponse GetLdapResponseCallback(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeout, bool exceptionOnTimeOut); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate Interop.BOOL QUERYCLIENTCERT(IntPtr Connection, IntPtr trusted_CAs, IntPtr* certificateHandle); public partial class LdapConnection : DirectoryConnection, IDisposable { internal enum LdapResult { LDAP_RES_SEARCH_RESULT = 0x65, LDAP_RES_SEARCH_ENTRY = 0x64, LDAP_RES_MODIFY = 0x67, LDAP_RES_ADD = 0x69, LDAP_RES_DELETE = 0x6b, LDAP_RES_MODRDN = 0x6d, LDAP_RES_COMPARE = 0x6f, LDAP_RES_REFERRAL = 0x73, LDAP_RES_EXTENDED = 0x78 } private const int LDAP_MOD_BVALUES = 0x80; internal static readonly object s_objectLock = new object(); internal static readonly Hashtable s_handleTable = new Hashtable(); private static readonly Hashtable s_asyncResultTable = Hashtable.Synchronized(new Hashtable()); private static readonly ManualResetEvent s_waitHandle = new ManualResetEvent(false); private static readonly LdapPartialResultsProcessor s_partialResultsProcessor = new LdapPartialResultsProcessor(s_waitHandle); private AuthType _connectionAuthType = AuthType.Negotiate; internal bool _needDispose = true; internal ConnectionHandle _ldapHandle; internal bool _disposed; private bool _bounded; private bool _needRebind; private bool _connected; internal QUERYCLIENTCERT _clientCertificateRoutine; public LdapConnection(string server) : this(new LdapDirectoryIdentifier(server)) { } public LdapConnection(LdapDirectoryIdentifier identifier) : this(identifier, null, AuthType.Negotiate) { } public LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential) : this(identifier, credential, AuthType.Negotiate) { } public unsafe LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType) { _directoryIdentifier = identifier; _directoryCredential = (credential != null) ? new NetworkCredential(credential.UserName, credential.Password, credential.Domain) : null; _connectionAuthType = authType; if (authType < AuthType.Anonymous || authType > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(authType), (int)authType, typeof(AuthType)); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (_directoryCredential != null && (!string.IsNullOrEmpty(_directoryCredential.Password) || !string.IsNullOrEmpty(_directoryCredential.UserName)))) { throw new ArgumentException(SR.InvalidAuthCredential); } Init(); SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } internal unsafe LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType, IntPtr handle) { _directoryIdentifier = identifier; _needDispose = false; _ldapHandle = new ConnectionHandle(handle, _needDispose); _directoryCredential = credential; _connectionAuthType = authType; SessionOptions = new LdapSessionOptions(this); _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate); } ~LdapConnection() => Dispose(false); public override TimeSpan Timeout { get => _connectionTimeOut; set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value)); } // Prevent integer overflow. if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } _connectionTimeOut = value; } } public AuthType AuthType { get => _connectionAuthType; set { if (value < AuthType.Anonymous || value > AuthType.Kerberos) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AuthType)); } // If the change is made after we have bound to the server and value is really // changed, set the flag to indicate the need to do rebind. if (_bounded && (value != _connectionAuthType)) { _needRebind = true; } _connectionAuthType = value; } } public LdapSessionOptions SessionOptions { get; } public override NetworkCredential Credential { set { if (_bounded && !SameCredential(_directoryCredential, value)) { _needRebind = true; } _directoryCredential = (value != null) ? new NetworkCredential(value.UserName, value.Password, value.Domain) : null; } } public bool AutoBind { get; set; } = true; internal bool NeedDispose { get => _needDispose; set { if (_ldapHandle != null) { _ldapHandle._needDispose = value; } _needDispose = value; } } internal void Init() { string hostname = null; string[] servers = ((LdapDirectoryIdentifier)_directoryIdentifier)?.Servers; if (servers != null && servers.Length != 0) { var temp = new StringBuilder(200); for (int i = 0; i < servers.Length; i++) { if (servers[i] != null) { temp.Append(servers[i]); if (i < servers.Length - 1) { temp.Append(' '); } } } if (temp.Length != 0) { hostname = temp.ToString(); } } InternalInitConnectionHandle(hostname); // Create a WeakReference object with the target of ldapHandle and put it into our handle table. lock (s_objectLock) { if (s_handleTable[_ldapHandle.DangerousGetHandle()] != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } s_handleTable.Add(_ldapHandle.DangerousGetHandle(), new WeakReference(this)); } } public override DirectoryResponse SendRequest(DirectoryRequest request) { // No request specific timeout is specified, use the connection timeout. return SendRequest(request, _connectionTimeOut); } public DirectoryResponse SendRequest(DirectoryRequest request, TimeSpan requestTimeout) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request is DsmlAuthRequest) { throw new NotSupportedException(SR.DsmlAuthRequestNotSupported); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { ValueTask<DirectoryResponse> vt = ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: true); Debug.Assert(vt.IsCompleted); return vt.GetAwaiter().GetResult(); } else { if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } } public IAsyncResult BeginSendRequest(DirectoryRequest request, PartialResultProcessing partialMode, AsyncCallback callback, object state) { return BeginSendRequest(request, _connectionTimeOut, partialMode, callback, state); } public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (request == null) { throw new ArgumentNullException(nameof(request)); } if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { throw new InvalidEnumArgumentException(nameof(partialMode), (int)partialMode, typeof(PartialResultProcessing)); } if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest)) { throw new NotSupportedException(SR.PartialResultsNotSupported); } if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && callback == null) { throw new ArgumentException(SR.CallBackIsNull, nameof(callback)); } int messageID = 0; int error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) { operation = LdapOperation.LdapDelete; } else if (request is AddRequest) { operation = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { operation = LdapOperation.LdapModify; } else if (request is SearchRequest) { operation = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { operation = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { operation = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { operation = LdapOperation.LdapExtendedRequest; } if (error == 0 && messageID != -1) { if (partialMode == PartialResultProcessing.NoPartialResultSupport) { var requestState = new LdapRequestState(); var asyncResult = new LdapAsyncResult(callback, state, false); requestState._ldapAsync = asyncResult; asyncResult._resultObject = requestState; s_asyncResultTable.Add(asyncResult, messageID); _ = ResponseCallback(ConstructResponseAsync(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, sync: false), requestState); static async Task ResponseCallback(ValueTask<DirectoryResponse> vt, LdapRequestState requestState) { try { DirectoryResponse response = await vt.ConfigureAwait(false); requestState._response = response; } catch (Exception e) { requestState._exception = e; requestState._response = null; } // Signal waitable object, indicate operation completed and fire callback. requestState._ldapAsync._manualResetEvent.Set(); requestState._ldapAsync._completed = true; if (requestState._ldapAsync._callback != null && !requestState._abortCalled) { requestState._ldapAsync._callback(requestState._ldapAsync); } } return asyncResult; } else { // the user registers to retrieve partial results bool partialCallback = partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback; var asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout); s_partialResultsProcessor.Add(asyncResult); return asyncResult; } } if (error == 0) { // Success code but message is -1, unexpected. error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } throw ConstructException(error, operation); } public void Abort(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } int messageId; LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } messageId = (int)(s_asyncResultTable[asyncResult]); // remove the asyncResult from our connection table s_asyncResultTable.Remove(asyncResult); } else { s_partialResultsProcessor.Remove((LdapPartialAsyncResult)asyncResult); messageId = ((LdapPartialAsyncResult)asyncResult)._messageID; } // Cancel the request. LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); LdapRequestState resultObject = result._resultObject; if (resultObject != null) { resultObject._abortCalled = true; } } public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } if (!(asyncResult is LdapPartialAsyncResult)) { throw new InvalidOperationException(SR.NoPartialResults); } return s_partialResultsProcessor.GetPartialResults((LdapPartialAsyncResult)asyncResult); } public DirectoryResponse EndSendRequest(IAsyncResult asyncResult) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } if (!(asyncResult is LdapAsyncResult)) { throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult))); } LdapAsyncResult result = (LdapAsyncResult)asyncResult; if (!result._partialResults) { // Not a partial results. if (!s_asyncResultTable.Contains(asyncResult)) { throw new ArgumentException(SR.InvalidAsyncResult); } // Remove the asyncResult from our connection table. s_asyncResultTable.Remove(asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); if (result._resultObject._exception != null) { throw result._resultObject._exception; } return result._resultObject._response; } // Deal with partial results. s_partialResultsProcessor.NeedCompleteResult((LdapPartialAsyncResult)asyncResult); asyncResult.AsyncWaitHandle.WaitOne(); return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult); } private int SendRequestHelper(DirectoryRequest request, ref int messageID) { IntPtr serverControlArray = IntPtr.Zero; LdapControl[] managedServerControls = null; IntPtr clientControlArray = IntPtr.Zero; LdapControl[] managedClientControls = null; var ptrToFree = new ArrayList(); LdapMod[] modifications = null; IntPtr modArray = IntPtr.Zero; int addModCount = 0; BerVal berValuePtr = null; IntPtr searchAttributes = IntPtr.Zero; int attributeCount = 0; int error = 0; // Connect to the server first if have not done so. if (!_connected) { Connect(); _connected = true; } // Bind if user has not turned off automatic bind, have not done so or there is a need // to do rebind, also connectionless LDAP does not need to do bind. if (AutoBind && (!_bounded || _needRebind) && ((LdapDirectoryIdentifier)Directory).Connectionless != true) { Debug.WriteLine("rebind occurs\n"); Bind(); } try { IntPtr tempPtr = IntPtr.Zero; // Build server control. managedServerControls = BuildControlArray(request.Controls, true); int structSize = Marshal.SizeOf(typeof(LdapControl)); if (managedServerControls != null) { serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1); for (int i = 0; i < managedServerControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedServerControls[i], controlPtr, false); tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // build client control managedClientControls = BuildControlArray(request.Controls, false); if (managedClientControls != null) { clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1); for (int i = 0; i < managedClientControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedClientControls[i], controlPtr, false); tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } if (request is DeleteRequest) { // It is an delete operation. error = LdapPal.DeleteDirectoryEntry(_ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID); } else if (request is ModifyDNRequest) { // It is a modify dn operation error = LdapPal.RenameDirectoryEntry( _ldapHandle, ((ModifyDNRequest)request).DistinguishedName, ((ModifyDNRequest)request).NewName, ((ModifyDNRequest)request).NewParentDistinguishedName, ((ModifyDNRequest)request).DeleteOldRdn ? 1 : 0, serverControlArray, clientControlArray, ref messageID); } else if (request is CompareRequest compareRequest) { // It is a compare request. DirectoryAttribute assertion = compareRequest.Assertion; if (assertion == null) { throw new ArgumentException(SR.WrongAssertionCompare); } if (assertion.Count != 1) { throw new ArgumentException(SR.WrongNumValuesCompare); } // Process the attribute. string stringValue = null; if (assertion[0] is byte[] byteArray) { if (byteArray != null && byteArray.Length != 0) { berValuePtr = new BerVal { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; Marshal.Copy(byteArray, 0, berValuePtr.bv_val, byteArray.Length); } } else { stringValue = assertion[0].ToString(); } // It is a compare request. error = LdapPal.CompareDirectoryEntries( _ldapHandle, ((CompareRequest)request).DistinguishedName, assertion.Name, stringValue, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is AddRequest || request is ModifyRequest) { // Build the attributes. if (request is AddRequest) { modifications = BuildAttributes(((AddRequest)request).Attributes, ptrToFree); } else { modifications = BuildAttributes(((ModifyRequest)request).Modifications, ptrToFree); } addModCount = (modifications == null ? 1 : modifications.Length + 1); modArray = Utility.AllocHGlobalIntPtrArray(addModCount); int modStructSize = Marshal.SizeOf(typeof(LdapMod)); int i = 0; for (i = 0; i < addModCount - 1; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(modStructSize); Marshal.StructureToPtr(modifications[i], controlPtr, false); tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); if (request is AddRequest) { error = LdapPal.AddDirectoryEntry( _ldapHandle, ((AddRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } else { error = LdapPal.ModifyDirectoryEntry( _ldapHandle, ((ModifyRequest)request).DistinguishedName, modArray, serverControlArray, clientControlArray, ref messageID); } } else if (request is ExtendedRequest extendedRequest) { string name = extendedRequest.RequestName; byte[] val = extendedRequest.RequestValue; // process the requestvalue if (val != null && val.Length != 0) { berValuePtr = new BerVal() { bv_len = val.Length, bv_val = Marshal.AllocHGlobal(val.Length) }; Marshal.Copy(val, 0, berValuePtr.bv_val, val.Length); } error = LdapPal.ExtendedDirectoryOperation( _ldapHandle, name, berValuePtr, serverControlArray, clientControlArray, ref messageID); } else if (request is SearchRequest searchRequest) { // Process the filter. object filter = searchRequest.Filter; if (filter != null) { // LdapConnection only supports ldap filter. if (filter is XmlDocument) { throw new ArgumentException(SR.InvalidLdapSearchRequestFilter); } } string searchRequestFilter = (string)filter; // Process the attributes. attributeCount = (searchRequest.Attributes == null ? 0 : searchRequest.Attributes.Count); if (attributeCount != 0) { searchAttributes = Utility.AllocHGlobalIntPtrArray(attributeCount + 1); int i = 0; for (i = 0; i < attributeCount; i++) { IntPtr controlPtr = LdapPal.StringToPtr(searchRequest.Attributes[i]); tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // Process the scope. int searchScope = (int)searchRequest.Scope; // Process the timelimit. int searchTimeLimit = (int)(searchRequest.TimeLimit.Ticks / TimeSpan.TicksPerSecond); // Process the alias. DereferenceAlias searchAliases = SessionOptions.DerefAlias; SessionOptions.DerefAlias = searchRequest.Aliases; try { error = LdapPal.SearchDirectory( _ldapHandle, searchRequest.DistinguishedName, searchScope, searchRequestFilter, searchAttributes, searchRequest.TypesOnly, serverControlArray, clientControlArray, searchTimeLimit, searchRequest.SizeLimit, ref messageID); } finally { // Revert back. SessionOptions.DerefAlias = searchAliases; } } else { throw new NotSupportedException(SR.InvliadRequestType); } // The asynchronous call itself timeout, this actually means that we time out the // LDAP_OPT_SEND_TIMEOUT specified in the session option wldap32 does not differentiate // that, but the application caller actually needs this information to determin what to // do with the error code if (error == (int)LdapError.TimeOut) { error = (int)LdapError.SendTimeOut; } return error; } finally { GC.KeepAlive(modifications); if (serverControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedServerControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(serverControlArray); } if (managedServerControls != null) { for (int i = 0; i < managedServerControls.Length; i++) { if (managedServerControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid); } if (managedServerControls[i].ldctl_value != null) { if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val); } } } } if (clientControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedClientControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(clientControlArray); } if (managedClientControls != null) { for (int i = 0; i < managedClientControls.Length; i++) { if (managedClientControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid); } if (managedClientControls[i].ldctl_value != null) { if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val); } } } } if (modArray != IntPtr.Zero) { // release the memory from the heap for (int i = 0; i < addModCount - 1; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(modArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(modArray); } // Free the pointers. for (int x = 0; x < ptrToFree.Count; x++) { IntPtr tempPtr = (IntPtr)ptrToFree[x]; Marshal.FreeHGlobal(tempPtr); } if (berValuePtr != null && berValuePtr.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(berValuePtr.bv_val); } if (searchAttributes != IntPtr.Zero) { for (int i = 0; i < attributeCount; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(searchAttributes, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(searchAttributes); } } } private unsafe Interop.BOOL ProcessClientCertificate(IntPtr ldapHandle, IntPtr CAs, IntPtr* certificate) { int count = ClientCertificates == null ? 0 : ClientCertificates.Count; if (count == 0 && SessionOptions._clientCertificateDelegate == null) { return Interop.BOOL.FALSE; } // If the user specify certificate through property and not though option, we don't need to check the certificate authority. if (SessionOptions._clientCertificateDelegate == null) { *certificate = ClientCertificates[0].Handle; return Interop.BOOL.TRUE; } // Processing the certificate authority. var list = new ArrayList(); if (CAs != IntPtr.Zero) { SecPkgContext_IssuerListInfoEx trustedCAs = (SecPkgContext_IssuerListInfoEx)Marshal.PtrToStructure(CAs, typeof(SecPkgContext_IssuerListInfoEx)); int issuerNumber = trustedCAs.cIssuers; for (int i = 0; i < issuerNumber; i++) { IntPtr tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i); CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB)); int dataLength = info.cbData; byte[] context = new byte[dataLength]; Marshal.Copy(info.pbData, context, 0, dataLength); list.Add(context); } } byte[][] certAuthorities = null; if (list.Count != 0) { certAuthorities = new byte[list.Count][]; for (int i = 0; i < list.Count; i++) { certAuthorities[i] = (byte[])list[i]; } } X509Certificate cert = SessionOptions._clientCertificateDelegate(this, certAuthorities); if (cert != null) { *certificate = cert.Handle; return Interop.BOOL.TRUE; } *certificate = IntPtr.Zero; return Interop.BOOL.FALSE; } private void Connect() { //Ccurrently ldap does not accept more than one certificate. if (ClientCertificates.Count > 1) { throw new InvalidOperationException(SR.InvalidClientCertificates); } // Set the certificate callback routine here if user adds the certifcate to the certificate collection. if (ClientCertificates.Count != 0) { int certError = LdapPal.SetClientCertOption(_ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _clientCertificateRoutine); if (certError != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(certError)) { string certerrorMessage = LdapErrorMappings.MapResultCode(certError); throw new LdapException(certError, certerrorMessage); } throw new LdapException(certError); } // When certificate is specified, automatic bind is disabled. AutoBind = false; } // Set the LDAP_OPT_AREC_EXCLUSIVE flag if necessary. if (((LdapDirectoryIdentifier)Directory).FullyQualifiedDnsHostName && !_setFQDNDone) { SessionOptions.SetFqdnRequired(); _setFQDNDone = true; } int error = InternalConnectToServer(); // Failed, throw an exception. if (error != (int)ResultCode.Success) { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); throw new LdapException(error, errorMessage); } throw new LdapException(error); } } public void Bind() => BindHelper(_directoryCredential, needSetCredential: false); public void Bind(NetworkCredential newCredential) => BindHelper(newCredential, needSetCredential: true); private void BindHelper(NetworkCredential newCredential, bool needSetCredential) { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } // Throw if user wants to do anonymous bind but specifies credentials. if (AuthType == AuthType.Anonymous && (newCredential != null && (!string.IsNullOrEmpty(newCredential.Password) || string.IsNullOrEmpty(newCredential.UserName)))) { throw new InvalidOperationException(SR.InvalidAuthCredential); } // Set the credential. NetworkCredential tempCredential; if (needSetCredential) { _directoryCredential = tempCredential = (newCredential != null ? new NetworkCredential(newCredential.UserName, newCredential.Password, newCredential.Domain) : null); } else { tempCredential = _directoryCredential; } // Connect to the server first. if (!_connected) { Connect(); _connected = true; } // Bind to the server. string username; string domainName; string password; if (tempCredential != null && tempCredential.UserName.Length == 0 && tempCredential.Password.Length == 0 && tempCredential.Domain.Length == 0) { // Default credentials. username = null; domainName = null; password = null; } else { username = tempCredential?.UserName; domainName = tempCredential?.Domain; password = tempCredential?.Password; } int error; if (AuthType == AuthType.Anonymous) { error = LdapPal.BindToDirectory(_ldapHandle, null, null); } else if (AuthType == AuthType.Basic) { var tempDomainName = new StringBuilder(100); if (domainName != null && domainName.Length != 0) { tempDomainName.Append(domainName); tempDomainName.Append('\\'); } tempDomainName.Append(username); error = LdapPal.BindToDirectory(_ldapHandle, tempDomainName.ToString(), password); } else { var cred = new SEC_WINNT_AUTH_IDENTITY_EX() { version = Interop.SEC_WINNT_AUTH_IDENTITY_VERSION, length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)), flags = Interop.SEC_WINNT_AUTH_IDENTITY_UNICODE }; if (AuthType == AuthType.Kerberos) { cred.packageList = Interop.MICROSOFT_KERBEROS_NAME_W; cred.packageListLength = cred.packageList.Length; } if (tempCredential != null) { cred.user = username; cred.userLength = (username == null ? 0 : username.Length); cred.domain = domainName; cred.domainLength = (domainName == null ? 0 : domainName.Length); cred.password = password; cred.passwordLength = (password == null ? 0 : password.Length); } BindMethod method = BindMethod.LDAP_AUTH_NEGOTIATE; switch (AuthType) { case AuthType.Negotiate: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Kerberos: method = BindMethod.LDAP_AUTH_NEGOTIATE; break; case AuthType.Ntlm: method = BindMethod.LDAP_AUTH_NTLM; break; case AuthType.Digest: method = BindMethod.LDAP_AUTH_DIGEST; break; case AuthType.Sicily: method = BindMethod.LDAP_AUTH_SICILY; break; case AuthType.Dpa: method = BindMethod.LDAP_AUTH_DPA; break; case AuthType.Msn: method = BindMethod.LDAP_AUTH_MSN; break; case AuthType.External: method = BindMethod.LDAP_AUTH_EXTERNAL; break; } error = InternalBind(tempCredential, cred, method); } // Failed, throw exception. if (error != (int)ResultCode.Success) { if (Utility.IsResultCode((ResultCode)error)) { string errorMessage = OperationErrorMappings.MapResultCode(error); throw new DirectoryOperationException(null, errorMessage); } else if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } throw new LdapException(error, errorMessage); } throw new LdapException(error); } // We successfully bound to the server. _bounded = true; // Rebind has been done. _needRebind = false; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // We need to remove the handle from the handle table. lock (s_objectLock) { if (_ldapHandle != null) { s_handleTable.Remove(_ldapHandle.DangerousGetHandle()); } } } // Close the ldap connection. if (_needDispose && _ldapHandle != null && !_ldapHandle.IsInvalid) { _ldapHandle.Dispose(); } _ldapHandle = null; _disposed = true; } internal static LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl) { LdapControl[] managedControls = null; if (controls != null && controls.Count != 0) { var controlList = new ArrayList(); foreach (DirectoryControl col in controls) { if (serverControl == true) { if (col.ServerSide) { controlList.Add(col); } } else if (!col.ServerSide) { controlList.Add(col); } } if (controlList.Count != 0) { int count = controlList.Count; managedControls = new LdapControl[count]; for (int i = 0; i < count; i++) { managedControls[i] = new LdapControl() { // Get the control type. ldctl_oid = LdapPal.StringToPtr(((DirectoryControl)controlList[i]).Type), // Get the control cricality. ldctl_iscritical = ((DirectoryControl)controlList[i]).IsCritical }; // Get the control value. DirectoryControl tempControl = (DirectoryControl)controlList[i]; byte[] byteControlValue = tempControl.GetValue(); if (byteControlValue == null || byteControlValue.Length == 0) { // Treat the control value as null. managedControls[i].ldctl_value = new BerVal { bv_len = 0, bv_val = IntPtr.Zero }; } else { managedControls[i].ldctl_value = new BerVal { bv_len = byteControlValue.Length, bv_val = Marshal.AllocHGlobal(sizeof(byte) * byteControlValue.Length) }; Marshal.Copy(byteControlValue, 0, managedControls[i].ldctl_value.bv_val, managedControls[i].ldctl_value.bv_len); } } } } return managedControls; } internal static LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree) { LdapMod[] attributes = null; if (directoryAttributes != null && directoryAttributes.Count != 0) { var encoder = new UTF8Encoding(); DirectoryAttributeModificationCollection modificationCollection = null; DirectoryAttributeCollection attributeCollection = null; if (directoryAttributes is DirectoryAttributeModificationCollection) { modificationCollection = (DirectoryAttributeModificationCollection)directoryAttributes; } else { attributeCollection = (DirectoryAttributeCollection)directoryAttributes; } attributes = new LdapMod[directoryAttributes.Count]; for (int i = 0; i < directoryAttributes.Count; i++) { // Get the managed attribute first. DirectoryAttribute modAttribute; if (attributeCollection != null) { modAttribute = attributeCollection[i]; } else { modAttribute = modificationCollection[i]; } attributes[i] = new LdapMod(); // Write the operation type. if (modAttribute is DirectoryAttributeModification) { attributes[i].type = (int)((DirectoryAttributeModification)modAttribute).Operation; } else { attributes[i].type = (int)DirectoryAttributeOperation.Add; } // We treat all the values as binary attributes[i].type |= LDAP_MOD_BVALUES; // Write the attribute name. attributes[i].attribute = LdapPal.StringToPtr(modAttribute.Name); // Write the values. int valuesCount = 0; BerVal[] berValues = null; if (modAttribute.Count > 0) { valuesCount = modAttribute.Count; berValues = new BerVal[valuesCount]; for (int j = 0; j < valuesCount; j++) { byte[] byteArray; if (modAttribute[j] is string) { byteArray = encoder.GetBytes((string)modAttribute[j]); } else if (modAttribute[j] is Uri) { byteArray = encoder.GetBytes(((Uri)modAttribute[j]).ToString()); } else { byteArray = (byte[])modAttribute[j]; } berValues[j] = new BerVal() { bv_len = byteArray.Length, bv_val = Marshal.AllocHGlobal(byteArray.Length) }; // need to free the memory allocated on the heap when we are done ptrToFree.Add(berValues[j].bv_val); Marshal.Copy(byteArray, 0, berValues[j].bv_val, berValues[j].bv_len); } } attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1); int structSize = Marshal.SizeOf(typeof(BerVal)); IntPtr controlPtr; IntPtr tempPtr; int m; for (m = 0; m < valuesCount; m++) { controlPtr = Marshal.AllocHGlobal(structSize); // Need to free the memory allocated on the heap when we are done. ptrToFree.Add(controlPtr); Marshal.StructureToPtr(berValues[m], controlPtr, false); tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } } return attributes; } internal async ValueTask<DirectoryResponse> ConstructResponseAsync(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut, bool sync) { var timeout = new LDAP_TIMEVAL() { tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond) }; IntPtr ldapResult = IntPtr.Zero; DirectoryResponse response = null; IntPtr requestName = IntPtr.Zero; IntPtr requestValue = IntPtr.Zero; IntPtr entryMessage; bool needAbandon = true; // processing for the partial results retrieval if (resultType != ResultAll.LDAP_MSG_ALL) { // we need to have 0 timeout as we are polling for the results and don't want to wait timeout.tv_sec = 0; timeout.tv_usec = 0; if (resultType == ResultAll.LDAP_MSG_POLLINGALL) { resultType = ResultAll.LDAP_MSG_ALL; } // when doing partial results retrieving, if ldap_result failed, we don't do ldap_abandon here. needAbandon = false; } int error; if (sync) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); } else { timeout.tv_sec = 0; timeout.tv_usec = 0; int iterationDelay = 1; // Underlying native libraries don't support callback-based function, so we will instead use polling and // use a Stopwatch to track the timeout manually. Stopwatch watch = Stopwatch.StartNew(); while (true) { error = LdapPal.GetResultFromAsyncOperation(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult); if (error != 0 || (requestTimeOut != Threading.Timeout.InfiniteTimeSpan && watch.Elapsed > requestTimeOut)) { break; } await Task.Delay(Math.Min(iterationDelay, 100)).ConfigureAwait(false); if (iterationDelay < 100) { iterationDelay *= 2; } } watch.Stop(); } if (error != -1 && error != 0) { // parsing the result int serverError = 0; try { int resultError = 0; string responseDn = null; string responseMessage = null; Uri[] responseReferral = null; DirectoryControl[] responseControl = null; // ldap_parse_result skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERRAL if (error != (int)LdapResult.LDAP_RES_SEARCH_ENTRY && error != (int)LdapResult.LDAP_RES_REFERRAL) { resultError = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl); } if (resultError == 0) { resultError = serverError; if (error == (int)LdapResult.LDAP_RES_ADD) { response = new AddResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODIFY) { response = new ModifyResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_DELETE) { response = new DeleteResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_MODRDN) { response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_COMPARE) { response = new CompareResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); } else if (error == (int)LdapResult.LDAP_RES_EXTENDED) { response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); if (resultError == (int)ResultCode.Success) { resultError = LdapPal.ParseExtendedResult(_ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/); if (resultError == 0) { string name = null; if (requestName != IntPtr.Zero) { name = LdapPal.PtrToString(requestName); } BerVal val = null; byte[] requestValueArray = null; if (requestValue != IntPtr.Zero) { val = new BerVal(); Marshal.PtrToStructure(requestValue, val); if (val.bv_len != 0 && val.bv_val != IntPtr.Zero) { requestValueArray = new byte[val.bv_len]; Marshal.Copy(val.bv_val, requestValueArray, 0, val.bv_len); } } ((ExtendedResponse)response).ResponseName = name; ((ExtendedResponse)response).ResponseValue = requestValueArray; } } } else if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT || error == (int)LdapResult.LDAP_RES_SEARCH_ENTRY || error == (int)LdapResult.LDAP_RES_REFERRAL) { response = new SearchResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral); //set the flag here so our partial result processor knows whether the search is done or not if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT) { ((SearchResponse)response).searchDone = true; } SearchResultEntryCollection searchResultEntries = new SearchResultEntryCollection(); SearchResultReferenceCollection searchResultReferences = new SearchResultReferenceCollection(); // parsing the resultentry entryMessage = LdapPal.GetFirstEntryFromResult(_ldapHandle, ldapResult); int entrycount = 0; while (entryMessage != IntPtr.Zero) { SearchResultEntry entry = ConstructEntry(entryMessage); if (entry != null) { searchResultEntries.Add(entry); } entrycount++; entryMessage = LdapPal.GetNextEntryFromResult(_ldapHandle, entryMessage); } // Parse the reference. IntPtr referenceMessage = LdapPal.GetFirstReferenceFromResult(_ldapHandle, ldapResult); while (referenceMessage != IntPtr.Zero) { SearchResultReference reference = ConstructReference(referenceMessage); if (reference != null) { searchResultReferences.Add(reference); } referenceMessage = LdapPal.GetNextReferenceFromResult(_ldapHandle, referenceMessage); } ((SearchResponse)response).Entries = searchResultEntries; ((SearchResponse)response).References = searchResultReferences; } if (resultError != (int)ResultCode.Success && resultError != (int)ResultCode.CompareFalse && resultError != (int)ResultCode.CompareTrue && resultError != (int)ResultCode.Referral && resultError != (int)ResultCode.ReferralV2) { // Throw operation exception. if (Utility.IsResultCode((ResultCode)resultError)) { throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resultError)); } else { // This should not occur. throw new DirectoryOperationException(response); } } return response; } else { // Fall through, throw the exception beow. error = resultError; } } finally { if (requestName != IntPtr.Zero) { LdapPal.FreeMemory(requestName); } if (requestValue != IntPtr.Zero) { LdapPal.FreeMemory(requestValue); } if (ldapResult != IntPtr.Zero) { LdapPal.FreeMessage(ldapResult); } } } else { // ldap_result failed if (error == 0) { if (exceptionOnTimeOut) { // Client side timeout. error = (int)LdapError.TimeOut; } else { // If we don't throw exception on time out (notification search for example), we // just return an empty response. return null; } } else { error = LdapPal.GetLastErrorFromConnection(_ldapHandle); } // Abandon the request. if (needAbandon) { LdapPal.CancelDirectoryAsyncOperation(_ldapHandle, messageId); } } // Throw the proper exception here. throw ConstructException(error, operation); } internal unsafe int ConstructParsedResult(IntPtr ldapResult, ref int serverError, ref string responseDn, ref string responseMessage, ref Uri[] responseReferral, ref DirectoryControl[] responseControl) { IntPtr dn = IntPtr.Zero; IntPtr message = IntPtr.Zero; IntPtr referral = IntPtr.Zero; IntPtr control = IntPtr.Zero; try { int resultError = LdapPal.ParseResult(_ldapHandle, ldapResult, ref serverError, ref dn, ref message, ref referral, ref control, 0 /* not free it */); if (resultError == 0) { // Parse the dn. responseDn = LdapPal.PtrToString(dn); // Parse the message. responseMessage = LdapPal.PtrToString(message); // Parse the referral. if (referral != IntPtr.Zero) { char** tempPtr = (char**)referral; char* singleReferral = tempPtr[0]; int i = 0; var referralList = new ArrayList(); while (singleReferral != null) { string s = LdapPal.PtrToString((IntPtr)singleReferral); referralList.Add(s); i++; singleReferral = tempPtr[i]; } if (referralList.Count > 0) { responseReferral = new Uri[referralList.Count]; for (int j = 0; j < referralList.Count; j++) { responseReferral[j] = new Uri((string)referralList[j]); } } } // Parse the control. if (control != IntPtr.Zero) { int i = 0; IntPtr tempControlPtr = control; IntPtr singleControl = Marshal.ReadIntPtr(tempControlPtr, 0); var controlList = new ArrayList(); while (singleControl != IntPtr.Zero) { DirectoryControl directoryControl = ConstructControl(singleControl); controlList.Add(directoryControl); i++; singleControl = Marshal.ReadIntPtr(tempControlPtr, i * IntPtr.Size); } responseControl = new DirectoryControl[controlList.Count]; controlList.CopyTo(responseControl); } } else { // we need to take care of one special case, when can't connect to the server, ldap_parse_result fails with local error if (resultError == (int)LdapError.LocalError) { int tmpResult = LdapPal.ResultToErrorCode(_ldapHandle, ldapResult, 0 /* not free it */); if (tmpResult != 0) { resultError = tmpResult; } } } return resultError; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (message != IntPtr.Zero) { LdapPal.FreeMemory(message); } if (referral != IntPtr.Zero) { LdapPal.FreeValue(referral); } if (control != IntPtr.Zero) { LdapPal.FreeDirectoryControls(control); } } } internal SearchResultEntry ConstructEntry(IntPtr entryMessage) { IntPtr dn = IntPtr.Zero; IntPtr attribute = IntPtr.Zero; IntPtr address = IntPtr.Zero; try { // Get the dn. string entryDn = null; dn = LdapPal.GetDistinguishedName(_ldapHandle, entryMessage); if (dn != IntPtr.Zero) { entryDn = LdapPal.PtrToString(dn); LdapPal.FreeMemory(dn); dn = IntPtr.Zero; } SearchResultEntry resultEntry = new SearchResultEntry(entryDn); SearchResultAttributeCollection attributes = resultEntry.Attributes; // Get attributes. attribute = LdapPal.GetFirstAttributeFromEntry(_ldapHandle, entryMessage, ref address); int tempcount = 0; while (attribute != IntPtr.Zero) { DirectoryAttribute attr = ConstructAttribute(entryMessage, attribute); attributes.Add(attr.Name, attr); LdapPal.FreeMemory(attribute); tempcount++; attribute = LdapPal.GetNextAttributeFromResult(_ldapHandle, entryMessage, address); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); address = IntPtr.Zero; } return resultEntry; } finally { if (dn != IntPtr.Zero) { LdapPal.FreeMemory(dn); } if (attribute != IntPtr.Zero) { LdapPal.FreeMemory(attribute); } if (address != IntPtr.Zero) { BerPal.FreeBerElement(address, 0); } } } internal DirectoryAttribute ConstructAttribute(IntPtr entryMessage, IntPtr attributeName) { var attribute = new DirectoryAttribute() { _isSearchResult = true }; string name = LdapPal.PtrToString(attributeName); attribute.Name = name; IntPtr valuesArray = LdapPal.GetValuesFromAttribute(_ldapHandle, entryMessage, name); try { if (valuesArray != IntPtr.Zero) { int count = 0; IntPtr tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { BerVal bervalue = new BerVal(); Marshal.PtrToStructure(tempPtr, bervalue); byte[] byteArray; if (bervalue.bv_len > 0 && bervalue.bv_val != IntPtr.Zero) { byteArray = new byte[bervalue.bv_len]; Marshal.Copy(bervalue.bv_val, byteArray, 0, bervalue.bv_len); attribute.Add(byteArray); } count++; tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count); } } } finally { if (valuesArray != IntPtr.Zero) { LdapPal.FreeAttributes(valuesArray); } } return attribute; } internal SearchResultReference ConstructReference(IntPtr referenceMessage) { IntPtr referenceArray = IntPtr.Zero; int error = LdapPal.ParseReference(_ldapHandle, referenceMessage, ref referenceArray); try { if (error == 0) { var referralList = new ArrayList(); IntPtr tempPtr; int count = 0; if (referenceArray != IntPtr.Zero) { tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); while (tempPtr != IntPtr.Zero) { string s = LdapPal.PtrToString(tempPtr); referralList.Add(s); count++; tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count); } LdapPal.FreeValue(referenceArray); referenceArray = IntPtr.Zero; } if (referralList.Count > 0) { Uri[] uris = new Uri[referralList.Count]; for (int i = 0; i < referralList.Count; i++) { uris[i] = new Uri((string)referralList[i]); } return new SearchResultReference(uris); } } } finally { if (referenceArray != IntPtr.Zero) { LdapPal.FreeValue(referenceArray); } } return null; } private DirectoryException ConstructException(int error, LdapOperation operation) { DirectoryResponse response = null; if (Utility.IsResultCode((ResultCode)error)) { if (operation == LdapOperation.LdapAdd) { response = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModify) { response = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapDelete) { response = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapModifyDn) { response = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapCompare) { response = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapSearch) { response = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } else if (operation == LdapOperation.LdapExtendedRequest) { response = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null); } string errorMessage = OperationErrorMappings.MapResultCode(error); return new DirectoryOperationException(response, errorMessage); } else { if (LdapErrorMappings.IsLdapError(error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); string serverErrorMessage = SessionOptions.ServerErrorMessage; if (!string.IsNullOrEmpty(serverErrorMessage)) { throw new LdapException(error, errorMessage, serverErrorMessage); } return new LdapException(error, errorMessage); } return new LdapException(error); } } private static DirectoryControl ConstructControl(IntPtr controlPtr) { LdapControl control = new LdapControl(); Marshal.PtrToStructure(controlPtr, control); Debug.Assert(control.ldctl_oid != IntPtr.Zero); string controlType = LdapPal.PtrToString(control.ldctl_oid); byte[] bytes = new byte[control.ldctl_value.bv_len]; Marshal.Copy(control.ldctl_value.bv_val, bytes, 0, control.ldctl_value.bv_len); bool criticality = control.ldctl_iscritical; return new DirectoryControl(controlType, bytes, criticality, true); } private static bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential) { if (oldCredential == null && newCredential == null) { return true; } else if (oldCredential == null && newCredential != null) { return false; } else if (oldCredential != null && newCredential == null) { return false; } else { if (oldCredential.Domain == newCredential.Domain && oldCredential.UserName == newCredential.UserName && oldCredential.Password == newCredential.Password) { return true; } else { return false; } } } } }
40.184853
248
0.48023
[ "MIT" ]
JensDll/runtime
src/libraries/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
80,651
C#
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Components.Authorization; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace AzureDevOpsTeamMembersVelocity.Autorization { /// <summary> /// When no authentification method is configured. This authorization handler is used. /// </summary> public class AllowAnonymousStateProvider : AuthenticationStateProvider, IHostEnvironmentAuthenticationStateProvider { private static readonly AuthenticationState _user = InstanciateUser(); /// <summary> /// This implementation return always the same user. This class should only be used in devloppement. /// </summary> /// <returns></returns> public override Task<AuthenticationState> GetAuthenticationStateAsync() { return Task.FromResult(_user); } /// <summary> /// This function do nothing. This should only be used in devloppment /// </summary> /// <param name="authenticationStateTask"></param> public void SetAuthenticationState(Task<AuthenticationState> authenticationStateTask) { } /// <summary> /// Create the default authentication state for the AllowAnonymousStateProvider /// </summary> /// <returns></returns> private static AuthenticationState InstanciateUser() { List<Claim> claims = new() { new Claim(ClaimTypes.Name, "User") }; ClaimsIdentity claimsIdentity = new(claims, CookieAuthenticationDefaults.AuthenticationScheme); ClaimsPrincipal user = new(claimsIdentity); return new AuthenticationState(user); } } }
35.36
119
0.675339
[ "MIT" ]
freddycoder/AzureDevOpsTeamMembersVelocity
AzureDevOpsTeamMembersVelocity/Autorization/AllowAnonymousStateProvider.cs
1,770
C#
using System; using System.Collections.Generic; namespace Section6.HandleQueue { public class Program { public static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.DarkMagenta; var flavio = "Flavio"; var luis = "Luis"; var fatima = "Fatima"; var fernando = "Fernando"; var queue = new CustomerQueue(); queue .Enqueue(flavio) .Enqueue(luis) .Enqueue(fatima) .Enqueue(fernando); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); Console.WriteLine(queue.Dequeue().GetOrElse("No customers")); } } public class CustomerQueue { private Queue<string> _customers = new Queue<string>(); public CustomerQueue Enqueue(string customer) { _customers.Enqueue(customer); return this; } public Maybe<string> Dequeue() { _customers.TryDequeue(out var customer); return Maybe<string>.Of(customer); } public Maybe<string> Peek() { _customers.TryPeek(out var customer); return Maybe<string>.Of(customer); } } public class Maybe<T> where T : class { private T _value; private Maybe(T value) { _value = value; } public static Maybe<T> Of(T value) { return new Maybe<T>(value); } public T GetOrElse(T value) { return _value ?? value; } } }
25.3125
74
0.519012
[ "MIT" ]
flaviogf/Cursos
alura/certificacao_csharp/Section6/Section6.HandleQueue/Program.cs
2,027
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; using Fonlow.Poco2Ts; using Fonlow.Poco2Client; namespace Poco2TsTests { public class Poco2TsHouseKeeping { [Fact] public void TestReadDataContractAttribute() { Assert.True(CherryPicking.IsCherryType(typeof(DemoWebApi.DemoData.Address), CherryPickingMethods.DataContract)); } [Fact] public void TestReadDataContractAttributePickNone() { Assert.False(CherryPicking.IsCherryType(typeof(DemoWebApi.Models.ChangePasswordBindingModel), CherryPickingMethods.DataContract)); } [Fact] public void TestReadJsonObjectAttribute() { Assert.True(CherryPicking.IsCherryType(typeof(DemoWebApi.Models.ChangePasswordBindingModel), CherryPickingMethods.NewtonsoftJson)); } [Fact] public void TestReadJsonObjectAttributePickNone() { Assert.False(CherryPicking.IsCherryType(typeof(DemoWebApi.DemoData.Address), CherryPickingMethods.NewtonsoftJson)); } [Fact] public void TestReadSerializableAttribute() { Assert.True(CherryPicking.IsCherryType(typeof(DemoWebApi.Models.ExternalLoginViewModel), CherryPickingMethods.Serializable)); } [Fact] public void TestPickTypeViaAspNet() { Assert.True(CherryPicking.IsCherryType(typeof(DemoWebApi.Models.ExternalLoginViewModel), CherryPickingMethods.AspNet)); } [Fact] public void TestPickTypeAlways() { Assert.True(CherryPicking.IsCherryType(typeof(DemoWebApi.Models.ExternalLoginViewModel), CherryPickingMethods.All)); } } }
30.576271
143
0.687361
[ "MIT" ]
Niklas007CR7/webapiclientgen
Tests/Poco2TsTestsShared/Poco2TsHouseKeeping.cs
1,806
C#
namespace Vulkan.Framework; public class ShaderResource { public VkShaderStageFlagBits Stages = new VkShaderStageFlagBits(); public ShaderResourceType Type = new ShaderResourceType(); public ShaderResourceMode Mode; public uint Set = new uint(); public uint Binding = new uint(); public uint Location = new uint(); public uint InputAttachmentIndex = new uint(); public uint VecSize = new uint(); public uint Columns = new uint(); public uint ArraySize = new uint(); public uint Offset = new uint(); public uint Size = new uint(); public uint ConstantId = new uint(); public uint Qualifiers = new uint(); public utf8string Name = ""; }
20.314286
70
0.676512
[ "BSD-3-Clause" ]
trmcnealy/Vulkan
Vulkan/Framework/ShaderResource.cs
713
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. namespace Microsoft.PowerShell.Commands { using System; using System.Collections; using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using Microsoft.PowerShell.Commands.Internal.Format; /// <summary> /// Null sink to absorb pipeline output /// </summary> [CmdletAttribute("Out", "Null", SupportsShouldProcess = false, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113366", RemotingCapability = RemotingCapability.None)] public class OutNullCommand : PSCmdlet { /// <summary> /// This parameter specifies the current pipeline object /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Do nothing /// </summary> protected override void ProcessRecord() { // explicitely overridden: // do not do any processing } } /// <summary> /// implementation for the out-default command /// this command it implicitly inject by the /// powershell host at the end of the pipeline as the /// default sink (display to console screen) /// </summary> [Cmdlet(VerbsData.Out, "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113362", RemotingCapability = RemotingCapability.None)] public class OutDefaultCommand : FrontEndCommandBase { /// <summary> /// Determines whether objects should be sent to API consumers. /// This command is automatically added to the pipeline when PowerShell is transcribing and /// invoked via API. This ensures that the objects pass through the formatting and output /// system, but can still make it to the API consumer. /// </summary> [Parameter()] public SwitchParameter Transcript { get; set; } /// <summary> /// set inner command /// </summary> public OutDefaultCommand() { this.implementation = new OutputManagerInner(); } /// <summary> /// just hook up the LineOutput interface /// </summary> protected override void BeginProcessing() { PSHostUserInterface console = this.Host.UI; ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, false, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; if (mrt != null) { mrt.MergeUnclaimedPreviousErrorResults = true; } if (Transcript) { _transcribeOnlyCookie = Host.UI.SetTranscribeOnly(); } // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. base.BeginProcessing(); if (Context.CurrentCommandProcessor.CommandRuntime.OutVarList != null) { _outVarResults = new ArrayList(); } } /// <summary> /// Process the OutVar, if set /// </summary> protected override void ProcessRecord() { if (Transcript) { WriteObject(InputObject); } // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. if (_outVarResults != null) { Object inputObjectBase = PSObject.Base(InputObject); // Ignore errors and formatting records, as those can't be captured if ( (inputObjectBase != null) && (!(inputObjectBase is ErrorRecord)) && (!inputObjectBase.GetType().FullName.StartsWith( "Microsoft.PowerShell.Commands.Internal.Format", StringComparison.OrdinalIgnoreCase))) { _outVarResults.Add(InputObject); } } base.ProcessRecord(); } /// <summary> /// Swap the outVar with what we've processed, if OutVariable is set. /// </summary> protected override void EndProcessing() { // This needs to be done directly through the command runtime, as Out-Default // doesn't actually write pipeline objects. if ((_outVarResults != null) && (_outVarResults.Count > 0)) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Clear(); foreach (Object item in _outVarResults) { Context.CurrentCommandProcessor.CommandRuntime.OutVarList.Add(item); } _outVarResults = null; } base.EndProcessing(); } /// <summary> /// Revert transcription state on Dispose /// </summary> protected override void InternalDispose() { try { base.InternalDispose(); } finally { if (_transcribeOnlyCookie != null) { _transcribeOnlyCookie.Dispose(); _transcribeOnlyCookie = null; } } } private ArrayList _outVarResults = null; private IDisposable _transcribeOnlyCookie = null; } /// <summary> /// implementation for the out-host command /// </summary> [Cmdlet(VerbsData.Out, "Host", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113365", RemotingCapability = RemotingCapability.None)] public class OutHostCommand : FrontEndCommandBase { #region Command Line Parameters /// <summary> /// non positional parameter to specify paging /// </summary> private bool _paging; #endregion /// <summary> /// constructor of OutHostCommand /// </summary> public OutHostCommand() { this.implementation = new OutputManagerInner(); } /// <summary> /// optional, non positional parameter to specify paging /// FALSE: names only /// TRUE: full info /// </summary> [Parameter] public SwitchParameter Paging { get { return _paging; } set { _paging = value; } } /// <summary> /// just hook up the LineOutput interface /// </summary> protected override void BeginProcessing() { PSHostUserInterface console = this.Host.UI; ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, _paging, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; base.BeginProcessing(); } } }
33.618605
144
0.570006
[ "MIT" ]
Francisco-Gamino/PowerShell
src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs
7,228
C#
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis. // <auto-generated/> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.BPerf.StackInformation.Etw { using System; using System.Runtime.InteropServices; using ULONG = System.UInt32; using LONG = System.Int32; using ULONGLONG = System.UInt64; using ULONG64 = System.UInt64; using LONGLONG = System.Int64; using LARGE_INTEGER = System.Int64; using USHORT = System.UInt16; using GUID = System.Guid; using UCHAR = System.Byte; using LPWSTR = System.String; [StructLayout(LayoutKind.Sequential)] public unsafe struct EVENT_RECORD { public USHORT Size; // Event Size public USHORT HeaderType; // Header Type public USHORT Flags; // Flags public USHORT EventProperty; // User given event property public ULONG ThreadId; // Thread Id public ULONG ProcessId; // Process Id public LARGE_INTEGER TimeStamp; // Event Timestamp public GUID ProviderId; // Provider Id public USHORT Id; public UCHAR Version; public UCHAR Channel; public UCHAR Level; public UCHAR Opcode; public USHORT Task; public ULONGLONG Keyword; public ULONG64 ProcessorTime; // Processor Clock public GUID ActivityId; // Activity Id public UCHAR ProcessorNumber; public UCHAR Alignment; public USHORT LoggerId; public USHORT ExtendedDataCount; // Number of extended // data items public USHORT UserDataLength; // User data length public EVENT_HEADER_EXTENDED_DATA_ITEM* ExtendedData; // Pointer to an array of extended data items public byte* UserData; // Pointer to user data public byte* UserDataFixed; // NOTE: actual field is "UserContext", but since we don't use it, using it for other purposes :-) } [StructLayout(LayoutKind.Sequential)] public struct EVENT_HEADER_EXTENDED_DATA_ITEM { public USHORT Reserved1; public USHORT ExtType; public USHORT Reserved2; public USHORT DataSize; public ULONGLONG DataPtr; } [StructLayout(LayoutKind.Sequential)] internal struct TRACE_LOGFILE_HEADER { public ULONG BufferSize; // Logger buffer size in Kbytes public ULONG Version; // Logger version public ULONG ProviderVersion; // defaults to NT version public ULONG NumberOfProcessors; // Number of Processors public LARGE_INTEGER EndTime; // Time when logger stops public ULONG TimerResolution; // assumes timer is constant!!! public ULONG MaximumFileSize; // Maximum in Mbytes public ULONG LogFileMode; // specify logfile mode public ULONG BuffersWritten; // used to file start of Circular File public ULONG StartBuffers; // Count of buffers written at start. public ULONG PointerSize; // Size of pointer type in bits public ULONG EventsLost; // Events losts during log session public ULONG CpuSpeedInMHz; // Cpu Speed in MHz public IntPtr LoggerName; public IntPtr LogFileName; public TIME_ZONE_INFORMATION TimeZone; public LARGE_INTEGER BootTime; public LARGE_INTEGER PerfFreq; // Reserved public LARGE_INTEGER StartTime; // Reserved public ULONG ReservedFlags; // ClockType public ULONG BuffersLost; } [StructLayout(LayoutKind.Sequential)] internal struct EVENT_TRACE_HEADER // overlays WNODE_HEADER { public USHORT Size; // Size of entire record public USHORT FieldTypeFlags; // Indicates valid fields public UCHAR Type; // event type public UCHAR Level; // trace instrumentation level public USHORT Version; // version of trace record public ULONG ThreadId; // Thread Id public ULONG ProcessId; // Process Id public LARGE_INTEGER TimeStamp; // time when event happens public GUID Guid; // Guid that identifies event public ULONG KernelTime; // Kernel Mode CPU ticks public ULONG UserTime; // User mode CPU ticks } [StructLayout(LayoutKind.Sequential)] internal struct EVENT_TRACE { public EVENT_TRACE_HEADER Header; // Event trace header public ULONG InstanceId; // Instance Id of this event public ULONG ParentInstanceId; // Parent Instance Id. public GUID ParentGuid; // Parent Guid; public IntPtr MofData; // Pointer to Variable Data public ULONG MofLength; // Variable Datablock Length public UCHAR ProcessorNumber; public UCHAR Alignment; public USHORT LoggerId; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct EVENT_TRACE_LOGFILEW { [MarshalAs(UnmanagedType.LPWStr)] public LPWSTR LogFileName; // Logfile Name [MarshalAs(UnmanagedType.LPWStr)] public LPWSTR LoggerName; // LoggerName public LONGLONG CurrentTime; // timestamp of last event public ULONG BuffersRead; // buffers read to date public ULONG LogFileMode; // Mode of the logfile public EVENT_TRACE CurrentEvent; // Current Event from this stream. public TRACE_LOGFILE_HEADER LogfileHeader; // logfile header structure public PEVENT_TRACE_BUFFER_CALLBACKW BufferCallback; // callback before each buffer is read // // following variables are filled for BufferCallback. // public LONG BufferSize; public LONG Filled; public LONG EventsLost; // // following needs to be propaged to each buffer // // Callback with EVENT_RECORD on Vista and above public PEVENT_RECORD_CALLBACK EventRecordCallback; public ULONG IsKernelTrace; // TRUE for kernel logfile public IntPtr Context; // reserved for internal use } [StructLayout(LayoutKind.Sequential, Size = 0xAC, CharSet = CharSet.Unicode)] internal struct TIME_ZONE_INFORMATION { public ULONG Bias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string StandardName; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U2, SizeConst = 8)] public USHORT[] StandardDate; public ULONG StandardBias; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DaylightName; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U2, SizeConst = 8)] public USHORT[] DaylightDate; public ULONG DaylightBias; } internal delegate bool PEVENT_TRACE_BUFFER_CALLBACKW([In] IntPtr logfile); internal unsafe delegate void PEVENT_RECORD_CALLBACK([In] EVENT_RECORD* eventRecord); internal static class Etw { [DllImport("advapi32.dll", EntryPoint = "OpenTraceW", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern UInt64 OpenTrace([In] [Out] ref EVENT_TRACE_LOGFILEW Logfile); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int ProcessTrace([In] ULONGLONG[] HandleArray, [In] ULONG HandleCount, [In] IntPtr StartTime, [In] IntPtr EndTime); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int CloseTrace([In] ULONGLONG TraceHandle); internal const ULONG EVENT_TRACE_FILE_MODE_NONE = 0x00000000; internal const ULONG EVENT_TRACE_FILE_MODE_SEQUENTIAL = 0x00000001; internal const ULONG EVENT_TRACE_FILE_MODE_CIRCULAR = 0x00000002; internal const ULONG EVENT_TRACE_FILE_MODE_APPEND = 0x00000004; internal const ULONG EVENT_TRACE_FILE_MODE_NEWFILE = 0x00000008; internal const USHORT EVENT_HEADER_EXT_TYPE_STACK_TRACE32 = 0x0005; internal const USHORT EVENT_HEADER_EXT_TYPE_STACK_TRACE64 = 0x0006; internal const USHORT EVENT_HEADER_FLAG_32_BIT_HEADER = 0x0020; internal const USHORT EVENT_HEADER_FLAG_64_BIT_HEADER = 0x0040; internal const USHORT EVENT_HEADER_FLAG_CLASSIC_HEADER = 0x0100; internal const ULONG PROCESS_TRACE_MODE_EVENT_RECORD = 0x10000000; internal const ULONG PROCESS_TRACE_MODE_RAW_TIMESTAMP = 0x00001000; } }
39.518349
146
0.685084
[ "MIT" ]
Bhaskers-Blu-Org2/BPerf
WebViewer/Microsoft.BPerf.StackInformation.Etw/Etw.cs
8,617
C#
namespace EFCorePowerTools.Dialogs { using Contracts.ViewModels; using Contracts.Views; using Shared.DAL; public partial class AboutDialog : IAboutDialog { public AboutDialog(ITelemetryAccess telemetryAccess, IAboutViewModel viewModel) { telemetryAccess.TrackPageView(nameof(AboutDialog)); DataContext = viewModel; viewModel.CloseRequested += (sender, args) => Close(); InitializeComponent(); } (bool ClosedByOK, object Payload) IDialog<object>.ShowAndAwaitUserResponse(bool modal) { bool closedByOkay; if (modal) { closedByOkay = ShowModal() == true; } else { closedByOkay = ShowDialog() == true; } return (closedByOkay, null); } } }
25.444444
94
0.542576
[ "MIT" ]
19317362/EFCorePowerTools
src/GUI/EFCorePowerTools/Dialogs/AboutDialog.xaml.cs
918
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using GitVersion; using NUnit.Framework; using Shouldly; namespace GitVersionCore.Tests { [TestFixture] public class GitVersionInformationGeneratorTests : TestBase { [SetUp] public void Setup() { ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestCaseAttribute>(); } [TestCase("cs")] [TestCase("fs")] [TestCase("vb")] [Category("NoMono")] [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void ShouldCreateFile(string fileExtension) { var fileSystem = new TestFileSystem(); var directory = Path.GetTempPath(); var fileName = "GitVersionInformation.g." + fileExtension; var fullPath = Path.Combine(directory, fileName); var semanticVersion = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData(5, "feature1", "commitSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; var variables = VariableProvider.GetVariablesFor(semanticVersion, new TestEffectiveConfiguration(), false); var generator = new GitVersionInformationGenerator(fileName, directory, variables, fileSystem); generator.Generate(); fileSystem.ReadAllText(fullPath).ShouldMatchApproved(c => c.SubFolder(Path.Combine("Approved", fileExtension))); } } }
34.735849
125
0.614883
[ "MIT" ]
gjsduarte/GitVersion
src/GitVersionCore.Tests/GitVersionInformationGeneratorTests.cs
1,791
C#
//********************************************************************************************************* // Written by Matthew Monroe for the US Department of Energy // Pacific Northwest National Laboratory, Richland, WA // Created 07/16/2014 // //********************************************************************************************************* using AnalysisManagerBase; using System; using System.Collections.Generic; using System.IO; using AnalysisManagerBase.AnalysisTool; using AnalysisManagerBase.JobConfig; namespace AnalysisManagerPBFGenerator { /// <summary> /// Class for creation PBF (PNNL Binary Format) files using PBFGen /// </summary> public class AnalysisToolRunnerPBFGenerator : AnalysisToolRunnerBase { private const string PBF_GEN_CONSOLE_OUTPUT = "PBFGen_ConsoleOutput.txt"; private const int PROGRESS_PCT_STARTING = 1; private const int PROGRESS_PCT_COMPLETE = 99; private string mConsoleOutputErrorMsg; private long mInstrumentFileSizeBytes; private string mResultsFilePath; private string mPbfFormatVersion; private DirectoryInfo mMSXmlCacheFolder; /// <summary> /// Generates a PBF file for the dataset /// </summary> /// <returns>CloseOutType enum indicating success or failure</returns> public override CloseOutType RunTool() { try { // Call base class for initial setup if (base.RunTool() != CloseOutType.CLOSEOUT_SUCCESS) { return CloseOutType.CLOSEOUT_FAILED; } if (mDebugLevel > 4) { LogDebug("AnalysisToolRunnerPBFGenerator.RunTool(): Enter"); } // Determine the path to the PbfGen program var progLoc = DetermineProgramLocation("PbfGenProgLoc", "PbfGen.exe"); if (string.IsNullOrWhiteSpace(progLoc)) { return CloseOutType.CLOSEOUT_FAILED; } // Store the PBFGen version info in the database if (!StoreToolVersionInfo(progLoc)) { LogError("Aborting since StoreToolVersionInfo returned false"); LogError("Error determining PBFGen version"); return CloseOutType.CLOSEOUT_FAILED; } var msXMLCacheFolderPath = mMgrParams.GetParam("MSXMLCacheFolderPath", string.Empty); mMSXmlCacheFolder = new DirectoryInfo(msXMLCacheFolderPath); if (!mMSXmlCacheFolder.Exists) { LogError("MSXmlCache folder not found: " + msXMLCacheFolderPath); return CloseOutType.CLOSEOUT_FAILED; } // Create the PBF file var processingSuccess = StartPBFFileCreation(progLoc); if (processingSuccess) { // Look for the results file var resultsFile = new FileInfo(Path.Combine(mWorkDir, mDatasetName + AnalysisResources.DOT_PBF_EXTENSION)); if (resultsFile.Exists) { // Success; validate mPbfFormatVersion if (string.IsNullOrEmpty(mPbfFormatVersion)) mPbfFormatVersion = string.Empty; var knownVersion = true; switch (mPbfFormatVersion) { case "150601": // This version is created by Pbf_Gen.exe v1.0.5311 // Make sure the output folder starts with PBF_Gen_1_191 // (which will be the case if the settings file has <item key="PbfFormatVersion" value="110569"/>) if (!mResultsDirectoryName.StartsWith("PBF_Gen_1_191")) { processingSuccess = false; } break; case "150604": // This version is created by Pbf_Gen.exe v1.0.5367 // Make sure the output folder starts with PBF_Gen_1_193 // (which will be the case if the settings file has <item key="PbfFormatVersion" value="150604"/>) if (!mResultsDirectoryName.StartsWith("PBF_Gen_1_193")) { processingSuccess = false; } break; case "150605": // This version is created by Pbf_Gen.exe v1.0.6526 // Make sure the output folder starts with PBF_Gen_1_214 // (which will be the case if the settings file has <item key="PbfFormatVersion" value="150605"/>) if (!mResultsDirectoryName.StartsWith("PBF_Gen_1_214")) { processingSuccess = false; } break; case "150608": // This version is created by Pbf_Gen.exe v1.0.5714 // Make sure the output folder starts with PBF_Gen_1_243 // (which will be the case if the settings file has <item key="PbfFormatVersion" value="150608"/>) if (!mResultsDirectoryName.StartsWith("PBF_Gen_1_243")) { processingSuccess = false; } break; default: processingSuccess = false; knownVersion = false; break; } if (!processingSuccess) { if (knownVersion) { LogError("Unrecognized PbfFormatVersion. Either create a new Settings file with PbfFormatVersion " + mPbfFormatVersion + " or update the version listed in the current, default settings file;" + " next, delete the job from the DMS_Pipeline database then update the job to use the new settings file (or reset the job)"); } else { LogError("Unrecognized PbfFormatVersion. Update file AnalysisToolRunnerPBFGenerator.cs in the PBFSpectraFileGen Plugin " + "of the Analysis Manager to add version " + mPbfFormatVersion + "; next, reset the failed job step"); } } else { // Copy the .pbf file to the MSXML cache var remoteCachefilePath = CopyFileToServerCache(mMSXmlCacheFolder.FullName, resultsFile.FullName, purgeOldFilesIfNeeded: true); if (string.IsNullOrEmpty(remoteCachefilePath)) { if (string.IsNullOrEmpty(mMessage)) { LogError("CopyFileToServerCache returned false for " + resultsFile.Name); } processingSuccess = false; } // Create the _CacheInfo.txt file var cacheInfoFilePath = resultsFile.FullName + "_CacheInfo.txt"; using (var writer = new StreamWriter(new FileStream(cacheInfoFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))) { writer.WriteLine(remoteCachefilePath); } mJobParams.AddResultFileToSkip(resultsFile.Name); } } else { if (string.IsNullOrEmpty(mMessage)) { LogError("PBF_Gen results file not found: " + resultsFile.Name); processingSuccess = false; } } } mProgress = PROGRESS_PCT_COMPLETE; // Stop the job timer mStopTime = DateTime.UtcNow; // Add the current job data to the summary file UpdateSummaryFile(); // Make sure objects are released PRISM.ProgRunner.GarbageCollectNow(); if (!processingSuccess) { // Something went wrong // In order to help diagnose things, we will move whatever files were created into the result folder, // archive it using CopyFailedResultsToArchiveDirectory, then return CloseOutType.CLOSEOUT_FAILED CopyFailedResultsToArchiveDirectory(); return CloseOutType.CLOSEOUT_FAILED; } mJobParams.AddResultFileExtensionToSkip("_ConsoleOutput.txt"); var success = CopyResultsToTransferDirectory(); return success ? CloseOutType.CLOSEOUT_SUCCESS : CloseOutType.CLOSEOUT_FAILED; } catch (Exception ex) { mMessage = "Error in AnalysisToolRunnerPBFGenerator->RunTool"; LogError(mMessage, ex); return CloseOutType.CLOSEOUT_FAILED; } } /// <summary> /// Copy failed results from the working directory to the DMS_FailedResults directory on the local computer /// </summary> public override void CopyFailedResultsToArchiveDirectory() { mJobParams.AddResultFileExtensionToSkip(AnalysisResources.DOT_PBF_EXTENSION); mJobParams.AddResultFileExtensionToSkip(AnalysisResources.DOT_RAW_EXTENSION); base.CopyFailedResultsToArchiveDirectory(); } /// <summary> /// Computes a crude estimate of % complete based on the input dataset file size and the file size of the result file /// This will always vastly underestimate the progress since the PBF file is always smaller than the .raw file /// Furthermore, it looks like all of the data in the .raw file is cached in memory and the .PBF file is not created until the very end /// and thus this progress estimation is useless /// </summary> private float EstimatePBFProgress() { try { var results = new FileInfo(mResultsFilePath); if (results.Exists && mInstrumentFileSizeBytes > 0) { var percentComplete = results.Length / (float)mInstrumentFileSizeBytes * 100; return percentComplete; } } catch (Exception) { // Ignore errors here } return 0; } /// <summary> /// Parse the PBFGen console output file to track the search progress /// </summary> /// <param name="consoleOutputFilePath"></param> private void ParseConsoleOutputFile(string consoleOutputFilePath) { // Example Console output // // Creating E:\DMS_WorkDir\Synocho_L2_1.pbf from E:\DMS_WorkDir\Synocho_L2_1.raw // PbfFormatVersion: 150601 try { if (!File.Exists(consoleOutputFilePath)) { if (mDebugLevel >= 4) { LogDebug("Console output file not found: " + consoleOutputFilePath); } return; } if (mDebugLevel >= 4) { LogDebug("Parsing file " + consoleOutputFilePath); } mConsoleOutputErrorMsg = string.Empty; using (var reader = new StreamReader(new FileStream(consoleOutputFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { while (!reader.EndOfStream) { var dataLine = reader.ReadLine(); if (!string.IsNullOrWhiteSpace(dataLine)) { var dataLineLCase = dataLine.ToLower(); if (dataLineLCase.StartsWith("error:") || dataLineLCase.Contains("unhandled exception")) { if (string.IsNullOrEmpty(mConsoleOutputErrorMsg)) { mConsoleOutputErrorMsg = "Error running PBFGen:"; } mConsoleOutputErrorMsg += "; " + dataLine; continue; } if (dataLineLCase.StartsWith("PbfFormatVersion:".ToLower())) { // Parse out the version number var version = dataLine.Substring("PbfFormatVersion:".Length).Trim(); mPbfFormatVersion = version; } } } } var progressComplete = EstimatePBFProgress(); if (mProgress < progressComplete) { mProgress = progressComplete; } } catch (Exception ex) { // Ignore errors here if (mDebugLevel >= 2) { LogError("Error parsing console output file (" + consoleOutputFilePath + ")", ex); } } } private bool StartPBFFileCreation(string progLoc) { mConsoleOutputErrorMsg = string.Empty; var rawDataTypeName = mJobParams.GetJobParameter("RawDataType", ""); var rawDataType = AnalysisResources.GetRawDataType(rawDataTypeName); if (rawDataType != AnalysisResources.RawDataTypeConstants.ThermoRawFile) { LogError("PBF generation presently only supports Thermo .Raw files"); return false; } var rawFilePath = Path.Combine(mWorkDir, mDatasetName + AnalysisResources.DOT_RAW_EXTENSION); // Cache the size of the instrument data file var instrumentFile = new FileInfo(rawFilePath); if (!instrumentFile.Exists) { LogError("Instrument data not found: " + rawFilePath); return false; } mInstrumentFileSizeBytes = instrumentFile.Length; mPbfFormatVersion = string.Empty; // Cache the full path to the expected output file mResultsFilePath = Path.Combine(mWorkDir, mDatasetName + AnalysisResources.DOT_PBF_EXTENSION); LogMessage("Running PBFGen to create the PBF file"); // Set up and execute a program runner to run PBFGen var arguments = " -s " + rawFilePath; // arguments += " -o " + mWorkDir if (mDebugLevel >= 1) { LogDebug(progLoc + arguments); } var cmdRunner = new RunDosProgram(mWorkDir, mDebugLevel); RegisterEvents(cmdRunner); cmdRunner.LoopWaiting += CmdRunner_LoopWaiting; cmdRunner.CreateNoWindow = true; cmdRunner.CacheStandardOutput = false; cmdRunner.EchoOutputToConsole = true; cmdRunner.WriteConsoleOutputToFile = true; cmdRunner.ConsoleOutputFilePath = Path.Combine(mWorkDir, PBF_GEN_CONSOLE_OUTPUT); mProgress = PROGRESS_PCT_STARTING; var success = cmdRunner.RunProgram(progLoc, arguments, "PbfGen", true); if (!cmdRunner.WriteConsoleOutputToFile) { // Write the console output to a text file Global.IdleLoop(0.25); using var writer = new StreamWriter(new FileStream(cmdRunner.ConsoleOutputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read)); writer.WriteLine(cmdRunner.CachedConsoleOutput); } if (!string.IsNullOrEmpty(mConsoleOutputErrorMsg)) { LogError(mConsoleOutputErrorMsg); } // Parse the console output file one more time to check for errors and to update mPbfFormatVersion Global.IdleLoop(0.25); ParseConsoleOutputFile(cmdRunner.ConsoleOutputFilePath); if (!string.IsNullOrEmpty(mConsoleOutputErrorMsg)) { LogError(mConsoleOutputErrorMsg); } if (!success) { LogError("Error running PBFGen to create a PBF file"); if (cmdRunner.ExitCode != 0) { LogWarning("PBFGen returned a non-zero exit code: " + cmdRunner.ExitCode); } else { LogWarning("Call to PBFGen failed (but exit code is 0)"); } return false; } mProgress = PROGRESS_PCT_COMPLETE; mStatusTools.UpdateAndWrite(mProgress); if (mDebugLevel >= 3) { LogDebug("PBF Generation Complete"); } return true; } /// <summary> /// Stores the tool version info in the database /// </summary> private bool StoreToolVersionInfo(string progLoc) { var additionalDLLs = new List<string> { "InformedProteomics.Backend.dll" }; var success = StoreDotNETToolVersionInfo(progLoc, additionalDLLs, true); return success; } private DateTime mLastConsoleOutputParse = DateTime.MinValue; /// <summary> /// Event handler for CmdRunner.LoopWaiting event /// </summary> private void CmdRunner_LoopWaiting() { UpdateStatusFile(); // Parse the console output file and estimate progress every 15 seconds if (DateTime.UtcNow.Subtract(mLastConsoleOutputParse).TotalSeconds >= 15) { mLastConsoleOutputParse = DateTime.UtcNow; ParseConsoleOutputFile(Path.Combine(mWorkDir, PBF_GEN_CONSOLE_OUTPUT)); LogProgress("PBFGenerator"); } } } }
41.54262
166
0.486087
[ "BSD-2-Clause" ]
PNNL-Comp-Mass-Spec/DMS-Analysis-Manager
Plugins/AM_PBFSpectraFileGen_PlugIn/AnalysisToolRunnerPBFGenerator.cs
19,984
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace NewPlatform.ClickHouseDataService.Tests { using System; using System.Xml; using ICSSoft.STORMNET; // *** Start programmer edit section *** (Using statements) // *** End programmer edit section *** (Using statements) /// <summary> /// cla. /// </summary> // *** Start programmer edit section *** (cla CustomAttributes) // *** End programmer edit section *** (cla CustomAttributes) [AutoAltered()] [AccessType(ICSSoft.STORMNET.AccessType.none)] public class cla : ICSSoft.STORMNET.DataObject { private string finfo; private NewPlatform.ClickHouseDataService.Tests.clb fparent; // *** Start programmer edit section *** (cla CustomMembers) // *** End programmer edit section *** (cla CustomMembers) /// <summary> /// info. /// </summary> // *** Start programmer edit section *** (cla.info CustomAttributes) // *** End programmer edit section *** (cla.info CustomAttributes) [StrLen(255)] public virtual string info { get { // *** Start programmer edit section *** (cla.info Get start) // *** End programmer edit section *** (cla.info Get start) string result = this.finfo; // *** Start programmer edit section *** (cla.info Get end) // *** End programmer edit section *** (cla.info Get end) return result; } set { // *** Start programmer edit section *** (cla.info Set start) // *** End programmer edit section *** (cla.info Set start) this.finfo = value; // *** Start programmer edit section *** (cla.info Set end) // *** End programmer edit section *** (cla.info Set end) } } /// <summary> /// cla. /// </summary> // *** Start programmer edit section *** (cla.parent CustomAttributes) // *** End programmer edit section *** (cla.parent CustomAttributes) [PropertyStorage(new string[] { "parent"})] public virtual NewPlatform.ClickHouseDataService.Tests.clb parent { get { // *** Start programmer edit section *** (cla.parent Get start) // *** End programmer edit section *** (cla.parent Get start) NewPlatform.ClickHouseDataService.Tests.clb result = this.fparent; // *** Start programmer edit section *** (cla.parent Get end) // *** End programmer edit section *** (cla.parent Get end) return result; } set { // *** Start programmer edit section *** (cla.parent Set start) // *** End programmer edit section *** (cla.parent Set start) this.fparent = value; // *** Start programmer edit section *** (cla.parent Set end) // *** End programmer edit section *** (cla.parent Set end) } } } }
33.266055
92
0.503861
[ "MIT" ]
Flexberry/NewPlatform.Flexberry.ORM.ClickHouseDataService
Tests/Objects/cla.cs
3,762
C#
/* http://www.cgsoso.com/forum-211-1.html CG搜搜 Unity3d 每日Unity3d插件免费更新 更有VIP资源! CGSOSO 主打游戏开发,影视设计等CG资源素材。 插件如若商用,请务必官网购买! daily assets update for try. U should buy the asset from home store if u use it in your project! */ #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Crypto.Utilities; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Math.Raw { internal abstract class Mod { public static void Invert(uint[] p, uint[] x, uint[] z) { int len = p.Length; if (Nat.IsZero(len, x)) throw new ArgumentException("cannot be 0", "x"); if (Nat.IsOne(len, x)) { Array.Copy(x, 0, z, 0, len); return; } uint[] u = Nat.Copy(len, x); uint[] a = Nat.Create(len); a[0] = 1; int ac = 0; if ((u[0] & 1) == 0) { InversionStep(p, u, len, a, ref ac); } if (Nat.IsOne(len, u)) { InversionResult(p, ac, a, z); return; } uint[] v = Nat.Copy(len, p); uint[] b = Nat.Create(len); int bc = 0; int uvLen = len; for (;;) { while (u[uvLen - 1] == 0 && v[uvLen - 1] == 0) { --uvLen; } if (Nat.Gte(len, u, v)) { Nat.SubFrom(len, v, u); Debug.Assert((u[0] & 1) == 0); ac += Nat.SubFrom(len, b, a) - bc; InversionStep(p, u, uvLen, a, ref ac); if (Nat.IsOne(len, u)) { InversionResult(p, ac, a, z); return; } } else { Nat.SubFrom(len, u, v); Debug.Assert((v[0] & 1) == 0); bc += Nat.SubFrom(len, a, b) - ac; InversionStep(p, v, uvLen, b, ref bc); if (Nat.IsOne(len, v)) { InversionResult(p, bc, b, z); return; } } } } public static uint[] Random(uint[] p) { int len = p.Length; Random rand = new Random(); uint[] s = Nat.Create(len); uint m = p[len - 1]; m |= m >> 1; m |= m >> 2; m |= m >> 4; m |= m >> 8; m |= m >> 16; do { byte[] bytes = new byte[len << 2]; rand.NextBytes(bytes); Pack.BE_To_UInt32(bytes, 0, s); s[len - 1] &= m; } while (Nat.Gte(len, s, p)); return s; } public static void Add(uint[] p, uint[] x, uint[] y, uint[] z) { int len = p.Length; uint c = Nat.Add(len, x, y, z); if (c != 0) { Nat.SubFrom(len, p, z); } } public static void Subtract(uint[] p, uint[] x, uint[] y, uint[] z) { int len = p.Length; int c = Nat.Sub(len, x, y, z); if (c != 0) { Nat.AddTo(len, p, z); } } private static void InversionResult(uint[] p, int ac, uint[] a, uint[] z) { if (ac < 0) { Nat.Add(p.Length, a, p, z); } else { Array.Copy(a, 0, z, 0, p.Length); } } private static void InversionStep(uint[] p, uint[] u, int uLen, uint[] x, ref int xc) { int len = p.Length; int count = 0; while (u[0] == 0) { Nat.ShiftDownWord(uLen, u, 0); count += 32; } { int zeroes = GetTrailingZeroes(u[0]); if (zeroes > 0) { Nat.ShiftDownBits(uLen, u, zeroes, 0); count += zeroes; } } for (int i = 0; i < count; ++i) { if ((x[0] & 1) != 0) { if (xc < 0) { xc += (int)Nat.AddTo(len, p, x); } else { xc += Nat.SubFrom(len, p, x); } } Debug.Assert(xc == 0 || xc == -1); Nat.ShiftDownBit(len, x, (uint)xc); } } private static int GetTrailingZeroes(uint x) { Debug.Assert(x != 0); int count = 0; while ((x & 1) == 0) { x >>= 1; ++count; } return count; } } } #endif
25.674877
93
0.348427
[ "MIT" ]
zhoumingliang/test-git-subtree
Assets/RotateMe/Scripts/Best HTTP (Pro)/BestHTTP/SecureProtocol/math/raw/Mod.cs
5,306
C#
// <auto-generated /> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace NotificationService.UnitTests.BusinessLibrary.Trackers { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using NotificationService.Contracts.Models.Trackers; using NUnit.Framework; /// <summary> /// Test class. /// </summary> /// <seealso cref=".UserConnectionTrackerBaseTests" /> [ExcludeFromCodeCoverage] public class GetUserConnectionIds_Tests : UserConnectionTrackerBaseTests { /// <summary> /// Initializes this instance. /// </summary> [SetUp] public void Initialize() => this.SetupBase(); /// <summary> /// Get the connection Ids with invalid user object indefier. /// </summary> /// <param name="userObjectIdentifier">The user object identifier.</param> [TestCase(null)] [TestCase("")] [TestCase(" ")] public void GetUserConnectionIds_WithInvalidUserObjectIndefier(string userObjectIdentifier) { string applicationName = "Some Application"; var ex = Assert.Throws<ArgumentException>(() => this.userConnectionTracker.GetUserConnectionIds(userObjectIdentifier, applicationName)); Assert.IsTrue(ex.Message.StartsWith("The user object identifier is not specified.", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Gets the user connection ids with invalid application name. /// </summary> /// <param name="applicationName">Name of the application.</param> [TestCase(null)] [TestCase("")] [TestCase(" ")] public void GetUserConnectionIds_WithInvalidApplicationName(string applicationName) { string userObjectIdentifier = Guid.NewGuid().ToString(); var ex = Assert.Throws<ArgumentException>(() => this.userConnectionTracker.GetUserConnectionIds(userObjectIdentifier, applicationName)); Assert.IsTrue(ex.Message.StartsWith("The application name is not specified.", StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Gets the user connection ids with valid inputs. /// </summary> [Test] public void GetUserConnectionIds_WithValidInputs() { string connectionId = Guid.NewGuid().ToString(); string userOid = "Test Oid"; string applicationName = "Some Application"; UserConnectionInfo userConnectionInfo = new UserConnectionInfo(connectionId, applicationName); this.userConnectionTracker.SetConnectionInfo(userOid, userConnectionInfo); this.userConnectionTracker.SetConnectionInfo(userOid, new UserConnectionInfo("some", "Browser")); var connectionIds = this.userConnectionTracker.GetUserConnectionIds(userOid, applicationName); Assert.IsTrue(connectionIds.First().Equals(userConnectionInfo.ConnectionId)); Assert.IsTrue(connectionIds.Count() == 1); } } }
42.986111
148
0.662359
[ "MIT" ]
tech4GT/notification-provider
NotificationService/NotificationService.UnitTests/BusinessLibrary/Trackers/GetUserConnectionIds_Tests.cs
3,097
C#
using NBi.GenbiL.Stateful; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.GenbiL.Action.Case { class DuplicateCaseAction : ISingleCaseAction { public string OriginalColumn { get; } public IEnumerable<string> NewColumns { get; } public DuplicateCaseAction(string originalColumn, IEnumerable<string> newColumns) { this.OriginalColumn = originalColumn; this.NewColumns = newColumns; } public void Execute(GenerationState state) => Execute(state.CaseCollection.CurrentScope); public void Execute(CaseSet testCases) { foreach (var newColumn in NewColumns) { var dataTable = testCases.Content; dataTable.Columns.Add(new DataColumn(newColumn, typeof(object)) { AllowDBNull = true, DefaultValue = DBNull.Value }); foreach (DataRow row in dataTable.Rows) if (!row.IsNull(OriginalColumn)) row[newColumn] = row[OriginalColumn]; } } public string Display => string.Format($"Duplicating column '{OriginalColumn}' as new column{(NewColumns.Count() > 1 ? "s" : string.Empty)} '{string.Join("', '", NewColumns)}'", NewColumns); } }
33.414634
198
0.634307
[ "Apache-2.0" ]
TheAutomatingMrLynch/NBi
NBi.genbiL/Action/Case/DuplicateCaseAction.cs
1,372
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 Float = System.Single; using System; using System.Linq; using System.Threading; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Internal.CpuMath; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Learners; using Microsoft.ML.Runtime.Numeric; using Microsoft.ML.Runtime.Training; using Microsoft.ML.Runtime.Internal.Internallearn; using Microsoft.ML.Core.Data; [assembly: LoadableClass(SdcaMultiClassTrainer.Summary, typeof(SdcaMultiClassTrainer), typeof(SdcaMultiClassTrainer.Arguments), new[] { typeof(SignatureMultiClassClassifierTrainer), typeof(SignatureTrainer), typeof(SignatureFeatureScorerTrainer) }, SdcaMultiClassTrainer.UserNameValue, SdcaMultiClassTrainer.LoadNameValue, SdcaMultiClassTrainer.ShortName)] namespace Microsoft.ML.Runtime.Learners { // SDCA linear multiclass trainer. /// <include file='doc.xml' path='doc/members/member[@name="SDCA"]/*' /> public class SdcaMultiClassTrainer : SdcaTrainerBase<MulticlassPredictionTransformer<MulticlassLogisticRegressionPredictor>, MulticlassLogisticRegressionPredictor> { public const string LoadNameValue = "SDCAMC"; public const string UserNameValue = "Fast Linear Multi-class Classification (SA-SDCA)"; public const string ShortName = "sasdcamc"; internal const string Summary = "The SDCA linear multi-class classification trainer."; public sealed class Arguments : ArgumentsBase { [Argument(ArgumentType.Multiple, HelpText = "Loss Function", ShortName = "loss", SortOrder = 50)] public ISupportSdcaClassificationLossFactory LossFunction = new LogLossFactory(); } private readonly ISupportSdcaClassificationLoss _loss; private readonly Arguments _args; public override PredictionKind PredictionKind => PredictionKind.MultiClassClassification; public SdcaMultiClassTrainer(IHostEnvironment env, Arguments args, string featureColumn, string labelColumn, string weightColumn = null) : base(Contracts.CheckRef(env, nameof(env)).Register(LoadNameValue), args, MakeFeatureColumn(featureColumn), MakeLabelColumn(labelColumn), MakeWeightColumn(weightColumn)) { _loss = args.LossFunction.CreateComponent(env); Loss = _loss; _args = args; } protected override SchemaShape.Column[] GetOutputColumnsCore(SchemaShape inputSchema) { bool success = inputSchema.TryFindColumn(LabelColumn.Name, out var labelCol); Contracts.Assert(success); var metadata = new SchemaShape(labelCol.Metadata.Columns.Where(x => x.Name == MetadataUtils.Kinds.KeyValues) .Concat(MetadataUtils.GetTrainerOutputMetadata())); return new[] { new SchemaShape.Column(DefaultColumnNames.Score, SchemaShape.Column.VectorKind.Vector, NumberType.R4, false, new SchemaShape(MetadataUtils.GetTrainerOutputMetadata())), new SchemaShape.Column(DefaultColumnNames.PredictedLabel, SchemaShape.Column.VectorKind.Scalar, NumberType.U4, true, metadata) }; } public SdcaMultiClassTrainer(IHostEnvironment env, Arguments args) : this(env, args, args.FeatureColumn, args.LabelColumn) { } protected override void CheckLabelCompatible(SchemaShape.Column labelCol) { Contracts.AssertValue(labelCol); Action error = () => throw Host.ExceptSchemaMismatch(nameof(labelCol), RoleMappedSchema.ColumnRole.Label.Value, labelCol.Name, "R8, R4 or a Key", labelCol.GetTypeString()); if (labelCol.Kind != SchemaShape.Column.VectorKind.Scalar) error(); if (!labelCol.IsKey && labelCol.ItemType != NumberType.R4 && labelCol.ItemType != NumberType.R8) error(); } private static SchemaShape.Column MakeWeightColumn(string weightColumn) { if (weightColumn == null) return null; return new SchemaShape.Column(weightColumn, SchemaShape.Column.VectorKind.Scalar, NumberType.R4, false); } private static SchemaShape.Column MakeLabelColumn(string labelColumn) { return new SchemaShape.Column(labelColumn, SchemaShape.Column.VectorKind.Scalar, NumberType.U4, true); } private static SchemaShape.Column MakeFeatureColumn(string featureColumn) { return new SchemaShape.Column(featureColumn, SchemaShape.Column.VectorKind.Vector, NumberType.R4, false); } /// <inheritdoc/> protected override void TrainWithoutLock(IProgressChannelProvider progress, FloatLabelCursor.Factory cursorFactory, IRandom rand, IdToIdxLookup idToIdx, int numThreads, DualsTableBase duals, Float[] biasReg, Float[] invariants, Float lambdaNInv, VBuffer<Float>[] weights, Float[] biasUnreg, VBuffer<Float>[] l1IntermediateWeights, Float[] l1IntermediateBias, Float[] featureNormSquared) { Contracts.AssertValueOrNull(progress); Contracts.Assert(_args.L1Threshold.HasValue); Contracts.AssertValueOrNull(idToIdx); Contracts.AssertValueOrNull(invariants); Contracts.AssertValueOrNull(featureNormSquared); int numClasses = Utils.Size(weights); Contracts.Assert(Utils.Size(biasReg) == numClasses); Contracts.Assert(Utils.Size(biasUnreg) == numClasses); int maxUpdateTrials = 2 * numThreads; var l1Threshold = _args.L1Threshold.Value; bool l1ThresholdZero = l1Threshold == 0; var lr = _args.BiasLearningRate * _args.L2Const.Value; var pch = progress != null ? progress.StartProgressChannel("Dual update") : null; using (pch) using (var cursor = _args.Shuffle ? cursorFactory.Create(rand) : cursorFactory.Create()) { long rowCount = 0; if (pch != null) pch.SetHeader(new ProgressHeader("examples"), e => e.SetProgress(0, rowCount)); Func<UInt128, long> getIndexFromId = GetIndexFromIdGetter(idToIdx, biasReg.Length); while (cursor.MoveNext()) { long idx = getIndexFromId(cursor.Id); long dualIndexInitPos = idx * numClasses; var features = cursor.Features; var label = (int)cursor.Label; Float invariant; Float normSquared; if (invariants != null) { invariant = invariants[idx]; Contracts.AssertValue(featureNormSquared); normSquared = featureNormSquared[idx]; } else { normSquared = VectorUtils.NormSquared(features); if (_args.BiasLearningRate == 0) normSquared += 1; invariant = _loss.ComputeDualUpdateInvariant(2 * normSquared * lambdaNInv * GetInstanceWeight(cursor)); } // The output for the label class using current weights and bias. var labelOutput = WDot(ref features, ref weights[label], biasReg[label] + biasUnreg[label]); var instanceWeight = GetInstanceWeight(cursor); // This will be the new dual variable corresponding to the label class. Float labelDual = 0; // This will be used to update the weights and regularized bias corresponding to the label class. Float labelPrimalUpdate = 0; // This will be used to update the unregularized bias corresponding to the label class. Float labelAdjustment = 0; // Iterates through all classes. for (int iClass = 0; iClass < numClasses; iClass++) { // Skip the dual/weights/bias update for label class. Will be taken care of at the end. if (iClass == label) continue; // Loop trials for compare-and-swap updates of duals. // In general, concurrent update conflict to the same dual variable is rare // if data is shuffled. for (int numTrials = 0; numTrials < maxUpdateTrials; numTrials++) { long dualIndex = iClass + dualIndexInitPos; var dual = duals[dualIndex]; var output = labelOutput + labelPrimalUpdate * normSquared - WDot(ref features, ref weights[iClass], biasReg[iClass] + biasUnreg[iClass]); var dualUpdate = _loss.DualUpdate(output, 1, dual, invariant, numThreads); // The successive over-relaxation apporach to adjust the sum of dual variables (biasReg) to zero. // Reference to details: http://stat.rutgers.edu/home/tzhang/papers/ml02_dual.pdf, pp. 16-17. var adjustment = l1ThresholdZero ? lr * biasReg[iClass] : lr * l1IntermediateBias[iClass]; dualUpdate -= adjustment; bool success = false; duals.ApplyAt(dualIndex, (long index, ref Float value) => success = Interlocked.CompareExchange(ref value, dual + dualUpdate, dual) == dual); if (success) { // Note: dualConstraint[iClass] = lambdaNInv * (sum of duals[iClass]) var primalUpdate = dualUpdate * lambdaNInv * instanceWeight; labelDual -= dual + dualUpdate; labelPrimalUpdate += primalUpdate; biasUnreg[iClass] += adjustment * lambdaNInv * instanceWeight; labelAdjustment -= adjustment; if (l1ThresholdZero) { VectorUtils.AddMult(ref features, weights[iClass].Values, -primalUpdate); biasReg[iClass] -= primalUpdate; } else { //Iterative shrinkage-thresholding (aka. soft-thresholding) //Update v=denseWeights as if there's no L1 //Thresholding: if |v[j]| < threshold, turn off weights[j] //If not, shrink: w[j] = v[i] - sign(v[j]) * threshold l1IntermediateBias[iClass] -= primalUpdate; if (_args.BiasLearningRate == 0) { biasReg[iClass] = Math.Abs(l1IntermediateBias[iClass]) - l1Threshold > 0.0 ? l1IntermediateBias[iClass] - Math.Sign(l1IntermediateBias[iClass]) * l1Threshold : 0; } if (features.IsDense) CpuMathUtils.SdcaL1UpdateDense(-primalUpdate, features.Length, features.Values, l1Threshold, l1IntermediateWeights[iClass].Values, weights[iClass].Values); else if (features.Count > 0) CpuMathUtils.SdcaL1UpdateSparse(-primalUpdate, features.Length, features.Values, features.Indices, features.Count, l1Threshold, l1IntermediateWeights[iClass].Values, weights[iClass].Values); } break; } } } // Updating with label class weights and dual variable. duals[label + dualIndexInitPos] = labelDual; biasUnreg[label] += labelAdjustment * lambdaNInv * instanceWeight; if (l1ThresholdZero) { VectorUtils.AddMult(ref features, weights[label].Values, labelPrimalUpdate); biasReg[label] += labelPrimalUpdate; } else { l1IntermediateBias[label] += labelPrimalUpdate; var intermediateBias = l1IntermediateBias[label]; biasReg[label] = Math.Abs(intermediateBias) - l1Threshold > 0.0 ? intermediateBias - Math.Sign(intermediateBias) * l1Threshold : 0; if (features.IsDense) CpuMathUtils.SdcaL1UpdateDense(labelPrimalUpdate, features.Length, features.Values, l1Threshold, l1IntermediateWeights[label].Values, weights[label].Values); else if (features.Count > 0) CpuMathUtils.SdcaL1UpdateSparse(labelPrimalUpdate, features.Length, features.Values, features.Indices, features.Count, l1Threshold, l1IntermediateWeights[label].Values, weights[label].Values); } rowCount++; } } } /// <inheritdoc/> protected override bool CheckConvergence( IProgressChannel pch, int iter, FloatLabelCursor.Factory cursorFactory, DualsTableBase duals, IdToIdxLookup idToIdx, VBuffer<Float>[] weights, VBuffer<Float>[] bestWeights, Float[] biasUnreg, Float[] bestBiasUnreg, Float[] biasReg, Float[] bestBiasReg, long count, Double[] metrics, ref Double bestPrimalLoss, ref int bestIter) { Contracts.AssertValue(weights); Contracts.AssertValue(duals); int numClasses = weights.Length; Contracts.Assert(duals.Length >= numClasses * count); Contracts.AssertValueOrNull(idToIdx); Contracts.Assert(Utils.Size(weights) == numClasses); Contracts.Assert(Utils.Size(biasReg) == numClasses); Contracts.Assert(Utils.Size(biasUnreg) == numClasses); Contracts.Assert(Utils.Size(metrics) == 6); var reportedValues = new Double?[metrics.Length + 1]; reportedValues[metrics.Length] = iter; var lossSum = new CompensatedSum(); var dualLossSum = new CompensatedSum(); int numFeatures = weights[0].Length; using (var cursor = cursorFactory.Create()) { long row = 0; Func<UInt128, long, long> getIndexFromIdAndRow = GetIndexFromIdAndRowGetter(idToIdx, biasReg.Length); // Iterates through data to compute loss function. while (cursor.MoveNext()) { var instanceWeight = GetInstanceWeight(cursor); var features = cursor.Features; var label = (int)cursor.Label; var labelOutput = WDot(ref features, ref weights[label], biasReg[label] + biasUnreg[label]); Double subLoss = 0; Double subDualLoss = 0; long idx = getIndexFromIdAndRow(cursor.Id, row); long dualIndex = idx * numClasses; for (int iClass = 0; iClass < numClasses; iClass++) { if (iClass == label) { dualIndex++; continue; } var currentClassOutput = WDot(ref features, ref weights[iClass], biasReg[iClass] + biasUnreg[iClass]); subLoss += _loss.Loss(labelOutput - currentClassOutput, 1); Contracts.Assert(dualIndex == iClass + idx * numClasses); var dual = duals[dualIndex++]; subDualLoss += _loss.DualLoss(1, dual); } lossSum.Add(subLoss * instanceWeight); dualLossSum.Add(subDualLoss * instanceWeight); row++; } Host.Assert(idToIdx == null || row * numClasses == duals.Length); } Contracts.Assert(_args.L2Const.HasValue); Contracts.Assert(_args.L1Threshold.HasValue); Double l2Const = _args.L2Const.Value; Double l1Threshold = _args.L1Threshold.Value; Double weightsL1Norm = 0; Double weightsL2NormSquared = 0; Double biasRegularizationAdjustment = 0; for (int iClass = 0; iClass < numClasses; iClass++) { weightsL1Norm += VectorUtils.L1Norm(ref weights[iClass]) + Math.Abs(biasReg[iClass]); weightsL2NormSquared += VectorUtils.NormSquared(weights[iClass]) + biasReg[iClass] * biasReg[iClass]; biasRegularizationAdjustment += biasReg[iClass] * biasUnreg[iClass]; } Double l1Regularizer = _args.L1Threshold.Value * l2Const * weightsL1Norm; var l2Regularizer = l2Const * weightsL2NormSquared * 0.5; var newLoss = lossSum.Sum / count + l2Regularizer + l1Regularizer; var newDualLoss = dualLossSum.Sum / count - l2Regularizer - l2Const * biasRegularizationAdjustment; var dualityGap = newLoss - newDualLoss; metrics[(int)MetricKind.Loss] = newLoss; metrics[(int)MetricKind.DualLoss] = newDualLoss; metrics[(int)MetricKind.DualityGap] = dualityGap; metrics[(int)MetricKind.BiasUnreg] = biasUnreg[0]; metrics[(int)MetricKind.BiasReg] = biasReg[0]; metrics[(int)MetricKind.L1Sparsity] = _args.L1Threshold == 0 ? 1 : weights.Sum( weight => weight.Values.Count(w => w != 0)) / (numClasses * numFeatures); bool converged = dualityGap / newLoss < _args.ConvergenceTolerance; if (metrics[(int)MetricKind.Loss] < bestPrimalLoss) { for (int iClass = 0; iClass < numClasses; iClass++) { // Maintain a copy of weights and bias with best primal loss thus far. // This is some extra work and uses extra memory, but it seems worth doing it. // REVIEW: Sparsify bestWeights? weights[iClass].CopyTo(ref bestWeights[iClass]); bestBiasReg[iClass] = biasReg[iClass]; bestBiasUnreg[iClass] = biasUnreg[iClass]; } bestPrimalLoss = metrics[(int)MetricKind.Loss]; bestIter = iter; } for (int i = 0; i < metrics.Length; i++) reportedValues[i] = metrics[i]; if (pch != null) pch.Checkpoint(reportedValues); return converged; } protected override MulticlassLogisticRegressionPredictor CreatePredictor(VBuffer<Float>[] weights, Float[] bias) { Host.CheckValue(weights, nameof(weights)); Host.CheckValue(bias, nameof(bias)); Host.CheckParam(weights.Length > 0, nameof(weights)); Host.CheckParam(weights.Length == bias.Length, nameof(weights)); return new MulticlassLogisticRegressionPredictor(Host, weights, bias, bias.Length, weights[0].Length, null, stats: null); } protected override void CheckLabel(RoleMappedData examples, out int weightSetCount) { examples.CheckMultiClassLabel(out weightSetCount); } protected override Float[] InitializeFeatureNormSquared(int length) { Contracts.Assert(0 < length & length <= Utils.ArrayMaxSize); return new Float[length]; } protected override Float GetInstanceWeight(FloatLabelCursor cursor) { return cursor.Weight; } protected override MulticlassPredictionTransformer<MulticlassLogisticRegressionPredictor> MakeTransformer(MulticlassLogisticRegressionPredictor model, ISchema trainSchema) => new MulticlassPredictionTransformer<MulticlassLogisticRegressionPredictor>(Host, model, trainSchema, FeatureColumn.Name, LabelColumn.Name); } /// <summary> /// The Entry Point for SDCA multiclass. /// </summary> public static partial class Sdca { [TlcModule.EntryPoint(Name = "Trainers.StochasticDualCoordinateAscentClassifier", Desc = SdcaMultiClassTrainer.Summary, UserName = SdcaMultiClassTrainer.UserNameValue, ShortName = SdcaMultiClassTrainer.ShortName, XmlInclude = new[] { @"<include file='../Microsoft.ML.StandardLearners/Standard/doc.xml' path='doc/members/member[@name=""SDCA""]/*' />", @"<include file='../Microsoft.ML.StandardLearners/Standard/doc.xml' path='doc/members/example[@name=""StochasticDualCoordinateAscentClassifier""]/*' />" })] public static CommonOutputs.MulticlassClassificationOutput TrainMultiClass(IHostEnvironment env, SdcaMultiClassTrainer.Arguments input) { Contracts.CheckValue(env, nameof(env)); var host = env.Register("TrainSDCA"); host.CheckValue(input, nameof(input)); EntryPointUtils.CheckInputArgs(host, input); return LearnerEntryPointsUtils.Train<SdcaMultiClassTrainer.Arguments, CommonOutputs.MulticlassClassificationOutput>(host, input, () => new SdcaMultiClassTrainer(host, input), () => LearnerEntryPointsUtils.FindColumn(host, input.TrainingData.Schema, input.LabelColumn)); } } }
51.268623
230
0.578725
[ "MIT" ]
naphtalidavies/machinelearning
src/Microsoft.ML.StandardLearners/Standard/SdcaMultiClass.cs
22,712
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace guzellikmerkezison { public partial class seansss : Form { public seansss() { InitializeComponent(); } private void göster1() { SqlConnection baglanti = new SqlConnection(bgl.adres); baglanti.Open(); string cümle = "select * from musteri"; SqlCommand komut = new SqlCommand(cümle, baglanti); SqlDataAdapter dataadapter = new SqlDataAdapter(komut); DataTable datatable = new DataTable(); dataadapter.Fill(datatable); dataGridView2.DataSource = datatable; baglanti.Close(); } private void göster2() { SqlConnection baglanti = new SqlConnection(bgl.adres); baglanti.Open(); string cümle = "select * from tahsilat1"; SqlCommand komut = new SqlCommand(cümle, baglanti); SqlDataAdapter dataadapter = new SqlDataAdapter(komut); DataTable datatable = new DataTable(); dataadapter.Fill(datatable); dataGridView3.DataSource = datatable; baglanti.Close(); } private void göster() { SqlConnection baglanti = new SqlConnection(bgl.adres); baglanti.Open(); string cümle = "select * from seansekleme1"; SqlCommand komut = new SqlCommand(cümle, baglanti); SqlDataAdapter dataadapter = new SqlDataAdapter(komut); DataTable datatable = new DataTable(); dataadapter.Fill(datatable); dataGridView1.DataSource = datatable; baglanti.Close(); } int sonuc; string odeme = ""; string durum = "Bekleniyor"; private void seansss_Load(object sender, EventArgs e) { göster(); göster1(); göster2(); } baglanti bgl = new baglanti(); private void button1_Click(object sender, EventArgs e) { int kontrol = 0; foreach (Control item in groupBox1.Controls) { if (item is TextBox) { if (item.Text == "") { kontrol = 1; } } } foreach (Control item in groupBox2.Controls) { if (item is TextBox) { if (item.Text == "") { kontrol = 1; } } } foreach (Control item in groupBox3.Controls) { if (item is TextBox) { if (item.Text == "") { kontrol = 1; } } } if (kontrol == 0) { SqlConnection baglanti = new SqlConnection(bgl.adres); if (sonuc == 0) { for (int i = 0; i < Convert.ToInt32(txtseans.Text); i++) { baglanti.Open(); int sayi1 = dataGridView1.Rows.Count; SqlCommand komut = new SqlCommand("insert into seansekleme1(sirano,adivesoyadi,telefon,yapilanis,seans,tarih,saat) values (@sirano,@adivesoyadi,@telefon,@yapilanis,@seans,@tarih,@saat)", baglanti); komut.Parameters.AddWithValue("@sirano", sayi1.ToString()); komut.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut.Parameters.AddWithValue("@telefon", txttelefon.Text); komut.Parameters.AddWithValue("@yapilanis", txtyapilanis.Text); komut.Parameters.AddWithValue("@seans", txtseans.Text); if (i == 0) { komut.Parameters.AddWithValue("@tarih",dateTimePicker2.Value.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd-MM-yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } komut.ExecuteNonQuery(); baglanti.Close(); baglanti.Open(); SqlCommand komut1 = new SqlCommand("insert into tarih2(musteriadi,tarih,saat) values (@musteriadi,@tarih,@saat)", baglanti); komut1.Parameters.AddWithValue("@musteriadi", txtadisoyadı.Text); if (i == 0) { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); DateTime gun = h.AddDays(-1); komut1.Parameters.AddWithValue("@tarih", gun.ToString()); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; int ekle1 = ekle - 1; DateTime gun = h.AddDays(ekle1); komut1.Parameters.AddWithValue("@tarih", gun.ToString("dd.MM.yyyy")); } komut1.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); komut1.ExecuteNonQuery(); baglanti.Close(); göster(); anasayfa ana = new anasayfa(); ana.button8_Click(sender, e); } baglanti.Open(); int sayi = dataGridView3.Rows.Count; SqlCommand komut2 = new SqlCommand("insert into tahsilat1(sirano,adivesoyadi,telefon,odenecektutar,yatirilantutar,kalantutar,odemeturu,durum,tarih) values(@sirano,@adivesoyadi,@telefon,@odenecektutar,@yatirilantutar,@kalantutar,@odemeturu,@durum,@tarih)", baglanti); komut2.Parameters.AddWithValue("@sirano", sayi.ToString()); komut2.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut2.Parameters.AddWithValue("@telefon", txttelefon.Text); komut2.Parameters.AddWithValue("@odenecektutar",txtucret.Text); komut2.Parameters.AddWithValue("@yatirilantutar", 0.ToString()); komut2.Parameters.AddWithValue("@kalantutar", txtucret.Text); komut2.Parameters.AddWithValue("@odemeturu", odeme); komut2.Parameters.AddWithValue("@durum", durum); komut2.Parameters.AddWithValue("@tarih", dateTimePicker2.Value.ToString("dd.MM.yyyy")); komut2.ExecuteNonQuery(); baglanti.Close(); göster2(); } if (sonuc == 3) { for (int i = 0; i < Convert.ToInt32(txtseans.Text); i++) { baglanti.Open(); int sayi = dataGridView1.Rows.Count; SqlCommand komut = new SqlCommand("insert into seansekleme1(sirano,adivesoyadi,telefon,yapilanis,seans,tarih,saat) values (@sirano,@adivesoyadi,@telefon,@yapilanis,@seans,@tarih,@saat)", baglanti); komut.Parameters.AddWithValue("@sirano", sayi.ToString()); komut.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut.Parameters.AddWithValue("@telefon", txttelefon.Text); komut.Parameters.AddWithValue("@yapilanis", txtyapilanis.Text); komut.Parameters.AddWithValue("@seans", txtseans.Text); if (i == 0) { komut.Parameters.AddWithValue("@tarih", dateTimePicker2.Value.ToString("dd.M.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } komut.ExecuteNonQuery(); baglanti.Close(); baglanti.Open(); SqlCommand komut1 = new SqlCommand("insert into tarih2(musteriadi,tarih,saat) values (@musteriadi,@tarih,@saat)", baglanti); komut1.Parameters.AddWithValue("@musteriadi", txtadisoyadı.Text); if (i == 0) { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); DateTime gun = h.AddDays(-1); komut1.Parameters.AddWithValue("@tarih", gun.ToString()); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; int ekle1 = ekle - 1; DateTime gun = h.AddDays(ekle1); komut1.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); } komut1.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); komut1.ExecuteNonQuery(); baglanti.Close(); göster(); anasayfa ana = new anasayfa(); ana.button8_Click(sender, e); } for (int i = 0; i < 3; i++) { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into tahsilat1(sirano,adivesoyadi,telefon,odenecektutar,yatirilantutar,kalantutar,odemeturu,durum,tarih) values(@sirano,@adivesoyadi,@telefon,@odenecektutar,@yatirilantutar,@kalantutar,@odemeturu,@durum,@tarih)", baglanti); int sayi = dataGridView3.Rows.Count; komut2.Parameters.AddWithValue("@sirano", sayi.ToString()); komut2.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut2.Parameters.AddWithValue("@telefon", txttelefon.Text); double toplam = Convert.ToDouble(txtucret.Text) / 3; toplam = Math.Round(toplam, 2); komut2.Parameters.AddWithValue("@odenecektutar", toplam.ToString()); komut2.Parameters.AddWithValue("@yatirilantutar", 0.ToString()); komut2.Parameters.AddWithValue("@kalantutar", toplam.ToString()); komut2.Parameters.AddWithValue("@odemeturu", odeme); komut2.Parameters.AddWithValue("@durum", durum); if (i == 0) { komut2.Parameters.AddWithValue("@tarih",dateTimePicker2.Value.ToString("dd.MM.yyyy")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut2.Parameters.AddWithValue("@tarih", gun.ToString("dd.MM.yyyy")); } komut2.ExecuteNonQuery(); baglanti.Close(); göster2(); } } if (sonuc == 6) { for (int i = 0; i < Convert.ToInt32(txtseans.Text); i++) { baglanti.Open(); int sayi = dataGridView1.Rows.Count; SqlCommand komut = new SqlCommand("insert into seansekleme1(sirano,adivesoyadi,telefon,yapilanis,seans,tarih,saat) values (@sirano,@adivesoyadi,@telefon,@yapilanis,@seans,@tarih,@saat)", baglanti); komut.Parameters.AddWithValue("@sirano", sayi.ToString()); komut.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut.Parameters.AddWithValue("@telefon", txttelefon.Text); komut.Parameters.AddWithValue("@yapilanis", txtyapilanis.Text); komut.Parameters.AddWithValue("@seans", txtseans.Text); if (i == 0) { komut.Parameters.AddWithValue("@tarih",dateTimePicker2.Value.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut.Parameters.AddWithValue("@tarih", gun.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } komut.ExecuteNonQuery(); baglanti.Close(); baglanti.Open(); SqlCommand komut1 = new SqlCommand("insert into tarih2(musteriadi,tarih,saat) values (@musteriadi,@tarih,@saat)", baglanti); komut1.Parameters.AddWithValue("@musteriadi", txtadisoyadı.Text); if (i == 0) { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM-yyyy")); DateTime h = Convert.ToDateTime(s); DateTime gun = h.AddDays(-1); komut1.Parameters.AddWithValue("@tarih", gun.ToString()); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; int ekle1 = ekle - 1; DateTime gun = h.AddDays(ekle1); komut1.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); } komut1.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); komut1.ExecuteNonQuery(); baglanti.Close(); göster(); anasayfa ana = new anasayfa(); ana.button8_Click(sender, e); } for (int i = 0; i < 6; i++) { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into tahsilat1(sirano,adivesoyadi,telefon,odenecektutar,yatirilantutar,kalantutar,odemeturu,durum,tarih) values(@sirano,@adivesoyadi,@telefon,@odenecektutar,@yatirilantutar,@kalantutar,@odemeturu,@durum,@tarih)", baglanti); int sayi = dataGridView3.Rows.Count; komut2.Parameters.AddWithValue("@sirano", sayi.ToString()); komut2.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut2.Parameters.AddWithValue("@telefon", txttelefon.Text); double toplam = Convert.ToDouble(txtucret.Text) / 6; toplam = Math.Round(toplam, 2); komut2.Parameters.AddWithValue("@odenecektutar", toplam.ToString()); komut2.Parameters.AddWithValue("@yatirilantutar", 0.ToString()); komut2.Parameters.AddWithValue("@kalantutar", toplam.ToString()); komut2.Parameters.AddWithValue("@odemeturu", odeme); komut2.Parameters.AddWithValue("@durum", durum); if (i == 0) { komut2.Parameters.AddWithValue("@tarih", dateTimePicker2.Value.ToString("dd.MM.yyyy")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut2.Parameters.AddWithValue("@tarih", gun.ToString("dd.MM.yyyy")); } komut2.ExecuteNonQuery(); baglanti.Close(); göster2(); } } if (sonuc == 9) { for (int i = 0; i < Convert.ToInt32(txtseans.Text); i++) { baglanti.Open(); int sayi = dataGridView1.Rows.Count; SqlCommand komut = new SqlCommand("insert into seansekleme1(sirano,adivesoyadi,telefon,yapilanis,seans,tarih,saat) values (@sirano,@adivesoyadi,@telefon,@yapilanis,@seans,@tarih,@saat)", baglanti); komut.Parameters.AddWithValue("@sirano", sayi.ToString()); komut.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut.Parameters.AddWithValue("@telefon", txttelefon.Text); komut.Parameters.AddWithValue("@yapilanis", txtyapilanis.Text); komut.Parameters.AddWithValue("@seans", txtseans.Text); if (i == 0) { komut.Parameters.AddWithValue("@tarih",dateTimePicker2.Value.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut.Parameters.AddWithValue("@tarih", gun.ToString("dd.MM.yyyy")); komut.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); } komut.ExecuteNonQuery(); baglanti.Close(); baglanti.Open(); SqlCommand komut1 = new SqlCommand("insert into tarih2(musteriadi,tarih,saat) values (@musteriadi,@tarih,@saat)", baglanti); komut1.Parameters.AddWithValue("@musteriadi", txtadisoyadı.Text); if (i == 0) { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); DateTime gun = h.AddDays(-1); komut1.Parameters.AddWithValue("@tarih", gun.ToString()); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd.MM.yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; int ekle1 = ekle - 1; DateTime gun = h.AddDays(ekle1); komut1.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); } komut1.Parameters.AddWithValue("@saat", dateTimePicker1.Value.ToString("HH:mm:ss")); komut1.ExecuteNonQuery(); baglanti.Close(); göster(); anasayfa ana = new anasayfa(); ana.button8_Click(sender, e); } for (int i = 0; i < 9; i++) { baglanti.Open(); SqlCommand komut2 = new SqlCommand("insert into tahsilat1(sirano,adivesoyadi,telefon,odenecektutar,yatirilantutar,kalantutar,odemeturu,durum,tarih) values(@sirano,@adivesoyadi,@telefon,@odenecektutar,@yatirilantutar,@kalantutar,@odemeturu,@durum,@tarih)", baglanti); int sayi = dataGridView3.Rows.Count; komut2.Parameters.AddWithValue("@sirano", sayi.ToString()); komut2.Parameters.AddWithValue("@adivesoyadi", txtadisoyadı.Text); komut2.Parameters.AddWithValue("@telefon", txttelefon.Text); double toplam = Convert.ToDouble(txtucret.Text) / 9; toplam = Math.Round(toplam, 2); komut2.Parameters.AddWithValue("@odenecektutar", toplam.ToString()); komut2.Parameters.AddWithValue("@yatirilantutar", 0.ToString()); komut2.Parameters.AddWithValue("@kalantutar", toplam.ToString()); komut2.Parameters.AddWithValue("@odemeturu", odeme); komut2.Parameters.AddWithValue("@durum", durum); if (i == 0) { komut2.Parameters.AddWithValue("@tarih", dateTimePicker2.Value.ToString("dd.MM.yyyy")); } else { string s = Convert.ToString(dateTimePicker2.Value.ToString("dd-MM-yyyy")); DateTime h = Convert.ToDateTime(s); int ekle = Convert.ToInt32(textBox2.Text) * i; DateTime gun = h.AddDays(ekle); komut2.Parameters.AddWithValue("@tarih",gun.ToString("dd.MM.yyyy")); } komut2.ExecuteNonQuery(); baglanti.Close(); göster2(); } } MessageBox.Show("Seans Başarı ile Eklendi"); } else { MessageBox.Show("Boş Alan Bırakmayınız!", "Hata Mesajı", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void timer1_Tick_1(object sender, EventArgs e) { } private void timer2_Tick(object sender, EventArgs e) { } private void dateTimePicker2_ValueChanged(object sender, EventArgs e) { DateTime bugün = DateTime.Parse(DateTime.Now.ToShortDateString()); DateTime yeni = DateTime.Parse(dateTimePicker2.Text); if (yeni < bugün) { MessageBox.Show("Eskiye Dönük İşlem Yapmayınız!"); } } private void radioButton1_CheckedChanged(object sender, EventArgs e) { odeme = "Nakit Ödeme"; checkBox1.Enabled = false; checkBox2.Enabled = false; checkBox3.Enabled = false; sonuc = 0; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { odeme = "Elden Taksit"; checkBox1.Enabled = true; checkBox2.Enabled = true; checkBox3.Enabled = true; } private void dataGridView2_CellEnter(object sender, DataGridViewCellEventArgs e) { txtmusterino.Text = dataGridView2.CurrentRow.Cells[0].Value.ToString(); txtadisoyadı.Text = dataGridView2.CurrentRow.Cells[1].Value.ToString(); txttelefon.Text = dataGridView2.CurrentRow.Cells[2].Value.ToString(); txttarih.Text = dataGridView2.CurrentRow.Cells[3].Value.ToString(); txtsaat.Text = dataGridView2.CurrentRow.Cells[4].Value.ToString(); } private void checkBox1_CheckedChanged_1(object sender, EventArgs e) { sonuc = 3; } private void checkBox2_CheckedChanged_1(object sender, EventArgs e) { sonuc = 6; } private void checkBox3_CheckedChanged_1(object sender, EventArgs e) { sonuc = 9; } private void button3_Click(object sender, EventArgs e) { SqlConnection baglanti = new SqlConnection(bgl.adres); string sorgu = "delete from seansekleme1 where sirano=@sirano"; SqlCommand komut = new SqlCommand(sorgu, baglanti); komut.Parameters.AddWithValue("@sirano", txtmusterino.Text); baglanti.Open(); komut.ExecuteNonQuery(); baglanti.Close(); göster(); } private void label10_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { var nesneler = groupBox1.Controls.OfType<TextBox>(); var nesneler2 = groupBox2.Controls.OfType<TextBox>(); var nesneler3 = groupBox3.Controls.OfType<TextBox>(); foreach (var nesne in nesneler) { nesne.Clear(); } foreach (var nesne in nesneler2) { nesne.Clear(); } foreach (var nesne in nesneler3) { nesne.Clear(); } } private void txtadisoyadı_KeyPress(object sender, KeyPressEventArgs e) { if (Char.IsDigit(e.KeyChar)) { e.Handled = true; } } private void txtseans_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } private void txtucret_TextChanged(object sender, EventArgs e) { } private void txtucret_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); } } }
41.584637
290
0.485223
[ "MIT" ]
Busra3021/CSharp_guzellik_merkezi_otomasyonu
guzellikmerkezison/guzellikmerkezison/seansss.cs
29,287
C#
 using System.Collections.Generic; using System.Linq; using System.Web; using Gym.Models.DAL; using Gym.Models.Entity; namespace Gym.Models.Manager { public class ManagerEquipment { public static void SaveEquipment(EquipmentEntity detail) { using (fitnessEntities dbe = new DAL.fitnessEntities()) { equipment equipment = new DAL.equipment(); equipment.equipment_id = detail.equipment_id; equipment.equipment_name = detail.equipment_name; equipment.equipment_quantity = detail.equipment_quantity; equipment.equipment_cost = detail.equipment_cost; equipment.equipment_photo = detail.equipment_photo; dbe.equipments.Add(equipment); dbe.SaveChanges(); } } public static void EditEquipment(EquipmentEntity detail) { using (fitnessEntities dbe = new DAL.fitnessEntities()) { equipment equipment = dbe.equipments.Find(detail.equipment_id); equipment.equipment_name = detail.equipment_name; equipment.equipment_quantity = detail.equipment_quantity; equipment.equipment_cost = detail.equipment_cost; // equipment.equipment_photo = detail.equipment_photo; // dbe.Entry(equipment).State = System.Data.Entity.EntityState.Modified; dbe.SaveChanges(); } } public static List<EquipmentEntity> GetEquipments() { List<EquipmentEntity> equipments = new List<Entity.EquipmentEntity>(); using (fitnessEntities dbe = new fitnessEntities()) { EquipmentEntity equipmentEntity; var equipmentList = dbe.equipments.ToList(); foreach (var equipment in equipmentList) { equipmentEntity = new Entity.EquipmentEntity(); equipmentEntity.equipment_id = equipment.equipment_id; equipmentEntity.equipment_name = equipment.equipment_name; equipmentEntity.equipment_quantity = equipment.equipment_quantity; equipmentEntity.equipment_cost = equipment.equipment_cost; equipmentEntity.equipment_photo = equipment.equipment_photo; equipments.Add(equipmentEntity); } } return equipments; } public static void DelEquipment(string Id) { using (fitnessEntities dbe = new fitnessEntities()) { equipment equipment = dbe.equipments.Where(o => o.equipment_id.Equals(Id)).SingleOrDefault(); dbe.equipments.Remove(equipment); dbe.SaveChanges(); } } public static EquipmentEntity DetailEquipment(string Id) { EquipmentEntity equipmentEntity = new Entity.EquipmentEntity(); using (fitnessEntities dbe = new fitnessEntities()) { equipment equipment = dbe.equipments.Where(o => o.equipment_id.Equals(Id)).SingleOrDefault(); equipmentEntity.equipment_id = equipment.equipment_id; equipmentEntity.equipment_name = equipment.equipment_name; equipmentEntity.equipment_quantity = equipment.equipment_quantity; equipmentEntity.equipment_cost = equipment.equipment_cost; equipmentEntity.equipment_photo = equipment.equipment_photo; } return equipmentEntity; } } }
35.786408
109
0.60255
[ "MIT" ]
anisha13/gym_mangemeny_system
Gym/Gym/Models/Manager/ManagerEquipment.cs
3,688
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using ECommerce.Domain.Models; using ECommerce.Domain.Services; using ECommerce.Extensions; using ECommerce.Resources.Purchase; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; namespace ECommerce.Controllers { [EnableCors("ecommerce-policy")] [Route("/api/ecommerce/purchases")] [Authorize] public class PurchaseController: ControllerBase { private readonly IPurchaseService _purchaseService; private readonly IMapper _mapper; public PurchaseController(IPurchaseService purchaseService, IMapper mapper) { _purchaseService = purchaseService; _mapper = mapper; } [HttpGet] public async Task<IEnumerable<PurchaseResource>> GetAllAsync() { var purchases = await _purchaseService.ListAsync(); var resource = _mapper.Map<IEnumerable<Purchase>, IEnumerable<PurchaseResource>>(purchases); return resource; } [HttpGet("{id:int}")] public async Task<IActionResult> GetAsync(int id) { var purchase = await _purchaseService.FindByIdAsync(id); if (purchase == null) return NoContent(); var resource = _mapper.Map<Purchase, PurchaseResource>(purchase); return Ok(resource); } [HttpPost] public async Task<IActionResult> PostAsync([FromBody] SavePurchaseResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); Console.Write(resource.Items); var purchase = _mapper.Map<SavePurchaseResource, Purchase>(resource); var result = await _purchaseService.SaveAsync(purchase); if (!result.Success) return BadRequest(); var purchaseResource = _mapper.Map<Purchase, PurchaseResource>(result.Purchase); return Ok(purchaseResource); } [HttpPut("{id:int}")] public async Task<IActionResult> PutAsync(int id, [FromBody] SavePurchaseResource resource) { if (!ModelState.IsValid) return BadRequest(ModelState.GetErrorMessages()); var purchase = _mapper.Map<SavePurchaseResource, Purchase>(resource); var result = await _purchaseService.UpdateAsync(id, purchase); if (!result.Success) return BadRequest(); var purchaseResource = _mapper.Map<Purchase, PurchaseResource>(result.Purchase); return Ok(purchaseResource); } [HttpDelete("{id:int}")] public async Task<IActionResult> DeleteAsync(int id) { var result = await _purchaseService.DeleteAsync(id); if (!result.Success) return NoContent(); var resource = _mapper.Map<Purchase, PurchaseResource>(result.Purchase); return Ok(resource); } } }
30.423077
104
0.622946
[ "Apache-2.0" ]
rafaelvieira95/curso-dfs
core/ECommerce/Controllers/PurchaseController.cs
3,164
C#
namespace WorkoutWotch.UnitTests.Models.Actions { using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using Builders; using Kent.Boogaart.PCLMock; using WorkoutWotch.Models; using WorkoutWotch.Models.Actions; using WorkoutWotch.UnitTests.Models.Mocks; using Xunit; public class SequenceActionFixture { [Fact] public void ctor_throws_if_children_is_null() { Assert.Throws<ArgumentNullException>(() => new SequenceAction(null)); } [Fact] public void ctor_throws_if_any_child_is_null() { Assert.Throws<ArgumentException>(() => new SequenceAction(new [] { new ActionMock(), null, new ActionMock() })); } [Fact] public void duration_is_zero_if_there_are_no_child_actions() { var sut = new SequenceActionBuilder() .Build(); Assert.Equal(TimeSpan.Zero, sut.Duration); } [Fact] public void duration_is_calculated_as_the_sum_of_child_durations() { var action1 = new ActionMock(); var action2 = new ActionMock(); var action3 = new ActionMock(); action1 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(10)); action2 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(1)); action3 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(7)); var sut = new SequenceActionBuilder() .AddChild(action1) .AddChild(action2) .AddChild(action3) .Build(); Assert.Equal(TimeSpan.FromSeconds(18), sut.Duration); } [Fact] public void execute_async_throws_if_context_is_null() { var sut = new SequenceActionBuilder() .Build(); Assert.Throws<ArgumentNullException>(() => sut.ExecuteAsync(null)); } [Fact] public void execute_async_executes_each_child_action() { var action1 = new ActionMock(MockBehavior.Loose); var action2 = new ActionMock(MockBehavior.Loose); var action3 = new ActionMock(MockBehavior.Loose); var sut = new SequenceActionBuilder() .AddChild(action1) .AddChild(action2) .AddChild(action3) .Build(); using (var context = new ExecutionContext()) { sut.ExecuteAsync(context); action1 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); action2 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); action3 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); } } [Fact] public void execute_async_executes_each_child_action_in_order() { var childCount = 10; var childExecutionOrder = new int[childCount]; var executionOrder = 0; var childActions = Enumerable .Range(0, childCount) .Select( (i, _) => { var childAction = new ActionMock(MockBehavior.Loose); childAction .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Do(() => childExecutionOrder[i] = Interlocked.Increment(ref executionOrder)) .Return(Observable.Return(Unit.Default)); return childAction; }) .ToList(); var sut = new SequenceActionBuilder() .AddChildren(childActions) .Build(); using (var context = new ExecutionContext()) { sut.ExecuteAsync(context); for (var i = 0; i < childExecutionOrder.Length; ++i) { Assert.Equal(i + 1, childExecutionOrder[i]); } } } [Fact] public void execute_async_skips_child_actions_that_are_shorter_than_the_skip_ahead() { var action1 = new ActionMock(); var action2 = new ActionMock(); var action3 = new ActionMock(MockBehavior.Loose); action1 .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Throw(); action2 .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Throw(); action1 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(3)); action2 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(8)); action3 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(2)); var sut = new SequenceActionBuilder() .AddChild(action1) .AddChild(action2) .AddChild(action3) .Build(); using (var context = new ExecutionContext(TimeSpan.FromSeconds(11))) { sut.ExecuteAsync(context); action3 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); } } [Fact] public void execute_async_skips_child_actions_that_are_shorter_than_the_skip_ahead_even_if_the_context_is_paused() { var action1 = new ActionMock(); var action2 = new ActionMock(); var action3 = new ActionMock(MockBehavior.Loose); action1 .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Throw(); action2 .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Throw(); action1 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(3)); action2 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(8)); action3 .When(x => x.Duration) .Return(TimeSpan.FromSeconds(2)); var sut = new SequenceActionBuilder() .AddChild(action1) .AddChild(action2) .AddChild(action3) .Build(); using (var context = new ExecutionContext(TimeSpan.FromSeconds(11))) { context.IsPaused = true; sut.ExecuteAsync(context); action3 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); } } [Fact] public void execute_async_stops_executing_if_the_context_is_cancelled() { var action1 = new ActionMock(MockBehavior.Loose); var action2 = new ActionMock(MockBehavior.Loose); var action3 = new ActionMock(MockBehavior.Loose); var sut = new SequenceActionBuilder() .AddChild(action1) .AddChild(action2) .AddChild(action3) .Build(); using (var context = new ExecutionContext()) { action2 .When(x => x.ExecuteAsync(It.IsAny<ExecutionContext>())) .Do(() => context.Cancel()) .Return(Observable.Return(Unit.Default)); Assert.ThrowsAsync<OperationCanceledException>(async () => await sut.ExecuteAsync(context)); action1 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); action2 .Verify(x => x.ExecuteAsync(context)) .WasCalledExactlyOnce(); action3 .Verify(x => x.ExecuteAsync(context)) .WasNotCalled(); } } [Fact] public void execute_async_completes_even_if_there_are_no_child_actions() { var sut = new SequenceActionBuilder() .Build(); var completed = false; sut .ExecuteAsync(new ExecutionContext()) .Subscribe(_ => completed = true); Assert.True(completed); } } }
31.673913
124
0.500572
[ "MIT" ]
reactiveui-forks/WorkoutWotch
Src/WorkoutWotch.UnitTests/Models/Actions/SequenceActionFixture.cs
8,744
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ZigBeeNet.Security; using ZigBeeNet.ZCL.Clusters.ColorControl; using ZigBeeNet.ZCL.Field; using ZigBeeNet.ZCL.Protocol; namespace ZigBeeNet.ZCL.Clusters.ColorControl { /// <summary> /// Step Color Command value object class. /// /// Cluster: Color Control. Command ID 0x09 is sent TO the server. /// This command is a specific command used for the Color Control cluster. /// /// Code is auto-generated. Modifications may be overwritten! /// </summary> public class StepColorCommand : ZclCommand { /// <summary> /// The cluster ID to which this command belongs. /// </summary> public const ushort CLUSTER_ID = 0x0300; /// <summary> /// The command ID. /// </summary> public const byte COMMAND_ID = 0x09; /// <summary> /// Step X command message field. /// </summary> public short StepX { get; set; } /// <summary> /// Step Y command message field. /// </summary> public short StepY { get; set; } /// <summary> /// Transition Time command message field. /// </summary> public ushort TransitionTime { get; set; } /// <summary> /// Default constructor. /// </summary> public StepColorCommand() { ClusterId = CLUSTER_ID; CommandId = COMMAND_ID; GenericCommand = false; CommandDirection = ZclCommandDirection.CLIENT_TO_SERVER; } internal override void Serialize(ZclFieldSerializer serializer) { serializer.Serialize(StepX, ZclDataType.Get(DataType.SIGNED_16_BIT_INTEGER)); serializer.Serialize(StepY, ZclDataType.Get(DataType.SIGNED_16_BIT_INTEGER)); serializer.Serialize(TransitionTime, ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER)); } internal override void Deserialize(ZclFieldDeserializer deserializer) { StepX = deserializer.Deserialize<short>(ZclDataType.Get(DataType.SIGNED_16_BIT_INTEGER)); StepY = deserializer.Deserialize<short>(ZclDataType.Get(DataType.SIGNED_16_BIT_INTEGER)); TransitionTime = deserializer.Deserialize<ushort>(ZclDataType.Get(DataType.UNSIGNED_16_BIT_INTEGER)); } public override string ToString() { var builder = new StringBuilder(); builder.Append("StepColorCommand ["); builder.Append(base.ToString()); builder.Append(", StepX="); builder.Append(StepX); builder.Append(", StepY="); builder.Append(StepY); builder.Append(", TransitionTime="); builder.Append(TransitionTime); builder.Append(']'); return builder.ToString(); } } }
32.296703
113
0.610752
[ "EPL-1.0" ]
DavidKarlas/ZigbeeNet
libraries/ZigBeeNet/ZCL/Clusters/ColorControl/StepColorCommand.cs
2,939
C#
using SoftJail.Data.Models.Enums; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; using System.Xml.Serialization; namespace SoftJail.DataProcessor.ImportDto { [XmlType("Officer")] public class ImportOfficersPrisonersDTO { //• Id – integer, Primary Key //• FullName – text with min length 3 and max length 30 (required) //• Salary – decimal(non - negative, minimum value: 0)(required) //• Position - Position enumeration with possible values: “Overseer, Guard, Watcher, Labour” (required) //• Weapon - Weapon enumeration with possible values: “Knife, FlashPulse, ChainRifle, Pistol, Sniper” (required) //• DepartmentId - integer, foreign key(required) //• Department – the officer's department (required) //• OfficerPrisoners - collection of type OfficerPrisoner [Required] [StringLength(30,MinimumLength = 3)] [XmlElement(ElementName = "Name")] public string Name { get; set; } [XmlElement(ElementName = "Money")] [Range(typeof(decimal), "0", "79228162514264337593543950335")] public decimal Money { get; set; } [XmlElement(ElementName = "Position")] [EnumDataType(typeof(Position))] public string Position { get; set; } [XmlElement(ElementName = "Weapon")] [EnumDataType(typeof(Weapon))] public string Weapon { get; set; } [XmlElement(ElementName = "DepartmentId")] [Required] public int DepartmentId { get; set; } [XmlArray("Prisoners")] [Required] public Prisoner[] Prisoners { get; set; } [XmlType("Prisoner")] public class Prisoner { [XmlAttribute(AttributeName = "id")] public int Id { get; set; } } } }
32.859649
120
0.628404
[ "MIT" ]
mirakis97/Entity-Framework
14.Exams/C# DB Advanced Retake Exam - 14 August 2020/SoftJail/DataProcessor/ImportDto/ImportOfficersPrisonersDTO.cs
1,907
C#
using core.Data.Repositories.User; using core.Domain.Entities.User; using System.Collections.Generic; using System.Threading.Tasks; namespace core.Services.Services.User { public class UserService : IUserService { private readonly IUserRepository _repo; public UserService(IUserRepository repo) { _repo = repo; } public async Task<IEnumerable<ApplicationUser>> GetUsers() { return await _repo.GetAllUsers(); } } }
22.173913
66
0.652941
[ "MIT" ]
alexsoler/nuxt-dotnet-authentication
backend/core.Services/Services/User/UserService.cs
512
C#
using System; namespace CCBPayWebDemo.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
17.666667
70
0.669811
[ "MIT" ]
EzrealJ/EasyPay
demo/CCBPayWebDemo/Models/ErrorViewModel.cs
212
C#
using System; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Elements.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using Elements.Services.Models.Account; using Elements.Common; using Elements.Services.Public.Interfaces; namespace Elements.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager<User> signInManager; private readonly UserManager<User> userManager; private readonly RoleManager<IdentityRole> roleManager; private readonly ILogger<RegisterModel> logger; private readonly IEmailSender emailSender; private readonly IDateTimeService dateTimeService; public RegisterModel( UserManager<User> userManager, RoleManager<IdentityRole> roleManager, SignInManager<User> signInManager, ILogger<RegisterModel> logger, IEmailSender emailSender, IDateTimeService dateTimeService) { this.userManager = userManager; this.roleManager = roleManager; this.signInManager = signInManager; this.logger = logger; this.emailSender = emailSender; this.dateTimeService = dateTimeService; } [BindProperty] public RegisterNewUserModel RegisterNewUserModel { get; set; } public string ReturnUrl { get; set; } public void OnGet(string returnUrl = null) { this.ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (this.ModelState.IsValid) { var user = new User { UserName = RegisterNewUserModel.Username, Email = RegisterNewUserModel.Email, RegisterDate = dateTimeService.Now, Avatar = Constants.DefaultAvatar, }; var result = await this.userManager.CreateAsync(user, RegisterNewUserModel.Password); if (result.Succeeded) { this.logger.LogInformation(string.Format("User created a new account with password. - {0}", user.UserName)); var code = await userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: Request.Scheme); await this.emailSender.SendEmailAsync(RegisterNewUserModel.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); await signInManager.SignInAsync(user, isPersistent: false); await userManager.AddToRoleAsync(user, Constants.UserRoleName); return this.LocalRedirect(returnUrl); } foreach (var error in result.Errors) { this.ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return this.Page(); } } }
37.642857
130
0.607211
[ "MIT" ]
Steffkn/ElementsWeb
Elements.Web/Areas/Identity/Pages/Account/Register.cshtml.cs
3,691
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace ApiVideo.Model { /// <summary> /// /// </summary> [DataContract] public class PlayerTheme { /// <summary> /// The name of the player theme /// </summary> /// <value>The name of the player theme</value> [DataMember(Name="name", EmitDefaultValue=false)] [JsonProperty(PropertyName = "name")] public string name { get; set; } /// <summary> /// RGBA color for timer text. Default: rgba(255, 255, 255, 1) /// </summary> /// <value>RGBA color for timer text. Default: rgba(255, 255, 255, 1)</value> [DataMember(Name="text", EmitDefaultValue=false)] [JsonProperty(PropertyName = "text")] public string text { get; set; } /// <summary> /// RGBA color for all controls. Default: rgba(255, 255, 255, 1) /// </summary> /// <value>RGBA color for all controls. Default: rgba(255, 255, 255, 1)</value> [DataMember(Name="link", EmitDefaultValue=false)] [JsonProperty(PropertyName = "link")] public string link { get; set; } /// <summary> /// RGBA color for all controls when hovered. Default: rgba(255, 255, 255, 1) /// </summary> /// <value>RGBA color for all controls when hovered. Default: rgba(255, 255, 255, 1)</value> [DataMember(Name="linkHover", EmitDefaultValue=false)] [JsonProperty(PropertyName = "linkHover")] public string linkhover { get; set; } /// <summary> /// RGBA color playback bar: played content. Default: rgba(88, 131, 255, .95) /// </summary> /// <value>RGBA color playback bar: played content. Default: rgba(88, 131, 255, .95)</value> [DataMember(Name="trackPlayed", EmitDefaultValue=false)] [JsonProperty(PropertyName = "trackPlayed")] public string trackplayed { get; set; } /// <summary> /// RGBA color playback bar: downloaded but unplayed (buffered) content. Default: rgba(255, 255, 255, .35) /// </summary> /// <value>RGBA color playback bar: downloaded but unplayed (buffered) content. Default: rgba(255, 255, 255, .35)</value> [DataMember(Name="trackUnplayed", EmitDefaultValue=false)] [JsonProperty(PropertyName = "trackUnplayed")] public string trackunplayed { get; set; } /// <summary> /// RGBA color playback bar: background. Default: rgba(255, 255, 255, .2) /// </summary> /// <value>RGBA color playback bar: background. Default: rgba(255, 255, 255, .2)</value> [DataMember(Name="trackBackground", EmitDefaultValue=false)] [JsonProperty(PropertyName = "trackBackground")] public string trackbackground { get; set; } /// <summary> /// RGBA color: top 50% of background. Default: rgba(0, 0, 0, .7) /// </summary> /// <value>RGBA color: top 50% of background. Default: rgba(0, 0, 0, .7)</value> [DataMember(Name="backgroundTop", EmitDefaultValue=false)] [JsonProperty(PropertyName = "backgroundTop")] public string backgroundtop { get; set; } /// <summary> /// RGBA color: bottom 50% of background. Default: rgba(0, 0, 0, .7) /// </summary> /// <value>RGBA color: bottom 50% of background. Default: rgba(0, 0, 0, .7)</value> [DataMember(Name="backgroundBottom", EmitDefaultValue=false)] [JsonProperty(PropertyName = "backgroundBottom")] public string backgroundbottom { get; set; } /// <summary> /// RGBA color for title text. Default: rgba(255, 255, 255, 1) /// </summary> /// <value>RGBA color for title text. Default: rgba(255, 255, 255, 1)</value> [DataMember(Name="backgroundText", EmitDefaultValue=false)] [JsonProperty(PropertyName = "backgroundText")] public string backgroundtext { get; set; } /// <summary> /// enable/disable player SDK access. Default: true /// </summary> /// <value>enable/disable player SDK access. Default: true</value> [DataMember(Name="enableApi", EmitDefaultValue=false)] [JsonProperty(PropertyName = "enableApi")] public Nullable<bool> enableapi { get; set; } /// <summary> /// enable/disable player controls. Default: true /// </summary> /// <value>enable/disable player controls. Default: true</value> [DataMember(Name="enableControls", EmitDefaultValue=false)] [JsonProperty(PropertyName = "enableControls")] public Nullable<bool> enablecontrols { get; set; } /// <summary> /// enable/disable player autoplay. Default: false /// </summary> /// <value>enable/disable player autoplay. Default: false</value> [DataMember(Name="forceAutoplay", EmitDefaultValue=false)] [JsonProperty(PropertyName = "forceAutoplay")] public Nullable<bool> forceautoplay { get; set; } /// <summary> /// enable/disable title. Default: false /// </summary> /// <value>enable/disable title. Default: false</value> [DataMember(Name="hideTitle", EmitDefaultValue=false)] [JsonProperty(PropertyName = "hideTitle")] public Nullable<bool> hidetitle { get; set; } /// <summary> /// enable/disable looping. Default: false /// </summary> /// <value>enable/disable looping. Default: false</value> [DataMember(Name="forceLoop", EmitDefaultValue=false)] [JsonProperty(PropertyName = "forceLoop")] public Nullable<bool> forceloop { get; set; } /// <summary> /// Gets or Sets PlayerId /// </summary> [DataMember(Name="playerId", EmitDefaultValue=false)] [JsonProperty(PropertyName = "playerId")] public string playerid { get; set; } /// <summary> /// When the player was created, presented in ISO-8601 format. /// </summary> /// <value>When the player was created, presented in ISO-8601 format.</value> [DataMember(Name="createdAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "createdAt")] public DateTime? createdat { get; set; } /// <summary> /// When the player was last updated, presented in ISO-8601 format. /// </summary> /// <value>When the player was last updated, presented in ISO-8601 format.</value> [DataMember(Name="updatedAt", EmitDefaultValue=false)] [JsonProperty(PropertyName = "updatedAt")] public DateTime? updatedat { get; set; } /// <summary> /// RGBA color for the play button when hovered. /// </summary> /// <value>RGBA color for the play button when hovered.</value> [DataMember(Name="linkActive", EmitDefaultValue=false)] [JsonProperty(PropertyName = "linkActive")] public string linkactive { get; set; } /// <summary> /// Gets or Sets Assets /// </summary> [DataMember(Name="assets", EmitDefaultValue=false)] [JsonProperty(PropertyName = "assets")] public PlayerThemeAssets assets { 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 PlayerTheme {\n"); sb.Append(" Name: ").Append(name).Append("\n"); sb.Append(" Text: ").Append(text).Append("\n"); sb.Append(" Link: ").Append(link).Append("\n"); sb.Append(" LinkHover: ").Append(linkhover).Append("\n"); sb.Append(" TrackPlayed: ").Append(trackplayed).Append("\n"); sb.Append(" TrackUnplayed: ").Append(trackunplayed).Append("\n"); sb.Append(" TrackBackground: ").Append(trackbackground).Append("\n"); sb.Append(" BackgroundTop: ").Append(backgroundtop).Append("\n"); sb.Append(" BackgroundBottom: ").Append(backgroundbottom).Append("\n"); sb.Append(" BackgroundText: ").Append(backgroundtext).Append("\n"); sb.Append(" EnableApi: ").Append(enableapi).Append("\n"); sb.Append(" EnableControls: ").Append(enablecontrols).Append("\n"); sb.Append(" ForceAutoplay: ").Append(forceautoplay).Append("\n"); sb.Append(" HideTitle: ").Append(hidetitle).Append("\n"); sb.Append(" ForceLoop: ").Append(forceloop).Append("\n"); sb.Append(" PlayerId: ").Append(playerid).Append("\n"); sb.Append(" CreatedAt: ").Append(createdat).Append("\n"); sb.Append(" UpdatedAt: ").Append(updatedat).Append("\n"); sb.Append(" LinkActive: ").Append(linkactive).Append("\n"); sb.Append(" Assets: ").Append(assets).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } } }
44.612245
125
0.646615
[ "MIT" ]
apivideo/csharp-api-client
src/Model/PlayerTheme.cs
8,744
C#
namespace MudBlazor; internal static class JsRuntimeEx { private const string Prefix = "MudBlazorRichTextEdit"; public static ValueTask InitAsync(this IJSRuntime @this, string elementId, DotNetObjectReference<InnerHtmlChangedInvokable> innerHtmlChangedInvokable) => @this.InvokeVoidAsync($"{Prefix}.init", elementId, innerHtmlChangedInvokable); public static ValueTask SetInnerHtmlAsync(this IJSRuntime @this, string elementId, string innerHtml) => @this.InvokeVoidAsync($"{Prefix}.setInnerHtml", elementId, innerHtml); public static ValueTask UnloadAsync(this IJSRuntime @this, string elementId) => @this.InvokeVoidAsync($"{Prefix}.dispose", elementId); public static ValueTask<bool> ApplyBoldFormattingAsync(this IJSRuntime @this, string elementId, bool isActive) => @this.ApplyFormattingAsync(elementId, "B", isActive); public static ValueTask<bool> ApplyItalicFormattingAsync(this IJSRuntime @this, string elementId, bool isActive) => @this.ApplyFormattingAsync(elementId, "I", isActive); public static ValueTask<bool> ApplyUnderlineFormattingAsync(this IJSRuntime @this, string elementId, bool isActive) => @this.ApplyFormattingAsync(elementId, "U", isActive); private static ValueTask<bool> ApplyFormattingAsync(this IJSRuntime @this, string elementId, string formatChar, bool isActive) => @this.InvokeAsync<bool>($"{Prefix}.applyFormatting", elementId, formatChar, isActive); }
50.571429
154
0.795198
[ "MIT" ]
MyNihongo/MudBlazor.RichTextField
src/MudBlazor.RichTextField/Utils/Extensions/JsRuntimeEx.cs
1,418
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:03:42 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using bytes = go.bytes_package; using fmt = go.fmt_package; using types = go.go.types_package; using io = go.io_package; using reflect = go.reflect_package; using strings = go.strings_package; using sync = go.sync_package; using @unsafe = go.@unsafe_package; using ssa = go.golang.org.x.tools.go.ssa_package; using typeutil = go.golang.org.x.tools.go.types.typeutil_package; using go; #nullable enable namespace go { namespace golang.org { namespace x { namespace tools { namespace go { namespace ssa { public static partial class interp_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct rtype { // Constructors public rtype(NilType _) { this.t = default; } public rtype(types.Type t = default) { this.t = t; } // Enable comparisons between nil and rtype struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(rtype value, NilType nil) => value.Equals(default(rtype)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(rtype value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, rtype value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, rtype value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator rtype(NilType nil) => default(rtype); } [GeneratedCode("go2cs", "0.1.0.0")] private static rtype rtype_cast(dynamic value) { return new rtype(value.t); } } }}}}}}
31.763158
101
0.610191
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/value_rtypeStruct.cs
2,414
C#
namespace StrongPlateEF.Migrations { using System; using System.Data.Entity.Migrations; public partial class ChangeColumnNames : DbMigration { public override void Up() { RenameColumn(table: "dbo.Employees", name: "Speed", newName: "AverageSpeed"); RenameColumn(table: "dbo.Employees", name: "Steadyness", newName: "AverageSteadyness"); } public override void Down() { RenameColumn(table: "dbo.Employees", name: "AverageSpeed", newName: "Speed"); RenameColumn(table: "dbo.Employees", name: "AverageSteadyness", newName: "Steadyness"); } } }
31.952381
99
0.611028
[ "MIT" ]
pxlit-projects/entmob2016_10
EF/StrongPlateEF/StrongPlateEF/Migrations/201611112216498_ChangeColumnNames.cs
671
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Sales { [Table("Orders")] public class Order { [Key] public Guid OrderId { get; set; } public OrderStatus Status { get; set; } } public enum OrderStatus { Pending = 0, ReadyToShip = 1, Shipped = 2, Cancelled = 3 } }
18.391304
51
0.595745
[ "MIT" ]
brianweet/LooselyCoupledMonolith
src/Sales/Order.cs
423
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 appstream-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AppStream.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AppStream.Model.Internal.MarshallTransformations { /// <summary> /// DisassociateFleet Request Marshaller /// </summary> public class DisassociateFleetRequestMarshaller : IMarshaller<IRequest, DisassociateFleetRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DisassociateFleetRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DisassociateFleetRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.AppStream"); string target = "PhotonAdminProxyService.DisassociateFleet"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2016-12-01"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetFleetName()) { context.Writer.WritePropertyName("FleetName"); context.Writer.Write(publicRequest.FleetName); } if(publicRequest.IsSetStackName()) { context.Writer.WritePropertyName("StackName"); context.Writer.Write(publicRequest.StackName); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DisassociateFleetRequestMarshaller _instance = new DisassociateFleetRequestMarshaller(); internal static DisassociateFleetRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DisassociateFleetRequestMarshaller Instance { get { return _instance; } } } }
35.513761
149
0.628003
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/AppStream/Generated/Model/Internal/MarshallTransformations/DisassociateFleetRequestMarshaller.cs
3,871
C#
using CowSpeak.Exceptions; using System; using System.Collections.Generic; using System.Linq; namespace CowSpeak { public static class Executor { public struct TokenLocation { public int LineIndex, TokenIndex; public TokenLocation(int LineIndex, int TokenIndex) { this.LineIndex = LineIndex; this.TokenIndex = TokenIndex; } } public static TokenLocation GetClosingBracket(List< Line > Lines, int start) { int skips = 0; // number of EndBracket(s) to skip for (int j = start; j < Lines.Count; j++) { for (int i = 0; i < Lines[j].Count; i++) { Token token = Lines[j][i]; if (token.type == TokenType.StartBracket) skips++; else if (token.type == TokenType.EndBracket) { skips--; if (skips <= 0) return new TokenLocation(j, i); } } } throw new BaseException("StartBracket is missing an EndBracket"); } public static Any Execute(List< Line > lines, int currentLineOffset = 0, bool nestedInFunction = false, bool nestedInConditional = false) { for (int i = 0; i < lines.Count; i++) { Interpreter.CurrentLine = i + 1 + currentLineOffset; // if this line starts with a ReturnStatement if (lines[i].FirstOrDefault() != null && lines[i].FirstOrDefault().type == TokenType.ReturnStatement) { if (nestedInFunction) { // no value is returned if (lines[i].Count < 2) return null; return new Line(new List<Token>{ lines[i][1] }).Execute(); } else throw new BaseException("ReturnStatement must be located inside of a FunctionDefinition"); } if (lines[i].IsFunctionDefinition || lines[i].IsConditional) { int itemIndex; // index of the token that the definition/conditional appears at if (lines[i].IsFunctionDefinition) itemIndex = 1; else itemIndex = 0; bool nextLineExists = lines.IsIndexValid(i + 1); bool hasPrecedingBracket = lines[i].IsIndexValid(itemIndex + 1) && lines[i][itemIndex + 1].type == TokenType.StartBracket; bool nextLineHasBracket = nextLineExists && lines[i + 1].FirstOrDefault() != null && lines[i + 1].FirstOrDefault().type == TokenType.StartBracket; if (!hasPrecedingBracket && !nextLineHasBracket) throw new BaseException("FunctionDefinition or Conditional is missing a preceding StartBracket"); TokenLocation startBracket = new TokenLocation(i, itemIndex + 1); // index of the line that the StartBracket appears at if (nextLineHasBracket) startBracket = new TokenLocation(i + 1, 0); TokenLocation endingBracket = GetClosingBracket(lines, i); if (lines[i].IsFunctionDefinition) { if (nestedInFunction || nestedInConditional) throw new BaseException("Function cannot be defined inside of a function or conditional"); string usage = lines[i][1].identifier; string dName = usage.Substring(0, usage.IndexOf("(")); // text before first '(' var definitionLines = Utils.GetContainedLines(lines, endingBracket, startBracket); Interpreter.Functions.Create(new UserFunction(dName, definitionLines, UserFunction.ParseDefinitionParams(usage.Substring(usage.IndexOf("("))), Type.GetType(lines[i][0].identifier), lines[i][0].identifier + " " + usage + ")", i)); } else if (lines[i].IsConditional) { var containedLines = Utils.GetContainedLines(lines, endingBracket, startBracket); if (lines[i][0].type == TokenType.IfConditional) { if (new Conditional(lines[i][0].identifier).EvaluateExpression()) { Scope scope = new Scope(); Execute(containedLines, i + 1 + currentLineOffset, nestedInFunction, true); scope.End(); } } else if (lines[i][0].type == TokenType.ElseConditional) { int parentIf = -1; if (i == 0 || (lines[i - 1].Count > 0 && lines[i - 1][0].type != TokenType.EndBracket)) throw new BaseException("ElseConditional must immediately precede an EndBracket"); for (int j = 0; j < i; j++) { if (lines[j].Count > 0 && lines[j][0].type == TokenType.IfConditional && GetClosingBracket(lines, j).LineIndex == i - 1) { parentIf = j; break; } } if (parentIf == -1) throw new BaseException("ElseConditional must immediately precede an EndBracket"); if (!new Conditional(lines[parentIf][0].identifier).EvaluateExpression()) { Scope scope = new Scope(); Execute(containedLines, i + 1 + currentLineOffset, nestedInFunction, true); scope.End(); } } else if (lines[i][0].type == TokenType.WhileConditional) { Conditional whileStatement = new Conditional(lines[i][0].identifier); while (whileStatement.EvaluateExpression()) { Scope scope = new Scope(); Execute(containedLines, i + 1 + currentLineOffset, nestedInFunction, true); scope.End(); } } else if (lines[i][0].type == TokenType.LoopConditional) { string usage = lines[i][0].identifier; Any[] loopParams = BaseFunction.ParseParameters(usage.Substring(usage.IndexOf("("), usage.LastIndexOf(")") - usage.IndexOf("(") + 1)); // throws errors if given parameters are bad BaseFunction.CheckParameters("Loop", new Parameter[] { new Parameter(Types.String, "indexVariableName"), new Parameter(Types.Integer, "start"), new Parameter(Types.Integer, "exclusiveEnd") }, loopParams.ToList()); Modules.Main.Loop(containedLines, i, currentLineOffset, nestedInFunction, loopParams[0].Value.ToString(), (int)loopParams[1].Value, (int)loopParams[2].Value); } } // skip to after the end of definition i = endingBracket.LineIndex; continue; } if (i >= lines.Count) break; bool shouldBeSet = false; // topmost variable in list should be set after exec if (lines[i].Count >= 2 && lines[i][0].type == TokenType.TypeIdentifier && lines[i][1].type == TokenType.VariableIdentifier) { var varType = Type.GetType(lines[i][0].identifier); var varName = lines[i][1].identifier; // initializing a variable whose type is a FastStruct if (varType is FastStruct) { // check if a variable exists with the same name if (Interpreter.Vars.ContainsKey(varName)) throw new BaseException("Variable '" + varName + "' has already been defined"); List<Variable> memberInstances = new List<Variable>(); foreach (var member in ((FastStruct)varType).Members) { var memberVariable = new Variable(member.Value.Type, varName + "." + member.Key); Interpreter.Vars.Add(memberVariable.Name, memberVariable); memberInstances.Add(Interpreter.Vars[memberVariable.Name]); } Interpreter.Vars.Create(new Variable(varType, varName, memberInstances)); } else Interpreter.Vars.Create(new Variable(varType, varName)); if (lines[i].Count >= 3 && lines[i][2].type == TokenType.EqualOperator) shouldBeSet = true; } // variable must be created before exec is called so that it may be accessed Any retVal = lines[i].Execute(); // Execute line if (retVal != null) { if (lines[i].Count >= 3 && lines[i][1].type == TokenType.VariableIdentifier && lines[i][2].type == TokenType.EqualOperator && !Conversion.IsCompatible(Interpreter.Vars[lines[i][1].identifier].Type, retVal.Type)) throw new ConversionException("Cannot set '" + lines[i][1].identifier + "', type '" + Interpreter.Vars[lines[i][1].identifier].Type.Name + "' is incompatible with type '" + retVal.Type.Name + "'"); // check if types are compatible else if (lines[i].Count >= 2 && lines[i][0].type == TokenType.VariableIdentifier && lines[i][1].type == TokenType.EqualOperator && !Conversion.IsCompatible(Interpreter.Vars[lines[i][0].identifier].Type, retVal.Type)) throw new ConversionException("Cannot set '" + lines[i][0].identifier + "', type '" + Interpreter.Vars[lines[i][0].identifier].Type.Name + "' is incompatible with type '" + retVal.Type.Name + "'"); // check if types are compatible } if (shouldBeSet) { Interpreter.Vars[lines[i][1].identifier].Value = retVal == null ? null : retVal.obj; } else if (lines[i].Count >= 2 && lines[i][0].type == TokenType.VariableIdentifier && lines[i][1].type == TokenType.EqualOperator) { if (!Interpreter.Vars.ContainsKey(lines[i][0].identifier)) throw new BaseException("Variable '" + lines[i][0].identifier + "' must be defined before it can be set"); // var not found Interpreter.Vars[lines[i][0].identifier].Value = retVal == null ? null : retVal.obj; } // type is not specified, var must already be defined } return null; } } }
39.565217
237
0.62967
[ "MIT" ]
CowNation/CowSpeak
CowSpeak-master/Executor.cs
9,100
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace MagiConsole.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Files", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: true), Extension = table.Column<string>(nullable: true), LastModified = table.Column<DateTimeOffset>(nullable: false), Hash = table.Column<string>(nullable: true), Status = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Files", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Files"); } } }
32.764706
81
0.523339
[ "MIT" ]
magico13/MagiCloud
MagiConsole/Migrations/20210909033913_InitialCreate.cs
1,116
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Device.Gpio; using System.Device.I2c; using System.Device.Spi; using System.Threading; using Iot.Device.Mcp23xxx; int s_deviceAddress = 0x20; Debug.WriteLine("Hello Mcp23xxx!"); using Mcp23xxx mcp23xxx = GetMcp23xxxDevice(Mcp23xxxDevice.Mcp23017); using GpioController controllerUsingMcp = new(PinNumberingScheme.Logical, mcp23xxx); // Samples are currently written specifically for the 16 bit variant if (mcp23xxx is Mcp23x1x mcp23x1x) { // Uncomment sample to run ReadSwitchesWriteLeds(mcp23x1x); // WriteByte(mcp23x1x); // WriteUshort(mcp23x1x); // WriteBits(mcp23x1x, controllerUsingMcp); } // Uncomment sample to run // ReadBits(controllerUsingMcp); // Program methods Mcp23xxx GetMcp23xxxDevice(Mcp23xxxDevice mcp23xxxDevice) => mcp23xxxDevice switch { // I2C Mcp23xxxDevice.Mcp23008 => new Mcp23008(NewI2c()), Mcp23xxxDevice.Mcp23009 => new Mcp23009(NewI2c()), Mcp23xxxDevice.Mcp23017 => new Mcp23017(NewI2c()), Mcp23xxxDevice.Mcp23018 => new Mcp23018(NewI2c()), // SPI. Mcp23xxxDevice.Mcp23S08 => new Mcp23s08(NewSpi(), s_deviceAddress), Mcp23xxxDevice.Mcp23S09 => new Mcp23s09(NewSpi()), Mcp23xxxDevice.Mcp23S17 => new Mcp23s17(NewSpi(), s_deviceAddress), Mcp23xxxDevice.Mcp23S18 => new Mcp23s18(NewSpi()), _ => throw new Exception($"Invalid Mcp23xxxDevice: {nameof(mcp23xxxDevice)}"), }; I2cDevice NewI2c() => I2cDevice.Create(new(1, s_deviceAddress)); SpiDevice NewSpi() => SpiDevice.Create(new(0, 0) { ClockFrequency = 1000000, Mode = SpiMode.Mode0 }); void ReadSwitchesWriteLeds(Mcp23x1x mcp23x1x) { Debug.WriteLine("Read Switches & Write LEDs"); // Input direction for switches. mcp23x1x.WriteByte(Register.IODIR, 0b1111_1111, Port.PortA); // Output direction for LEDs. mcp23x1x.WriteByte(Register.IODIR, 0b0000_0000, Port.PortB); while (true) { // Read switches. byte data = mcp23x1x.ReadByte(Register.GPIO, Port.PortA); // Write data to LEDs. mcp23x1x.WriteByte(Register.GPIO, data, Port.PortB); Debug.WriteLine(data); Thread.Sleep(500); } } void WriteByte(Mcp23x1x mcp23x1x) { // This assumes the device is in default Sequential Operation mode. Debug.WriteLine("Write Individual Byte"); Register register = Register.IODIR; void IndividualRead(Mcp23xxx mcp, Register registerToRead) { byte dataRead = mcp23x1x.ReadByte(registerToRead, Port.PortB); Debug.WriteLine($"\tIODIRB: 0x{dataRead:X2}"); } Debug.WriteLine("Before Write"); IndividualRead(mcp23x1x, register); mcp23x1x.WriteByte(register, 0x12, Port.PortB); Debug.WriteLine("After Write"); IndividualRead(mcp23x1x, register); mcp23x1x.WriteByte(register, 0xFF, Port.PortB); Debug.WriteLine("After Writing Again"); IndividualRead(mcp23x1x, register); } void WriteUshort(Mcp23x1x mcp23x1x) { // This assumes the device is in default Sequential Operation mode. Debug.WriteLine("Write Sequential Bytes"); void SequentialRead(Mcp23x1x mcp) { ushort dataRead = mcp.ReadUInt16(Register.IODIR); Debug.WriteLine($"\tIODIRA: 0x{(byte)dataRead:X2}"); Debug.WriteLine($"\tIODIRB: 0x{(byte)dataRead >> 8:X2}"); } Debug.WriteLine("Before Write"); SequentialRead(mcp23x1x); mcp23x1x.WriteUInt16(Register.IODIR, 0x3412); Debug.WriteLine("After Write"); SequentialRead(mcp23x1x); mcp23x1x.WriteUInt16(Register.IODIR, 0xFFFF); Debug.WriteLine("After Writing Again"); SequentialRead(mcp23x1x); } // This is now Read(pinNumber) void ReadBits(GpioController controller) { Debug.WriteLine("Read Bits"); for (int bitNumber = 0; bitNumber < 8; bitNumber++) { PinValue bit = controller.Read(bitNumber); Debug.WriteLine($"{bitNumber}: {bit}"); } } // This is now Write(pinNumber) void WriteBits(Mcp23x1x mcp23x1x, GpioController controller) { Debug.WriteLine("Write Bits"); // Make port output and set all pins. // (SetPinMode will also set the direction for each GPIO pin) mcp23x1x.WriteByte(Register.IODIR, 0x00, Port.PortB); mcp23x1x.WriteByte(Register.GPIO, 0xFF, Port.PortB); for (int bitNumber = 9; bitNumber < 16; bitNumber++) { controller.Write(bitNumber, PinValue.Low); Debug.WriteLine($"Bit {bitNumber} low"); Thread.Sleep(500); controller.Write(bitNumber, PinValue.High); Debug.WriteLine($"Bit {bitNumber} high"); Thread.Sleep(500); } } /// <summary> /// Devive types for Mcp23xxx devices. /// </summary> internal enum Mcp23xxxDevice { // I2C. Mcp23008, Mcp23009, Mcp23017, Mcp23018, // SPI. Mcp23S08, Mcp23S09, Mcp23S17, Mcp23S18 }
28.039773
84
0.693212
[ "MIT" ]
Manny27nyc/nanoFramework.IoT.Device
src/devices_generated/Mcp23xxx/samples/Program.cs
4,935
C#
using System.Collections.Generic; using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; namespace JsonApiDotNetCoreExampleTests.IntegrationTests.QueryStrings { [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class Calendar : Identifiable { [Attr] public string TimeZone { get; set; } [Attr] public int DefaultAppointmentDurationInMinutes { get; set; } [HasMany] public ISet<Appointment> Appointments { get; set; } } }
26.52381
69
0.723519
[ "MIT" ]
3volutionsAG/JsonApiDotNetCore
test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/Calendar.cs
557
C#
using rest_api_blueprint.Constants; using System; using System.ComponentModel.DataAnnotations; namespace rest_api_blueprint.Models.Identity.User { public class SignUpUser { [Required] [MinLength(InputSizes.DEFAULT_TEXT_MIN_LENGTH)] [MaxLength(InputSizes.DEFAULT_TEXT_MAX_LENGTH)] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required] [MaxLength(InputSizes.DEFAULT_TEXT_MAX_LENGTH)] [DataType(DataType.Password)] public string Password { get; set; } public DateTime? Birthday { get; set; } [Required] [MinLength(InputSizes.DEFAULT_TEXT_MIN_LENGTH)] [MaxLength(InputSizes.DEFAULT_TEXT_MAX_LENGTH)] public string FirstName { get; set; } public char? Gender { get; set; } [MinLength(InputSizes.DEFAULT_TEXT_MIN_LENGTH)] [MaxLength(InputSizes.DEFAULT_TEXT_MAX_LENGTH)] public string? LastName { get; set; } } }
30.205882
56
0.653359
[ "MIT" ]
florianrubel/rest-api-blueprint
rest-api-blueprint/Models/Identity/User/SignUpUser.cs
1,029
C#
using UnityEngine; using System.Collections; public class ProgressionScript : MonoBehaviour { public bool route1AStart; public bool route1AEnd; public bool route1BStart; public bool route1BEnd; public bool route2AStart; public bool route2AEnd; public bool route2BStart; public bool route2BEnd; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter(Collider other) { if (other.tag == "Waypoint1AStart") { route1AStart = true; // Debug.LogError("Works"); } if (other.tag == "Waypoint1BStart") { route1BStart = true; } if (other.tag == "Waypoint1AEnd") { route1AEnd = true; } if (other.tag == "Waypoint1BEnd") { route1BEnd = true; } if (other.tag == "Waypoint2AStart") { route2AStart = true; } if (other.tag == "Waypoint2BStart") { route2BStart = true; } if (other.tag == "Waypoint2AEnd") { route2AEnd = true; } if (other.tag == "Waypoint2BEnd") { route2BEnd = true; } } }
15.391304
48
0.637476
[ "Apache-2.0" ]
ChrisMcF/CouchCrusaderRedux
Dungeon/Assets/Scripts/TestScripts/ProgressionScript.cs
1,064
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.MachineLearningServices.V20200101.Outputs { /// <summary> /// A DataFactory compute. /// </summary> [OutputType] public sealed class DataFactoryResponse { /// <summary> /// Location for the underlying compute /// </summary> public readonly string? ComputeLocation; /// <summary> /// The type of compute /// Expected value is 'DataFactory'. /// </summary> public readonly string ComputeType; /// <summary> /// The date and time when the compute was created. /// </summary> public readonly string CreatedOn; /// <summary> /// The description of the Machine Learning compute. /// </summary> public readonly string? Description; /// <summary> /// Indicating whether the compute was provisioned by user and brought from outside if true, or machine learning service provisioned it if false. /// </summary> public readonly bool IsAttachedCompute; /// <summary> /// The date and time when the compute was last modified. /// </summary> public readonly string ModifiedOn; /// <summary> /// Errors during provisioning /// </summary> public readonly ImmutableArray<Outputs.MachineLearningServiceErrorResponse> ProvisioningErrors; /// <summary> /// The provision state of the cluster. Valid values are Unknown, Updating, Provisioning, Succeeded, and Failed. /// </summary> public readonly string ProvisioningState; /// <summary> /// ARM resource id of the underlying compute /// </summary> public readonly string? ResourceId; [OutputConstructor] private DataFactoryResponse( string? computeLocation, string computeType, string createdOn, string? description, bool isAttachedCompute, string modifiedOn, ImmutableArray<Outputs.MachineLearningServiceErrorResponse> provisioningErrors, string provisioningState, string? resourceId) { ComputeLocation = computeLocation; ComputeType = computeType; CreatedOn = createdOn; Description = description; IsAttachedCompute = isAttachedCompute; ModifiedOn = modifiedOn; ProvisioningErrors = provisioningErrors; ProvisioningState = provisioningState; ResourceId = resourceId; } } }
32.741573
153
0.617708
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/MachineLearningServices/V20200101/Outputs/DataFactoryResponse.cs
2,914
C#
#region License // Copyright (c) 2011, ClearCanvas Inc. // All rights reserved. // http://www.clearcanvas.ca // // This software is licensed under the Open Software License v3.0. // For the complete license, see http://www.clearcanvas.ca/OSLv3.0 #endregion using System.Runtime.Serialization; using ClearCanvas.Common.Serialization; using ClearCanvas.Ris.Application.Common; namespace ClearCanvas.Ris.Application.Extended.Common.Admin.ProtocolAdmin { [DataContract] public class AddProtocolGroupResponse : DataContractBase { public AddProtocolGroupResponse(ProtocolGroupSummary summary) { Summary = summary; } [DataMember] public ProtocolGroupSummary Summary; } }
26.344828
74
0.698953
[ "Apache-2.0" ]
SNBnani/Xian
Ris/Application/Extended/Common/Admin/ProtocolAdmin/AddProtocolGroupResponse.cs
764
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Xamarin.Forms.DataGrid.UnitTest.Common; namespace Xamarin.Forms.DataGrid.UnitTest { [TestClass] public class SortingIconTest { [ClassInitialize] public static void Init(TestContext context) { MockPlatform.MockForms.Init(); } [TestMethod] public void SortingIconOnInit() { var dg = new DataGrid { ItemsSource = Util.GetTeams(), Columns = Util.CreateColumns(), }; foreach (var c in dg.Columns) Assert.IsTrue(c.SortingIcon.Source == null); } [TestMethod] public void SortingIconSort() { var dg = new DataGrid { ItemsSource = Util.GetTeams(), Columns = Util.CreateColumns(), }; dg.SortItems(0); Assert.IsTrue(dg.SortedColumnIndex.Index == 0); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.AscendingIcon); for (int i = 1; i < dg.Columns.Count; i++) Assert.IsTrue(dg.Columns[i].SortingIcon.Source == null); } [TestMethod] public void SortingIconSortTwice() { var dg = new DataGrid { ItemsSource = Util.GetTeams(), Columns = Util.CreateColumns(), }; dg.SortItems(0); Assert.IsTrue(dg.SortedColumnIndex.Index == 0); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.AscendingIcon); dg.SortItems(new SortData(0, SortingOrder.Descendant)); Assert.IsTrue(dg.SortedColumnIndex.Index == 0); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Descendant); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.DescendingIcon); for (int i = 1; i < dg.Columns.Count; i++) Assert.IsTrue(dg.Columns[i].SortingIcon.Source == null); } [TestMethod] public void SortingIconSortDifferentColumns() { var dg = new DataGrid { ItemsSource = Util.GetTeams(), Columns = Util.CreateColumns(), }; dg.SortItems(0); Assert.IsTrue(dg.SortedColumnIndex.Index == 0); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.AscendingIcon); dg.SortItems(1); Assert.IsTrue(dg.SortedColumnIndex.Index == 1); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); for (int i = 0; i < dg.Columns.Count; i++) { if (i == 1) Assert.IsTrue(dg.Columns[i].SortingIcon.Source == dg.AscendingIcon); else Assert.IsTrue(dg.Columns[i].SortingIcon.Source == null); } } [TestMethod] public void SortingIconSortColumns010() { var dg = new DataGrid { ItemsSource = Util.GetTeams(), Columns = Util.CreateColumns(), }; dg.SortItems(0); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.AscendingIcon); dg.SortItems(1); Assert.IsTrue(dg.SortedColumnIndex.Index == 1); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); dg.SortItems(0); Assert.IsTrue(dg.Columns[0].SortingIcon.Source == dg.AscendingIcon); Assert.IsTrue(dg.SortedColumnIndex.Index == 0); Assert.IsTrue(dg.SortedColumnIndex.Order == SortingOrder.Ascendant); for (int i = 1; i < dg.Columns.Count; i++) Assert.IsTrue(dg.Columns[i].SortingIcon.Source == null); } } }
26.585366
73
0.690214
[ "MIT" ]
BenCamps/Xamarin.Forms.DataGrid
Xamarin.Forms.DataGrid.UnitTest/SortingIconTest.cs
3,272
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Launch_EventsCollector_WPF.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.870968
151
0.587419
[ "MIT" ]
SammyKrosoft/Get-EventsFromEventLogs
VisualStudio2017WPFDesign/Launch-EventsCollector-WPF/Launch-EventsCollector-WPF/Properties/Settings.Designer.cs
1,083
C#
using Android.App; using Android.Content; using Android.Support.CustomTabs; using Plugin.CurrentActivity; using Plugin.Share.Abstractions; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Plugin.Share { /// <summary> /// Implementation for Feature /// </summary> public class ShareImplementation : IShare { /// <summary> /// Open a browser to a specific url /// </summary> /// <param name="url">Url to open</param> /// <param name="options">Platform specific options</param> /// <returns>True if the operation was successful, false otherwise</returns> public Task<bool> OpenBrowser(string url, BrowserOptions options = null) { try { if (options == null) options = new BrowserOptions(); if (CrossCurrentActivity.Current.Activity == null) { var intent = new Intent(Intent.ActionView); intent.SetData(Android.Net.Uri.Parse(url)); intent.SetFlags(ActivityFlags.ClearTop); intent.SetFlags(ActivityFlags.NewTask); Application.Context.StartActivity(intent); } else { var tabsBuilder = new CustomTabsIntent.Builder(); tabsBuilder.SetShowTitle(options?.ChromeShowTitle ?? false); var toolbarColor = options?.ChromeToolbarColor; if (toolbarColor != null) tabsBuilder.SetToolbarColor(toolbarColor.ToNativeColor()); var intent = tabsBuilder.Build(); intent.LaunchUrl(CrossCurrentActivity.Current.Activity, Android.Net.Uri.Parse(url)); } return Task.FromResult(true); } catch (Exception ex) { Console.WriteLine("Unable to open browser: " + ex.Message); return Task.FromResult(false); } } /// <summary> /// Share a message with compatible services /// </summary> /// <param name="message">Message to share</param> /// <param name="options">Platform specific options</param> /// <returns>True if the operation was successful, false otherwise</returns> public Task<bool> Share(ShareMessage message, ShareOptions options = null) { if (message == null) throw new ArgumentNullException(nameof(message)); try { var items = new List<string>(); if (message.Text != null) items.Add(message.Text); if (message.Url != null) items.Add(message.Url); var intent = new Intent(Intent.ActionSend); intent.SetType("text/plain"); intent.PutExtra(Intent.ExtraText, string.Join(Environment.NewLine, items)); if (message.Title != null) intent.PutExtra(Intent.ExtraSubject, message.Title); var chooserIntent = Intent.CreateChooser(intent, options?.ChooserTitle); chooserIntent.SetFlags(ActivityFlags.ClearTop); chooserIntent.SetFlags(ActivityFlags.NewTask); Application.Context.StartActivity(chooserIntent); return Task.FromResult(true); } catch (Exception ex) { Console.WriteLine("Unable to share: " + ex.Message); return Task.FromResult(false); } } /// <summary> /// Sets text of the clipboard /// </summary> /// <param name="text">Text to set</param> /// <param name="label">Label to display (not required, Android only)</param> /// <returns>True if the operation was successful, false otherwise</returns> public Task<bool> SetClipboardText(string text, string label = null) { try { var sdk = (int)Android.OS.Build.VERSION.SdkInt; if (sdk < (int)Android.OS.BuildVersionCodes.Honeycomb) { var clipboard = (Android.Text.ClipboardManager)Application.Context.GetSystemService(Context.ClipboardService); clipboard.Text = text; } else { var clipboard = (ClipboardManager)Application.Context.GetSystemService(Context.ClipboardService); clipboard.PrimaryClip = ClipData.NewPlainText(label ?? string.Empty, text); } return Task.FromResult(true); } catch (Exception ex) { Console.WriteLine("Unable to copy to clipboard: " + ex.Message); return Task.FromResult(false); } } /// <summary> /// Checks if the url can be opened /// </summary> /// <param name="url">Url to check</param> /// <returns>True if it can</returns> public bool CanOpenUrl(string url) { try { var context = CrossCurrentActivity.Current.Activity ?? Application.Context; var intent = new Intent(Intent.ActionView); intent.SetData(Android.Net.Uri.Parse(url)); intent.SetFlags(ActivityFlags.ClearTop); intent.SetFlags(ActivityFlags.NewTask); return intent.ResolveActivity(context.PackageManager) != null; } catch (Exception ex) { return false; } } /// <summary> /// Gets if cliboard is supported /// </summary> public bool SupportsClipboard => true; } }
35.81875
130
0.557494
[ "MIT" ]
AndreiMisiukevich/SharePlugin
Share/Share.Plugin.Android/ShareImplementation.cs
5,731
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CarServiceProject { using System; using System.Collections.Generic; public partial class Client { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Client() { this.Automobile = new HashSet<Auto>(); this.Comenzi = new HashSet<Comanda>(); } public int Id { get; private set; } public string Nume { get; private set; } public string Prenume { get; private set; } public string Adresa { get; private set; } public string Localitate { get; private set; } public string Judet { get; private set; } public string Telefon { get; private set; } public string Email { get; private set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Auto> Automobile { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Comanda> Comenzi { get; set; } } }
41.769231
128
0.60221
[ "Apache-2.0" ]
ioanabirsan/advanced-topics-net
project-2/CarServiceProject/CarServiceProject/Client.cs
1,629
C#
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Reflection; namespace omopcdmlib.Utils { //https://stackoverflow.com/questions/23225973/parsing-tab-delimited-text-files public class ReadCdmFile<T> { public List<T> Read(string filename, int count = 147483648) { DataTable datatable = new DataTable(); StreamReader streamreader = new StreamReader(filename); char[] delimiter = new char[] { '\t' }; string[] columnheaders = streamreader.ReadLine().Split(delimiter); foreach (string columnheader in columnheaders) { datatable.Columns.Add(columnheader); // I've added the column headers here. } int sample = 0; while (streamreader.Peek() > 0 && sample < count) { DataRow datarow = datatable.NewRow(); datarow.ItemArray = streamreader.ReadLine().Split(delimiter); datatable.Rows.Add(datarow); sample ++; } return ConvertDataTable(datatable); } // https://www.c-sharpcorner.com/UploadFile/ee01e6/different-way-to-convert-datatable-to-list/ private static List<T> ConvertDataTable(DataTable dt) { List<T> data = new List<T>(); int id = 0; foreach (DataRow row in dt.Rows) { T item = GetItem(row, id); data.Add(item); id++; } return data; } private static T GetItem(DataRow dr, int id) { Type temp = typeof(T); T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in dr.Table.Columns) { foreach (PropertyInfo pro in temp.GetProperties()) { // Convert field names to ClassNames before checking Ex: concept_id to ConceptId if (pro.Name == TitleCaseConvert(column.ColumnName)) { // Null values to 0 if("" == (string)dr[column.ColumnName]) dr[column.ColumnName] = "0"; try // setting a string value { pro.SetValue(obj, dr[column.ColumnName], null); }catch // set as an integer { pro.SetValue(obj, Int32.Parse((string)dr[column.ColumnName]), null); } } else if (pro.Name == "Id") pro.SetValue(obj, id, null); else continue; } } return obj; } private static string TitleCaseConvert(string title) { return new CultureInfo("en").TextInfo.ToTitleCase(title.ToLower().Replace("_", " ")).Replace(" ", ""); } } }
36.872093
114
0.483759
[ "MIT" ]
dermatologist/omopcdm-dot-net
omopcdmlib/Utils/ReadCdmFile.cs
3,171
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ClaseNormal { int numero1; int numero2; public ClaseNormal(int param1, int param2) { numero1 = param1; numero2 = param2; } public ClaseNormal(float param1, float param2) { numero1 = (int)param1; numero2 = (int)param2; } public int SumarEnteros(int a, int b) { return a + b; } public float SumarFlotantes(float a, float b) { return a + b; } public static float MultiplicarFlotantes(float a, float b) { return a * b; } }
17.486486
63
0.587326
[ "MIT" ]
diegohdezr/repositorioclaseebac
ProyectoInicialEBAC/Assets/Scripts/ClaseNormal.cs
647
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace ServiceHealthStatus { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddHealthChecksUI() .AddInMemoryStorage(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecksUI(); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
28.345455
106
0.585632
[ "MIT" ]
myexplore/mycart
Sources/Services/Common/ServiceHealthStatus/Startup.cs
1,559
C#
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ElectricStore.Models; public class Customer { public int CustomerId { get; set; } [Display(Name = "First Name")] [Required(ErrorMessage = "Please enter your first name")] public string FirstName { get; set; } = null!; [Display(Name = "Last Name")] [Required(ErrorMessage = "Please enter your last name")] public string LastName { get; set; } = null!; [DataType(DataType.EmailAddress)] [Required(ErrorMessage = "Please enter your email address")] public string Email { get; set; } = null!; [Display(Name = "Phone"), DataType(DataType.PhoneNumber)] public int PhoneNumber { get; set; } [Required(ErrorMessage = "Please enter your adress")] public string Address { get; set; } = null!; public virtual List<CustomersProducts> CustomerProducts { get; set; } = null!; [NotMapped] [Display(Name = "Products List")] public List<int> SelectedProductsList { get; set; } = null!; }
31.176471
82
0.680189
[ "MIT" ]
EricCote/20486D-New
Allfiles/Mod12/Labfiles/01_ElectricStore_end/ElectricStore/Models/Customer.cs
1,062
C#
#if !NETSTANDARD_TODO using System.Collections.Generic; using System.Threading.Tasks; using AWSUtils.Tests.StorageTests; using Orleans.Providers.Streams; using Orleans.Storage; using Orleans.TestingHost; using OrleansAWSUtils.Streams; using UnitTests.StreamingTests; using Xunit; using Orleans.Runtime.Configuration; using TestExtensions; using UnitTests.Streaming; namespace AWSUtils.Tests.Streaming { [TestCategory("AWS"), TestCategory("SQS")] public class SQSStreamTests : TestClusterPerTest { public static readonly string SQS_STREAM_PROVIDER_NAME = "SQSProvider"; private SingleStreamTestRunner runner; public override TestCluster CreateTestCluster() { var options = new TestClusterOptions(); //from the config files options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore", numStorageGrains: 1); options.ClusterConfiguration.AddSimpleMessageStreamProvider("SMSProvider", fireAndForgetDelivery: false); options.ClientConfiguration.AddSimpleMessageStreamProvider("SMSProvider", fireAndForgetDelivery: false); //previous silo creation options.ClusterConfiguration.Globals.DataConnectionString = AWSTestConstants.DefaultSQSConnectionString; options.ClientConfiguration.DataConnectionString = AWSTestConstants.DefaultSQSConnectionString; var streamConnectionString = new Dictionary<string, string> { { "DataConnectionString", AWSTestConstants.DefaultSQSConnectionString} }; options.ClientConfiguration.RegisterStreamProvider<SQSStreamProvider>("SQSProvider", streamConnectionString); options.ClusterConfiguration.Globals.RegisterStreamProvider<SQSStreamProvider>("SQSProvider", streamConnectionString); options.ClusterConfiguration.Globals.RegisterStreamProvider<SQSStreamProvider>("SQSProvider2", streamConnectionString); var storageConnectionString = new Dictionary<string, string> { { "DataConnectionString", $"Service={AWSTestConstants.Service}"}, { "DeleteStateOnClear", "true"} }; options.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBStorageProvider>("DynamoDBStore", storageConnectionString); var storageConnectionString2 = new Dictionary<string, string> { { "DataConnectionString", $"Service={AWSTestConstants.Service}"}, { "DeleteStateOnClear", "true"}, { "UseJsonFormat", "true"} }; options.ClusterConfiguration.Globals.RegisterStorageProvider<DynamoDBStorageProvider>("PubSubStore", storageConnectionString2); return new TestCluster(options); } public SQSStreamTests() { runner = new SingleStreamTestRunner(this.InternalClient, SQS_STREAM_PROVIDER_NAME); } public override void Dispose() { var deploymentId = HostedCluster.DeploymentId; base.Dispose(); SQSStreamProviderUtils.DeleteAllUsedQueues(SQS_STREAM_PROVIDER_NAME, deploymentId, AWSTestConstants.DefaultSQSConnectionString).Wait(); } ////------------------------ One to One ----------------------// [Fact] public async Task SQS_01_OneProducerGrainOneConsumerGrain() { await runner.StreamTest_01_OneProducerGrainOneConsumerGrain(); } [Fact] public async Task SQS_02_OneProducerGrainOneConsumerClient() { await runner.StreamTest_02_OneProducerGrainOneConsumerClient(); } [Fact] public async Task SQS_03_OneProducerClientOneConsumerGrain() { await runner.StreamTest_03_OneProducerClientOneConsumerGrain(); } [Fact] public async Task SQS_04_OneProducerClientOneConsumerClient() { await runner.StreamTest_04_OneProducerClientOneConsumerClient(); } //------------------------ MANY to Many different grains ----------------------// [Fact] public async Task SQS_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains() { await runner.StreamTest_05_ManyDifferent_ManyProducerGrainsManyConsumerGrains(); } [Fact] public async Task SQS_06_ManyDifferent_ManyProducerGrainManyConsumerClients() { await runner.StreamTest_06_ManyDifferent_ManyProducerGrainManyConsumerClients(); } [Fact] public async Task SQS_07_ManyDifferent_ManyProducerClientsManyConsumerGrains() { await runner.StreamTest_07_ManyDifferent_ManyProducerClientsManyConsumerGrains(); } [Fact] public async Task SQS_08_ManyDifferent_ManyProducerClientsManyConsumerClients() { await runner.StreamTest_08_ManyDifferent_ManyProducerClientsManyConsumerClients(); } //------------------------ MANY to Many Same grains ----------------------// [Fact] public async Task SQS_09_ManySame_ManyProducerGrainsManyConsumerGrains() { await runner.StreamTest_09_ManySame_ManyProducerGrainsManyConsumerGrains(); } [Fact] public async Task SQS_10_ManySame_ManyConsumerGrainsManyProducerGrains() { await runner.StreamTest_10_ManySame_ManyConsumerGrainsManyProducerGrains(); } [Fact] public async Task SQS_11_ManySame_ManyProducerGrainsManyConsumerClients() { await runner.StreamTest_11_ManySame_ManyProducerGrainsManyConsumerClients(); } [Fact] public async Task SQS_12_ManySame_ManyProducerClientsManyConsumerGrains() { await runner.StreamTest_12_ManySame_ManyProducerClientsManyConsumerGrains(); } //------------------------ MANY to Many producer consumer same grain ----------------------// [Fact] public async Task SQS_13_SameGrain_ConsumerFirstProducerLater() { await runner.StreamTest_13_SameGrain_ConsumerFirstProducerLater(false); } [Fact] public async Task SQS_14_SameGrain_ProducerFirstConsumerLater() { await runner.StreamTest_14_SameGrain_ProducerFirstConsumerLater(false); } //----------------------------------------------// [Fact] public async Task SQS_15_ConsumeAtProducersRequest() { await runner.StreamTest_15_ConsumeAtProducersRequest(); } [Fact] public async Task SQS_16_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains() { var multiRunner = new MultipleStreamsTestRunner(this.InternalClient, SQS_STREAM_PROVIDER_NAME, 16, false); await multiRunner.StreamTest_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains(); } [Fact] public async Task SQS_17_MultipleStreams_1J_ManyProducerGrainsManyConsumerGrains() { var multiRunner = new MultipleStreamsTestRunner(this.InternalClient, SQS_STREAM_PROVIDER_NAME, 17, false); await multiRunner.StreamTest_MultipleStreams_ManyDifferent_ManyProducerGrainsManyConsumerGrains( this.HostedCluster.StartAdditionalSilo); } } } #endif
38.803109
147
0.665242
[ "MIT" ]
flint-stone/orleans
test/AWSUtils.Tests/Streaming/SQSStreamTests.cs
7,491
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.269 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Plugin.sqlite { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SqlScripts { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SqlScripts() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Plugin.sqlite.SqlScripts", typeof(SqlScripts).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to CREATE TRIGGER &lt;trigger_name&gt; UPDATE OF &lt;column&gt; ON &lt;table&gt; /// BEGIN /// -- UPDATE orders SET address = new.address WHERE customer_name = old.name; /// END; ///. /// </summary> internal static string createtrigger { get { return ResourceManager.GetString("createtrigger", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot;?&gt; ///&lt;SyntaxDefinition name=&quot;Sql_sqlite&quot; extensions=&quot;.sql&quot;&gt; /// &lt;Digits name=&quot;Digits&quot; bold=&quot;false&quot; italic=&quot;false&quot; color=&quot;DarkBlue&quot;/&gt; /// /// &lt;RuleSets&gt; /// &lt;RuleSet ignorecase=&quot;true&quot;&gt; /// &lt;Delimiters&gt;&amp;amp;&amp;lt;&amp;gt;~!%^*()-+=|\#/{}[]:;&quot;&apos; , .?&lt;/Delimiters&gt; /// /// &lt;Span name=&quot;LineComment&quot; stopateol=&quot;true&quot; bold=&quot;false&quot; italic=&quot;false&quot; color=&quot;Gray&quot; &gt; /// &lt;Begin &gt;--&lt;/Begin&gt; /// &lt;/Span&gt; /// /// &lt;Span name=&quot;BlockComment&quot; stopateol=&quot;false&quot; bold=&quot;false&quot; italic=&quot;false&quot; color=&quot;Gray&quot; [rest of string was truncated]&quot;;. /// </summary> internal static string syntax { get { return ResourceManager.GetString("syntax", resourceCulture); } } } }
45.673469
190
0.584004
[ "MIT" ]
dbgate/datadmin
Plugin.sqlite/SqlScripts.Designer.cs
4,478
C#
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XF.Material.Forms.Resources; namespace XF.Material.Forms.UI.Internals { /// <summary> /// Internal base class of selection controls such as <see cref="MaterialCheckbox"/> and <see cref="MaterialRadioButton"/>. /// </summary> [XamlCompilation(XamlCompilationOptions.Compile)] public partial class BaseMaterialSelectionControl : ContentView { /// <summary> /// Backing field for the bindable property <see cref="FontFamily"/>. /// </summary> public static readonly BindableProperty FontFamilyProperty = BindableProperty.Create(nameof(FontFamily), typeof(string), typeof(BaseMaterialSelectionControl), string.Empty); /// <summary> /// Backing field for the bindable property <see cref="FontSize"/>. /// </summary> public static readonly BindableProperty FontSizeProperty = BindableProperty.Create(nameof(FontSize), typeof(double), typeof(BaseMaterialSelectionControl), Material.GetResource<double>(MaterialConstants.MATERIAL_FONTSIZE_BODY1)); /// <summary> /// Backing field for the bindable property <see cref="HorizontalSpacing"/>. /// </summary> public static readonly BindableProperty HorizontalSpacingProperty = BindableProperty.Create(nameof(HorizontalSpacing), typeof(double), typeof(BaseMaterialSelectionControl), 0.0); /// <summary> /// Backing field for the bindable property <see cref="IsSelected"/>. /// </summary> public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create(nameof(IsSelected), typeof(bool), typeof(BaseMaterialSelectionControl), false, BindingMode.TwoWay); /// <summary> /// Backing field for the bindable property <see cref="SelectedChangeCommand"/>. /// </summary> public static readonly BindableProperty SelectedChangeCommandProperty = BindableProperty.Create(nameof(SelectedChangeCommand), typeof(Command<bool>), typeof(BaseMaterialSelectionControl)); /// <summary> /// Backing field for the bindable property <see cref="SelectedColor"/>. /// </summary> public static readonly BindableProperty SelectedColorProperty = BindableProperty.Create(nameof(SelectedColor), typeof(Color), typeof(BaseMaterialSelectionControl), Material.Color.Secondary); /// <summary> /// Backing field for the bindable property <see cref="TextColor"/>. /// </summary> public static readonly BindableProperty TextColorProperty = BindableProperty.Create(nameof(TextColor), typeof(Color), typeof(BaseMaterialSelectionControl), Color.FromHex("#DE000000")); /// <summary> /// Backing field for the bindable property <see cref="Text"/>. /// </summary> public static readonly BindableProperty TextProperty = BindableProperty.Create(nameof(Text), typeof(string), typeof(BaseMaterialSelectionControl), string.Empty); /// <summary> /// Backing field for the bindable property <see cref="UnselectedColor"/>. /// </summary> public static readonly BindableProperty UnselectedColorProperty = BindableProperty.Create(nameof(UnselectedColor), typeof(Color), typeof(BaseMaterialSelectionControl), Color.FromHex("#84000000")); /// <summary> /// Backing field for the bindable property <see cref="VerticalSpacing"/>. /// </summary> public static readonly BindableProperty VerticalSpacingProperty = BindableProperty.Create(nameof(VerticalSpacing), typeof(double), typeof(BaseMaterialSelectionControlGroup), 0.0); private readonly Dictionary<string, Action> _propertyChangeActions; private string _selectedSource; private string _unselectedSource; internal BaseMaterialSelectionControl(MaterialSelectionControlType controlType) { InitializeComponent(); SetPropertyChangeHandler(ref _propertyChangeActions); SetControlType(controlType); SetControl(); } /// <summary> /// Raised when this selection control was selected or deselected. /// </summary> public event EventHandler<SelectedChangedEventArgs> SelectedChanged; /// <summary> /// Gets or sets the font family of the selection control's text. /// </summary> public string FontFamily { get => (string)GetValue(FontFamilyProperty); set => SetValue(FontFamilyProperty, value); } /// <summary> /// Gets or sets the font size of the selection control's text. /// </summary> public double FontSize { get => (double)GetValue(FontSizeProperty); set => SetValue(FontSizeProperty, value); } /// <summary> /// Gets or sets the spacing between the selection control's image and text. /// </summary> public double HorizontalSpacing { get => (double)GetValue(HorizontalSpacingProperty); set => SetValue(HorizontalSpacingProperty, value); } /// <summary> /// Gets or sets the boolean value whether this selection control was selected or not. /// </summary> public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); } /// <summary> /// Gets or sets the command that will execute when this selection control was selected or not. /// </summary> public Command<bool> SelectedChangeCommand { get => (Command<bool>)GetValue(SelectedChangeCommandProperty); set => SetValue(SelectedChangeCommandProperty, value); } /// <summary> /// Gets or sets the color of the selection control image if it was selected. /// </summary> public Color SelectedColor { get => (Color)GetValue(SelectedColorProperty); set => SetValue(SelectedColorProperty, value); } /// <summary> /// Gets or sets the selection control's text. /// </summary> public string Text { get => (string)GetValue(TextProperty); set => SetValue(TextProperty, value); } /// <summary> /// Gets or sets the selection control's text color. /// </summary> public Color TextColor { get => (Color)GetValue(TextColorProperty); set => SetValue(TextColorProperty, value); } /// <summary> /// Gets or sets the color of the selection control image if it was not selected. /// </summary> public Color UnselectedColor { get => (Color)GetValue(UnselectedColorProperty); set => SetValue(UnselectedColorProperty, value); } internal double VerticalSpacing { get => (double)GetValue(VerticalSpacingProperty); set => SetValue(VerticalSpacingProperty, value); } protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) { base.OnPropertyChanged(propertyName); if (propertyName == null) { return; } if (_propertyChangeActions != null && _propertyChangeActions.TryGetValue(propertyName, out var handlePropertyChange)) { handlePropertyChange(); } } private void OnEnableChanged(bool isEnabled) { Opacity = isEnabled ? 1.0 : 0.38; } private void OnFontFamilyChanged(string fontFamily) { selectionText.FontFamily = fontFamily; } private void OnFontSizeChanged(double fontSize) { selectionText.FontSize = fontSize; } private void OnHorizontalSpacingChanged(double value) { selectionText.Margin = new Thickness(value, 16, 0, 16); } private void OnSelectedChanged(bool isSelected) { selectionIcon.Source = isSelected ? _selectedSource : _unselectedSource; selectionIcon.TintColor = isSelected ? SelectedColor : UnselectedColor; SelectedChanged?.Invoke(this, new SelectedChangedEventArgs(isSelected)); SelectedChangeCommand?.Execute(isSelected); } private void OnStateColorChanged(bool isSelected) { selectionIcon.TintColor = isSelected ? SelectedColor : UnselectedColor; } private void OnTextChanged() { selectionText.Text = Text; } private void OnTextColorChanged() { selectionText.TextColor = TextColor; } private void OnVerticalSpacingChanged(double value) { Margin = new Thickness(Margin.Left, Margin.Top, Margin.Right, value); } private void SetControl() { selectionIcon.Source = IsSelected ? _selectedSource : _unselectedSource; selectionIcon.TintColor = IsSelected ? SelectedColor : UnselectedColor; iconButton.Command = selectionButton.Command = new Command(() => { IsSelected = !IsSelected; }); selectionText.Text = Text; } private void SetControlType(MaterialSelectionControlType controlType) { switch (controlType) { case MaterialSelectionControlType.Checkbox: _selectedSource = "xf_checkbox_selected"; _unselectedSource = "xf_checkbox_unselected"; break; case MaterialSelectionControlType.RadioButton: _selectedSource = "xf_radio_button_selected"; _unselectedSource = "xf_radio_button_unselected"; selectionIcon.WidthRequest = selectionIcon.HeightRequest = 20; break; } } private void SetPropertyChangeHandler(ref Dictionary<string, Action> propertyChangeActions) { propertyChangeActions = new Dictionary<string, Action> { { nameof(Text), OnTextChanged }, { nameof(TextColor), OnTextColorChanged }, { nameof(IsSelected), () => OnSelectedChanged(IsSelected) }, { nameof(SelectedColor), () => OnStateColorChanged(IsSelected) }, { nameof(UnselectedColor), () => OnStateColorChanged(IsSelected) }, { nameof(IsEnabled), () => OnEnableChanged(IsEnabled) }, { nameof(FontFamily), () => OnFontFamilyChanged(FontFamily) }, { nameof(HorizontalSpacing), () => OnHorizontalSpacingChanged(HorizontalSpacing) }, { nameof(VerticalSpacing), () => OnVerticalSpacingChanged(VerticalSpacing) }, { nameof(FontSize), () => OnFontSizeChanged(FontSize) }, }; } } }
40.218638
236
0.623028
[ "MIT" ]
Arbalets/XF-Material-Library
XF.Material/UI/Internals/BaseMaterialSelectionControl.xaml.cs
11,223
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Upgrade.InternalController.Steps { using System; using System.IO; using System.Web; using DotNetNuke.Common; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Membership; using DotNetNuke.Services.FileSystem; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Upgrade.Internals; using DotNetNuke.Services.Upgrade.Internals.InstallConfiguration; using DotNetNuke.Services.Upgrade.Internals.Steps; /// ----------------------------------------------------------------------------- /// <summary> /// InstallSiteStep - Step that installs Website. /// </summary> /// ----------------------------------------------------------------------------- public class InstallSiteStep : BaseInstallationStep { /// <summary> /// Main method to execute the step. /// </summary> public override void Execute() { this.Percentage = 0; this.Status = StepStatus.Running; // Set Status to None Globals.SetStatus(Globals.UpgradeStatus.None); var installConfig = InstallController.Instance.GetInstallConfig(); var percentForEachStep = 100 / installConfig.Portals.Count; var counter = 0; foreach (var portal in installConfig.Portals) { string description = Localization.GetString("CreatingSite", this.LocalInstallResourceFile); this.Details = string.Format(description, portal.PortalName); this.CreateSite(portal, installConfig); counter++; this.Percentage = percentForEachStep * counter++; } Globals.ResetAppStartElapseTime(); this.Status = StepStatus.Done; } private void CreateSite(PortalConfig portal, InstallConfig installConfig) { var domain = string.Empty; if (HttpContext.Current != null) { domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install/launchautoinstall", string.Empty).Replace("/install", string.Empty).Replace("/runinstall", string.Empty); } var serverPath = Globals.ApplicationMapPath + "\\"; // Get the Portal Alias var portalAlias = domain; if (portal.PortAliases.Count > 0) { portalAlias = portal.PortAliases[0]; } // Verify that portal alias is not present if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) { string description = Localization.GetString("SkipCreatingSite", this.LocalInstallResourceFile); this.Details = string.Format(description, portalAlias); return; } // Create default email var email = portal.AdminEmail; if (string.IsNullOrEmpty(email)) { email = "admin@" + domain.Replace("www.", string.Empty); // Remove any domain subfolder information ( if it exists ) if (email.IndexOf("/") != -1) { email = email.Substring(0, email.IndexOf("/")); } } // install LP if installing in a different language string culture = installConfig.InstallCulture; if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); string lpFilePath = installFolder + "\\installlanguage.resources"; if (File.Exists(lpFilePath)) { if (!Upgrade.InstallPackage(lpFilePath, "Language", false)) { culture = Localization.SystemLocale; } } else { culture = Localization.SystemLocale; } } var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); UserInfo userInfo; if (!string.IsNullOrEmpty(portal.AdminUserName)) { userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); } else { userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); } var childPath = string.Empty; if (portal.IsChild) { childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); } // Create Folder Mappings config if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } // add item to identity install from install wizard. if (HttpContext.Current != null) { HttpContext.Current.Items.Add("InstallFromWizard", true); } // Create Portal var portalId = PortalController.Instance.CreatePortal( portal.PortalName, userInfo, portal.Description, portal.Keywords, template, portal.HomeDirectory, portalAlias, serverPath, serverPath + childPath, portal.IsChild); if (portalId > -1) { foreach (var alias in portal.PortAliases) { PortalController.Instance.AddPortalAlias(portalId, alias); } } // remove en-US from portal if installing in a different language if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { var locale = LocaleController.Instance.GetLocale("en-US"); Localization.RemoveLanguageFromPortal(portalId, locale.LanguageId, true); } // Log user in to site var loginStatus = UserLoginStatus.LOGIN_FAILURE; UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, string.Empty, string.Empty, string.Empty, ref loginStatus, false); InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); } // private void CreateFolderMappingConfig(string folderMappinsSettings) // { // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); // if (!File.Exists(folderMappingsConfigPath)) // { // File.AppendAllText(folderMappingsConfigPath, "<folderMappingsSettings>" + folderMappinsSettings + "</folderMappingsSettings>"); // } // } } }
40.095238
224
0.573898
[ "MIT" ]
Mariusz11711/DNN
DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs
7,580
C#
// // EndpointDispatcher.cs // // Author: // Atsushi Enomoto <atsushi@ximian.com> // // Copyright (C) 2005-2010 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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.ServiceModel.Description; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security.Tokens; using System.Text; namespace System.ServiceModel.Dispatcher { public class EndpointDispatcher { EndpointAddress address; string contract_name, contract_ns; ChannelDispatcher channel_dispatcher; MessageFilter address_filter; MessageFilter contract_filter; int filter_priority; DispatchRuntime dispatch_runtime; // Umm, this API is ugly, since it or its members will // anyways require ServiceEndpoint, those arguments are // likely to be replaced by ServiceEndpoint (especially // considering about possible EndpointAddress inconsistency). public EndpointDispatcher (EndpointAddress address, string contractName, string contractNamespace) { if (contractName == null) throw new ArgumentNullException ("contractName"); if (contractNamespace == null) throw new ArgumentNullException ("contractNamespace"); if (address == null) throw new ArgumentNullException ("address"); this.address = address; contract_name = contractName; contract_ns = contractNamespace; dispatch_runtime = new DispatchRuntime (this, null); this.address_filter = new EndpointAddressMessageFilter (address); } public DispatchRuntime DispatchRuntime { get { return dispatch_runtime; } } public string ContractName { get { return contract_name; } } public string ContractNamespace { get { return contract_ns; } } public ChannelDispatcher ChannelDispatcher { get { return channel_dispatcher; } internal set { channel_dispatcher = value; } } public MessageFilter AddressFilter { get { return address_filter; } set { if (value == null) throw new ArgumentNullException ("value"); address_filter = value; } } public MessageFilter ContractFilter { get { return contract_filter ?? (contract_filter = new MatchAllMessageFilter ()); } set { if (value == null) throw new ArgumentNullException ("value"); contract_filter = value; } } public EndpointAddress EndpointAddress { get { return address; } } public int FilterPriority { get { return filter_priority; } set { filter_priority = value; } } public bool IsSystemEndpoint { get; private set; } internal void InitializeServiceEndpoint (bool isCallback, Type serviceType, ServiceEndpoint se) { IsSystemEndpoint = se.IsSystemEndpoint; this.ContractFilter = GetContractFilter (se.Contract, isCallback); this.DispatchRuntime.Type = serviceType; //Build the dispatch operations DispatchRuntime db = this.DispatchRuntime; if (!isCallback && se.Contract.CallbackContractType != null) { var ccd = se.Contract; db.CallbackClientRuntime.CallbackClientType = se.Contract.CallbackContractType; db.CallbackClientRuntime.ContractClientType = se.Contract.ContractType; ccd.FillClientOperations (db.CallbackClientRuntime, true); } foreach (OperationDescription od in se.Contract.Operations) if (od.InCallbackContract == isCallback/* && !db.Operations.Contains (od.Name)*/) PopulateDispatchOperation (db, od); } void PopulateDispatchOperation (DispatchRuntime db, OperationDescription od) { string reqA = null, resA = null; foreach (MessageDescription m in od.Messages) { if (m.IsRequest) reqA = m.Action; else resA = m.Action; } DispatchOperation o = od.IsOneWay ? new DispatchOperation (db, od.Name, reqA) : new DispatchOperation (db, od.Name, reqA, resA); o.IsTerminating = od.IsTerminating; bool no_serialized_reply = od.IsOneWay; foreach (MessageDescription md in od.Messages) { if (md.IsRequest && md.Body.Parts.Count == 1 && md.Body.Parts [0].Type == typeof (Message)) o.DeserializeRequest = false; if (!md.IsRequest && md.Body.ReturnValue != null) { if (md.Body.ReturnValue.Type == typeof (Message)) o.SerializeReply = false; else if (md.Body.ReturnValue.Type == typeof (void)) no_serialized_reply = true; } } foreach (var fd in od.Faults) o.FaultContractInfos.Add (new FaultContractInfo (fd.Action, fd.DetailType)); // Setup Invoker o.Invoker = new DefaultOperationInvoker (od); // Setup Formater // FIXME: this seems to be null at initializing, and should be set after applying all behaviors. // I leave this as is to not regress and it's cosmetic compatibility to fix. // FIXME: pass correct isRpc, isEncoded o.Formatter = new OperationFormatter (od, false, false); if (o.Action == "*" && (o.IsOneWay || o.ReplyAction == "*")) { //Signature : Message (Message) // : void (Message) //FIXME: void (IChannel) if (!o.DeserializeRequest && (!o.SerializeReply || no_serialized_reply)) // what is this double-ish check for? db.UnhandledDispatchOperation = o; } db.Operations.Add (o); } MessageFilter GetContractFilter (ContractDescription cd, bool isCallback) { List<string> actions = new List<string> (); foreach (var od in cd.Operations) { foreach (var md in od.Messages) // For callback EndpointDispatcher (i.e. for duplex client), it should get "incoming" request for callback operations and "outgoing" response for non-callback operations. // For non-callback EndpointDispatcher, it should get "outgoing" request for non-callback operations and "incoming" response for callback operations. if ((od.InCallbackContract == isCallback) == md.IsRequest) { if (md.Action == "*") return new MatchAllMessageFilter (); else actions.Add (md.Action); } } return new ActionMessageFilter (actions.ToArray ()); } } }
33.961722
175
0.718794
[ "Apache-2.0" ]
AvolitesMarkDaniel/mono
mcs/class/System.ServiceModel/System.ServiceModel.Dispatcher/EndpointDispatcher.cs
7,098
C#
using System.Threading.Tasks; using NServiceBus; #region InjectingDependency public class MyHandler : IHandleMessages<MyMessage> { MyService myService; public MyHandler(MyService myService) { this.myService = myService; } public Task Handle(MyMessage message, IMessageHandlerContext context) { myService.WriteHello(); return Task.CompletedTask; } } #endregion
20.904762
74
0.671982
[ "Apache-2.0" ]
A-Franklin/docs.particular.net
samples/containers/autofac/Autofac_6/Sample/MyHandler.cs
421
C#
using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using AutoMapper.QueryableExtensions; using AutoMapper.UnitTests; using Shouldly; using Xunit; namespace AutoMapper.IntegrationTests.Net4 { public class NestedExplicitExpand : AutoMapperSpecBase { protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { var mappingClass1 = cfg.CreateProjection<Class1, Class1DTO>(); mappingClass1.ForMember(dest => dest.IdDTO, opt => opt.MapFrom(src => src.Id)); mappingClass1.ForMember(dest => dest.NameDTO, opt => opt.MapFrom(src => src.Name)); mappingClass1.ForMember(dest => dest.Class2DTO, opt => { opt.MapFrom(src => src.Class2); opt.ExplicitExpansion(); }); var mappingClass2 = cfg.CreateProjection<Class2, Class2DTO>(); mappingClass2.ForMember(dest => dest.IdDTO, opt => opt.MapFrom(src => src.Id)); mappingClass2.ForMember(dest => dest.NameDTO, opt => opt.MapFrom(src => src.Name)); mappingClass2.ForMember(dest => dest.Class3DTO, opt => { opt.MapFrom(src => src.Class3); opt.ExplicitExpansion(); }); var mappingClass3 = cfg.CreateProjection<Class3, Class3DTO>(); mappingClass3.ForMember(dest => dest.IdDTO, opt => opt.MapFrom(src => src.Id)); mappingClass3.ForMember(dest => dest.NameDTO, opt => opt.MapFrom(src => src.Name)); //This is the trouble mapping mappingClass3.ForMember(dest => dest.Class2DTO, opt => { opt.MapFrom(src => src.Class2); opt.ExplicitExpansion(); }); }); [Fact] public void Should_handle_nested_explicit_expand_with_expressions() { Class1DTO[] dtos; using(TestContext context = new TestContext()) { context.Database.Log = s => Debug.WriteLine(s); dtos = ProjectTo<Class1DTO>(context.Class1Set, null, r => r.Class2DTO, r => r.Class2DTO.Class3DTO).ToArray(); } Check(dtos); } [Fact] public void Should_handle_nested_explicit_expand_with_strings() { Class1DTO[] dtos; using(TestContext context = new TestContext()) { context.Database.Log = s => Debug.WriteLine(s); dtos = ProjectTo<Class1DTO>(context.Class1Set, null, "Class2DTO", "Class2DTO.Class3DTO").ToArray(); } Check(dtos); } private void Check(Class1DTO[] dtos) { dtos.Length.ShouldBe(3); dtos.Select(d => d.IdDTO).ShouldBe(new[] { 1, 2, 3 }); dtos.Select(d => d.Class2DTO.IdDTO).ShouldBe(new[] { 1, 2, 3 }); dtos.Select(d => d.Class2DTO.Class3DTO.IdDTO).ShouldBe(new[] { 1, 2, 3 }); dtos.Select(d => d.Class2DTO.Class3DTO.Class2DTO).ShouldBe(new Class2DTO[] { null, null, null }); } public class TestContext : System.Data.Entity.DbContext { public TestContext() { Database.SetInitializer<TestContext>(new DatabaseInitializer()); } public DbSet<Class1> Class1Set { get; set; } public DbSet<Class2> Class2Set { get; set; } public DbSet<Class3> Class3Set { get; set; } } public class DatabaseInitializer : CreateDatabaseIfNotExists<TestContext> { protected override void Seed(TestContext context) { context.Class1Set.AddRange(new[] { new Class1 { Class2 = new Class2 { Class3 = new Class3 { Name = "SomeValue" }}, Name = "Alain Brito"}, new Class1 { Class2 = new Class2 { Class3 = new Class3 { Name = "OtherValue" }}, Name = "Jimmy Bogard"}, new Class1 { Class2 = new Class2 { Class3 = new Class3 { Name = "SomeValue" }}, Name = "Bill Gates"} }); base.Seed(context); } } public class Class1DTO { public int IdDTO { get; set; } public string NameDTO { get; set; } public Class2DTO Class2DTO { get; set; } } public class Class2DTO { public int IdDTO { get; set; } public string NameDTO { get; set; } public Class3DTO Class3DTO { get; set; } } public class Class3DTO { public int IdDTO { get; set; } public string NameDTO { get; set; } public Class2DTO Class2DTO { get; set; } } public class Class1 { [System.ComponentModel.DataAnnotations.Key] public int Id { get; set; } public string Name { get; set; } public Class2 Class2 { get; set; } } public class Class2 { [System.ComponentModel.DataAnnotations.Key] public int Id { get; set; } public string Name { get; set; } public Class3 Class3 { get; set; } } public class Class3 { [System.ComponentModel.DataAnnotations.Key, System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute("Class2")] public int Id { get; set; } public string Name { get; set; } public Class2 Class2 { get; set; } } } }
36.140127
141
0.550405
[ "MIT" ]
AutoMapper/AutoMapper
src/IntegrationTests/ExplicitExpansion/NestedExplicitExpand.cs
5,676
C#
using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Text; namespace Rye.Security { /// <summary> /// Hash操作类 /// </summary> public static class HashManager { /// <summary> /// 获取字符串的MD5哈希值,默认编码为UTF8 /// </summary> /// <param name="value">字符串</param> /// <param name="encoding">编码</param> public static string GetMd5(string value, Encoding encoding = null) { Check.NotNullOrEmpty(value, nameof(value)); if (encoding == null) { encoding = Encoding.UTF8; } byte[] bytes = encoding.GetBytes(value); return GetMd5(bytes); } /// <summary> /// 获取字节数组的MD5哈希值 /// </summary> /// <param name="bytes">字节数组</param> public static string GetMd5(byte[] bytes) { Check.NotNullOrEmpty(bytes, nameof(bytes)); StringBuilder sb = new StringBuilder(); using (MD5 hash = new MD5CryptoServiceProvider()) { bytes = hash.ComputeHash(bytes); foreach (byte b in bytes) { sb.AppendFormat("{0:x2}", b); } return sb.ToString(); } } /// <summary> /// 获取字符串的SHA1哈希值,默认编码为UTF8 /// </summary> /// <param name="value">字符串</param> /// <param name="encoding">编码</param> public static string GetSha1(string value, Encoding encoding = null) { Check.NotNullOrEmpty(value, nameof(value)); StringBuilder sb = new StringBuilder(); using (SHA1Managed hash = new SHA1Managed()) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] bytes = hash.ComputeHash(encoding.GetBytes(value)); foreach (byte b in bytes) { sb.AppendFormat("{0:x2}", b); } return sb.ToString(); } } /// <summary> /// 获取字符串的Sha256哈希值,默认编码为UTF8 /// </summary> /// <param name="value">字符串</param> /// <param name="encoding">编码</param> public static string GetSha256(string value, Encoding encoding = null) { Check.NotNullOrEmpty(value, nameof(value)); StringBuilder sb = new StringBuilder(); using (SHA256Managed hash = new SHA256Managed()) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] bytes = hash.ComputeHash(encoding.GetBytes(value)); foreach (byte b in bytes) { sb.AppendFormat("{0:x2}", b); } return sb.ToString(); } } /// <summary> /// 获取字符串的Sha512哈希值,默认编码为UTF8 /// </summary> /// <param name="value">字符串</param> /// <param name="encoding">编码</param> public static string GetSha512(string value, Encoding encoding = null) { Check.NotNullOrEmpty(value, nameof(value)); StringBuilder sb = new StringBuilder(); using (SHA512Managed hash = new SHA512Managed()) { if (encoding == null) { encoding = Encoding.UTF8; } byte[] bytes = hash.ComputeHash(encoding.GetBytes(value)); foreach (byte b in bytes) { sb.AppendFormat("{0:x2}", b); } return sb.ToString(); } } } }
30.68
78
0.4691
[ "MIT" ]
JolyneStone/Monica
src/Core/Rye/Security/HashManager.cs
4,031
C#
using System; using System.Net; using SDL2; namespace RogueLibTerminal { public static class Terminal { internal static TerminalWindow TerminalInstance; public static int WindowWidth { get => TerminalInstance.WindowWidth; set => TerminalInstance.WindowWidth = value; } public static int WindowHeight { get => TerminalInstance.WindowHeight; set => TerminalInstance.WindowHeight = value; } public static int BufferWidth { get => TerminalInstance.BufferWidth; set => TerminalInstance.BufferWidth = value; } public static int BufferHeight { get => TerminalInstance.BufferHeight; set => TerminalInstance.BufferHeight = value; } public static TerminalColor ForegroundColor { get => TerminalInstance.ForegroundColor; set => TerminalInstance.ForegroundColor = value; } public static TerminalColor BackgroundColor { get => TerminalInstance.BackgroundColor; set => TerminalInstance.BackgroundColor = value; } public static TerminalColor DefaultForegroundColor { get => TerminalInstance.DefaultForegroundColor; set => TerminalInstance.DefaultForegroundColor = value; } public static TerminalColor DefaultBackgroundColor { get => TerminalInstance.DefaultBackgroundColor; set => TerminalInstance.DefaultBackgroundColor = value; } public static bool CapsLock => TerminalInstance.CapsLock; public static int CursorLeft { get => TerminalInstance.CursorLeft; set => TerminalInstance.CursorLeft = value; } public static int CursorTop { get => TerminalInstance.CursorTop; set => TerminalInstance.CursorTop = value; } public static Point CursorSize { get => TerminalInstance.CursorSize; set => TerminalInstance.CursorSize = value; } public static bool KeyAvailable => TerminalInstance.KeyAvailable; public static string Title { get => TerminalInstance.Title; set => TerminalInstance.Title = value; } public static Point BufferPosition { get => TerminalInstance.BufferPosition; set => TerminalInstance.BufferPosition = value; } public static Point BufferSize { get => TerminalInstance.BufferSize; set => TerminalInstance.BufferSize = value; } public static Point? WindowPosition { get => TerminalInstance.WindowPosition; set => TerminalInstance.WindowPosition = value; } static Terminal() { InitTerminalWindow(); } private static void InitTerminalWindow() { TerminalInstance = new TerminalWindow(); TerminalInstance.Init(); } public static void Write(string value) { throw new NotImplementedException(); } public static void WriteLine(string value) { throw new NotImplementedException(); } public static void WriteAt(string value, Point position) { throw new NotImplementedException(); } public static void WriteLineAt(string value, Point position) { throw new NotImplementedException(); } public static void WriteEx(string value, Point offset) { throw new NotImplementedException(); } public static void WriteLineEx(string value, Point offset) { throw new NotImplementedException(); } public static void WriteAtEx(string value, Point position, Point offset) { throw new NotImplementedException(); } public static void WriteLineAtEx(string value, Point position, Point offset) { throw new NotImplementedException(); } public static void Refresh() { throw new NotImplementedException(); } public static void RefreshAt(Point position) { RefreshAt(position, Point.Unit); } public static void RefreshAt(Point position, Point size) { throw new NotImplementedException(); } public static string ReadLine() { throw new NotImplementedException(); } public static int Read() { throw new NotImplementedException(); } public static SDL.SDL_Keycode ReadKey() { throw new NotImplementedException(); } public static void RestoreDefaultColors() { throw new NotImplementedException(); } public static void Beep() { throw new NotImplementedException(); } public static void PlaySound() { throw new NotImplementedException(); } public static void Clear() { throw new NotImplementedException(); } public static void ClearAt(Point position) { ClearAt(position, Point.Unit); } public static void ClearAt(Point position, Point size) { throw new NotImplementedException(); } public static void Destroy() { TerminalInstance.Dispose(); } } }
27.887805
84
0.569529
[ "MIT" ]
lunacys/RogueLibTerminal
Source/RogueLibTerminal/Terminal.cs
5,719
C#
using System.ComponentModel; namespace Sample.XrmToolBox.TestPlugin { partial class ControlTesterPluginControl { /// <summary> /// Variable nécessaire au concepteur. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Nettoyage des ressources utilisées. /// </summary> /// <param name="disposing">true si les ressources managées doivent être supprimées ; sinon, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Code généré par le Concepteur de composants /// <summary> /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas /// le contenu de cette méthode avec l'éditeur de code. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ControlTesterPluginControl)); xrmtb.XrmToolBox.Controls.XMLViewerSettings xmlViewerSettings1 = new xrmtb.XrmToolBox.Controls.XMLViewerSettings(); xrmtb.XrmToolBox.Controls.XMLViewerSettings xmlViewerSettings2 = new xrmtb.XrmToolBox.Controls.XMLViewerSettings(); xrmtb.XrmToolBox.Controls.XMLViewerSettings xmlViewerSettings3 = new xrmtb.XrmToolBox.Controls.XMLViewerSettings(); xrmtb.XrmToolBox.Controls.XMLViewerSettings xmlViewerSettings4 = new xrmtb.XrmToolBox.Controls.XMLViewerSettings(); xrmtb.XrmToolBox.Controls.XMLViewerSettings xmlViewerSettings5 = new xrmtb.XrmToolBox.Controls.XMLViewerSettings(); this.toolStripMenu = new System.Windows.Forms.ToolStrip(); this.tsbClose = new System.Windows.Forms.ToolStripButton(); this.tssSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripDropDownButton1 = new System.Windows.Forms.ToolStripDropDownButton(); this.toolButton_LoadData = new System.Windows.Forms.ToolStripMenuItem(); this.toolButton_ClearData = new System.Windows.Forms.ToolStripMenuItem(); this.toolButton_UpdateConnection = new System.Windows.Forms.ToolStripMenuItem(); this.toolButton_Close = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabelFilter = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextFilter = new System.Windows.Forms.ToolStripTextBox(); this.tabControlMain = new System.Windows.Forms.TabControl(); this.tabPageEntList = new System.Windows.Forms.TabPage(); this.splitterEntityList = new System.Windows.Forms.SplitContainer(); this.EntityListControl = new xrmtb.XrmToolBox.Controls.EntitiesListControl(); this.tableEntListDetails = new System.Windows.Forms.TableLayoutPanel(); this.panel1 = new System.Windows.Forms.Panel(); this.radioEntListShowProps = new System.Windows.Forms.RadioButton(); this.label1 = new System.Windows.Forms.Label(); this.radioEntListShowEnt = new System.Windows.Forms.RadioButton(); this.propGridEntList = new System.Windows.Forms.PropertyGrid(); this.textEntListLog = new System.Windows.Forms.TextBox(); this.tabPageEntListViewBase = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.EntityListViewBase = new xrmtb.XrmToolBox.Controls.EntityListViewBaseControl(); this.flowLayoutPanelToolbar = new System.Windows.Forms.FlowLayoutPanel(); this.buttonLoadItems = new System.Windows.Forms.Button(); this.checkBoxCheckAllNone = new System.Windows.Forms.CheckBox(); this.labelFilter = new System.Windows.Forms.Label(); this.textFilterList = new System.Windows.Forms.TextBox(); this.buttonClearFilter = new System.Windows.Forms.Button(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.panel10 = new System.Windows.Forms.Panel(); this.radioEntLVBaseShowProps = new System.Windows.Forms.RadioButton(); this.label20 = new System.Windows.Forms.Label(); this.radioButton2 = new System.Windows.Forms.RadioButton(); this.propGridEntLVBase = new System.Windows.Forms.PropertyGrid(); this.textBox2 = new System.Windows.Forms.TextBox(); this.tabPageEntDropdown = new System.Windows.Forms.TabPage(); this.splitterEntDropdown = new System.Windows.Forms.SplitContainer(); this.tableEntDropdown = new System.Windows.Forms.TableLayoutPanel(); this.label7 = new System.Windows.Forms.Label(); this.EntityDropdown = new xrmtb.XrmToolBox.Controls.EntitiesDropdownControl(); this.labelEntityDropdown = new System.Windows.Forms.Label(); this.listBoxEntities = new System.Windows.Forms.ListBox(); this.tableEntDropdownDetail = new System.Windows.Forms.TableLayoutPanel(); this.propGridEntDropdown = new System.Windows.Forms.PropertyGrid(); this.textEntDropdownLog = new System.Windows.Forms.TextBox(); this.panel3 = new System.Windows.Forms.Panel(); this.label3 = new System.Windows.Forms.Label(); this.radioEntDropdownShowEnt = new System.Windows.Forms.RadioButton(); this.radioEntDropdownShowProps = new System.Windows.Forms.RadioButton(); this.tabPageAttrList = new System.Windows.Forms.TabPage(); this.splitterAttribList = new System.Windows.Forms.SplitContainer(); this.tableAttribList = new System.Windows.Forms.TableLayoutPanel(); this.label10 = new System.Windows.Forms.Label(); this.EntityDropdownAttribList = new xrmtb.XrmToolBox.Controls.EntitiesDropdownControl(); this.label11 = new System.Windows.Forms.Label(); this.AttribListControl = new xrmtb.XrmToolBox.Controls.AttributeListControl(); this.tableAttribListDetail = new System.Windows.Forms.TableLayoutPanel(); this.propGridAttrList = new System.Windows.Forms.PropertyGrid(); this.textAttribListLog = new System.Windows.Forms.TextBox(); this.panel5 = new System.Windows.Forms.Panel(); this.radioAttribListShowProps = new System.Windows.Forms.RadioButton(); this.label13 = new System.Windows.Forms.Label(); this.radioAttribListShowAttrib = new System.Windows.Forms.RadioButton(); this.tabPageAttrDropDown = new System.Windows.Forms.TabPage(); this.splitterAttribDropdown = new System.Windows.Forms.SplitContainer(); this.tableAttribDropdown = new System.Windows.Forms.TableLayoutPanel(); this.labelAttributes = new System.Windows.Forms.Label(); this.EntityDropdownAttribs = new xrmtb.XrmToolBox.Controls.EntitiesDropdownControl(); this.label4 = new System.Windows.Forms.Label(); this.listBoxAttributes = new System.Windows.Forms.ListBox(); this.label6 = new System.Windows.Forms.Label(); this.panelAttrDropdown = new System.Windows.Forms.Panel(); this.AttributeDropdownBase = new xrmtb.XrmToolBox.Controls.AttributeDropdownBaseControl(); this.buttonReload = new System.Windows.Forms.Button(); this.tableAttribDropdownDetail = new System.Windows.Forms.TableLayoutPanel(); this.propGridAttribDropdown = new System.Windows.Forms.PropertyGrid(); this.textAttribDropdownLog = new System.Windows.Forms.TextBox(); this.panel2 = new System.Windows.Forms.Panel(); this.radioAttribDropdownShowProps = new System.Windows.Forms.RadioButton(); this.label5 = new System.Windows.Forms.Label(); this.radioAttribDropdownShowAttrib = new System.Windows.Forms.RadioButton(); this.tabPageSolution = new System.Windows.Forms.TabPage(); this.splitterSolnDropdown = new System.Windows.Forms.SplitContainer(); this.tableSolnDropdown = new System.Windows.Forms.TableLayoutPanel(); this.label9 = new System.Windows.Forms.Label(); this.SolutionDropdown = new xrmtb.XrmToolBox.Controls.SolutionsDropdownControl(); this.label2 = new System.Windows.Forms.Label(); this.listBoxSolutions = new System.Windows.Forms.ListBox(); this.tableSolnDropdownDetail = new System.Windows.Forms.TableLayoutPanel(); this.propGridSolutions = new System.Windows.Forms.PropertyGrid(); this.textSolnDropdownLog = new System.Windows.Forms.TextBox(); this.panel4 = new System.Windows.Forms.Panel(); this.radioSolnDropdownShowProps = new System.Windows.Forms.RadioButton(); this.label8 = new System.Windows.Forms.Label(); this.radioSolnDropdownShowSoln = new System.Windows.Forms.RadioButton(); this.tabPageViewsDropdown = new System.Windows.Forms.TabPage(); this.splitterViewDropdown = new System.Windows.Forms.SplitContainer(); this.tableViewDropdown = new System.Windows.Forms.TableLayoutPanel(); this.label12 = new System.Windows.Forms.Label(); this.EntityDropdownViews = new xrmtb.XrmToolBox.Controls.EntitiesDropdownControl(); this.label14 = new System.Windows.Forms.Label(); this.listBoxViews = new System.Windows.Forms.ListBox(); this.label15 = new System.Windows.Forms.Label(); this.ViewDropdown = new xrmtb.XrmToolBox.Controls.ViewsDropdownControl(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.propGridViewDropdown = new System.Windows.Forms.PropertyGrid(); this.textViewsDropdownLog = new System.Windows.Forms.TextBox(); this.panel6 = new System.Windows.Forms.Panel(); this.radioViewDropdownShowProps = new System.Windows.Forms.RadioButton(); this.label16 = new System.Windows.Forms.Label(); this.radioAttribDropdownShowView = new System.Windows.Forms.RadioButton(); this.tabPageGlobalOptSets = new System.Windows.Forms.TabPage(); this.splitterGlobalOptsList = new System.Windows.Forms.SplitContainer(); this.GlobalOptionSetList = new xrmtb.XrmToolBox.Controls.GlobalOptionSetListControl(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.panel7 = new System.Windows.Forms.Panel(); this.radioGlobalOptsListShowProps = new System.Windows.Forms.RadioButton(); this.label17 = new System.Windows.Forms.Label(); this.radioEntDropdownShowOptionSet = new System.Windows.Forms.RadioButton(); this.propGridGlobalOptsList = new System.Windows.Forms.PropertyGrid(); this.textGlobalOptsListLog = new System.Windows.Forms.TextBox(); this.tabPageCRMGridView = new System.Windows.Forms.TabPage(); this.splitterCRMGridView = new System.Windows.Forms.SplitContainer(); this.tableCRMGridView = new System.Windows.Forms.TableLayoutPanel(); this.panelCrmGridViewControls = new System.Windows.Forms.Panel(); this.dataGridViewGrouperControl1 = new Subro.Controls.DataGridViewGrouperControl(); this.CrmGridView = new xrmtb.XrmToolBox.Controls.CRMGridView(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.labelExecFetch = new System.Windows.Forms.Label(); this.buttonExecFetch = new System.Windows.Forms.Button(); this.XmlViewerCRMDataGrid = new xrmtb.XrmToolBox.Controls.XMLViewer(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.panel8 = new System.Windows.Forms.Panel(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.button1 = new System.Windows.Forms.Button(); this.label23 = new System.Windows.Forms.Label(); this.cdsDataTextBox = new xrmtb.XrmToolBox.Controls.Controls.CDSDataTextBox(); this.label22 = new System.Windows.Forms.Label(); this.textCdsDataComboBoxFormat = new System.Windows.Forms.TextBox(); this.label21 = new System.Windows.Forms.Label(); this.cdsDataComboBox = new xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox(); this.panel12 = new System.Windows.Forms.Panel(); this.radioCRMGridViewLkpDlg = new System.Windows.Forms.RadioButton(); this.radioCRMGridViewTxtBx = new System.Windows.Forms.RadioButton(); this.radioCRMGridViewCmbBx = new System.Windows.Forms.RadioButton(); this.radioCRMGridViewRightShowProps = new System.Windows.Forms.RadioButton(); this.radioCRMGridViewSelEntity = new System.Windows.Forms.RadioButton(); this.radioCRMGridViewShowProps = new System.Windows.Forms.RadioButton(); this.label18 = new System.Windows.Forms.Label(); this.propCRMGridView = new System.Windows.Forms.PropertyGrid(); this.panel11 = new System.Windows.Forms.Panel(); this.CrmGridViewDesignedCols = new xrmtb.XrmToolBox.Controls.CRMGridView(); this.name = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.revenue = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.buttonExecPredefinedCrmGridViewQuery = new System.Windows.Forms.Button(); this.tabPageXrmViewer = new System.Windows.Forms.TabPage(); this.TableXmlViewers = new System.Windows.Forms.TableLayoutPanel(); this.splitterXmlViewerControl = new System.Windows.Forms.SplitContainer(); this.XmlViewerControl = new xrmtb.XrmToolBox.Controls.XmlViewerControl(); this.propGridXmlViewerControl = new System.Windows.Forms.PropertyGrid(); this.splitterXmlViewer = new System.Windows.Forms.SplitContainer(); this.XmlViewer = new xrmtb.XrmToolBox.Controls.XMLViewer(); this.propGridXmlViewer = new System.Windows.Forms.PropertyGrid(); this.labelXmlViewerControlTitle = new System.Windows.Forms.Label(); this.labelXmlViewerTitle = new System.Windows.Forms.Label(); this.tabPageBoundListIVew = new System.Windows.Forms.TabPage(); this.splitterBoundListView = new System.Windows.Forms.SplitContainer(); this.splitterEntList = new System.Windows.Forms.Splitter(); this.listViewEntCollection = new xrmtb.XrmToolBox.Controls.EntitiesCollectionListView(); this.xmlViewerEntColl = new xrmtb.XrmToolBox.Controls.XMLViewer(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.labelExecFetchBoundList = new System.Windows.Forms.Label(); this.buttonExecFetchBoundList = new System.Windows.Forms.Button(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this.panel9 = new System.Windows.Forms.Panel(); this.radioBoundListShowProps = new System.Windows.Forms.RadioButton(); this.label19 = new System.Windows.Forms.Label(); this.radioEntListShowObj = new System.Windows.Forms.RadioButton(); this.propGridBoundListView = new System.Windows.Forms.PropertyGrid(); this.textBox1 = new System.Windows.Forms.TextBox(); this.tabPageCDSDataComboBox = new System.Windows.Forms.TabPage(); this.tableLayoutPanel6 = new System.Windows.Forms.TableLayoutPanel(); this.xmlViewerFetchCDSCombo = new xrmtb.XrmToolBox.Controls.XmlViewerControl(); this.textBoxCDSComboProgress = new System.Windows.Forms.TextBox(); this.panelCDSComboRetrieve = new System.Windows.Forms.FlowLayoutPanel(); this.cdsDataComboRetrieve = new xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox(); this.buttonCDSComboRetrieve = new System.Windows.Forms.Button(); this.cdsLookupDialog1 = new xrmtb.XrmToolBox.Controls.Controls.CDSLookupDialog(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.toolStripMenu.SuspendLayout(); this.tabControlMain.SuspendLayout(); this.tabPageEntList.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterEntityList)).BeginInit(); this.splitterEntityList.Panel1.SuspendLayout(); this.splitterEntityList.Panel2.SuspendLayout(); this.splitterEntityList.SuspendLayout(); this.tableEntListDetails.SuspendLayout(); this.panel1.SuspendLayout(); this.tabPageEntListViewBase.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.flowLayoutPanelToolbar.SuspendLayout(); this.tableLayoutPanel5.SuspendLayout(); this.panel10.SuspendLayout(); this.tabPageEntDropdown.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterEntDropdown)).BeginInit(); this.splitterEntDropdown.Panel1.SuspendLayout(); this.splitterEntDropdown.Panel2.SuspendLayout(); this.splitterEntDropdown.SuspendLayout(); this.tableEntDropdown.SuspendLayout(); this.tableEntDropdownDetail.SuspendLayout(); this.panel3.SuspendLayout(); this.tabPageAttrList.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterAttribList)).BeginInit(); this.splitterAttribList.Panel1.SuspendLayout(); this.splitterAttribList.Panel2.SuspendLayout(); this.splitterAttribList.SuspendLayout(); this.tableAttribList.SuspendLayout(); this.tableAttribListDetail.SuspendLayout(); this.panel5.SuspendLayout(); this.tabPageAttrDropDown.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterAttribDropdown)).BeginInit(); this.splitterAttribDropdown.Panel1.SuspendLayout(); this.splitterAttribDropdown.Panel2.SuspendLayout(); this.splitterAttribDropdown.SuspendLayout(); this.tableAttribDropdown.SuspendLayout(); this.panelAttrDropdown.SuspendLayout(); this.tableAttribDropdownDetail.SuspendLayout(); this.panel2.SuspendLayout(); this.tabPageSolution.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterSolnDropdown)).BeginInit(); this.splitterSolnDropdown.Panel1.SuspendLayout(); this.splitterSolnDropdown.Panel2.SuspendLayout(); this.splitterSolnDropdown.SuspendLayout(); this.tableSolnDropdown.SuspendLayout(); this.tableSolnDropdownDetail.SuspendLayout(); this.panel4.SuspendLayout(); this.tabPageViewsDropdown.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterViewDropdown)).BeginInit(); this.splitterViewDropdown.Panel1.SuspendLayout(); this.splitterViewDropdown.Panel2.SuspendLayout(); this.splitterViewDropdown.SuspendLayout(); this.tableViewDropdown.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.panel6.SuspendLayout(); this.tabPageGlobalOptSets.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterGlobalOptsList)).BeginInit(); this.splitterGlobalOptsList.Panel1.SuspendLayout(); this.splitterGlobalOptsList.Panel2.SuspendLayout(); this.splitterGlobalOptsList.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.panel7.SuspendLayout(); this.tabPageCRMGridView.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterCRMGridView)).BeginInit(); this.splitterCRMGridView.Panel1.SuspendLayout(); this.splitterCRMGridView.Panel2.SuspendLayout(); this.splitterCRMGridView.SuspendLayout(); this.tableCRMGridView.SuspendLayout(); this.panelCrmGridViewControls.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CrmGridView)).BeginInit(); this.flowLayoutPanel1.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); this.panel8.SuspendLayout(); this.groupBox1.SuspendLayout(); this.panel12.SuspendLayout(); this.panel11.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CrmGridViewDesignedCols)).BeginInit(); this.tabPageXrmViewer.SuspendLayout(); this.TableXmlViewers.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterXmlViewerControl)).BeginInit(); this.splitterXmlViewerControl.Panel1.SuspendLayout(); this.splitterXmlViewerControl.Panel2.SuspendLayout(); this.splitterXmlViewerControl.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterXmlViewer)).BeginInit(); this.splitterXmlViewer.Panel1.SuspendLayout(); this.splitterXmlViewer.Panel2.SuspendLayout(); this.splitterXmlViewer.SuspendLayout(); this.tabPageBoundListIVew.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitterBoundListView)).BeginInit(); this.splitterBoundListView.Panel1.SuspendLayout(); this.splitterBoundListView.Panel2.SuspendLayout(); this.splitterBoundListView.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this.panel9.SuspendLayout(); this.tabPageCDSDataComboBox.SuspendLayout(); this.tableLayoutPanel6.SuspendLayout(); this.panelCDSComboRetrieve.SuspendLayout(); this.SuspendLayout(); // // toolStripMenu // this.toolStripMenu.ImageScalingSize = new System.Drawing.Size(24, 24); this.toolStripMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsbClose, this.tssSeparator1, this.toolStripDropDownButton1, this.toolStripSeparator1, this.toolStripLabelFilter, this.toolStripTextFilter}); this.toolStripMenu.Location = new System.Drawing.Point(0, 0); this.toolStripMenu.Name = "toolStripMenu"; this.toolStripMenu.Padding = new System.Windows.Forms.Padding(0, 0, 2, 0); this.toolStripMenu.Size = new System.Drawing.Size(915, 25); this.toolStripMenu.TabIndex = 4; this.toolStripMenu.Text = "toolStrip1"; // // tsbClose // this.tsbClose.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.tsbClose.Name = "tsbClose"; this.tsbClose.Size = new System.Drawing.Size(86, 22); this.tsbClose.Text = "Close this tool"; this.tsbClose.Click += new System.EventHandler(this.tsbClose_Click); // // tssSeparator1 // this.tssSeparator1.Name = "tssSeparator1"; this.tssSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripDropDownButton1 // this.toolStripDropDownButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripDropDownButton1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolButton_LoadData, this.toolButton_ClearData, this.toolButton_UpdateConnection, this.toolButton_Close}); this.toolStripDropDownButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripDropDownButton1.Image"))); this.toolStripDropDownButton1.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripDropDownButton1.Name = "toolStripDropDownButton1"; this.toolStripDropDownButton1.Size = new System.Drawing.Size(139, 22); this.toolStripDropDownButton1.Text = "Call External Method..."; // // toolButton_LoadData // this.toolButton_LoadData.Name = "toolButton_LoadData"; this.toolButton_LoadData.Size = new System.Drawing.Size(182, 22); this.toolButton_LoadData.Text = "LoadData()"; this.toolButton_LoadData.Click += new System.EventHandler(this.ToolButtonLoadData_Click); // // toolButton_ClearData // this.toolButton_ClearData.Name = "toolButton_ClearData"; this.toolButton_ClearData.Size = new System.Drawing.Size(182, 22); this.toolButton_ClearData.Text = "ClearData()"; this.toolButton_ClearData.Click += new System.EventHandler(this.ToolButtonClearData_Click); // // toolButton_UpdateConnection // this.toolButton_UpdateConnection.Name = "toolButton_UpdateConnection"; this.toolButton_UpdateConnection.Size = new System.Drawing.Size(182, 22); this.toolButton_UpdateConnection.Text = "UpdateConnection()"; this.toolButton_UpdateConnection.Click += new System.EventHandler(this.ToolButtonUpdateConnection_Click); // // toolButton_Close // this.toolButton_Close.Name = "toolButton_Close"; this.toolButton_Close.Size = new System.Drawing.Size(182, 22); this.toolButton_Close.Text = "Close()"; this.toolButton_Close.Click += new System.EventHandler(this.ToolButtonClose_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripLabelFilter // this.toolStripLabelFilter.Name = "toolStripLabelFilter"; this.toolStripLabelFilter.Size = new System.Drawing.Size(82, 22); this.toolStripLabelFilter.Text = "Filter ListView:"; // // toolStripTextFilter // this.toolStripTextFilter.Font = new System.Drawing.Font("Segoe UI", 9F); this.toolStripTextFilter.Name = "toolStripTextFilter"; this.toolStripTextFilter.Size = new System.Drawing.Size(102, 25); this.toolStripTextFilter.TextChanged += new System.EventHandler(this.toolStripTextFilter_TextChanged); // // tabControlMain // this.tabControlMain.Appearance = System.Windows.Forms.TabAppearance.FlatButtons; this.tabControlMain.Controls.Add(this.tabPageEntList); this.tabControlMain.Controls.Add(this.tabPageEntListViewBase); this.tabControlMain.Controls.Add(this.tabPageEntDropdown); this.tabControlMain.Controls.Add(this.tabPageAttrList); this.tabControlMain.Controls.Add(this.tabPageAttrDropDown); this.tabControlMain.Controls.Add(this.tabPageSolution); this.tabControlMain.Controls.Add(this.tabPageViewsDropdown); this.tabControlMain.Controls.Add(this.tabPageGlobalOptSets); this.tabControlMain.Controls.Add(this.tabPageCRMGridView); this.tabControlMain.Controls.Add(this.tabPageXrmViewer); this.tabControlMain.Controls.Add(this.tabPageBoundListIVew); this.tabControlMain.Controls.Add(this.tabPageCDSDataComboBox); this.tabControlMain.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControlMain.ItemSize = new System.Drawing.Size(150, 30); this.tabControlMain.Location = new System.Drawing.Point(0, 25); this.tabControlMain.Margin = new System.Windows.Forms.Padding(2); this.tabControlMain.Name = "tabControlMain"; this.tabControlMain.SelectedIndex = 0; this.tabControlMain.Size = new System.Drawing.Size(915, 602); this.tabControlMain.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.tabControlMain.TabIndex = 7; this.tabControlMain.SelectedIndexChanged += new System.EventHandler(this.tabControlMain_SelectedIndexChanged); // // tabPageEntList // this.tabPageEntList.Controls.Add(this.splitterEntityList); this.tabPageEntList.Location = new System.Drawing.Point(4, 34); this.tabPageEntList.Margin = new System.Windows.Forms.Padding(2); this.tabPageEntList.Name = "tabPageEntList"; this.tabPageEntList.Padding = new System.Windows.Forms.Padding(3); this.tabPageEntList.Size = new System.Drawing.Size(907, 564); this.tabPageEntList.TabIndex = 0; this.tabPageEntList.Text = "Entity List Control"; // // splitterEntityList // this.splitterEntityList.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterEntityList.Location = new System.Drawing.Point(3, 3); this.splitterEntityList.Margin = new System.Windows.Forms.Padding(2); this.splitterEntityList.Name = "splitterEntityList"; // // splitterEntityList.Panel1 // this.splitterEntityList.Panel1.Controls.Add(this.EntityListControl); // // splitterEntityList.Panel2 // this.splitterEntityList.Panel2.Controls.Add(this.tableEntListDetails); this.splitterEntityList.Size = new System.Drawing.Size(901, 558); this.splitterEntityList.SplitterDistance = 295; this.splitterEntityList.SplitterWidth = 10; this.splitterEntityList.TabIndex = 0; // // EntityListControl // this.EntityListControl.AutoLoadData = false; this.EntityListControl.AutosizeColumns = System.Windows.Forms.ColumnHeaderAutoResizeStyle.None; this.EntityListControl.Checkboxes = true; this.EntityListControl.DisplaySolutionDropdown = false; this.EntityListControl.DisplayToolbar = false; this.EntityListControl.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityListControl.EntityTypes = xrmtb.XrmToolBox.Controls.EnumEntityTypes.BothCustomAndSystem; this.EntityListControl.LanguageCode = 1033; this.EntityListControl.ListViewColDefs = new xrmtb.XrmToolBox.Controls.ListViewColumnDef[] { ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListControl.ListViewColDefs"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListControl.ListViewColDefs1"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListControl.ListViewColDefs2"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListControl.ListViewColDefs3"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListControl.ListViewColDefs4")))}; this.EntityListControl.Location = new System.Drawing.Point(0, 0); this.EntityListControl.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.EntityListControl.Name = "EntityListControl"; this.EntityListControl.Padding = new System.Windows.Forms.Padding(4, 3, 4, 3); this.EntityListControl.RetrieveAsIfPublished = true; this.EntityListControl.Service = null; this.EntityListControl.Size = new System.Drawing.Size(295, 558); this.EntityListControl.SolutionFilter = null; this.EntityListControl.TabIndex = 13; this.EntityListControl.SelectedItemChanged += new System.EventHandler(this.EntitiesListControl_SelectedItemChanged); this.EntityListControl.CheckedItemsChanged += new System.EventHandler(this.EntitiesListControl_CheckedItemsChanged); this.EntityListControl.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.EntitiesListControl_ProgressChanged); this.EntityListControl.LoadDataComplete += new System.EventHandler(this.EntitiesListControl_LoadDataComplete); this.EntityListControl.ClearDataComplete += new System.EventHandler(this.EntitiesListControl_ClearDataComplete); this.EntityListControl.CloseComplete += new System.EventHandler(this.EntitiesListControl_CloseComplete); this.EntityListControl.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // tableEntListDetails // this.tableEntListDetails.ColumnCount = 2; this.tableEntListDetails.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableEntListDetails.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableEntListDetails.Controls.Add(this.panel1, 0, 1); this.tableEntListDetails.Controls.Add(this.propGridEntList, 0, 0); this.tableEntListDetails.Controls.Add(this.textEntListLog, 1, 0); this.tableEntListDetails.Dock = System.Windows.Forms.DockStyle.Fill; this.tableEntListDetails.Location = new System.Drawing.Point(0, 0); this.tableEntListDetails.Margin = new System.Windows.Forms.Padding(2); this.tableEntListDetails.Name = "tableEntListDetails"; this.tableEntListDetails.RowCount = 2; this.tableEntListDetails.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableEntListDetails.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableEntListDetails.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableEntListDetails.Size = new System.Drawing.Size(596, 558); this.tableEntListDetails.TabIndex = 20; // // panel1 // this.tableEntListDetails.SetColumnSpan(this.panel1, 2); this.panel1.Controls.Add(this.radioEntListShowProps); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.radioEntListShowEnt); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(2, 504); this.panel1.Margin = new System.Windows.Forms.Padding(2); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(592, 52); this.panel1.TabIndex = 16; // // radioEntListShowProps // this.radioEntListShowProps.AutoSize = true; this.radioEntListShowProps.Checked = true; this.radioEntListShowProps.Location = new System.Drawing.Point(10, 27); this.radioEntListShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntListShowProps.Name = "radioEntListShowProps"; this.radioEntListShowProps.Size = new System.Drawing.Size(129, 17); this.radioEntListShowProps.TabIndex = 3; this.radioEntListShowProps.TabStop = true; this.radioEntListShowProps.Text = "Entity ListView Control"; this.radioEntListShowProps.UseVisualStyleBackColor = true; this.radioEntListShowProps.CheckedChanged += new System.EventHandler(this.RadioEntitiesList_CheckedChanged); // // label1 // this.label1.Dock = System.Windows.Forms.DockStyle.Top; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(592, 23); this.label1.TabIndex = 4; this.label1.Text = "Choose what displays in the property control"; // // radioEntListShowEnt // this.radioEntListShowEnt.AutoSize = true; this.radioEntListShowEnt.Location = new System.Drawing.Point(150, 27); this.radioEntListShowEnt.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntListShowEnt.Name = "radioEntListShowEnt"; this.radioEntListShowEnt.Size = new System.Drawing.Size(96, 17); this.radioEntListShowEnt.TabIndex = 2; this.radioEntListShowEnt.TabStop = true; this.radioEntListShowEnt.Text = "Selected Entity"; this.radioEntListShowEnt.UseVisualStyleBackColor = true; this.radioEntListShowEnt.CheckedChanged += new System.EventHandler(this.RadioEntitiesList_CheckedChanged); // // propGridEntList // this.propGridEntList.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridEntList.Location = new System.Drawing.Point(4, 3); this.propGridEntList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridEntList.Name = "propGridEntList"; this.propGridEntList.Size = new System.Drawing.Size(290, 496); this.propGridEntList.TabIndex = 8; // // textEntListLog // this.textEntListLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textEntListLog.Location = new System.Drawing.Point(302, 3); this.textEntListLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textEntListLog.Multiline = true; this.textEntListLog.Name = "textEntListLog"; this.textEntListLog.ReadOnly = true; this.textEntListLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textEntListLog.Size = new System.Drawing.Size(290, 496); this.textEntListLog.TabIndex = 7; // // tabPageEntListViewBase // this.tabPageEntListViewBase.Controls.Add(this.splitContainer1); this.tabPageEntListViewBase.Location = new System.Drawing.Point(4, 34); this.tabPageEntListViewBase.Margin = new System.Windows.Forms.Padding(2); this.tabPageEntListViewBase.Name = "tabPageEntListViewBase"; this.tabPageEntListViewBase.Padding = new System.Windows.Forms.Padding(2); this.tabPageEntListViewBase.Size = new System.Drawing.Size(907, 564); this.tabPageEntListViewBase.TabIndex = 10; this.tabPageEntListViewBase.Text = "Entity ListView Base"; this.tabPageEntListViewBase.UseVisualStyleBackColor = true; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(2, 2); this.splitContainer1.Margin = new System.Windows.Forms.Padding(2); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.EntityListViewBase); this.splitContainer1.Panel1.Controls.Add(this.flowLayoutPanelToolbar); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.tableLayoutPanel5); this.splitContainer1.Size = new System.Drawing.Size(903, 560); this.splitContainer1.SplitterDistance = 295; this.splitContainer1.SplitterWidth = 10; this.splitContainer1.TabIndex = 1; // // EntityListViewBase // this.EntityListViewBase.AutoLoadData = false; this.EntityListViewBase.AutosizeColumns = System.Windows.Forms.ColumnHeaderAutoResizeStyle.None; this.EntityListViewBase.CheckBoxes = true; this.EntityListViewBase.DisplayCheckBoxes = true; this.EntityListViewBase.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityListViewBase.HideSelection = false; this.EntityListViewBase.LanguageCode = 1033; this.EntityListViewBase.ListViewColDefs = new xrmtb.XrmToolBox.Controls.ListViewColumnDef[] { ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListViewBase.ListViewColDefs"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListViewBase.ListViewColDefs1"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListViewBase.ListViewColDefs2"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListViewBase.ListViewColDefs3"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("EntityListViewBase.ListViewColDefs4")))}; this.EntityListViewBase.Location = new System.Drawing.Point(0, 30); this.EntityListViewBase.Margin = new System.Windows.Forms.Padding(2); this.EntityListViewBase.Name = "EntityListViewBase"; this.EntityListViewBase.RetrieveAsIfPublished = true; this.EntityListViewBase.Service = null; this.EntityListViewBase.Size = new System.Drawing.Size(295, 530); this.EntityListViewBase.SolutionFilter = null; this.EntityListViewBase.TabIndex = 0; this.EntityListViewBase.UseCompatibleStateImageBehavior = false; this.EntityListViewBase.View = System.Windows.Forms.View.Details; this.EntityListViewBase.SelectedItemChanged += new System.EventHandler(this.EntityListViewBase_SelectedItemChanged); // // flowLayoutPanelToolbar // this.flowLayoutPanelToolbar.Controls.Add(this.buttonLoadItems); this.flowLayoutPanelToolbar.Controls.Add(this.checkBoxCheckAllNone); this.flowLayoutPanelToolbar.Controls.Add(this.labelFilter); this.flowLayoutPanelToolbar.Controls.Add(this.textFilterList); this.flowLayoutPanelToolbar.Controls.Add(this.buttonClearFilter); this.flowLayoutPanelToolbar.Dock = System.Windows.Forms.DockStyle.Top; this.flowLayoutPanelToolbar.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanelToolbar.Margin = new System.Windows.Forms.Padding(0); this.flowLayoutPanelToolbar.Name = "flowLayoutPanelToolbar"; this.flowLayoutPanelToolbar.Size = new System.Drawing.Size(295, 30); this.flowLayoutPanelToolbar.TabIndex = 9; this.flowLayoutPanelToolbar.WrapContents = false; // // buttonLoadItems // this.buttonLoadItems.FlatAppearance.BorderColor = System.Drawing.SystemColors.ButtonFace; this.buttonLoadItems.Image = ((System.Drawing.Image)(resources.GetObject("buttonLoadItems.Image"))); this.buttonLoadItems.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.buttonLoadItems.Location = new System.Drawing.Point(0, 0); this.buttonLoadItems.Margin = new System.Windows.Forms.Padding(0); this.buttonLoadItems.MinimumSize = new System.Drawing.Size(75, 14); this.buttonLoadItems.Name = "buttonLoadItems"; this.buttonLoadItems.Size = new System.Drawing.Size(75, 27); this.buttonLoadItems.TabIndex = 0; this.buttonLoadItems.Text = "Load Items"; this.buttonLoadItems.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.buttonLoadItems.UseVisualStyleBackColor = true; this.buttonLoadItems.Click += new System.EventHandler(this.EntLVBaseLoadItems_Click); // // checkBoxCheckAllNone // this.checkBoxCheckAllNone.FlatAppearance.BorderColor = System.Drawing.SystemColors.ButtonFace; this.checkBoxCheckAllNone.FlatAppearance.BorderSize = 0; this.checkBoxCheckAllNone.Location = new System.Drawing.Point(85, 2); this.checkBoxCheckAllNone.Margin = new System.Windows.Forms.Padding(10, 2, 2, 2); this.checkBoxCheckAllNone.Name = "checkBoxCheckAllNone"; this.checkBoxCheckAllNone.Size = new System.Drawing.Size(103, 23); this.checkBoxCheckAllNone.TabIndex = 6; this.checkBoxCheckAllNone.Text = "Check All/None"; this.checkBoxCheckAllNone.UseVisualStyleBackColor = true; // // labelFilter // this.labelFilter.Location = new System.Drawing.Point(200, 0); this.labelFilter.Margin = new System.Windows.Forms.Padding(10, 0, 3, 0); this.labelFilter.Name = "labelFilter"; this.labelFilter.Size = new System.Drawing.Size(38, 27); this.labelFilter.TabIndex = 3; this.labelFilter.Text = "Filter:"; this.labelFilter.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // textFilterList // this.textFilterList.Anchor = System.Windows.Forms.AnchorStyles.None; this.textFilterList.Location = new System.Drawing.Point(241, 0); this.textFilterList.Margin = new System.Windows.Forms.Padding(0); this.textFilterList.MaxLength = 100; this.textFilterList.MinimumSize = new System.Drawing.Size(90, 46); this.textFilterList.Name = "textFilterList"; this.textFilterList.Size = new System.Drawing.Size(121, 20); this.textFilterList.TabIndex = 4; this.textFilterList.WordWrap = false; // // buttonClearFilter // this.buttonClearFilter.AutoSize = true; this.buttonClearFilter.FlatAppearance.BorderColor = System.Drawing.SystemColors.ButtonFace; this.buttonClearFilter.Font = new System.Drawing.Font("Arial Rounded MT Bold", 10.125F); this.buttonClearFilter.ForeColor = System.Drawing.SystemColors.ControlDarkDark; this.buttonClearFilter.Location = new System.Drawing.Point(362, 0); this.buttonClearFilter.Margin = new System.Windows.Forms.Padding(0); this.buttonClearFilter.Name = "buttonClearFilter"; this.buttonClearFilter.Size = new System.Drawing.Size(35, 38); this.buttonClearFilter.TabIndex = 5; this.buttonClearFilter.Text = "x"; this.buttonClearFilter.UseVisualStyleBackColor = true; // // tableLayoutPanel5 // this.tableLayoutPanel5.ColumnCount = 2; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel5.Controls.Add(this.panel10, 0, 1); this.tableLayoutPanel5.Controls.Add(this.propGridEntLVBase, 0, 0); this.tableLayoutPanel5.Controls.Add(this.textBox2, 1, 0); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel5.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 2; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel5.Size = new System.Drawing.Size(598, 560); this.tableLayoutPanel5.TabIndex = 20; // // panel10 // this.tableLayoutPanel5.SetColumnSpan(this.panel10, 2); this.panel10.Controls.Add(this.radioEntLVBaseShowProps); this.panel10.Controls.Add(this.label20); this.panel10.Controls.Add(this.radioButton2); this.panel10.Dock = System.Windows.Forms.DockStyle.Fill; this.panel10.Location = new System.Drawing.Point(2, 506); this.panel10.Margin = new System.Windows.Forms.Padding(2); this.panel10.Name = "panel10"; this.panel10.Size = new System.Drawing.Size(594, 52); this.panel10.TabIndex = 16; // // radioEntLVBaseShowProps // this.radioEntLVBaseShowProps.AutoSize = true; this.radioEntLVBaseShowProps.Checked = true; this.radioEntLVBaseShowProps.Location = new System.Drawing.Point(10, 27); this.radioEntLVBaseShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntLVBaseShowProps.Name = "radioEntLVBaseShowProps"; this.radioEntLVBaseShowProps.Size = new System.Drawing.Size(156, 17); this.radioEntLVBaseShowProps.TabIndex = 3; this.radioEntLVBaseShowProps.TabStop = true; this.radioEntLVBaseShowProps.Text = "Entity ListView Base Control"; this.radioEntLVBaseShowProps.UseVisualStyleBackColor = true; // // label20 // this.label20.Dock = System.Windows.Forms.DockStyle.Top; this.label20.Location = new System.Drawing.Point(0, 0); this.label20.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label20.Name = "label20"; this.label20.Size = new System.Drawing.Size(594, 23); this.label20.TabIndex = 4; this.label20.Text = "Choose what displays in the property control"; // // radioButton2 // this.radioButton2.AutoSize = true; this.radioButton2.Location = new System.Drawing.Point(175, 27); this.radioButton2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioButton2.Name = "radioButton2"; this.radioButton2.Size = new System.Drawing.Size(96, 17); this.radioButton2.TabIndex = 2; this.radioButton2.TabStop = true; this.radioButton2.Text = "Selected Entity"; this.radioButton2.UseVisualStyleBackColor = true; // // propGridEntLVBase // this.propGridEntLVBase.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridEntLVBase.Location = new System.Drawing.Point(4, 3); this.propGridEntLVBase.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridEntLVBase.Name = "propGridEntLVBase"; this.propGridEntLVBase.Size = new System.Drawing.Size(291, 498); this.propGridEntLVBase.TabIndex = 8; // // textBox2 // this.textBox2.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox2.Location = new System.Drawing.Point(303, 3); this.textBox2.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"; this.textBox2.ReadOnly = true; this.textBox2.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox2.Size = new System.Drawing.Size(291, 498); this.textBox2.TabIndex = 7; // // tabPageEntDropdown // this.tabPageEntDropdown.Controls.Add(this.splitterEntDropdown); this.tabPageEntDropdown.Location = new System.Drawing.Point(4, 34); this.tabPageEntDropdown.Margin = new System.Windows.Forms.Padding(2); this.tabPageEntDropdown.Name = "tabPageEntDropdown"; this.tabPageEntDropdown.Padding = new System.Windows.Forms.Padding(3); this.tabPageEntDropdown.Size = new System.Drawing.Size(907, 564); this.tabPageEntDropdown.TabIndex = 1; this.tabPageEntDropdown.Text = "Entity Dropdown Control"; this.tabPageEntDropdown.UseVisualStyleBackColor = true; // // splitterEntDropdown // this.splitterEntDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterEntDropdown.Location = new System.Drawing.Point(3, 3); this.splitterEntDropdown.Margin = new System.Windows.Forms.Padding(2); this.splitterEntDropdown.Name = "splitterEntDropdown"; // // splitterEntDropdown.Panel1 // this.splitterEntDropdown.Panel1.Controls.Add(this.tableEntDropdown); // // splitterEntDropdown.Panel2 // this.splitterEntDropdown.Panel2.Controls.Add(this.tableEntDropdownDetail); this.splitterEntDropdown.Size = new System.Drawing.Size(901, 558); this.splitterEntDropdown.SplitterDistance = 295; this.splitterEntDropdown.SplitterWidth = 10; this.splitterEntDropdown.TabIndex = 18; // // tableEntDropdown // this.tableEntDropdown.ColumnCount = 1; this.tableEntDropdown.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableEntDropdown.Controls.Add(this.label7, 0, 2); this.tableEntDropdown.Controls.Add(this.EntityDropdown, 0, 1); this.tableEntDropdown.Controls.Add(this.labelEntityDropdown, 0, 0); this.tableEntDropdown.Controls.Add(this.listBoxEntities, 0, 3); this.tableEntDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.tableEntDropdown.Location = new System.Drawing.Point(0, 0); this.tableEntDropdown.Margin = new System.Windows.Forms.Padding(2); this.tableEntDropdown.Name = "tableEntDropdown"; this.tableEntDropdown.RowCount = 4; this.tableEntDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableEntDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableEntDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableEntDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableEntDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableEntDropdown.Size = new System.Drawing.Size(295, 558); this.tableEntDropdown.TabIndex = 19; // // label7 // this.label7.Dock = System.Windows.Forms.DockStyle.Top; this.label7.Location = new System.Drawing.Point(3, 62); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(289, 23); this.label7.TabIndex = 21; this.label7.Text = "Full list of Entities"; // // EntityDropdown // this.EntityDropdown.AutoLoadData = false; this.EntityDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityDropdown.LanguageCode = 1033; this.EntityDropdown.Location = new System.Drawing.Point(4, 29); this.EntityDropdown.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.EntityDropdown.Name = "EntityDropdown"; this.EntityDropdown.Service = null; this.EntityDropdown.Size = new System.Drawing.Size(287, 30); this.EntityDropdown.SolutionFilter = null; this.EntityDropdown.TabIndex = 15; this.EntityDropdown.SelectedItemChanged += new System.EventHandler(this.EntityDropdown_SelectedItemChanged); this.EntityDropdown.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.EntityDropdown_ProgressChanged); this.EntityDropdown.BeginLoadData += new System.EventHandler(this.EntityDropdown_BeginLoadData); this.EntityDropdown.LoadDataComplete += new System.EventHandler(this.EntityDropdown_LoadDataComplete); this.EntityDropdown.BeginClearData += new System.EventHandler(this.EntityDropdown_BeginClearData); this.EntityDropdown.ClearDataComplete += new System.EventHandler(this.EntityDropdown_ClearDataComplete); this.EntityDropdown.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // labelEntityDropdown // this.labelEntityDropdown.Location = new System.Drawing.Point(2, 0); this.labelEntityDropdown.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelEntityDropdown.Name = "labelEntityDropdown"; this.labelEntityDropdown.Size = new System.Drawing.Size(260, 15); this.labelEntityDropdown.TabIndex = 0; this.labelEntityDropdown.Text = "Entity Dropdown Control"; // // listBoxEntities // this.listBoxEntities.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxEntities.FormattingEnabled = true; this.listBoxEntities.Location = new System.Drawing.Point(3, 91); this.listBoxEntities.Name = "listBoxEntities"; this.listBoxEntities.Size = new System.Drawing.Size(289, 489); this.listBoxEntities.TabIndex = 16; // // tableEntDropdownDetail // this.tableEntDropdownDetail.ColumnCount = 2; this.tableEntDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableEntDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableEntDropdownDetail.Controls.Add(this.propGridEntDropdown, 0, 0); this.tableEntDropdownDetail.Controls.Add(this.textEntDropdownLog, 1, 0); this.tableEntDropdownDetail.Controls.Add(this.panel3, 0, 1); this.tableEntDropdownDetail.Dock = System.Windows.Forms.DockStyle.Fill; this.tableEntDropdownDetail.Location = new System.Drawing.Point(0, 0); this.tableEntDropdownDetail.Margin = new System.Windows.Forms.Padding(2); this.tableEntDropdownDetail.Name = "tableEntDropdownDetail"; this.tableEntDropdownDetail.RowCount = 2; this.tableEntDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableEntDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableEntDropdownDetail.Size = new System.Drawing.Size(596, 558); this.tableEntDropdownDetail.TabIndex = 21; // // propGridEntDropdown // this.propGridEntDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridEntDropdown.Location = new System.Drawing.Point(4, 3); this.propGridEntDropdown.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridEntDropdown.Name = "propGridEntDropdown"; this.propGridEntDropdown.Size = new System.Drawing.Size(290, 496); this.propGridEntDropdown.TabIndex = 8; // // textEntDropdownLog // this.textEntDropdownLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textEntDropdownLog.Location = new System.Drawing.Point(302, 3); this.textEntDropdownLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textEntDropdownLog.Multiline = true; this.textEntDropdownLog.Name = "textEntDropdownLog"; this.textEntDropdownLog.ReadOnly = true; this.textEntDropdownLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textEntDropdownLog.Size = new System.Drawing.Size(290, 496); this.textEntDropdownLog.TabIndex = 7; // // panel3 // this.tableEntDropdownDetail.SetColumnSpan(this.panel3, 2); this.panel3.Controls.Add(this.label3); this.panel3.Controls.Add(this.radioEntDropdownShowEnt); this.panel3.Controls.Add(this.radioEntDropdownShowProps); this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; this.panel3.Location = new System.Drawing.Point(2, 504); this.panel3.Margin = new System.Windows.Forms.Padding(2); this.panel3.Name = "panel3"; this.panel3.Size = new System.Drawing.Size(592, 52); this.panel3.TabIndex = 16; // // label3 // this.label3.Dock = System.Windows.Forms.DockStyle.Top; this.label3.Location = new System.Drawing.Point(0, 0); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(592, 25); this.label3.TabIndex = 4; this.label3.Text = "Choose what displays in the property control"; // // radioEntDropdownShowEnt // this.radioEntDropdownShowEnt.Location = new System.Drawing.Point(170, 20); this.radioEntDropdownShowEnt.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntDropdownShowEnt.Name = "radioEntDropdownShowEnt"; this.radioEntDropdownShowEnt.Size = new System.Drawing.Size(135, 23); this.radioEntDropdownShowEnt.TabIndex = 2; this.radioEntDropdownShowEnt.TabStop = true; this.radioEntDropdownShowEnt.Text = "Selected Entity"; this.radioEntDropdownShowEnt.UseVisualStyleBackColor = true; this.radioEntDropdownShowEnt.CheckedChanged += new System.EventHandler(this.RadioEntDropdown_CheckedChanged); // // radioEntDropdownShowProps // this.radioEntDropdownShowProps.Checked = true; this.radioEntDropdownShowProps.Location = new System.Drawing.Point(14, 20); this.radioEntDropdownShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntDropdownShowProps.Name = "radioEntDropdownShowProps"; this.radioEntDropdownShowProps.Size = new System.Drawing.Size(148, 23); this.radioEntDropdownShowProps.TabIndex = 3; this.radioEntDropdownShowProps.TabStop = true; this.radioEntDropdownShowProps.Text = "Entity Dropdown Control"; this.radioEntDropdownShowProps.UseVisualStyleBackColor = true; this.radioEntDropdownShowProps.CheckedChanged += new System.EventHandler(this.RadioEntDropdown_CheckedChanged); // // tabPageAttrList // this.tabPageAttrList.Controls.Add(this.splitterAttribList); this.tabPageAttrList.Location = new System.Drawing.Point(4, 34); this.tabPageAttrList.Margin = new System.Windows.Forms.Padding(2); this.tabPageAttrList.Name = "tabPageAttrList"; this.tabPageAttrList.Padding = new System.Windows.Forms.Padding(2); this.tabPageAttrList.Size = new System.Drawing.Size(907, 564); this.tabPageAttrList.TabIndex = 4; this.tabPageAttrList.Text = "Attribute List Control"; this.tabPageAttrList.UseVisualStyleBackColor = true; // // splitterAttribList // this.splitterAttribList.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterAttribList.Location = new System.Drawing.Point(2, 2); this.splitterAttribList.Margin = new System.Windows.Forms.Padding(2); this.splitterAttribList.Name = "splitterAttribList"; // // splitterAttribList.Panel1 // this.splitterAttribList.Panel1.Controls.Add(this.tableAttribList); // // splitterAttribList.Panel2 // this.splitterAttribList.Panel2.Controls.Add(this.tableAttribListDetail); this.splitterAttribList.Size = new System.Drawing.Size(903, 560); this.splitterAttribList.SplitterDistance = 295; this.splitterAttribList.SplitterWidth = 10; this.splitterAttribList.TabIndex = 20; // // tableAttribList // this.tableAttribList.ColumnCount = 1; this.tableAttribList.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableAttribList.Controls.Add(this.label10, 0, 2); this.tableAttribList.Controls.Add(this.EntityDropdownAttribList, 0, 1); this.tableAttribList.Controls.Add(this.label11, 0, 0); this.tableAttribList.Controls.Add(this.AttribListControl, 0, 3); this.tableAttribList.Dock = System.Windows.Forms.DockStyle.Fill; this.tableAttribList.Location = new System.Drawing.Point(0, 0); this.tableAttribList.Margin = new System.Windows.Forms.Padding(2); this.tableAttribList.Name = "tableAttribList"; this.tableAttribList.RowCount = 4; this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 10F)); this.tableAttribList.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 10F)); this.tableAttribList.Size = new System.Drawing.Size(295, 560); this.tableAttribList.TabIndex = 19; // // label10 // this.label10.Dock = System.Windows.Forms.DockStyle.Fill; this.label10.Location = new System.Drawing.Point(2, 62); this.label10.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(291, 26); this.label10.TabIndex = 18; this.label10.Text = "Attributes List"; // // EntityDropdownAttribList // this.EntityDropdownAttribList.AutoLoadData = false; this.EntityDropdownAttribList.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityDropdownAttribList.LanguageCode = 1033; this.EntityDropdownAttribList.Location = new System.Drawing.Point(4, 29); this.EntityDropdownAttribList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.EntityDropdownAttribList.Name = "EntityDropdownAttribList"; this.EntityDropdownAttribList.Service = null; this.EntityDropdownAttribList.Size = new System.Drawing.Size(287, 30); this.EntityDropdownAttribList.SolutionFilter = null; this.EntityDropdownAttribList.TabIndex = 15; this.EntityDropdownAttribList.SelectedItemChanged += new System.EventHandler(this.EntityDropdownAttribList_SelectedItemChanged); // // label11 // this.label11.Dock = System.Windows.Forms.DockStyle.Fill; this.label11.Location = new System.Drawing.Point(2, 0); this.label11.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(291, 26); this.label11.TabIndex = 0; this.label11.Text = "Entity Dropdown Control"; // // AttribListControl // this.AttribListControl.AutoLoadData = false; this.AttribListControl.AutosizeColumns = System.Windows.Forms.ColumnHeaderAutoResizeStyle.None; this.AttribListControl.Checkboxes = true; this.AttribListControl.DisplayToolbar = false; this.AttribListControl.Dock = System.Windows.Forms.DockStyle.Fill; this.AttribListControl.LanguageCode = 1033; this.AttribListControl.ListViewColDefs = new xrmtb.XrmToolBox.Controls.ListViewColumnDef[] { ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs1"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs2"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs3"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs4"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs5"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("AttribListControl.ListViewColDefs6")))}; this.AttribListControl.Location = new System.Drawing.Point(0, 89); this.AttribListControl.Margin = new System.Windows.Forms.Padding(0, 1, 0, 1); this.AttribListControl.Name = "AttribListControl"; this.AttribListControl.ParentEntity = null; this.AttribListControl.ParentEntityLogicalName = null; this.AttribListControl.Service = null; this.AttribListControl.Size = new System.Drawing.Size(295, 495); this.AttribListControl.TabIndex = 19; this.AttribListControl.SelectedItemChanged += new System.EventHandler(this.AttribListControl_SelectedItemChanged); this.AttribListControl.CheckedItemsChanged += new System.EventHandler(this.AttribListControl_CheckedItemsChanged); this.AttribListControl.FilterListComplete += new System.EventHandler(this.AttribListControl_FilterListComplete); this.AttribListControl.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.AttribListControl_ProgressChanged); this.AttribListControl.LoadDataComplete += new System.EventHandler(this.AttribListControl_LoadDataComplete); this.AttribListControl.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // tableAttribListDetail // this.tableAttribListDetail.ColumnCount = 2; this.tableAttribListDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableAttribListDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableAttribListDetail.Controls.Add(this.propGridAttrList, 0, 0); this.tableAttribListDetail.Controls.Add(this.textAttribListLog, 1, 0); this.tableAttribListDetail.Controls.Add(this.panel5, 0, 1); this.tableAttribListDetail.Dock = System.Windows.Forms.DockStyle.Fill; this.tableAttribListDetail.Location = new System.Drawing.Point(0, 0); this.tableAttribListDetail.Margin = new System.Windows.Forms.Padding(2); this.tableAttribListDetail.Name = "tableAttribListDetail"; this.tableAttribListDetail.RowCount = 2; this.tableAttribListDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableAttribListDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableAttribListDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableAttribListDetail.Size = new System.Drawing.Size(598, 560); this.tableAttribListDetail.TabIndex = 21; // // propGridAttrList // this.propGridAttrList.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridAttrList.Location = new System.Drawing.Point(4, 3); this.propGridAttrList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridAttrList.Name = "propGridAttrList"; this.propGridAttrList.Size = new System.Drawing.Size(291, 498); this.propGridAttrList.TabIndex = 8; // // textAttribListLog // this.textAttribListLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textAttribListLog.Location = new System.Drawing.Point(303, 3); this.textAttribListLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textAttribListLog.Multiline = true; this.textAttribListLog.Name = "textAttribListLog"; this.textAttribListLog.ReadOnly = true; this.textAttribListLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textAttribListLog.Size = new System.Drawing.Size(291, 498); this.textAttribListLog.TabIndex = 7; // // panel5 // this.tableAttribListDetail.SetColumnSpan(this.panel5, 2); this.panel5.Controls.Add(this.radioAttribListShowProps); this.panel5.Controls.Add(this.label13); this.panel5.Controls.Add(this.radioAttribListShowAttrib); this.panel5.Dock = System.Windows.Forms.DockStyle.Fill; this.panel5.Location = new System.Drawing.Point(2, 506); this.panel5.Margin = new System.Windows.Forms.Padding(2); this.panel5.Name = "panel5"; this.panel5.Size = new System.Drawing.Size(594, 52); this.panel5.TabIndex = 16; // // radioAttribListShowProps // this.radioAttribListShowProps.AutoSize = true; this.radioAttribListShowProps.Checked = true; this.radioAttribListShowProps.Location = new System.Drawing.Point(14, 20); this.radioAttribListShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioAttribListShowProps.Name = "radioAttribListShowProps"; this.radioAttribListShowProps.Size = new System.Drawing.Size(119, 17); this.radioAttribListShowProps.TabIndex = 3; this.radioAttribListShowProps.TabStop = true; this.radioAttribListShowProps.Text = "Attribute List Control"; this.radioAttribListShowProps.UseVisualStyleBackColor = true; this.radioAttribListShowProps.CheckedChanged += new System.EventHandler(this.RadioAttribList_CheckedChanged); // // label13 // this.label13.Dock = System.Windows.Forms.DockStyle.Top; this.label13.Location = new System.Drawing.Point(0, 0); this.label13.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(594, 18); this.label13.TabIndex = 4; this.label13.Text = "Choose what displays in the property control"; // // radioAttribListShowAttrib // this.radioAttribListShowAttrib.AutoSize = true; this.radioAttribListShowAttrib.Location = new System.Drawing.Point(170, 20); this.radioAttribListShowAttrib.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioAttribListShowAttrib.Name = "radioAttribListShowAttrib"; this.radioAttribListShowAttrib.Size = new System.Drawing.Size(109, 17); this.radioAttribListShowAttrib.TabIndex = 2; this.radioAttribListShowAttrib.TabStop = true; this.radioAttribListShowAttrib.Text = "Selected Attribute"; this.radioAttribListShowAttrib.UseVisualStyleBackColor = true; this.radioAttribListShowAttrib.CheckedChanged += new System.EventHandler(this.RadioAttribList_CheckedChanged); // // tabPageAttrDropDown // this.tabPageAttrDropDown.Controls.Add(this.splitterAttribDropdown); this.tabPageAttrDropDown.Location = new System.Drawing.Point(4, 34); this.tabPageAttrDropDown.Margin = new System.Windows.Forms.Padding(2); this.tabPageAttrDropDown.Name = "tabPageAttrDropDown"; this.tabPageAttrDropDown.Padding = new System.Windows.Forms.Padding(3); this.tabPageAttrDropDown.Size = new System.Drawing.Size(907, 564); this.tabPageAttrDropDown.TabIndex = 2; this.tabPageAttrDropDown.Text = "Attributes Dropdown"; this.tabPageAttrDropDown.UseVisualStyleBackColor = true; // // splitterAttribDropdown // this.splitterAttribDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterAttribDropdown.Location = new System.Drawing.Point(3, 3); this.splitterAttribDropdown.Margin = new System.Windows.Forms.Padding(2); this.splitterAttribDropdown.Name = "splitterAttribDropdown"; // // splitterAttribDropdown.Panel1 // this.splitterAttribDropdown.Panel1.Controls.Add(this.tableAttribDropdown); // // splitterAttribDropdown.Panel2 // this.splitterAttribDropdown.Panel2.Controls.Add(this.tableAttribDropdownDetail); this.splitterAttribDropdown.Size = new System.Drawing.Size(901, 558); this.splitterAttribDropdown.SplitterDistance = 295; this.splitterAttribDropdown.SplitterWidth = 10; this.splitterAttribDropdown.TabIndex = 19; // // tableAttribDropdown // this.tableAttribDropdown.ColumnCount = 1; this.tableAttribDropdown.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableAttribDropdown.Controls.Add(this.labelAttributes, 0, 2); this.tableAttribDropdown.Controls.Add(this.EntityDropdownAttribs, 0, 1); this.tableAttribDropdown.Controls.Add(this.label4, 0, 0); this.tableAttribDropdown.Controls.Add(this.listBoxAttributes, 0, 5); this.tableAttribDropdown.Controls.Add(this.label6, 0, 4); this.tableAttribDropdown.Controls.Add(this.panelAttrDropdown, 0, 3); this.tableAttribDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.tableAttribDropdown.Location = new System.Drawing.Point(0, 0); this.tableAttribDropdown.Margin = new System.Windows.Forms.Padding(2); this.tableAttribDropdown.Name = "tableAttribDropdown"; this.tableAttribDropdown.RowCount = 6; this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableAttribDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableAttribDropdown.Size = new System.Drawing.Size(295, 558); this.tableAttribDropdown.TabIndex = 19; // // labelAttributes // this.labelAttributes.Dock = System.Windows.Forms.DockStyle.Fill; this.labelAttributes.Location = new System.Drawing.Point(2, 62); this.labelAttributes.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelAttributes.Name = "labelAttributes"; this.labelAttributes.Size = new System.Drawing.Size(291, 26); this.labelAttributes.TabIndex = 18; this.labelAttributes.Text = "Attributes Dropdown"; // // EntityDropdownAttribs // this.EntityDropdownAttribs.AutoLoadData = false; this.EntityDropdownAttribs.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityDropdownAttribs.LanguageCode = 1033; this.EntityDropdownAttribs.Location = new System.Drawing.Point(4, 29); this.EntityDropdownAttribs.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.EntityDropdownAttribs.Name = "EntityDropdownAttribs"; this.EntityDropdownAttribs.Service = null; this.EntityDropdownAttribs.Size = new System.Drawing.Size(287, 30); this.EntityDropdownAttribs.SolutionFilter = null; this.EntityDropdownAttribs.TabIndex = 15; this.EntityDropdownAttribs.SelectedItemChanged += new System.EventHandler(this.EntityDropdownAttribs_SelectedItemChanged); this.EntityDropdownAttribs.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.EntityDropdownAttribs_ProgressChanged); this.EntityDropdownAttribs.BeginLoadData += new System.EventHandler(this.EntityDropdownAttribs_BeginLoadData); this.EntityDropdownAttribs.LoadDataComplete += new System.EventHandler(this.EntityDropdownAttribs_LoadDataComplete); this.EntityDropdownAttribs.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // label4 // this.label4.Dock = System.Windows.Forms.DockStyle.Fill; this.label4.Location = new System.Drawing.Point(2, 0); this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(291, 26); this.label4.TabIndex = 0; this.label4.Text = "Entity Dropdown Control"; // // listBoxAttributes // this.listBoxAttributes.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxAttributes.FormattingEnabled = true; this.listBoxAttributes.Location = new System.Drawing.Point(3, 153); this.listBoxAttributes.Name = "listBoxAttributes"; this.listBoxAttributes.Size = new System.Drawing.Size(289, 427); this.listBoxAttributes.TabIndex = 19; // // label6 // this.label6.Dock = System.Windows.Forms.DockStyle.Top; this.label6.Location = new System.Drawing.Point(3, 124); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(289, 23); this.label6.TabIndex = 20; this.label6.Text = "Full list of Attributes"; // // panelAttrDropdown // this.panelAttrDropdown.Controls.Add(this.AttributeDropdownBase); this.panelAttrDropdown.Controls.Add(this.buttonReload); this.panelAttrDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.panelAttrDropdown.Location = new System.Drawing.Point(2, 90); this.panelAttrDropdown.Margin = new System.Windows.Forms.Padding(2); this.panelAttrDropdown.Name = "panelAttrDropdown"; this.panelAttrDropdown.Padding = new System.Windows.Forms.Padding(5); this.panelAttrDropdown.Size = new System.Drawing.Size(291, 32); this.panelAttrDropdown.TabIndex = 21; // // AttributeDropdownBase // this.AttributeDropdownBase.AutoLoadData = false; this.AttributeDropdownBase.Dock = System.Windows.Forms.DockStyle.Fill; this.AttributeDropdownBase.FormattingEnabled = true; this.AttributeDropdownBase.LanguageCode = 1033; this.AttributeDropdownBase.Location = new System.Drawing.Point(5, 5); this.AttributeDropdownBase.Margin = new System.Windows.Forms.Padding(2); this.AttributeDropdownBase.Name = "AttributeDropdownBase"; this.AttributeDropdownBase.ParentEntity = null; this.AttributeDropdownBase.ParentEntityLogicalName = null; this.AttributeDropdownBase.Service = null; this.AttributeDropdownBase.Size = new System.Drawing.Size(262, 21); this.AttributeDropdownBase.TabIndex = 0; // // buttonReload // this.buttonReload.Dock = System.Windows.Forms.DockStyle.Right; this.buttonReload.Font = new System.Drawing.Font("Wingdings 3", 8.142858F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2))); this.buttonReload.Location = new System.Drawing.Point(267, 5); this.buttonReload.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.buttonReload.MinimumSize = new System.Drawing.Size(19, 19); this.buttonReload.Name = "buttonReload"; this.buttonReload.Size = new System.Drawing.Size(19, 22); this.buttonReload.TabIndex = 2; this.buttonReload.Text = "P"; this.buttonReload.UseVisualStyleBackColor = true; this.buttonReload.Click += new System.EventHandler(this.buttonReload_Click); // // tableAttribDropdownDetail // this.tableAttribDropdownDetail.ColumnCount = 2; this.tableAttribDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableAttribDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableAttribDropdownDetail.Controls.Add(this.propGridAttribDropdown, 0, 0); this.tableAttribDropdownDetail.Controls.Add(this.textAttribDropdownLog, 1, 0); this.tableAttribDropdownDetail.Controls.Add(this.panel2, 0, 1); this.tableAttribDropdownDetail.Dock = System.Windows.Forms.DockStyle.Fill; this.tableAttribDropdownDetail.Location = new System.Drawing.Point(0, 0); this.tableAttribDropdownDetail.Margin = new System.Windows.Forms.Padding(2); this.tableAttribDropdownDetail.Name = "tableAttribDropdownDetail"; this.tableAttribDropdownDetail.RowCount = 2; this.tableAttribDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableAttribDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableAttribDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableAttribDropdownDetail.Size = new System.Drawing.Size(596, 558); this.tableAttribDropdownDetail.TabIndex = 21; // // propGridAttribDropdown // this.propGridAttribDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridAttribDropdown.Location = new System.Drawing.Point(4, 3); this.propGridAttribDropdown.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridAttribDropdown.Name = "propGridAttribDropdown"; this.propGridAttribDropdown.Size = new System.Drawing.Size(290, 496); this.propGridAttribDropdown.TabIndex = 8; // // textAttribDropdownLog // this.textAttribDropdownLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textAttribDropdownLog.Location = new System.Drawing.Point(302, 3); this.textAttribDropdownLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textAttribDropdownLog.Multiline = true; this.textAttribDropdownLog.Name = "textAttribDropdownLog"; this.textAttribDropdownLog.ReadOnly = true; this.textAttribDropdownLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textAttribDropdownLog.Size = new System.Drawing.Size(290, 496); this.textAttribDropdownLog.TabIndex = 7; // // panel2 // this.tableAttribDropdownDetail.SetColumnSpan(this.panel2, 2); this.panel2.Controls.Add(this.radioAttribDropdownShowProps); this.panel2.Controls.Add(this.label5); this.panel2.Controls.Add(this.radioAttribDropdownShowAttrib); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(2, 504); this.panel2.Margin = new System.Windows.Forms.Padding(2); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(592, 52); this.panel2.TabIndex = 16; // // radioAttribDropdownShowProps // this.radioAttribDropdownShowProps.AutoSize = true; this.radioAttribDropdownShowProps.Checked = true; this.radioAttribDropdownShowProps.Location = new System.Drawing.Point(14, 20); this.radioAttribDropdownShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioAttribDropdownShowProps.Name = "radioAttribDropdownShowProps"; this.radioAttribDropdownShowProps.Size = new System.Drawing.Size(152, 17); this.radioAttribDropdownShowProps.TabIndex = 3; this.radioAttribDropdownShowProps.TabStop = true; this.radioAttribDropdownShowProps.Text = "Attribute Dropdown Control"; this.radioAttribDropdownShowProps.UseVisualStyleBackColor = true; this.radioAttribDropdownShowProps.CheckedChanged += new System.EventHandler(this.RadioAttribDropdown_CheckedChanged); // // label5 // this.label5.Dock = System.Windows.Forms.DockStyle.Top; this.label5.Location = new System.Drawing.Point(0, 0); this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(592, 18); this.label5.TabIndex = 4; this.label5.Text = "Choose what displays in the property control"; // // radioAttribDropdownShowAttrib // this.radioAttribDropdownShowAttrib.AutoSize = true; this.radioAttribDropdownShowAttrib.Location = new System.Drawing.Point(170, 20); this.radioAttribDropdownShowAttrib.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioAttribDropdownShowAttrib.Name = "radioAttribDropdownShowAttrib"; this.radioAttribDropdownShowAttrib.Size = new System.Drawing.Size(109, 17); this.radioAttribDropdownShowAttrib.TabIndex = 2; this.radioAttribDropdownShowAttrib.TabStop = true; this.radioAttribDropdownShowAttrib.Text = "Selected Attribute"; this.radioAttribDropdownShowAttrib.UseVisualStyleBackColor = true; // // tabPageSolution // this.tabPageSolution.Controls.Add(this.splitterSolnDropdown); this.tabPageSolution.Location = new System.Drawing.Point(4, 34); this.tabPageSolution.Margin = new System.Windows.Forms.Padding(2); this.tabPageSolution.Name = "tabPageSolution"; this.tabPageSolution.Padding = new System.Windows.Forms.Padding(3); this.tabPageSolution.Size = new System.Drawing.Size(907, 564); this.tabPageSolution.TabIndex = 3; this.tabPageSolution.Text = "Solutions Dropdown"; this.tabPageSolution.UseVisualStyleBackColor = true; // // splitterSolnDropdown // this.splitterSolnDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterSolnDropdown.Location = new System.Drawing.Point(3, 3); this.splitterSolnDropdown.Margin = new System.Windows.Forms.Padding(2); this.splitterSolnDropdown.Name = "splitterSolnDropdown"; // // splitterSolnDropdown.Panel1 // this.splitterSolnDropdown.Panel1.Controls.Add(this.tableSolnDropdown); // // splitterSolnDropdown.Panel2 // this.splitterSolnDropdown.Panel2.Controls.Add(this.tableSolnDropdownDetail); this.splitterSolnDropdown.Size = new System.Drawing.Size(901, 558); this.splitterSolnDropdown.SplitterDistance = 295; this.splitterSolnDropdown.SplitterWidth = 10; this.splitterSolnDropdown.TabIndex = 20; // // tableSolnDropdown // this.tableSolnDropdown.ColumnCount = 1; this.tableSolnDropdown.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableSolnDropdown.Controls.Add(this.label9, 0, 2); this.tableSolnDropdown.Controls.Add(this.SolutionDropdown, 0, 1); this.tableSolnDropdown.Controls.Add(this.label2, 0, 0); this.tableSolnDropdown.Controls.Add(this.listBoxSolutions, 0, 3); this.tableSolnDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.tableSolnDropdown.Location = new System.Drawing.Point(0, 0); this.tableSolnDropdown.Margin = new System.Windows.Forms.Padding(2); this.tableSolnDropdown.Name = "tableSolnDropdown"; this.tableSolnDropdown.RowCount = 4; this.tableSolnDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableSolnDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableSolnDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableSolnDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableSolnDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableSolnDropdown.Size = new System.Drawing.Size(295, 558); this.tableSolnDropdown.TabIndex = 18; // // label9 // this.label9.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label9.Location = new System.Drawing.Point(2, 62); this.label9.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(291, 26); this.label9.TabIndex = 21; this.label9.Text = "Solutions Dropdown Control"; // // SolutionDropdown // this.SolutionDropdown.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.SolutionDropdown.AutoLoadData = false; this.SolutionDropdown.LanguageCode = 1033; this.SolutionDropdown.Location = new System.Drawing.Point(0, 27); this.SolutionDropdown.Margin = new System.Windows.Forms.Padding(0, 1, 0, 1); this.SolutionDropdown.Name = "SolutionDropdown"; this.SolutionDropdown.PublisherPrefixes = ((System.Collections.Generic.List<string>)(resources.GetObject("SolutionDropdown.PublisherPrefixes"))); this.SolutionDropdown.Service = null; this.SolutionDropdown.Size = new System.Drawing.Size(295, 34); this.SolutionDropdown.TabIndex = 19; this.SolutionDropdown.SelectedItemChanged += new System.EventHandler(this.SolutionDropdown_SelectedItemChanged); this.SolutionDropdown.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.SolutionDropdown_ProgressChanged); this.SolutionDropdown.BeginLoadData += new System.EventHandler(this.SolutionDropdown_BeginLoadData); this.SolutionDropdown.LoadDataComplete += new System.EventHandler(this.SolutionsDropdown_LoadDataComplete); this.SolutionDropdown.BeginClearData += new System.EventHandler(this.SolutionDropdown_BeginClearData); this.SolutionDropdown.ClearDataComplete += new System.EventHandler(this.SolutionDropdown_ClearDataComplete); this.SolutionDropdown.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // label2 // this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(2, 0); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(291, 26); this.label2.TabIndex = 0; this.label2.Text = "Solutions Dropdown Control"; // // listBoxSolutions // this.listBoxSolutions.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxSolutions.FormattingEnabled = true; this.listBoxSolutions.Location = new System.Drawing.Point(3, 91); this.listBoxSolutions.Name = "listBoxSolutions"; this.listBoxSolutions.Size = new System.Drawing.Size(289, 489); this.listBoxSolutions.TabIndex = 20; // // tableSolnDropdownDetail // this.tableSolnDropdownDetail.ColumnCount = 2; this.tableSolnDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableSolnDropdownDetail.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableSolnDropdownDetail.Controls.Add(this.propGridSolutions, 0, 0); this.tableSolnDropdownDetail.Controls.Add(this.textSolnDropdownLog, 1, 0); this.tableSolnDropdownDetail.Controls.Add(this.panel4, 0, 1); this.tableSolnDropdownDetail.Dock = System.Windows.Forms.DockStyle.Fill; this.tableSolnDropdownDetail.Location = new System.Drawing.Point(0, 0); this.tableSolnDropdownDetail.Margin = new System.Windows.Forms.Padding(2); this.tableSolnDropdownDetail.Name = "tableSolnDropdownDetail"; this.tableSolnDropdownDetail.RowCount = 2; this.tableSolnDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableSolnDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableSolnDropdownDetail.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableSolnDropdownDetail.Size = new System.Drawing.Size(596, 558); this.tableSolnDropdownDetail.TabIndex = 20; // // propGridSolutions // this.propGridSolutions.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridSolutions.Location = new System.Drawing.Point(4, 3); this.propGridSolutions.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridSolutions.Name = "propGridSolutions"; this.propGridSolutions.Size = new System.Drawing.Size(290, 496); this.propGridSolutions.TabIndex = 8; // // textSolnDropdownLog // this.textSolnDropdownLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textSolnDropdownLog.Location = new System.Drawing.Point(302, 3); this.textSolnDropdownLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textSolnDropdownLog.Multiline = true; this.textSolnDropdownLog.Name = "textSolnDropdownLog"; this.textSolnDropdownLog.ReadOnly = true; this.textSolnDropdownLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textSolnDropdownLog.Size = new System.Drawing.Size(290, 496); this.textSolnDropdownLog.TabIndex = 7; // // panel4 // this.tableSolnDropdownDetail.SetColumnSpan(this.panel4, 2); this.panel4.Controls.Add(this.radioSolnDropdownShowProps); this.panel4.Controls.Add(this.label8); this.panel4.Controls.Add(this.radioSolnDropdownShowSoln); this.panel4.Dock = System.Windows.Forms.DockStyle.Fill; this.panel4.Location = new System.Drawing.Point(2, 504); this.panel4.Margin = new System.Windows.Forms.Padding(2); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(592, 52); this.panel4.TabIndex = 16; // // radioSolnDropdownShowProps // this.radioSolnDropdownShowProps.AutoSize = true; this.radioSolnDropdownShowProps.Checked = true; this.radioSolnDropdownShowProps.Location = new System.Drawing.Point(14, 20); this.radioSolnDropdownShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioSolnDropdownShowProps.Name = "radioSolnDropdownShowProps"; this.radioSolnDropdownShowProps.Size = new System.Drawing.Size(152, 17); this.radioSolnDropdownShowProps.TabIndex = 3; this.radioSolnDropdownShowProps.TabStop = true; this.radioSolnDropdownShowProps.Text = "Attribute Dropdown Control"; this.radioSolnDropdownShowProps.UseVisualStyleBackColor = true; this.radioSolnDropdownShowProps.CheckedChanged += new System.EventHandler(this.RadioSolnDropdownShowProps_CheckedChanged); // // label8 // this.label8.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label8.Location = new System.Drawing.Point(0, 0); this.label8.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(592, 18); this.label8.TabIndex = 4; this.label8.Text = "Choose what displays in the property control"; // // radioSolnDropdownShowSoln // this.radioSolnDropdownShowSoln.AutoSize = true; this.radioSolnDropdownShowSoln.Location = new System.Drawing.Point(170, 20); this.radioSolnDropdownShowSoln.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioSolnDropdownShowSoln.Name = "radioSolnDropdownShowSoln"; this.radioSolnDropdownShowSoln.Size = new System.Drawing.Size(96, 17); this.radioSolnDropdownShowSoln.TabIndex = 2; this.radioSolnDropdownShowSoln.TabStop = true; this.radioSolnDropdownShowSoln.Text = "Selected Entity"; this.radioSolnDropdownShowSoln.UseVisualStyleBackColor = true; // // tabPageViewsDropdown // this.tabPageViewsDropdown.Controls.Add(this.splitterViewDropdown); this.tabPageViewsDropdown.Location = new System.Drawing.Point(4, 34); this.tabPageViewsDropdown.Margin = new System.Windows.Forms.Padding(2); this.tabPageViewsDropdown.Name = "tabPageViewsDropdown"; this.tabPageViewsDropdown.Padding = new System.Windows.Forms.Padding(2); this.tabPageViewsDropdown.Size = new System.Drawing.Size(907, 564); this.tabPageViewsDropdown.TabIndex = 5; this.tabPageViewsDropdown.Text = "Views Dropdown"; this.tabPageViewsDropdown.UseVisualStyleBackColor = true; // // splitterViewDropdown // this.splitterViewDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterViewDropdown.Location = new System.Drawing.Point(2, 2); this.splitterViewDropdown.Margin = new System.Windows.Forms.Padding(2); this.splitterViewDropdown.Name = "splitterViewDropdown"; // // splitterViewDropdown.Panel1 // this.splitterViewDropdown.Panel1.Controls.Add(this.tableViewDropdown); // // splitterViewDropdown.Panel2 // this.splitterViewDropdown.Panel2.Controls.Add(this.tableLayoutPanel2); this.splitterViewDropdown.Size = new System.Drawing.Size(903, 560); this.splitterViewDropdown.SplitterDistance = 296; this.splitterViewDropdown.SplitterWidth = 10; this.splitterViewDropdown.TabIndex = 20; // // tableViewDropdown // this.tableViewDropdown.ColumnCount = 1; this.tableViewDropdown.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableViewDropdown.Controls.Add(this.label12, 0, 2); this.tableViewDropdown.Controls.Add(this.EntityDropdownViews, 0, 1); this.tableViewDropdown.Controls.Add(this.label14, 0, 0); this.tableViewDropdown.Controls.Add(this.listBoxViews, 0, 5); this.tableViewDropdown.Controls.Add(this.label15, 0, 4); this.tableViewDropdown.Controls.Add(this.ViewDropdown, 0, 3); this.tableViewDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.tableViewDropdown.Location = new System.Drawing.Point(0, 0); this.tableViewDropdown.Margin = new System.Windows.Forms.Padding(2); this.tableViewDropdown.Name = "tableViewDropdown"; this.tableViewDropdown.RowCount = 6; this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 36F)); this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 26F)); this.tableViewDropdown.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableViewDropdown.Size = new System.Drawing.Size(296, 560); this.tableViewDropdown.TabIndex = 19; // // label12 // this.label12.Dock = System.Windows.Forms.DockStyle.Fill; this.label12.Location = new System.Drawing.Point(2, 62); this.label12.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(292, 26); this.label12.TabIndex = 18; this.label12.Text = "Views Dropdown"; // // EntityDropdownViews // this.EntityDropdownViews.AutoLoadData = false; this.EntityDropdownViews.Dock = System.Windows.Forms.DockStyle.Fill; this.EntityDropdownViews.LanguageCode = 1033; this.EntityDropdownViews.Location = new System.Drawing.Point(4, 29); this.EntityDropdownViews.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.EntityDropdownViews.Name = "EntityDropdownViews"; this.EntityDropdownViews.Service = null; this.EntityDropdownViews.Size = new System.Drawing.Size(288, 30); this.EntityDropdownViews.SolutionFilter = null; this.EntityDropdownViews.TabIndex = 15; this.EntityDropdownViews.SelectedItemChanged += new System.EventHandler(this.EntityDropdownViews_SelectedItemChanged); // // label14 // this.label14.Dock = System.Windows.Forms.DockStyle.Fill; this.label14.Location = new System.Drawing.Point(2, 0); this.label14.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(292, 26); this.label14.TabIndex = 0; this.label14.Text = "Entity Dropdown Control"; // // listBoxViews // this.listBoxViews.Dock = System.Windows.Forms.DockStyle.Fill; this.listBoxViews.FormattingEnabled = true; this.listBoxViews.Location = new System.Drawing.Point(3, 153); this.listBoxViews.Name = "listBoxViews"; this.listBoxViews.Size = new System.Drawing.Size(290, 430); this.listBoxViews.TabIndex = 19; // // label15 // this.label15.Dock = System.Windows.Forms.DockStyle.Top; this.label15.Location = new System.Drawing.Point(3, 124); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(290, 23); this.label15.TabIndex = 20; this.label15.Text = "Full list of Views"; // // ViewDropdown // this.ViewDropdown.AutoLoadData = false; this.ViewDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.ViewDropdown.IncludePersonalViews = false; this.ViewDropdown.LanguageCode = 1033; this.ViewDropdown.Location = new System.Drawing.Point(0, 89); this.ViewDropdown.Margin = new System.Windows.Forms.Padding(0, 1, 0, 1); this.ViewDropdown.Name = "ViewDropdown"; this.ViewDropdown.ParentEntity = null; this.ViewDropdown.ParentEntityLogicalName = null; this.ViewDropdown.Service = null; this.ViewDropdown.Size = new System.Drawing.Size(296, 34); this.ViewDropdown.TabIndex = 21; this.ViewDropdown.SelectedItemChanged += new System.EventHandler(this.ViewDropdown_SelectedItemChanged); this.ViewDropdown.BeginLoadData += new System.EventHandler(this.ViewDropdown_BeginLoadData); this.ViewDropdown.LoadDataComplete += new System.EventHandler(this.ViewDropdown_LoadDataComplete); this.ViewDropdown.BeginClearData += new System.EventHandler(this.ViewDropdown_BeginClearData); this.ViewDropdown.ClearDataComplete += new System.EventHandler(this.ViewDropdown_ClearDataComplete); this.ViewDropdown.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 2; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Controls.Add(this.propGridViewDropdown, 0, 0); this.tableLayoutPanel2.Controls.Add(this.textViewsDropdownLog, 1, 0); this.tableLayoutPanel2.Controls.Add(this.panel6, 0, 1); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 2; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(597, 560); this.tableLayoutPanel2.TabIndex = 21; // // propGridViewDropdown // this.propGridViewDropdown.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridViewDropdown.Location = new System.Drawing.Point(4, 3); this.propGridViewDropdown.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridViewDropdown.Name = "propGridViewDropdown"; this.propGridViewDropdown.Size = new System.Drawing.Size(290, 498); this.propGridViewDropdown.TabIndex = 8; // // textViewsDropdownLog // this.textViewsDropdownLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textViewsDropdownLog.Location = new System.Drawing.Point(302, 3); this.textViewsDropdownLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textViewsDropdownLog.Multiline = true; this.textViewsDropdownLog.Name = "textViewsDropdownLog"; this.textViewsDropdownLog.ReadOnly = true; this.textViewsDropdownLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textViewsDropdownLog.Size = new System.Drawing.Size(291, 498); this.textViewsDropdownLog.TabIndex = 7; // // panel6 // this.tableLayoutPanel2.SetColumnSpan(this.panel6, 2); this.panel6.Controls.Add(this.radioViewDropdownShowProps); this.panel6.Controls.Add(this.label16); this.panel6.Controls.Add(this.radioAttribDropdownShowView); this.panel6.Dock = System.Windows.Forms.DockStyle.Fill; this.panel6.Location = new System.Drawing.Point(2, 506); this.panel6.Margin = new System.Windows.Forms.Padding(2); this.panel6.Name = "panel6"; this.panel6.Size = new System.Drawing.Size(593, 52); this.panel6.TabIndex = 16; // // radioViewDropdownShowProps // this.radioViewDropdownShowProps.AutoSize = true; this.radioViewDropdownShowProps.Checked = true; this.radioViewDropdownShowProps.Location = new System.Drawing.Point(14, 20); this.radioViewDropdownShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioViewDropdownShowProps.Name = "radioViewDropdownShowProps"; this.radioViewDropdownShowProps.Size = new System.Drawing.Size(136, 17); this.radioViewDropdownShowProps.TabIndex = 3; this.radioViewDropdownShowProps.TabStop = true; this.radioViewDropdownShowProps.Text = "View Dropdown Control"; this.radioViewDropdownShowProps.UseVisualStyleBackColor = true; this.radioViewDropdownShowProps.CheckedChanged += new System.EventHandler(this.RadioViewsDropdown_CheckedChanged); // // label16 // this.label16.Dock = System.Windows.Forms.DockStyle.Top; this.label16.Location = new System.Drawing.Point(0, 0); this.label16.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label16.Name = "label16"; this.label16.Size = new System.Drawing.Size(593, 18); this.label16.TabIndex = 4; this.label16.Text = "Choose what displays in the property control"; // // radioAttribDropdownShowView // this.radioAttribDropdownShowView.AutoSize = true; this.radioAttribDropdownShowView.Location = new System.Drawing.Point(170, 20); this.radioAttribDropdownShowView.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioAttribDropdownShowView.Name = "radioAttribDropdownShowView"; this.radioAttribDropdownShowView.Size = new System.Drawing.Size(93, 17); this.radioAttribDropdownShowView.TabIndex = 2; this.radioAttribDropdownShowView.TabStop = true; this.radioAttribDropdownShowView.Text = "Selected View"; this.radioAttribDropdownShowView.UseVisualStyleBackColor = true; this.radioAttribDropdownShowView.CheckedChanged += new System.EventHandler(this.RadioViewsDropdown_CheckedChanged); // // tabPageGlobalOptSets // this.tabPageGlobalOptSets.Controls.Add(this.splitterGlobalOptsList); this.tabPageGlobalOptSets.Location = new System.Drawing.Point(4, 34); this.tabPageGlobalOptSets.Margin = new System.Windows.Forms.Padding(2); this.tabPageGlobalOptSets.Name = "tabPageGlobalOptSets"; this.tabPageGlobalOptSets.Padding = new System.Windows.Forms.Padding(2); this.tabPageGlobalOptSets.Size = new System.Drawing.Size(907, 564); this.tabPageGlobalOptSets.TabIndex = 6; this.tabPageGlobalOptSets.Text = "Global OptionSet ListView"; this.tabPageGlobalOptSets.UseVisualStyleBackColor = true; // // splitterGlobalOptsList // this.splitterGlobalOptsList.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterGlobalOptsList.Location = new System.Drawing.Point(2, 2); this.splitterGlobalOptsList.Margin = new System.Windows.Forms.Padding(2); this.splitterGlobalOptsList.Name = "splitterGlobalOptsList"; // // splitterGlobalOptsList.Panel1 // this.splitterGlobalOptsList.Panel1.Controls.Add(this.GlobalOptionSetList); // // splitterGlobalOptsList.Panel2 // this.splitterGlobalOptsList.Panel2.Controls.Add(this.tableLayoutPanel1); this.splitterGlobalOptsList.Size = new System.Drawing.Size(903, 560); this.splitterGlobalOptsList.SplitterDistance = 296; this.splitterGlobalOptsList.SplitterWidth = 10; this.splitterGlobalOptsList.TabIndex = 1; // // GlobalOptionSetList // this.GlobalOptionSetList.AutoLoadData = false; this.GlobalOptionSetList.AutosizeColumns = System.Windows.Forms.ColumnHeaderAutoResizeStyle.None; this.GlobalOptionSetList.Checkboxes = true; this.GlobalOptionSetList.DisplayToolbar = false; this.GlobalOptionSetList.Dock = System.Windows.Forms.DockStyle.Fill; this.GlobalOptionSetList.LanguageCode = 1033; this.GlobalOptionSetList.ListViewColDefs = new xrmtb.XrmToolBox.Controls.ListViewColumnDef[] { ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("GlobalOptionSetList.ListViewColDefs"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("GlobalOptionSetList.ListViewColDefs1"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("GlobalOptionSetList.ListViewColDefs2"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("GlobalOptionSetList.ListViewColDefs3"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("GlobalOptionSetList.ListViewColDefs4")))}; this.GlobalOptionSetList.Location = new System.Drawing.Point(0, 0); this.GlobalOptionSetList.Margin = new System.Windows.Forms.Padding(1); this.GlobalOptionSetList.Name = "GlobalOptionSetList"; this.GlobalOptionSetList.RetrieveAsIfPublished = false; this.GlobalOptionSetList.Service = null; this.GlobalOptionSetList.Size = new System.Drawing.Size(296, 560); this.GlobalOptionSetList.TabIndex = 0; this.GlobalOptionSetList.SelectedItemChanged += new System.EventHandler(this.GlobalOptionSetList_SelectedItemChanged); this.GlobalOptionSetList.CheckedItemsChanged += new System.EventHandler(this.GlobalOptionSetList_CheckedItemsChanged); this.GlobalOptionSetList.ProgressChanged += new System.EventHandler<System.ComponentModel.ProgressChangedEventArgs>(this.GlobalOptionSetList_ProgressChanged); this.GlobalOptionSetList.BeginLoadData += new System.EventHandler(this.SolutionDropdown_BeginLoadData); this.GlobalOptionSetList.LoadDataComplete += new System.EventHandler(this.GlobalOptionSetList_LoadDataComplete); this.GlobalOptionSetList.ClearDataComplete += new System.EventHandler(this.GlobalOptionSetList_ClearDataComplete); this.GlobalOptionSetList.CloseComplete += new System.EventHandler(this.GlobalOptionSetList_CloseComplete); this.GlobalOptionSetList.NotificationMessage += new System.EventHandler<xrmtb.XrmToolBox.Controls.NotificationEventArgs>(this.AllControls_NotificationMessage); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.panel7, 0, 1); this.tableLayoutPanel1.Controls.Add(this.propGridGlobalOptsList, 0, 0); this.tableLayoutPanel1.Controls.Add(this.textGlobalOptsListLog, 1, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(597, 560); this.tableLayoutPanel1.TabIndex = 20; // // panel7 // this.tableLayoutPanel1.SetColumnSpan(this.panel7, 2); this.panel7.Controls.Add(this.radioGlobalOptsListShowProps); this.panel7.Controls.Add(this.label17); this.panel7.Controls.Add(this.radioEntDropdownShowOptionSet); this.panel7.Dock = System.Windows.Forms.DockStyle.Fill; this.panel7.Location = new System.Drawing.Point(2, 506); this.panel7.Margin = new System.Windows.Forms.Padding(2); this.panel7.Name = "panel7"; this.panel7.Size = new System.Drawing.Size(593, 52); this.panel7.TabIndex = 16; // // radioGlobalOptsListShowProps // this.radioGlobalOptsListShowProps.AutoSize = true; this.radioGlobalOptsListShowProps.Checked = true; this.radioGlobalOptsListShowProps.Location = new System.Drawing.Point(10, 27); this.radioGlobalOptsListShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioGlobalOptsListShowProps.Name = "radioGlobalOptsListShowProps"; this.radioGlobalOptsListShowProps.Size = new System.Drawing.Size(183, 17); this.radioGlobalOptsListShowProps.TabIndex = 3; this.radioGlobalOptsListShowProps.TabStop = true; this.radioGlobalOptsListShowProps.Text = "Global OptionSet ListView Control"; this.radioGlobalOptsListShowProps.UseVisualStyleBackColor = true; this.radioGlobalOptsListShowProps.CheckedChanged += new System.EventHandler(this.RadioGlobalOptionSetList_CheckedChanged); // // label17 // this.label17.Dock = System.Windows.Forms.DockStyle.Top; this.label17.Location = new System.Drawing.Point(0, 0); this.label17.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label17.Name = "label17"; this.label17.Size = new System.Drawing.Size(593, 23); this.label17.TabIndex = 4; this.label17.Text = "Choose what displays in the property control"; // // radioEntDropdownShowOptionSet // this.radioEntDropdownShowOptionSet.AutoSize = true; this.radioEntDropdownShowOptionSet.Location = new System.Drawing.Point(204, 27); this.radioEntDropdownShowOptionSet.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntDropdownShowOptionSet.Name = "radioEntDropdownShowOptionSet"; this.radioEntDropdownShowOptionSet.Size = new System.Drawing.Size(150, 17); this.radioEntDropdownShowOptionSet.TabIndex = 2; this.radioEntDropdownShowOptionSet.TabStop = true; this.radioEntDropdownShowOptionSet.Text = "Selected Global OptionSet"; this.radioEntDropdownShowOptionSet.UseVisualStyleBackColor = true; this.radioEntDropdownShowOptionSet.CheckedChanged += new System.EventHandler(this.RadioGlobalOptionSetList_CheckedChanged); // // propGridGlobalOptsList // this.propGridGlobalOptsList.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridGlobalOptsList.Location = new System.Drawing.Point(4, 3); this.propGridGlobalOptsList.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridGlobalOptsList.Name = "propGridGlobalOptsList"; this.propGridGlobalOptsList.Size = new System.Drawing.Size(290, 498); this.propGridGlobalOptsList.TabIndex = 8; // // textGlobalOptsListLog // this.textGlobalOptsListLog.Dock = System.Windows.Forms.DockStyle.Fill; this.textGlobalOptsListLog.Location = new System.Drawing.Point(302, 3); this.textGlobalOptsListLog.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textGlobalOptsListLog.Multiline = true; this.textGlobalOptsListLog.Name = "textGlobalOptsListLog"; this.textGlobalOptsListLog.ReadOnly = true; this.textGlobalOptsListLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textGlobalOptsListLog.Size = new System.Drawing.Size(291, 498); this.textGlobalOptsListLog.TabIndex = 7; // // tabPageCRMGridView // this.tabPageCRMGridView.Controls.Add(this.splitterCRMGridView); this.tabPageCRMGridView.Location = new System.Drawing.Point(4, 34); this.tabPageCRMGridView.Name = "tabPageCRMGridView"; this.tabPageCRMGridView.Padding = new System.Windows.Forms.Padding(3); this.tabPageCRMGridView.Size = new System.Drawing.Size(907, 564); this.tabPageCRMGridView.TabIndex = 7; this.tabPageCRMGridView.Text = "CRM GridView"; this.tabPageCRMGridView.UseVisualStyleBackColor = true; // // splitterCRMGridView // this.splitterCRMGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterCRMGridView.Location = new System.Drawing.Point(3, 3); this.splitterCRMGridView.Margin = new System.Windows.Forms.Padding(2); this.splitterCRMGridView.Name = "splitterCRMGridView"; // // splitterCRMGridView.Panel1 // this.splitterCRMGridView.Panel1.Controls.Add(this.tableCRMGridView); // // splitterCRMGridView.Panel2 // this.splitterCRMGridView.Panel2.Controls.Add(this.tableLayoutPanel3); this.splitterCRMGridView.Size = new System.Drawing.Size(901, 558); this.splitterCRMGridView.SplitterDistance = 299; this.splitterCRMGridView.SplitterWidth = 10; this.splitterCRMGridView.TabIndex = 2; // // tableCRMGridView // this.tableCRMGridView.ColumnCount = 1; this.tableCRMGridView.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableCRMGridView.Controls.Add(this.panelCrmGridViewControls, 0, 0); this.tableCRMGridView.Controls.Add(this.CrmGridView, 0, 2); this.tableCRMGridView.Controls.Add(this.XmlViewerCRMDataGrid, 0, 1); this.tableCRMGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.tableCRMGridView.Location = new System.Drawing.Point(0, 0); this.tableCRMGridView.Margin = new System.Windows.Forms.Padding(2); this.tableCRMGridView.Name = "tableCRMGridView"; this.tableCRMGridView.RowCount = 3; this.tableCRMGridView.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 54F)); this.tableCRMGridView.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 40F)); this.tableCRMGridView.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 60F)); this.tableCRMGridView.Size = new System.Drawing.Size(299, 558); this.tableCRMGridView.TabIndex = 0; // // panelCrmGridViewControls // this.panelCrmGridViewControls.Controls.Add(this.dataGridViewGrouperControl1); this.panelCrmGridViewControls.Controls.Add(this.flowLayoutPanel1); this.panelCrmGridViewControls.Dock = System.Windows.Forms.DockStyle.Fill; this.panelCrmGridViewControls.Location = new System.Drawing.Point(2, 2); this.panelCrmGridViewControls.Margin = new System.Windows.Forms.Padding(2); this.panelCrmGridViewControls.Name = "panelCrmGridViewControls"; this.panelCrmGridViewControls.Size = new System.Drawing.Size(295, 50); this.panelCrmGridViewControls.TabIndex = 5; // // dataGridViewGrouperControl1 // this.dataGridViewGrouperControl1.AllowDrop = true; this.dataGridViewGrouperControl1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.dataGridViewGrouperControl1.DataGridView = this.CrmGridView; this.dataGridViewGrouperControl1.Dock = System.Windows.Forms.DockStyle.Bottom; this.dataGridViewGrouperControl1.Location = new System.Drawing.Point(0, 26); this.dataGridViewGrouperControl1.Margin = new System.Windows.Forms.Padding(6); this.dataGridViewGrouperControl1.Name = "dataGridViewGrouperControl1"; this.dataGridViewGrouperControl1.Padding = new System.Windows.Forms.Padding(0, 0, 10, 0); this.dataGridViewGrouperControl1.Size = new System.Drawing.Size(295, 24); this.dataGridViewGrouperControl1.TabIndex = 5; // // CrmGridView // this.CrmGridView.AllowUserToOrderColumns = true; this.CrmGridView.AllowUserToResizeRows = false; this.CrmGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.CrmGridView.ColumnOrder = ""; this.CrmGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.CrmGridView.FilterColumns = ""; this.CrmGridView.Location = new System.Drawing.Point(3, 258); this.CrmGridView.Name = "CrmGridView"; this.CrmGridView.OrganizationService = null; this.CrmGridView.RowHeadersWidth = 72; this.CrmGridView.ShowFriendlyNames = true; this.CrmGridView.Size = new System.Drawing.Size(293, 297); this.CrmGridView.TabIndex = 2; this.CrmGridView.RecordClick += new xrmtb.XrmToolBox.Controls.CRMRecordEventHandler(this.crmGridView1_RecordClick); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.labelExecFetch); this.flowLayoutPanel1.Controls.Add(this.buttonExecFetch); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Top; this.flowLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(2); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(295, 29); this.flowLayoutPanel1.TabIndex = 4; // // labelExecFetch // this.labelExecFetch.Dock = System.Windows.Forms.DockStyle.Right; this.labelExecFetch.Location = new System.Drawing.Point(2, 0); this.labelExecFetch.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelExecFetch.Name = "labelExecFetch"; this.labelExecFetch.Size = new System.Drawing.Size(131, 39); this.labelExecFetch.TabIndex = 3; this.labelExecFetch.Text = "Enter FetchXml below: "; this.labelExecFetch.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // buttonExecFetch // this.buttonExecFetch.AutoSize = true; this.buttonExecFetch.Dock = System.Windows.Forms.DockStyle.Right; this.buttonExecFetch.Location = new System.Drawing.Point(137, 2); this.buttonExecFetch.Margin = new System.Windows.Forms.Padding(2); this.buttonExecFetch.Name = "buttonExecFetch"; this.buttonExecFetch.Size = new System.Drawing.Size(147, 35); this.buttonExecFetch.TabIndex = 4; this.buttonExecFetch.Text = "Execute Fetch"; this.buttonExecFetch.UseVisualStyleBackColor = true; this.buttonExecFetch.Click += new System.EventHandler(this.buttonExecFetch_Click); // // XmlViewerCRMDataGrid // this.XmlViewerCRMDataGrid.CurrentParseError = ((System.Exception)(resources.GetObject("XmlViewerCRMDataGrid.CurrentParseError"))); this.XmlViewerCRMDataGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlViewerCRMDataGrid.FormatAsYouType = true; this.XmlViewerCRMDataGrid.Location = new System.Drawing.Point(2, 56); this.XmlViewerCRMDataGrid.Margin = new System.Windows.Forms.Padding(2); this.XmlViewerCRMDataGrid.Name = "XmlViewerCRMDataGrid"; xmlViewerSettings1.AttributeKey = System.Drawing.Color.Blue; xmlViewerSettings1.AttributeValue = System.Drawing.Color.DarkRed; xmlViewerSettings1.Comment = System.Drawing.Color.Gray; xmlViewerSettings1.Element = System.Drawing.Color.DarkGreen; xmlViewerSettings1.FontName = "Consolas"; xmlViewerSettings1.FontSize = 9F; xmlViewerSettings1.QuoteCharacter = '\"'; xmlViewerSettings1.Tag = System.Drawing.Color.ForestGreen; xmlViewerSettings1.Value = System.Drawing.Color.Black; this.XmlViewerCRMDataGrid.Settings = xmlViewerSettings1; this.XmlViewerCRMDataGrid.Size = new System.Drawing.Size(295, 197); this.XmlViewerCRMDataGrid.TabIndex = 5; this.XmlViewerCRMDataGrid.Text = ""; this.XmlViewerCRMDataGrid.TextChanged += new System.EventHandler(this.XmlViewerCRMDataGrid_TextChanged); // // tableLayoutPanel3 // this.tableLayoutPanel3.ColumnCount = 2; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel3.Controls.Add(this.panel8, 0, 1); this.tableLayoutPanel3.Controls.Add(this.propCRMGridView, 0, 0); this.tableLayoutPanel3.Controls.Add(this.panel11, 1, 0); this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel3.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 2; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 105F)); this.tableLayoutPanel3.Size = new System.Drawing.Size(592, 558); this.tableLayoutPanel3.TabIndex = 20; // // panel8 // this.tableLayoutPanel3.SetColumnSpan(this.panel8, 2); this.panel8.Controls.Add(this.groupBox1); this.panel8.Controls.Add(this.panel12); this.panel8.Dock = System.Windows.Forms.DockStyle.Fill; this.panel8.Location = new System.Drawing.Point(2, 455); this.panel8.Margin = new System.Windows.Forms.Padding(2); this.panel8.Name = "panel8"; this.panel8.Size = new System.Drawing.Size(588, 101); this.panel8.TabIndex = 16; // // groupBox1 // this.groupBox1.Controls.Add(this.button1); this.groupBox1.Controls.Add(this.label23); this.groupBox1.Controls.Add(this.cdsDataTextBox); this.groupBox1.Controls.Add(this.label22); this.groupBox1.Controls.Add(this.textCdsDataComboBoxFormat); this.groupBox1.Controls.Add(this.label21); this.groupBox1.Controls.Add(this.cdsDataComboBox); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(237, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(351, 101); this.groupBox1.TabIndex = 6; this.groupBox1.TabStop = false; this.groupBox1.Text = "CDSDataComboBox"; // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image"))); this.button1.Location = new System.Drawing.Point(324, 71); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(21, 21); this.button1.TabIndex = 11; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label23 // this.label23.AutoSize = true; this.label23.Location = new System.Drawing.Point(13, 74); this.label23.Name = "label23"; this.label23.Size = new System.Drawing.Size(34, 13); this.label23.TabIndex = 10; this.label23.Text = "TxtBx"; // // cdsDataTextBox // this.cdsDataTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cdsDataTextBox.BackColor = System.Drawing.SystemColors.Window; this.cdsDataTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.cdsDataTextBox.DisplayFormat = ""; this.cdsDataTextBox.Entity = null; this.cdsDataTextBox.EntityReference = null; this.cdsDataTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cdsDataTextBox.ForeColor = System.Drawing.SystemColors.ControlText; this.cdsDataTextBox.Id = new System.Guid("00000000-0000-0000-0000-000000000000"); this.cdsDataTextBox.Location = new System.Drawing.Point(58, 71); this.cdsDataTextBox.LogicalName = ""; this.cdsDataTextBox.Name = "cdsDataTextBox"; this.cdsDataTextBox.OrganizationService = null; this.cdsDataTextBox.Size = new System.Drawing.Size(255, 20); this.cdsDataTextBox.TabIndex = 9; this.cdsDataTextBox.RecordClick += new xrmtb.XrmToolBox.Controls.CDSRecordEventHandler(this.cdsDataTextBox_RecordClick); // // label22 // this.label22.AutoSize = true; this.label22.Location = new System.Drawing.Point(13, 47); this.label22.Name = "label22"; this.label22.Size = new System.Drawing.Size(40, 13); this.label22.TabIndex = 8; this.label22.Text = "CmbBx"; // // textCdsDataComboBoxFormat // this.textCdsDataComboBoxFormat.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textCdsDataComboBoxFormat.Location = new System.Drawing.Point(58, 17); this.textCdsDataComboBoxFormat.Name = "textCdsDataComboBoxFormat"; this.textCdsDataComboBoxFormat.Size = new System.Drawing.Size(287, 20); this.textCdsDataComboBoxFormat.TabIndex = 7; this.textCdsDataComboBoxFormat.TextChanged += new System.EventHandler(this.textCdsDataComboBoxFormat_TextChanged); // // label21 // this.label21.AutoSize = true; this.label21.Location = new System.Drawing.Point(13, 20); this.label21.Name = "label21"; this.label21.Size = new System.Drawing.Size(39, 13); this.label21.TabIndex = 6; this.label21.Text = "Format"; // // cdsDataComboBox // this.cdsDataComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cdsDataComboBox.DisplayFormat = ""; this.cdsDataComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cdsDataComboBox.FormattingEnabled = true; this.cdsDataComboBox.Location = new System.Drawing.Point(58, 44); this.cdsDataComboBox.Name = "cdsDataComboBox"; this.cdsDataComboBox.OrganizationService = null; this.cdsDataComboBox.Size = new System.Drawing.Size(287, 21); this.cdsDataComboBox.TabIndex = 5; this.cdsDataComboBox.SelectedIndexChanged += new System.EventHandler(this.cdsDataComboBox_SelectedIndexChanged); // // panel12 // this.panel12.Controls.Add(this.radioCRMGridViewLkpDlg); this.panel12.Controls.Add(this.radioCRMGridViewTxtBx); this.panel12.Controls.Add(this.radioCRMGridViewCmbBx); this.panel12.Controls.Add(this.radioCRMGridViewRightShowProps); this.panel12.Controls.Add(this.radioCRMGridViewSelEntity); this.panel12.Controls.Add(this.radioCRMGridViewShowProps); this.panel12.Controls.Add(this.label18); this.panel12.Dock = System.Windows.Forms.DockStyle.Left; this.panel12.Location = new System.Drawing.Point(0, 0); this.panel12.Name = "panel12"; this.panel12.Size = new System.Drawing.Size(237, 101); this.panel12.TabIndex = 8; // // radioCRMGridViewLkpDlg // this.radioCRMGridViewLkpDlg.AutoSize = true; this.radioCRMGridViewLkpDlg.Location = new System.Drawing.Point(159, 72); this.radioCRMGridViewLkpDlg.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewLkpDlg.Name = "radioCRMGridViewLkpDlg"; this.radioCRMGridViewLkpDlg.Size = new System.Drawing.Size(59, 17); this.radioCRMGridViewLkpDlg.TabIndex = 10; this.radioCRMGridViewLkpDlg.Text = "LkpDlg"; this.radioCRMGridViewLkpDlg.UseVisualStyleBackColor = true; this.radioCRMGridViewLkpDlg.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // radioCRMGridViewTxtBx // this.radioCRMGridViewTxtBx.AutoSize = true; this.radioCRMGridViewTxtBx.Location = new System.Drawing.Point(159, 45); this.radioCRMGridViewTxtBx.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewTxtBx.Name = "radioCRMGridViewTxtBx"; this.radioCRMGridViewTxtBx.Size = new System.Drawing.Size(52, 17); this.radioCRMGridViewTxtBx.TabIndex = 9; this.radioCRMGridViewTxtBx.Text = "TxtBx"; this.radioCRMGridViewTxtBx.UseVisualStyleBackColor = true; this.radioCRMGridViewTxtBx.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // radioCRMGridViewCmbBx // this.radioCRMGridViewCmbBx.AutoSize = true; this.radioCRMGridViewCmbBx.Location = new System.Drawing.Point(159, 18); this.radioCRMGridViewCmbBx.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewCmbBx.Name = "radioCRMGridViewCmbBx"; this.radioCRMGridViewCmbBx.Size = new System.Drawing.Size(58, 17); this.radioCRMGridViewCmbBx.TabIndex = 8; this.radioCRMGridViewCmbBx.Text = "CmbBx"; this.radioCRMGridViewCmbBx.UseVisualStyleBackColor = true; this.radioCRMGridViewCmbBx.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // radioCRMGridViewRightShowProps // this.radioCRMGridViewRightShowProps.AutoSize = true; this.radioCRMGridViewRightShowProps.Location = new System.Drawing.Point(14, 45); this.radioCRMGridViewRightShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewRightShowProps.Name = "radioCRMGridViewRightShowProps"; this.radioCRMGridViewRightShowProps.Size = new System.Drawing.Size(119, 17); this.radioCRMGridViewRightShowProps.TabIndex = 7; this.radioCRMGridViewRightShowProps.Text = "CRMGridView Right"; this.radioCRMGridViewRightShowProps.UseVisualStyleBackColor = true; this.radioCRMGridViewRightShowProps.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // radioCRMGridViewSelEntity // this.radioCRMGridViewSelEntity.AutoSize = true; this.radioCRMGridViewSelEntity.Location = new System.Drawing.Point(14, 72); this.radioCRMGridViewSelEntity.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewSelEntity.Name = "radioCRMGridViewSelEntity"; this.radioCRMGridViewSelEntity.Size = new System.Drawing.Size(96, 17); this.radioCRMGridViewSelEntity.TabIndex = 2; this.radioCRMGridViewSelEntity.Text = "Selected Entity"; this.radioCRMGridViewSelEntity.UseVisualStyleBackColor = true; this.radioCRMGridViewSelEntity.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // radioCRMGridViewShowProps // this.radioCRMGridViewShowProps.AutoSize = true; this.radioCRMGridViewShowProps.Checked = true; this.radioCRMGridViewShowProps.Location = new System.Drawing.Point(14, 18); this.radioCRMGridViewShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioCRMGridViewShowProps.Name = "radioCRMGridViewShowProps"; this.radioCRMGridViewShowProps.Size = new System.Drawing.Size(112, 17); this.radioCRMGridViewShowProps.TabIndex = 3; this.radioCRMGridViewShowProps.TabStop = true; this.radioCRMGridViewShowProps.Text = "CRMGridView Left"; this.radioCRMGridViewShowProps.UseVisualStyleBackColor = true; this.radioCRMGridViewShowProps.CheckedChanged += new System.EventHandler(this.RadioCRMGridViewShowProps_CheckedChanged); // // label18 // this.label18.Location = new System.Drawing.Point(4, 0); this.label18.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(222, 23); this.label18.TabIndex = 4; this.label18.Text = "Choose what displays in the property control"; // // propCRMGridView // this.propCRMGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.propCRMGridView.Location = new System.Drawing.Point(4, 3); this.propCRMGridView.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propCRMGridView.Name = "propCRMGridView"; this.propCRMGridView.Size = new System.Drawing.Size(288, 447); this.propCRMGridView.TabIndex = 8; // // panel11 // this.panel11.Controls.Add(this.CrmGridViewDesignedCols); this.panel11.Controls.Add(this.buttonExecPredefinedCrmGridViewQuery); this.panel11.Dock = System.Windows.Forms.DockStyle.Fill; this.panel11.Location = new System.Drawing.Point(299, 3); this.panel11.Name = "panel11"; this.panel11.Size = new System.Drawing.Size(290, 447); this.panel11.TabIndex = 17; // // CrmGridViewDesignedCols // this.CrmGridViewDesignedCols.AllowUserToOrderColumns = true; this.CrmGridViewDesignedCols.AllowUserToResizeRows = false; this.CrmGridViewDesignedCols.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.CrmGridViewDesignedCols.ColumnOrder = ""; this.CrmGridViewDesignedCols.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.name, this.revenue}); this.CrmGridViewDesignedCols.Dock = System.Windows.Forms.DockStyle.Fill; this.CrmGridViewDesignedCols.EnableHeadersVisualStyles = false; this.CrmGridViewDesignedCols.FilterColumns = "name"; this.CrmGridViewDesignedCols.Location = new System.Drawing.Point(0, 23); this.CrmGridViewDesignedCols.Name = "CrmGridViewDesignedCols"; this.CrmGridViewDesignedCols.OrganizationService = null; this.CrmGridViewDesignedCols.ShowFriendlyNames = true; this.CrmGridViewDesignedCols.ShowIdColumn = false; this.CrmGridViewDesignedCols.ShowIndexColumn = false; this.CrmGridViewDesignedCols.ShowLocalTimes = true; this.CrmGridViewDesignedCols.Size = new System.Drawing.Size(290, 424); this.CrmGridViewDesignedCols.TabIndex = 0; this.CrmGridViewDesignedCols.RecordClick += new xrmtb.XrmToolBox.Controls.CRMRecordEventHandler(this.CrmGridViewDesignedCols_RecordClick); // // name // this.name.HeaderText = "Account Name"; this.name.Name = "name"; this.name.ReadOnly = true; // // revenue // this.revenue.HeaderText = "Revenue"; this.revenue.Name = "revenue"; this.revenue.ReadOnly = true; // // buttonExecPredefinedCrmGridViewQuery // this.buttonExecPredefinedCrmGridViewQuery.Dock = System.Windows.Forms.DockStyle.Top; this.buttonExecPredefinedCrmGridViewQuery.Location = new System.Drawing.Point(0, 0); this.buttonExecPredefinedCrmGridViewQuery.Name = "buttonExecPredefinedCrmGridViewQuery"; this.buttonExecPredefinedCrmGridViewQuery.Size = new System.Drawing.Size(290, 23); this.buttonExecPredefinedCrmGridViewQuery.TabIndex = 1; this.buttonExecPredefinedCrmGridViewQuery.Text = "Execute predefined query"; this.buttonExecPredefinedCrmGridViewQuery.UseVisualStyleBackColor = true; this.buttonExecPredefinedCrmGridViewQuery.Click += new System.EventHandler(this.buttonExecPredefinedCrmGridViewQuery_Click); // // tabPageXrmViewer // this.tabPageXrmViewer.Controls.Add(this.TableXmlViewers); this.tabPageXrmViewer.Location = new System.Drawing.Point(4, 34); this.tabPageXrmViewer.Margin = new System.Windows.Forms.Padding(2); this.tabPageXrmViewer.Name = "tabPageXrmViewer"; this.tabPageXrmViewer.Padding = new System.Windows.Forms.Padding(2); this.tabPageXrmViewer.Size = new System.Drawing.Size(907, 564); this.tabPageXrmViewer.TabIndex = 8; this.tabPageXrmViewer.Text = "XmlViewer"; this.tabPageXrmViewer.UseVisualStyleBackColor = true; // // TableXmlViewers // this.TableXmlViewers.ColumnCount = 1; this.TableXmlViewers.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.TableXmlViewers.Controls.Add(this.splitterXmlViewerControl, 0, 1); this.TableXmlViewers.Controls.Add(this.splitterXmlViewer, 0, 3); this.TableXmlViewers.Controls.Add(this.labelXmlViewerControlTitle, 0, 0); this.TableXmlViewers.Controls.Add(this.labelXmlViewerTitle, 0, 2); this.TableXmlViewers.Dock = System.Windows.Forms.DockStyle.Fill; this.TableXmlViewers.Location = new System.Drawing.Point(2, 2); this.TableXmlViewers.Margin = new System.Windows.Forms.Padding(2); this.TableXmlViewers.Name = "TableXmlViewers"; this.TableXmlViewers.RowCount = 4; this.TableXmlViewers.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 23F)); this.TableXmlViewers.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.TableXmlViewers.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 23F)); this.TableXmlViewers.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.TableXmlViewers.Size = new System.Drawing.Size(903, 560); this.TableXmlViewers.TabIndex = 2; // // splitterXmlViewerControl // this.splitterXmlViewerControl.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterXmlViewerControl.Location = new System.Drawing.Point(2, 25); this.splitterXmlViewerControl.Margin = new System.Windows.Forms.Padding(2); this.splitterXmlViewerControl.Name = "splitterXmlViewerControl"; // // splitterXmlViewerControl.Panel1 // this.splitterXmlViewerControl.Panel1.Controls.Add(this.XmlViewerControl); // // splitterXmlViewerControl.Panel2 // this.splitterXmlViewerControl.Panel2.Controls.Add(this.propGridXmlViewerControl); this.splitterXmlViewerControl.Size = new System.Drawing.Size(899, 253); this.splitterXmlViewerControl.SplitterDistance = 454; this.splitterXmlViewerControl.SplitterWidth = 8; this.splitterXmlViewerControl.TabIndex = 1; // // XmlViewerControl // this.XmlViewerControl.AcceptsTab = false; this.XmlViewerControl.AutoWordSelection = false; this.XmlViewerControl.BulletIndent = 0; this.XmlViewerControl.DetectUrls = true; this.XmlViewerControl.DisplayParseErrors = true; this.XmlViewerControl.DisplayToolbar = false; this.XmlViewerControl.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlViewerControl.EnableAutoDragDrop = false; this.XmlViewerControl.FormatAsYouType = true; this.XmlViewerControl.HideSelection = true; this.XmlViewerControl.Location = new System.Drawing.Point(0, 0); this.XmlViewerControl.Margin = new System.Windows.Forms.Padding(2); this.XmlViewerControl.MaxLength = 2147483647; this.XmlViewerControl.Multiline = true; this.XmlViewerControl.Name = "XmlViewerControl"; this.XmlViewerControl.ReadOnly = false; this.XmlViewerControl.RightMargin = 0; this.XmlViewerControl.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both; xmlViewerSettings2.AttributeKey = System.Drawing.Color.Blue; xmlViewerSettings2.AttributeValue = System.Drawing.Color.DarkRed; xmlViewerSettings2.Comment = System.Drawing.Color.Gray; xmlViewerSettings2.Element = System.Drawing.Color.DarkGreen; xmlViewerSettings2.FontName = "Consolas"; xmlViewerSettings2.FontSize = 9F; xmlViewerSettings2.QuoteCharacter = '\"'; xmlViewerSettings2.Tag = System.Drawing.Color.ForestGreen; xmlViewerSettings2.Value = System.Drawing.Color.Black; this.XmlViewerControl.Settings = xmlViewerSettings2; this.XmlViewerControl.ShortcutsEnabled = true; this.XmlViewerControl.ShowSelectionMargin = false; this.XmlViewerControl.Size = new System.Drawing.Size(454, 253); this.XmlViewerControl.TabIndex = 0; this.XmlViewerControl.WordWrap = true; this.XmlViewerControl.ZoomFactor = 1F; // // propGridXmlViewerControl // this.propGridXmlViewerControl.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridXmlViewerControl.Location = new System.Drawing.Point(0, 0); this.propGridXmlViewerControl.Margin = new System.Windows.Forms.Padding(2); this.propGridXmlViewerControl.Name = "propGridXmlViewerControl"; this.propGridXmlViewerControl.SelectedObject = this.XmlViewerControl; this.propGridXmlViewerControl.Size = new System.Drawing.Size(437, 253); this.propGridXmlViewerControl.TabIndex = 0; // // splitterXmlViewer // this.splitterXmlViewer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterXmlViewer.Location = new System.Drawing.Point(2, 305); this.splitterXmlViewer.Margin = new System.Windows.Forms.Padding(2); this.splitterXmlViewer.Name = "splitterXmlViewer"; // // splitterXmlViewer.Panel1 // this.splitterXmlViewer.Panel1.Controls.Add(this.XmlViewer); // // splitterXmlViewer.Panel2 // this.splitterXmlViewer.Panel2.Controls.Add(this.propGridXmlViewer); this.splitterXmlViewer.Size = new System.Drawing.Size(899, 253); this.splitterXmlViewer.SplitterDistance = 460; this.splitterXmlViewer.SplitterWidth = 8; this.splitterXmlViewer.TabIndex = 2; // // XmlViewer // this.XmlViewer.CurrentParseError = null; this.XmlViewer.Dock = System.Windows.Forms.DockStyle.Fill; this.XmlViewer.FormatAsYouType = true; this.XmlViewer.Location = new System.Drawing.Point(0, 0); this.XmlViewer.Margin = new System.Windows.Forms.Padding(2); this.XmlViewer.Name = "XmlViewer"; xmlViewerSettings3.AttributeKey = System.Drawing.Color.Blue; xmlViewerSettings3.AttributeValue = System.Drawing.Color.DarkRed; xmlViewerSettings3.Comment = System.Drawing.Color.Gray; xmlViewerSettings3.Element = System.Drawing.Color.DarkGreen; xmlViewerSettings3.FontName = "Consolas"; xmlViewerSettings3.FontSize = 9F; xmlViewerSettings3.QuoteCharacter = '\"'; xmlViewerSettings3.Tag = System.Drawing.Color.ForestGreen; xmlViewerSettings3.Value = System.Drawing.Color.Black; this.XmlViewer.Settings = xmlViewerSettings3; this.XmlViewer.Size = new System.Drawing.Size(460, 253); this.XmlViewer.TabIndex = 0; this.XmlViewer.Text = ""; // // propGridXmlViewer // this.propGridXmlViewer.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridXmlViewer.Location = new System.Drawing.Point(0, 0); this.propGridXmlViewer.Margin = new System.Windows.Forms.Padding(2); this.propGridXmlViewer.Name = "propGridXmlViewer"; this.propGridXmlViewer.SelectedObject = this.XmlViewer; this.propGridXmlViewer.Size = new System.Drawing.Size(431, 253); this.propGridXmlViewer.TabIndex = 0; // // labelXmlViewerControlTitle // this.labelXmlViewerControlTitle.AutoSize = true; this.labelXmlViewerControlTitle.Dock = System.Windows.Forms.DockStyle.Fill; this.labelXmlViewerControlTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelXmlViewerControlTitle.Location = new System.Drawing.Point(2, 0); this.labelXmlViewerControlTitle.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelXmlViewerControlTitle.Name = "labelXmlViewerControlTitle"; this.labelXmlViewerControlTitle.Size = new System.Drawing.Size(899, 23); this.labelXmlViewerControlTitle.TabIndex = 3; this.labelXmlViewerControlTitle.Text = "XmlViewerControl"; this.labelXmlViewerControlTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // labelXmlViewerTitle // this.labelXmlViewerTitle.AutoSize = true; this.labelXmlViewerTitle.Dock = System.Windows.Forms.DockStyle.Fill; this.labelXmlViewerTitle.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labelXmlViewerTitle.Location = new System.Drawing.Point(2, 280); this.labelXmlViewerTitle.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelXmlViewerTitle.Name = "labelXmlViewerTitle"; this.labelXmlViewerTitle.Size = new System.Drawing.Size(899, 23); this.labelXmlViewerTitle.TabIndex = 4; this.labelXmlViewerTitle.Text = "XmlViewer"; this.labelXmlViewerTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tabPageBoundListIVew // this.tabPageBoundListIVew.Controls.Add(this.splitterBoundListView); this.tabPageBoundListIVew.Location = new System.Drawing.Point(4, 34); this.tabPageBoundListIVew.Margin = new System.Windows.Forms.Padding(2); this.tabPageBoundListIVew.Name = "tabPageBoundListIVew"; this.tabPageBoundListIVew.Padding = new System.Windows.Forms.Padding(2); this.tabPageBoundListIVew.Size = new System.Drawing.Size(907, 564); this.tabPageBoundListIVew.TabIndex = 9; this.tabPageBoundListIVew.Text = "BoundListView"; this.tabPageBoundListIVew.UseVisualStyleBackColor = true; // // splitterBoundListView // this.splitterBoundListView.Dock = System.Windows.Forms.DockStyle.Fill; this.splitterBoundListView.Location = new System.Drawing.Point(2, 2); this.splitterBoundListView.Margin = new System.Windows.Forms.Padding(2); this.splitterBoundListView.Name = "splitterBoundListView"; // // splitterBoundListView.Panel1 // this.splitterBoundListView.Panel1.Controls.Add(this.splitterEntList); this.splitterBoundListView.Panel1.Controls.Add(this.listViewEntCollection); this.splitterBoundListView.Panel1.Controls.Add(this.xmlViewerEntColl); this.splitterBoundListView.Panel1.Controls.Add(this.flowLayoutPanel2); // // splitterBoundListView.Panel2 // this.splitterBoundListView.Panel2.Controls.Add(this.tableLayoutPanel4); this.splitterBoundListView.Size = new System.Drawing.Size(903, 560); this.splitterBoundListView.SplitterDistance = 295; this.splitterBoundListView.SplitterWidth = 10; this.splitterBoundListView.TabIndex = 1; // // splitterEntList // this.splitterEntList.Dock = System.Windows.Forms.DockStyle.Top; this.splitterEntList.Location = new System.Drawing.Point(0, 336); this.splitterEntList.Margin = new System.Windows.Forms.Padding(2); this.splitterEntList.Name = "splitterEntList"; this.splitterEntList.Size = new System.Drawing.Size(295, 5); this.splitterEntList.TabIndex = 10; this.splitterEntList.TabStop = false; // // listViewEntCollection // this.listViewEntCollection.AutoLoadData = false; this.listViewEntCollection.AutoRefresh = false; this.listViewEntCollection.AutosizeColumns = System.Windows.Forms.ColumnHeaderAutoResizeStyle.None; this.listViewEntCollection.CheckBoxes = true; this.listViewEntCollection.DisplayCheckBoxes = true; this.listViewEntCollection.Dock = System.Windows.Forms.DockStyle.Fill; this.listViewEntCollection.FullRowSelect = true; this.listViewEntCollection.HideSelection = false; this.listViewEntCollection.LanguageCode = 1033; this.listViewEntCollection.ListViewColDefs = new xrmtb.XrmToolBox.Controls.ListViewColumnDef[] { ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("listViewEntCollection.ListViewColDefs"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("listViewEntCollection.ListViewColDefs1"))), ((xrmtb.XrmToolBox.Controls.ListViewColumnDef)(resources.GetObject("listViewEntCollection.ListViewColDefs2")))}; this.listViewEntCollection.Location = new System.Drawing.Point(0, 336); this.listViewEntCollection.Margin = new System.Windows.Forms.Padding(2); this.listViewEntCollection.Name = "listViewEntCollection"; this.listViewEntCollection.Service = null; this.listViewEntCollection.ShowFriendlyNames = true; this.listViewEntCollection.ShowLocalTimes = true; this.listViewEntCollection.Size = new System.Drawing.Size(295, 224); this.listViewEntCollection.TabIndex = 1; this.listViewEntCollection.UseCompatibleStateImageBehavior = false; this.listViewEntCollection.View = System.Windows.Forms.View.Details; // // xmlViewerEntColl // this.xmlViewerEntColl.CurrentParseError = ((System.Exception)(resources.GetObject("xmlViewerEntColl.CurrentParseError"))); this.xmlViewerEntColl.Dock = System.Windows.Forms.DockStyle.Top; this.xmlViewerEntColl.FormatAsYouType = true; this.xmlViewerEntColl.Location = new System.Drawing.Point(0, 34); this.xmlViewerEntColl.Margin = new System.Windows.Forms.Padding(2); this.xmlViewerEntColl.Name = "xmlViewerEntColl"; xmlViewerSettings4.AttributeKey = System.Drawing.Color.Blue; xmlViewerSettings4.AttributeValue = System.Drawing.Color.DarkRed; xmlViewerSettings4.Comment = System.Drawing.Color.Gray; xmlViewerSettings4.Element = System.Drawing.Color.DarkGreen; xmlViewerSettings4.FontName = "Consolas"; xmlViewerSettings4.FontSize = 9F; xmlViewerSettings4.QuoteCharacter = '\"'; xmlViewerSettings4.Tag = System.Drawing.Color.ForestGreen; xmlViewerSettings4.Value = System.Drawing.Color.Black; this.xmlViewerEntColl.Settings = xmlViewerSettings4; this.xmlViewerEntColl.Size = new System.Drawing.Size(295, 302); this.xmlViewerEntColl.TabIndex = 8; this.xmlViewerEntColl.Text = ""; // // flowLayoutPanel2 // this.flowLayoutPanel2.Controls.Add(this.labelExecFetchBoundList); this.flowLayoutPanel2.Controls.Add(this.buttonExecFetchBoundList); this.flowLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Top; this.flowLayoutPanel2.Location = new System.Drawing.Point(0, 0); this.flowLayoutPanel2.Margin = new System.Windows.Forms.Padding(2); this.flowLayoutPanel2.Name = "flowLayoutPanel2"; this.flowLayoutPanel2.Size = new System.Drawing.Size(295, 34); this.flowLayoutPanel2.TabIndex = 9; // // labelExecFetchBoundList // this.labelExecFetchBoundList.Dock = System.Windows.Forms.DockStyle.Right; this.labelExecFetchBoundList.Location = new System.Drawing.Point(2, 0); this.labelExecFetchBoundList.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.labelExecFetchBoundList.Name = "labelExecFetchBoundList"; this.labelExecFetchBoundList.Size = new System.Drawing.Size(131, 27); this.labelExecFetchBoundList.TabIndex = 3; this.labelExecFetchBoundList.Text = "Enter FetchXml below: "; this.labelExecFetchBoundList.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // buttonExecFetchBoundList // this.buttonExecFetchBoundList.AutoSize = true; this.buttonExecFetchBoundList.Dock = System.Windows.Forms.DockStyle.Right; this.buttonExecFetchBoundList.Location = new System.Drawing.Point(137, 2); this.buttonExecFetchBoundList.Margin = new System.Windows.Forms.Padding(2); this.buttonExecFetchBoundList.Name = "buttonExecFetchBoundList"; this.buttonExecFetchBoundList.Size = new System.Drawing.Size(123, 23); this.buttonExecFetchBoundList.TabIndex = 4; this.buttonExecFetchBoundList.Text = "Execute Fetch"; this.buttonExecFetchBoundList.UseVisualStyleBackColor = true; this.buttonExecFetchBoundList.Click += new System.EventHandler(this.buttonExecFetchBoundList_Click); // // tableLayoutPanel4 // this.tableLayoutPanel4.ColumnCount = 2; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel4.Controls.Add(this.panel9, 0, 1); this.tableLayoutPanel4.Controls.Add(this.propGridBoundListView, 0, 0); this.tableLayoutPanel4.Controls.Add(this.textBox1, 1, 0); this.tableLayoutPanel4.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel4.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel4.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 2; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 90F)); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.tableLayoutPanel4.Size = new System.Drawing.Size(598, 560); this.tableLayoutPanel4.TabIndex = 20; // // panel9 // this.tableLayoutPanel4.SetColumnSpan(this.panel9, 2); this.panel9.Controls.Add(this.radioBoundListShowProps); this.panel9.Controls.Add(this.label19); this.panel9.Controls.Add(this.radioEntListShowObj); this.panel9.Dock = System.Windows.Forms.DockStyle.Fill; this.panel9.Location = new System.Drawing.Point(2, 506); this.panel9.Margin = new System.Windows.Forms.Padding(2); this.panel9.Name = "panel9"; this.panel9.Size = new System.Drawing.Size(594, 52); this.panel9.TabIndex = 16; // // radioBoundListShowProps // this.radioBoundListShowProps.AutoSize = true; this.radioBoundListShowProps.Checked = true; this.radioBoundListShowProps.Location = new System.Drawing.Point(10, 27); this.radioBoundListShowProps.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioBoundListShowProps.Name = "radioBoundListShowProps"; this.radioBoundListShowProps.Size = new System.Drawing.Size(134, 17); this.radioBoundListShowProps.TabIndex = 3; this.radioBoundListShowProps.TabStop = true; this.radioBoundListShowProps.Text = "Bound ListView Control"; this.radioBoundListShowProps.UseVisualStyleBackColor = true; this.radioBoundListShowProps.CheckedChanged += new System.EventHandler(this.RadioBoundListShowProps_CheckedChanged); // // label19 // this.label19.Dock = System.Windows.Forms.DockStyle.Top; this.label19.Location = new System.Drawing.Point(0, 0); this.label19.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label19.Name = "label19"; this.label19.Size = new System.Drawing.Size(594, 23); this.label19.TabIndex = 4; this.label19.Text = "Choose what displays in the property control"; // // radioEntListShowObj // this.radioEntListShowObj.AutoSize = true; this.radioEntListShowObj.Location = new System.Drawing.Point(150, 27); this.radioEntListShowObj.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.radioEntListShowObj.Name = "radioEntListShowObj"; this.radioEntListShowObj.Size = new System.Drawing.Size(101, 17); this.radioEntListShowObj.TabIndex = 2; this.radioEntListShowObj.TabStop = true; this.radioEntListShowObj.Text = "Selected Object"; this.radioEntListShowObj.UseVisualStyleBackColor = true; // // propGridBoundListView // this.propGridBoundListView.Dock = System.Windows.Forms.DockStyle.Fill; this.propGridBoundListView.Location = new System.Drawing.Point(4, 3); this.propGridBoundListView.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.propGridBoundListView.Name = "propGridBoundListView"; this.propGridBoundListView.Size = new System.Drawing.Size(291, 498); this.propGridBoundListView.TabIndex = 8; // // textBox1 // this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.textBox1.Location = new System.Drawing.Point(303, 3); this.textBox1.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBox1.Size = new System.Drawing.Size(291, 498); this.textBox1.TabIndex = 7; // // tabPageCDSDataComboBox // this.tabPageCDSDataComboBox.Controls.Add(this.tableLayoutPanel6); this.tabPageCDSDataComboBox.Location = new System.Drawing.Point(4, 34); this.tabPageCDSDataComboBox.Name = "tabPageCDSDataComboBox"; this.tabPageCDSDataComboBox.Padding = new System.Windows.Forms.Padding(3); this.tabPageCDSDataComboBox.Size = new System.Drawing.Size(907, 564); this.tabPageCDSDataComboBox.TabIndex = 11; this.tabPageCDSDataComboBox.Text = "CDSDataComboBox"; this.tabPageCDSDataComboBox.UseVisualStyleBackColor = true; // // tableLayoutPanel6 // this.tableLayoutPanel6.ColumnCount = 2; this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel6.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel6.Controls.Add(this.xmlViewerFetchCDSCombo, 0, 1); this.tableLayoutPanel6.Controls.Add(this.textBoxCDSComboProgress, 1, 0); this.tableLayoutPanel6.Controls.Add(this.panelCDSComboRetrieve, 0, 0); this.tableLayoutPanel6.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel6.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel6.Margin = new System.Windows.Forms.Padding(2); this.tableLayoutPanel6.Name = "tableLayoutPanel6"; this.tableLayoutPanel6.Padding = new System.Windows.Forms.Padding(5); this.tableLayoutPanel6.RowCount = 2; this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 33F)); this.tableLayoutPanel6.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel6.Size = new System.Drawing.Size(901, 558); this.tableLayoutPanel6.TabIndex = 11; // // xmlViewerFetchCDSCombo // this.xmlViewerFetchCDSCombo.AcceptsTab = false; this.xmlViewerFetchCDSCombo.AutoWordSelection = false; this.xmlViewerFetchCDSCombo.BackColor = System.Drawing.SystemColors.Window; this.xmlViewerFetchCDSCombo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.xmlViewerFetchCDSCombo.BulletIndent = 0; this.xmlViewerFetchCDSCombo.DetectUrls = true; this.xmlViewerFetchCDSCombo.DisplayParseErrors = true; this.xmlViewerFetchCDSCombo.DisplayToolbar = false; this.xmlViewerFetchCDSCombo.Dock = System.Windows.Forms.DockStyle.Fill; this.xmlViewerFetchCDSCombo.EnableAutoDragDrop = false; this.xmlViewerFetchCDSCombo.FormatAsYouType = true; this.xmlViewerFetchCDSCombo.HideSelection = true; this.xmlViewerFetchCDSCombo.Location = new System.Drawing.Point(7, 40); this.xmlViewerFetchCDSCombo.Margin = new System.Windows.Forms.Padding(2); this.xmlViewerFetchCDSCombo.MaxLength = 2147483647; this.xmlViewerFetchCDSCombo.Multiline = true; this.xmlViewerFetchCDSCombo.Name = "xmlViewerFetchCDSCombo"; this.xmlViewerFetchCDSCombo.ReadOnly = false; this.xmlViewerFetchCDSCombo.RightMargin = 0; this.xmlViewerFetchCDSCombo.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.Both; xmlViewerSettings5.AttributeKey = System.Drawing.Color.Blue; xmlViewerSettings5.AttributeValue = System.Drawing.Color.DarkRed; xmlViewerSettings5.Comment = System.Drawing.Color.Gray; xmlViewerSettings5.Element = System.Drawing.Color.DarkGreen; xmlViewerSettings5.FontName = "Consolas"; xmlViewerSettings5.FontSize = 9F; xmlViewerSettings5.QuoteCharacter = '\"'; xmlViewerSettings5.Tag = System.Drawing.Color.ForestGreen; xmlViewerSettings5.Value = System.Drawing.Color.Black; this.xmlViewerFetchCDSCombo.Settings = xmlViewerSettings5; this.xmlViewerFetchCDSCombo.ShortcutsEnabled = true; this.xmlViewerFetchCDSCombo.ShowSelectionMargin = false; this.xmlViewerFetchCDSCombo.Size = new System.Drawing.Size(441, 511); this.xmlViewerFetchCDSCombo.TabIndex = 10; this.xmlViewerFetchCDSCombo.WordWrap = true; this.xmlViewerFetchCDSCombo.ZoomFactor = 1F; // // textBoxCDSComboProgress // this.textBoxCDSComboProgress.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxCDSComboProgress.Location = new System.Drawing.Point(454, 8); this.textBoxCDSComboProgress.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.textBoxCDSComboProgress.Multiline = true; this.textBoxCDSComboProgress.Name = "textBoxCDSComboProgress"; this.textBoxCDSComboProgress.ReadOnly = true; this.tableLayoutPanel6.SetRowSpan(this.textBoxCDSComboProgress, 2); this.textBoxCDSComboProgress.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBoxCDSComboProgress.Size = new System.Drawing.Size(438, 542); this.textBoxCDSComboProgress.TabIndex = 8; // // panelCDSComboRetrieve // this.panelCDSComboRetrieve.Controls.Add(this.cdsDataComboRetrieve); this.panelCDSComboRetrieve.Controls.Add(this.buttonCDSComboRetrieve); this.panelCDSComboRetrieve.Location = new System.Drawing.Point(7, 7); this.panelCDSComboRetrieve.Margin = new System.Windows.Forms.Padding(2); this.panelCDSComboRetrieve.Name = "panelCDSComboRetrieve"; this.panelCDSComboRetrieve.Size = new System.Drawing.Size(441, 29); this.panelCDSComboRetrieve.TabIndex = 12; // // cdsDataComboRetrieve // this.cdsDataComboRetrieve.DisplayFormat = ""; this.cdsDataComboRetrieve.FormattingEnabled = true; this.cdsDataComboRetrieve.Location = new System.Drawing.Point(3, 3); this.cdsDataComboRetrieve.Margin = new System.Windows.Forms.Padding(3, 3, 7, 3); this.cdsDataComboRetrieve.Name = "cdsDataComboRetrieve"; this.cdsDataComboRetrieve.OrganizationService = null; this.cdsDataComboRetrieve.Size = new System.Drawing.Size(356, 21); this.cdsDataComboRetrieve.TabIndex = 0; // // buttonCDSComboRetrieve // this.buttonCDSComboRetrieve.Location = new System.Drawing.Point(368, 2); this.buttonCDSComboRetrieve.Margin = new System.Windows.Forms.Padding(2); this.buttonCDSComboRetrieve.Name = "buttonCDSComboRetrieve"; this.buttonCDSComboRetrieve.Size = new System.Drawing.Size(70, 21); this.buttonCDSComboRetrieve.TabIndex = 10; this.buttonCDSComboRetrieve.Text = "Retireve!"; this.buttonCDSComboRetrieve.UseVisualStyleBackColor = true; this.buttonCDSComboRetrieve.Click += new System.EventHandler(this.buttonCDSComboRetrieve_Click); // // cdsLookupDialog1 // this.cdsLookupDialog1.Entity = null; this.cdsLookupDialog1.LogicalNames = new string[] { "account", "contact", "hej", "hopp"}; this.cdsLookupDialog1.Multiselect = false; this.cdsLookupDialog1.Service = null; // // openFileDialog1 // this.openFileDialog1.FileName = "openFileDialog1"; // // ControlTesterPluginControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tabControlMain); this.Controls.Add(this.toolStripMenu); this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3); this.Name = "ControlTesterPluginControl"; this.Size = new System.Drawing.Size(915, 627); this.Load += new System.EventHandler(this.MyPluginControl_Load); this.toolStripMenu.ResumeLayout(false); this.toolStripMenu.PerformLayout(); this.tabControlMain.ResumeLayout(false); this.tabPageEntList.ResumeLayout(false); this.splitterEntityList.Panel1.ResumeLayout(false); this.splitterEntityList.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterEntityList)).EndInit(); this.splitterEntityList.ResumeLayout(false); this.tableEntListDetails.ResumeLayout(false); this.tableEntListDetails.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.tabPageEntListViewBase.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.flowLayoutPanelToolbar.ResumeLayout(false); this.flowLayoutPanelToolbar.PerformLayout(); this.tableLayoutPanel5.ResumeLayout(false); this.tableLayoutPanel5.PerformLayout(); this.panel10.ResumeLayout(false); this.panel10.PerformLayout(); this.tabPageEntDropdown.ResumeLayout(false); this.splitterEntDropdown.Panel1.ResumeLayout(false); this.splitterEntDropdown.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterEntDropdown)).EndInit(); this.splitterEntDropdown.ResumeLayout(false); this.tableEntDropdown.ResumeLayout(false); this.tableEntDropdownDetail.ResumeLayout(false); this.tableEntDropdownDetail.PerformLayout(); this.panel3.ResumeLayout(false); this.tabPageAttrList.ResumeLayout(false); this.splitterAttribList.Panel1.ResumeLayout(false); this.splitterAttribList.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterAttribList)).EndInit(); this.splitterAttribList.ResumeLayout(false); this.tableAttribList.ResumeLayout(false); this.tableAttribListDetail.ResumeLayout(false); this.tableAttribListDetail.PerformLayout(); this.panel5.ResumeLayout(false); this.panel5.PerformLayout(); this.tabPageAttrDropDown.ResumeLayout(false); this.splitterAttribDropdown.Panel1.ResumeLayout(false); this.splitterAttribDropdown.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterAttribDropdown)).EndInit(); this.splitterAttribDropdown.ResumeLayout(false); this.tableAttribDropdown.ResumeLayout(false); this.panelAttrDropdown.ResumeLayout(false); this.tableAttribDropdownDetail.ResumeLayout(false); this.tableAttribDropdownDetail.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.tabPageSolution.ResumeLayout(false); this.splitterSolnDropdown.Panel1.ResumeLayout(false); this.splitterSolnDropdown.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterSolnDropdown)).EndInit(); this.splitterSolnDropdown.ResumeLayout(false); this.tableSolnDropdown.ResumeLayout(false); this.tableSolnDropdownDetail.ResumeLayout(false); this.tableSolnDropdownDetail.PerformLayout(); this.panel4.ResumeLayout(false); this.panel4.PerformLayout(); this.tabPageViewsDropdown.ResumeLayout(false); this.splitterViewDropdown.Panel1.ResumeLayout(false); this.splitterViewDropdown.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterViewDropdown)).EndInit(); this.splitterViewDropdown.ResumeLayout(false); this.tableViewDropdown.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.panel6.ResumeLayout(false); this.panel6.PerformLayout(); this.tabPageGlobalOptSets.ResumeLayout(false); this.splitterGlobalOptsList.Panel1.ResumeLayout(false); this.splitterGlobalOptsList.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterGlobalOptsList)).EndInit(); this.splitterGlobalOptsList.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.panel7.ResumeLayout(false); this.panel7.PerformLayout(); this.tabPageCRMGridView.ResumeLayout(false); this.splitterCRMGridView.Panel1.ResumeLayout(false); this.splitterCRMGridView.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterCRMGridView)).EndInit(); this.splitterCRMGridView.ResumeLayout(false); this.tableCRMGridView.ResumeLayout(false); this.panelCrmGridViewControls.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CrmGridView)).EndInit(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); this.panel8.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.panel12.ResumeLayout(false); this.panel12.PerformLayout(); this.panel11.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CrmGridViewDesignedCols)).EndInit(); this.tabPageXrmViewer.ResumeLayout(false); this.TableXmlViewers.ResumeLayout(false); this.TableXmlViewers.PerformLayout(); this.splitterXmlViewerControl.Panel1.ResumeLayout(false); this.splitterXmlViewerControl.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterXmlViewerControl)).EndInit(); this.splitterXmlViewerControl.ResumeLayout(false); this.splitterXmlViewer.Panel1.ResumeLayout(false); this.splitterXmlViewer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterXmlViewer)).EndInit(); this.splitterXmlViewer.ResumeLayout(false); this.tabPageBoundListIVew.ResumeLayout(false); this.splitterBoundListView.Panel1.ResumeLayout(false); this.splitterBoundListView.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitterBoundListView)).EndInit(); this.splitterBoundListView.ResumeLayout(false); this.flowLayoutPanel2.ResumeLayout(false); this.flowLayoutPanel2.PerformLayout(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); this.panel9.ResumeLayout(false); this.panel9.PerformLayout(); this.tabPageCDSDataComboBox.ResumeLayout(false); this.tableLayoutPanel6.ResumeLayout(false); this.tableLayoutPanel6.PerformLayout(); this.panelCDSComboRetrieve.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStripMenu; private System.Windows.Forms.ToolStripButton tsbClose; private System.Windows.Forms.ToolStripSeparator tssSeparator1; private System.Windows.Forms.TabControl tabControlMain; private System.Windows.Forms.TabPage tabPageEntList; private System.Windows.Forms.SplitContainer splitterEntityList; private System.Windows.Forms.SplitContainer splitterEntDropdown; private System.Windows.Forms.TabPage tabPageEntDropdown; private System.Windows.Forms.TabPage tabPageAttrDropDown; private System.Windows.Forms.TabPage tabPageSolution; private System.Windows.Forms.SplitContainer splitterAttribDropdown; private xrmtb.XrmToolBox.Controls.EntitiesListControl EntityListControl; private System.Windows.Forms.TableLayoutPanel tableEntListDetails; private System.Windows.Forms.PropertyGrid propGridEntList; private System.Windows.Forms.RadioButton radioEntListShowProps; private System.Windows.Forms.RadioButton radioEntListShowEnt; private System.Windows.Forms.TextBox textEntListLog; private System.Windows.Forms.TableLayoutPanel tableEntDropdown; private xrmtb.XrmToolBox.Controls.EntitiesDropdownControl EntityDropdown; private System.Windows.Forms.Label labelEntityDropdown; private System.Windows.Forms.TableLayoutPanel tableEntDropdownDetail; private System.Windows.Forms.PropertyGrid propGridEntDropdown; private System.Windows.Forms.Label label3; private System.Windows.Forms.RadioButton radioEntDropdownShowProps; private System.Windows.Forms.RadioButton radioEntDropdownShowEnt; private System.Windows.Forms.TextBox textEntDropdownLog; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.TableLayoutPanel tableAttribDropdown; private System.Windows.Forms.Label labelAttributes; private xrmtb.XrmToolBox.Controls.EntitiesDropdownControl EntityDropdownAttribs; private System.Windows.Forms.Label label4; private System.Windows.Forms.TableLayoutPanel tableAttribDropdownDetail; private System.Windows.Forms.PropertyGrid propGridAttribDropdown; private System.Windows.Forms.TextBox textAttribDropdownLog; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.RadioButton radioAttribDropdownShowProps; private System.Windows.Forms.Label label5; private System.Windows.Forms.RadioButton radioAttribDropdownShowAttrib; private System.Windows.Forms.SplitContainer splitterSolnDropdown; private System.Windows.Forms.TableLayoutPanel tableSolnDropdown; private System.Windows.Forms.Label label2; private System.Windows.Forms.TableLayoutPanel tableSolnDropdownDetail; private System.Windows.Forms.PropertyGrid propGridSolutions; private System.Windows.Forms.TextBox textSolnDropdownLog; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.RadioButton radioSolnDropdownShowProps; private System.Windows.Forms.Label label8; private System.Windows.Forms.RadioButton radioSolnDropdownShowSoln; private xrmtb.XrmToolBox.Controls.SolutionsDropdownControl SolutionDropdown; private System.Windows.Forms.ListBox listBoxSolutions; private System.Windows.Forms.Label label7; private System.Windows.Forms.ListBox listBoxEntities; private System.Windows.Forms.ListBox listBoxAttributes; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label9; private System.Windows.Forms.TabPage tabPageAttrList; private System.Windows.Forms.SplitContainer splitterAttribList; private System.Windows.Forms.TableLayoutPanel tableAttribList; private System.Windows.Forms.Label label10; private xrmtb.XrmToolBox.Controls.EntitiesDropdownControl EntityDropdownAttribList; private System.Windows.Forms.Label label11; private System.Windows.Forms.TableLayoutPanel tableAttribListDetail; private System.Windows.Forms.PropertyGrid propGridAttrList; private System.Windows.Forms.TextBox textAttribListLog; private System.Windows.Forms.Panel panel5; private System.Windows.Forms.RadioButton radioAttribListShowProps; private System.Windows.Forms.Label label13; private System.Windows.Forms.RadioButton radioAttribListShowAttrib; private xrmtb.XrmToolBox.Controls.AttributeListControl AttribListControl; private System.Windows.Forms.ToolStripDropDownButton toolStripDropDownButton1; private System.Windows.Forms.ToolStripMenuItem toolButton_LoadData; private System.Windows.Forms.ToolStripMenuItem toolButton_ClearData; private System.Windows.Forms.ToolStripMenuItem toolButton_UpdateConnection; private System.Windows.Forms.ToolStripMenuItem toolButton_Close; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripLabel toolStripLabelFilter; private System.Windows.Forms.ToolStripTextBox toolStripTextFilter; private System.Windows.Forms.TabPage tabPageViewsDropdown; private System.Windows.Forms.SplitContainer splitterViewDropdown; private System.Windows.Forms.TableLayoutPanel tableViewDropdown; private System.Windows.Forms.Label label12; private xrmtb.XrmToolBox.Controls.EntitiesDropdownControl EntityDropdownViews; private System.Windows.Forms.Label label14; private System.Windows.Forms.ListBox listBoxViews; private System.Windows.Forms.Label label15; private xrmtb.XrmToolBox.Controls.ViewsDropdownControl ViewDropdown; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.PropertyGrid propGridViewDropdown; private System.Windows.Forms.TextBox textViewsDropdownLog; private System.Windows.Forms.Panel panel6; private System.Windows.Forms.RadioButton radioViewDropdownShowProps; private System.Windows.Forms.Label label16; private System.Windows.Forms.RadioButton radioAttribDropdownShowView; private System.Windows.Forms.TabPage tabPageGlobalOptSets; private System.Windows.Forms.SplitContainer splitterGlobalOptsList; private xrmtb.XrmToolBox.Controls.GlobalOptionSetListControl GlobalOptionSetList; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Panel panel7; private System.Windows.Forms.RadioButton radioGlobalOptsListShowProps; private System.Windows.Forms.Label label17; private System.Windows.Forms.RadioButton radioEntDropdownShowOptionSet; private System.Windows.Forms.PropertyGrid propGridGlobalOptsList; private System.Windows.Forms.TextBox textGlobalOptsListLog; private System.Windows.Forms.TabPage tabPageCRMGridView; private System.Windows.Forms.SplitContainer splitterCRMGridView; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.Panel panel8; private System.Windows.Forms.RadioButton radioCRMGridViewShowProps; private System.Windows.Forms.Label label18; private System.Windows.Forms.RadioButton radioCRMGridViewSelEntity; private System.Windows.Forms.PropertyGrid propCRMGridView; private System.Windows.Forms.TableLayoutPanel tableCRMGridView; private System.Windows.Forms.Label labelExecFetch; private xrmtb.XrmToolBox.Controls.CRMGridView CrmGridView; private System.Windows.Forms.TabPage tabPageXrmViewer; private xrmtb.XrmToolBox.Controls.XmlViewerControl XmlViewerControl; private System.Windows.Forms.SplitContainer splitterXmlViewerControl; private System.Windows.Forms.PropertyGrid propGridXmlViewerControl; private System.Windows.Forms.TableLayoutPanel TableXmlViewers; private System.Windows.Forms.SplitContainer splitterXmlViewer; private xrmtb.XrmToolBox.Controls.XMLViewer XmlViewer; private System.Windows.Forms.PropertyGrid propGridXmlViewer; private System.Windows.Forms.Label labelXmlViewerControlTitle; private System.Windows.Forms.Label labelXmlViewerTitle; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button buttonExecFetch; private xrmtb.XrmToolBox.Controls.XMLViewer XmlViewerCRMDataGrid; private Subro.Controls.DataGridViewGrouperControl dataGridViewGrouperControl1; private System.Windows.Forms.Panel panelCrmGridViewControls; private System.Windows.Forms.TabPage tabPageBoundListIVew; private System.Windows.Forms.SplitContainer splitterBoundListView; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.Panel panel9; private System.Windows.Forms.RadioButton radioBoundListShowProps; private System.Windows.Forms.Label label19; private System.Windows.Forms.RadioButton radioEntListShowObj; private System.Windows.Forms.PropertyGrid propGridBoundListView; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TabPage tabPageEntListViewBase; private System.Windows.Forms.SplitContainer splitContainer1; private xrmtb.XrmToolBox.Controls.EntityListViewBaseControl EntityListViewBase; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private System.Windows.Forms.Panel panel10; private System.Windows.Forms.RadioButton radioEntLVBaseShowProps; private System.Windows.Forms.Label label20; private System.Windows.Forms.RadioButton radioButton2; private System.Windows.Forms.PropertyGrid propGridEntLVBase; private System.Windows.Forms.TextBox textBox2; protected System.Windows.Forms.FlowLayoutPanel flowLayoutPanelToolbar; protected System.Windows.Forms.Button buttonLoadItems; protected System.Windows.Forms.CheckBox checkBoxCheckAllNone; protected System.Windows.Forms.Label labelFilter; protected System.Windows.Forms.TextBox textFilterList; protected System.Windows.Forms.Button buttonClearFilter; private xrmtb.XrmToolBox.Controls.EntitiesCollectionListView listViewEntCollection; private System.Windows.Forms.Panel panelAttrDropdown; private xrmtb.XrmToolBox.Controls.AttributeDropdownBaseControl AttributeDropdownBase; private System.Windows.Forms.Button buttonReload; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox textCdsDataComboBoxFormat; private System.Windows.Forms.Label label21; private xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox cdsDataComboBox; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel2; private System.Windows.Forms.Label labelExecFetchBoundList; private System.Windows.Forms.Button buttonExecFetchBoundList; private xrmtb.XrmToolBox.Controls.XMLViewer xmlViewerEntColl; private System.Windows.Forms.Splitter splitterEntList; private System.Windows.Forms.TabPage tabPageCDSDataComboBox; private System.Windows.Forms.TextBox textBoxCDSComboProgress; private xrmtb.XrmToolBox.Controls.Controls.CDSDataComboBox cdsDataComboRetrieve; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel6; private xrmtb.XrmToolBox.Controls.XmlViewerControl xmlViewerFetchCDSCombo; private System.Windows.Forms.Button buttonCDSComboRetrieve; private System.Windows.Forms.FlowLayoutPanel panelCDSComboRetrieve; private System.Windows.Forms.Panel panel11; private xrmtb.XrmToolBox.Controls.CRMGridView CrmGridViewDesignedCols; private System.Windows.Forms.DataGridViewTextBoxColumn name; private System.Windows.Forms.DataGridViewTextBoxColumn revenue; private System.Windows.Forms.Button buttonExecPredefinedCrmGridViewQuery; private System.Windows.Forms.RadioButton radioCRMGridViewRightShowProps; private System.Windows.Forms.Label label23; private xrmtb.XrmToolBox.Controls.Controls.CDSDataTextBox cdsDataTextBox; private System.Windows.Forms.Label label22; private System.Windows.Forms.Panel panel12; private System.Windows.Forms.RadioButton radioCRMGridViewTxtBx; private System.Windows.Forms.RadioButton radioCRMGridViewCmbBx; private xrmtb.XrmToolBox.Controls.Controls.CDSLookupDialog cdsLookupDialog1; private System.Windows.Forms.Button button1; private System.Windows.Forms.RadioButton radioCRMGridViewLkpDlg; private System.Windows.Forms.OpenFileDialog openFileDialog1; } }
63.271441
186
0.669024
[ "MIT" ]
jamesnovak/xrmtb.XrmToolBox.Controls
XrmToolBox.Controls.TestPlugin/ControlTesterPluginControl.designer.cs
210,264
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using Agent.Sdk; using Microsoft.TeamFoundation.DistributedTask.Pipelines; using Microsoft.VisualStudio.Services.Agent.Util; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Util { public sealed class RepositoryUtilL0 { [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void TrimStandardBranchPrefix_should_return_correct_values() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Equal(null, RepositoryUtil.TrimStandardBranchPrefix(null)); Assert.Equal("", RepositoryUtil.TrimStandardBranchPrefix("")); Assert.Equal("refs/branchName", RepositoryUtil.TrimStandardBranchPrefix("refs/branchName")); Assert.Equal("branchName", RepositoryUtil.TrimStandardBranchPrefix("refs/heads/branchName")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void HasMultipleCheckouts_should_not_throw() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(null)); var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict.Add("x", "y"); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict.Add(WellKnownJobSettings.HasMultipleCheckouts, "burger"); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void HasMultipleCheckouts_should_return_true_when_set_correctly() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(null)); var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); dict[WellKnownJobSettings.HasMultipleCheckouts] = "true"; Assert.Equal(true, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "TRUE"; Assert.Equal(true, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "True"; Assert.Equal(true, RepositoryUtil.HasMultipleCheckouts(dict)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void HasMultipleCheckouts_should_return_false_when_not_set_correctly() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(null)); var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); dict[WellKnownJobSettings.HasMultipleCheckouts] = "!true"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "false"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "FALSE"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "False"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "0"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); dict[WellKnownJobSettings.HasMultipleCheckouts] = "1"; Assert.Equal(false, RepositoryUtil.HasMultipleCheckouts(dict)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void IsPrimaryRepositoryName_should_work_correctly() { using (TestHostContext hc = new TestHostContext(this)) { Assert.Equal(false, RepositoryUtil.IsPrimaryRepositoryName(null)); Assert.Equal(false, RepositoryUtil.IsPrimaryRepositoryName("")); Assert.Equal(false, RepositoryUtil.IsPrimaryRepositoryName("none")); Assert.Equal(false, RepositoryUtil.IsPrimaryRepositoryName("some random string")); Assert.Equal(true, RepositoryUtil.IsPrimaryRepositoryName("self")); Assert.Equal(true, RepositoryUtil.IsPrimaryRepositoryName("SELF")); Assert.Equal(true, RepositoryUtil.IsPrimaryRepositoryName("Self")); Assert.Equal(true, RepositoryUtil.IsPrimaryRepositoryName("sELF")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetPrimaryRepository_should_return_correct_value_when_called() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); var repo1 = new RepositoryResource { Alias = "repo1", Id = "repo1", Type = "git", }; var repo2 = new RepositoryResource { Alias = "repo2", Id = "repo2", Type = "git", }; var repoSelf = new RepositoryResource { Alias = "self", Id = "repo3", Type = "git", }; // No properties set Assert.Equal(null, RepositoryUtil.GetPrimaryRepository(null)); Assert.Equal(repo1, RepositoryUtil.GetPrimaryRepository(new[] { repo1 })); Assert.Equal(repo2, RepositoryUtil.GetPrimaryRepository(new[] { repo2 })); Assert.Equal(repoSelf, RepositoryUtil.GetPrimaryRepository(new[] { repoSelf })); Assert.Equal(null, RepositoryUtil.GetPrimaryRepository(new[] { repo1, repo2 })); Assert.Equal(repoSelf, RepositoryUtil.GetPrimaryRepository(new[] { repoSelf, repo1, repo2 })); Assert.Equal(repoSelf, RepositoryUtil.GetPrimaryRepository(new[] { repo1, repoSelf, repo2 })); Assert.Equal(repoSelf, RepositoryUtil.GetPrimaryRepository(new[] { repo1, repo2, repoSelf })); // With IsPrimaryRepository set repo2.Properties.Set(RepositoryUtil.IsPrimaryRepository, Boolean.TrueString); Assert.Equal(repo2, RepositoryUtil.GetPrimaryRepository(new[] { repo1, repo2, repoSelf })); repo2.Properties.Set(RepositoryUtil.IsPrimaryRepository, Boolean.FalseString); Assert.Equal(repoSelf, RepositoryUtil.GetPrimaryRepository(new[] { repo1, repo2, repoSelf })); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetRepositoryForLocalPath_should_return_correct_values() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); var repo1 = new RepositoryResource { Alias = "repo1", Id = "repo1", Type = "git", }; repo1.Properties.Set(RepositoryPropertyNames.Path, Path.Combine("root", "1", "s", "repo1")); var repo2 = new RepositoryResource { Alias = "repo2", Id = "repo2", Type = "git", }; repo2.Properties.Set(RepositoryPropertyNames.Path, Path.Combine("root", "1", "s", "repo2")); var repo3 = new RepositoryResource { Alias = "repo3", Id = "repo3", Type = "git", }; // repo3 has no path // Make sure null is returned if nothing matches or inputs are invalid Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(null, null)); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(null, Path.Combine("root", "1", "s", "not_a_repo"))); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, null)); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, "not a path")); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "not_a_repo"))); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s"))); Assert.Equal(null, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "repo3"))); // Make sure the first repo is returned if there is only one Assert.Equal(repo1, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1 }, Path.Combine("root", "1", "s", "not_a_repo"))); Assert.Equal(repo2, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo2 }, "not a path")); Assert.Equal(repo3, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo3 }, "not a path")); // Make sure the matching repo is returned if there is more than one Assert.Equal(repo1, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "repo1"))); Assert.Equal(repo1, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "repo1", "sub", "path", "file.txt"))); Assert.Equal(repo2, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "repo2"))); Assert.Equal(repo2, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo1, repo2, repo3 }, Path.Combine("root", "1", "s", "repo2", "sub", "path", "file.txt"))); Assert.Equal(repo2, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo3, repo1, repo2 }, Path.Combine("root", "1", "s", "repo2"))); Assert.Equal(repo2, RepositoryUtil.GetRepositoryForLocalPath(new[] { repo3, repo1, repo2 }, Path.Combine("root", "1", "s", "repo2", "sub", "path", "file.txt"))); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetRepository_should_return_correct_value_when_called() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); var repo1 = new RepositoryResource { Alias = "repo1", Id = "repo1", Type = "git", }; var repo2 = new RepositoryResource { Alias = "repo2", Id = "repo2", Type = "git", }; var repoSelf = new RepositoryResource { Alias = "self", Id = "repo3", Type = "git", }; Assert.Equal(null, RepositoryUtil.GetRepository(null, null)); Assert.Equal(null, RepositoryUtil.GetRepository(null, "repo1")); Assert.Equal(null, RepositoryUtil.GetRepository(new[] { repoSelf, repo1, repo2 }, null)); Assert.Equal(null, RepositoryUtil.GetRepository(new[] { repoSelf, repo1, repo2 }, "unknown")); Assert.Equal(repo1, RepositoryUtil.GetRepository(new[] { repo1, repo2 }, "repo1")); Assert.Equal(repo2, RepositoryUtil.GetRepository(new[] { repo1, repo2 }, "repo2")); Assert.Equal(repo1, RepositoryUtil.GetRepository(new[] { repoSelf, repo1, repo2 }, "repo1")); Assert.Equal(repo2, RepositoryUtil.GetRepository(new[] { repoSelf, repo1, repo2 }, "repo2")); Assert.Equal(repoSelf, RepositoryUtil.GetRepository(new[] { repoSelf, repo1, repo2 }, "self")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GuessRepositoryType_should_return_correct_values_when_called() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType(null)); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("garbage")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("github")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("azuredevops")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("https://githubenterprise.com/microsoft/somerepo.git")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("https://almost.visual.studio.com/microsoft/somerepo.git")); Assert.Equal(string.Empty, RepositoryUtil.GuessRepositoryType("https://almost.dev2.azure.com/microsoft/somerepo.git")); Assert.Equal(RepositoryTypes.GitHub, RepositoryUtil.GuessRepositoryType("https://github.com/microsoft/somerepo.git")); Assert.Equal(RepositoryTypes.Git, RepositoryUtil.GuessRepositoryType("https://user1@dev.azure.com/org/project/_git/reponame")); Assert.Equal(RepositoryTypes.Git, RepositoryUtil.GuessRepositoryType("https://user1@myorg.visualstudio.com/project/_git/reponame")); Assert.Equal(RepositoryTypes.Tfvc, RepositoryUtil.GuessRepositoryType("https://user1@myorg.visualstudio.com/project")); Assert.Equal(RepositoryTypes.Tfvc, RepositoryUtil.GuessRepositoryType("https://user1@dev.azure.com/org/project")); Assert.Equal(RepositoryTypes.Bitbucket, RepositoryUtil.GuessRepositoryType("https://user1@bitbucket.org/user1/mybucket.git")); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetCloneDirectory_REPO_should_throw_on_null() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Throws<ArgumentNullException>(() => RepositoryUtil.GetCloneDirectory((RepositoryResource)null)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetCloneDirectory_REPO_should_return_proper_value_when_called() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); var repo = new RepositoryResource() { Alias = "alias", Id = "repo1", Type = "git", Url = null, }; // If name is not set and url is not set, then it should use alias Assert.Equal("alias", RepositoryUtil.GetCloneDirectory(repo)); // If url is set, it should choose url over alias repo.Url = new Uri("https://jpricket@codedev.ms/jpricket/MyFirstProject/_git/repo1_url"); Assert.Equal("repo1_url", RepositoryUtil.GetCloneDirectory(repo)); // If name is set, it should choose name over alias or url repo.Properties.Set(RepositoryPropertyNames.Name, "MyFirstProject/repo1_name"); Assert.Equal("repo1_name", RepositoryUtil.GetCloneDirectory(repo)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetCloneDirectory_STRING_should_throw_on_null() { using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); Assert.Throws<ArgumentNullException>(() => RepositoryUtil.GetCloneDirectory((string)null)); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Common")] public void GetCloneDirectory_STRING_should_return_proper_value_when_called() { // These test cases were inspired by the test cases that git.exe uses // see https://github.com/git/git/blob/53f9a3e157dbbc901a02ac2c73346d375e24978c/t/t5603-clone-dirname.sh#L21 using (TestHostContext hc = new TestHostContext(this)) { Tracing trace = hc.GetTrace(); // basic syntax with bare and non-bare variants Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo.git")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo/.git")); // similar, but using ssh URL rather than host:path syntax Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo.git")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo/.git")); // we should remove trailing slashes and .git suffixes Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo/.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo.git///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo///.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("ssh://host/foo/.git///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo/.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo.git///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo///.git/")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo/.git///")); Assert.Equal("foo", RepositoryUtil.GetCloneDirectory("host:foo/.git///")); Assert.Equal("repo", RepositoryUtil.GetCloneDirectory("host:foo/repo")); // omitting the path should default to the hostname Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://host/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://host:1234/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://user@host/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("host:/")); // auth materials should be redacted Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://user:password@host/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://user:password@host:1234/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("ssh://user:passw@rd@host:1234/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("user@host:/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("user:password@host:/")); Assert.Equal("host", RepositoryUtil.GetCloneDirectory("user:passw@rd@host:/")); // trailing port-like numbers should not be stripped for paths Assert.Equal("1234", RepositoryUtil.GetCloneDirectory("ssh://user:password@host/test:1234")); Assert.Equal("1234", RepositoryUtil.GetCloneDirectory("ssh://user:password@host/test:1234.git")); } } } }
51.941176
177
0.588807
[ "MIT" ]
amjn/azure-pipelines-agent
src/Test/L0/Util/RepositoryUtilL0.cs
21,192
C#
using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreExampleTests.IntegrationTests.HostingInIIS { public sealed class HostingTests : IClassFixture<ExampleIntegrationTestContext<HostingStartup<HostingDbContext>, HostingDbContext>> { private const string HostPrefix = "http://localhost"; private readonly ExampleIntegrationTestContext<HostingStartup<HostingDbContext>, HostingDbContext> _testContext; private readonly HostingFakers _fakers = new(); public HostingTests(ExampleIntegrationTestContext<HostingStartup<HostingDbContext>, HostingDbContext> testContext) { _testContext = testContext; testContext.UseController<PaintingsController>(); testContext.UseController<ArtGalleriesController>(); } [Fact] public async Task Get_primary_resources_with_include_returns_links() { // Arrange ArtGallery gallery = _fakers.ArtGallery.Generate(); gallery.Paintings = _fakers.Painting.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<ArtGallery>(); dbContext.ArtGalleries.Add(gallery); await dbContext.SaveChangesAsync(); }); const string route = "/iis-application-virtual-directory/public-api/artGalleries?include=paintings"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(HostPrefix + route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().Be(HostPrefix + route); responseDocument.Links.Last.Should().Be(HostPrefix + route); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string galleryLink = HostPrefix + $"/iis-application-virtual-directory/public-api/artGalleries/{gallery.StringId}"; responseDocument.ManyData.Should().HaveCount(1); responseDocument.ManyData[0].Links.Self.Should().Be(galleryLink); responseDocument.ManyData[0].Relationships["paintings"].Links.Self.Should().Be(galleryLink + "/relationships/paintings"); responseDocument.ManyData[0].Relationships["paintings"].Links.Related.Should().Be(galleryLink + "/paintings"); string paintingLink = HostPrefix + $"/iis-application-virtual-directory/custom/path/to/paintings-of-the-world/{gallery.Paintings.ElementAt(0).StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(paintingLink); responseDocument.Included[0].Relationships["exposedAt"].Links.Self.Should().Be(paintingLink + "/relationships/exposedAt"); responseDocument.Included[0].Relationships["exposedAt"].Links.Related.Should().Be(paintingLink + "/exposedAt"); } [Fact] public async Task Get_primary_resources_with_include_on_custom_route_returns_links() { // Arrange Painting painting = _fakers.Painting.Generate(); painting.ExposedAt = _fakers.ArtGallery.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Painting>(); dbContext.Paintings.Add(painting); await dbContext.SaveChangesAsync(); }); const string route = "/iis-application-virtual-directory/custom/path/to/paintings-of-the-world?include=exposedAt"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Links.Self.Should().Be(HostPrefix + route); responseDocument.Links.Related.Should().BeNull(); responseDocument.Links.First.Should().Be(HostPrefix + route); responseDocument.Links.Last.Should().Be(HostPrefix + route); responseDocument.Links.Prev.Should().BeNull(); responseDocument.Links.Next.Should().BeNull(); string paintingLink = HostPrefix + $"/iis-application-virtual-directory/custom/path/to/paintings-of-the-world/{painting.StringId}"; responseDocument.ManyData.Should().HaveCount(1); responseDocument.ManyData[0].Links.Self.Should().Be(paintingLink); responseDocument.ManyData[0].Relationships["exposedAt"].Links.Self.Should().Be(paintingLink + "/relationships/exposedAt"); responseDocument.ManyData[0].Relationships["exposedAt"].Links.Related.Should().Be(paintingLink + "/exposedAt"); string galleryLink = HostPrefix + $"/iis-application-virtual-directory/public-api/artGalleries/{painting.ExposedAt.StringId}"; responseDocument.Included.Should().HaveCount(1); responseDocument.Included[0].Links.Self.Should().Be(galleryLink); responseDocument.Included[0].Relationships["paintings"].Links.Self.Should().Be(galleryLink + "/relationships/paintings"); responseDocument.Included[0].Relationships["paintings"].Links.Related.Should().Be(galleryLink + "/paintings"); } } }
49.358974
143
0.679481
[ "MIT" ]
sgryphon/JsonApiDotNetCore
test/JsonApiDotNetCoreExampleTests/IntegrationTests/HostingInIIS/HostingTests.cs
5,775
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 04:45:17 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using @unsafe = go.@unsafe_package; #nullable enable namespace go { public static partial class reflect_package { [GeneratedCode("go2cs", "0.1.0.0")] private partial struct visit { // Constructors public visit(NilType _) { this.a1 = default; this.a2 = default; this.typ = default; } public visit(unsafe.Pointer a1 = default, unsafe.Pointer a2 = default, Type typ = default) { this.a1 = a1; this.a2 = a2; this.typ = typ; } // Enable comparisons between nil and visit struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(visit value, NilType nil) => value.Equals(default(visit)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(visit value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, visit value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, visit value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator visit(NilType nil) => default(visit); } [GeneratedCode("go2cs", "0.1.0.0")] private static visit visit_cast(dynamic value) { return new visit(value.a1, value.a2, value.typ); } } }
33.646154
102
0.568358
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/reflect/deepequal_visitStruct.cs
2,187
C#
using Settings; namespace Client.UI.ViewModel { public class UI_EditAvatar: UIBase<View_EditAvatar> { public string Url { get; private set; } private Data_GameRecord Record { get; set; } protected override void OnInit(IUIParams p) { base.OnInit(p); View.Confrim.onClick.Add(Confirm_OnClick); Record = DBManager.Inst.Query<Data_GameRecord>(); Url = Record.Head; var nodes = View.AvatarList.GetChildren(); for (int index = 0; index < nodes.Length; index++) { var node = nodes[index]; var button = node.asButton; if (button.icon == Record.Head) { View.AvatarList.selectedIndex = index; break; } } if (string.IsNullOrEmpty(Url)) { Url = "ui://Settings/0"; } } private void Confirm_OnClick() { Record.Head = View.AvatarList.GetChildAt(View.AvatarList.selectedIndex).asButton.icon; Url = Record.Head; DBManager.Inst.Update(Record); CloseMySelf(); } } }
29.595238
98
0.507643
[ "MIT" ]
Noname-Studio/ET
Unity/Assets/Scripts/Client/UI/ViewModel/UI_EditAvatar.cs
1,245
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.DotNet.Interactive.Commands; using Microsoft.DotNet.Interactive.Events; using Microsoft.DotNet.Interactive.Formatting; using Microsoft.DotNet.Interactive.PowerShell.Host; using Microsoft.DotNet.Interactive.ValueSharing; using Microsoft.PowerShell; using Microsoft.PowerShell.Commands; namespace Microsoft.DotNet.Interactive.PowerShell { using System.Management.Automation; using Microsoft.DotNet.Interactive.Utility; public class PowerShellKernel : Kernel, ISupportGetValue, ISupportSetClrValue, IKernelCommandHandler<RequestCompletions>, IKernelCommandHandler<RequestDiagnostics>, IKernelCommandHandler<SubmitCode> { private const string PSTelemetryEnvName = "POWERSHELL_DISTRIBUTION_CHANNEL"; private const string PSTelemetryChannel = "dotnet-interactive-powershell"; private const string PSModulePathEnvName = "PSModulePath"; internal const string DefaultKernelName = "pwsh"; private static readonly CmdletInfo _outDefaultCommand; private static readonly PropertyInfo _writeStreamProperty; private static readonly object _errorStreamValue; private static readonly MethodInfo _addAccelerator; private readonly PSKernelHost _psHost; private readonly Lazy<PowerShell> _lazyPwsh; private PowerShell pwsh => _lazyPwsh.Value; public Func<string, string> ReadInput { get; set; } public Func<string, PasswordString> ReadPassword { get; set; } internal AzShellConnectionUtils AzShell { get; set; } internal int DefaultRunspaceId => _lazyPwsh.IsValueCreated ? pwsh.Runspace.Id : -1; static PowerShellKernel() { // Prepare for marking PSObject as error with 'WriteStream'. _writeStreamProperty = typeof(PSObject).GetProperty("WriteStream", BindingFlags.Instance | BindingFlags.NonPublic); var writeStreamType = typeof(PSObject).Assembly.GetType("System.Management.Automation.WriteStreamType"); _errorStreamValue = Enum.Parse(writeStreamType, "Error"); // When the downstream cmdlet of a native executable is 'Out-Default', PowerShell assumes // it's running in the console where the 'Out-Default' would be added by default. Hence, // PowerShell won't redirect the standard output of the executable. // To workaround that, we rename 'Out-Default' to 'Out-Default2' to make sure the standard // output is captured. _outDefaultCommand = new CmdletInfo("Out-Default2", typeof(OutDefaultCommand)); // Get the AddAccelerator method var acceleratorType = typeof(PSObject).Assembly.GetType("System.Management.Automation.TypeAccelerators"); _addAccelerator = acceleratorType?.GetMethod("Add", new[] { typeof(string), typeof(Type) }); } public PowerShellKernel() : base(DefaultKernelName) { _psHost = new PSKernelHost(); _lazyPwsh = new Lazy<PowerShell>(CreatePowerShell); } private PowerShell CreatePowerShell() { // Set the distribution channel so telemetry can be distinguished in PS7+ telemetry Environment.SetEnvironmentVariable(PSTelemetryEnvName, PSTelemetryChannel); // Create PowerShell instance var iss = InitialSessionState.CreateDefault2(); if (Platform.IsWindows) { // This sets the execution policy on Windows to RemoteSigned. iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned; } // Set $PROFILE. var profileValue = DollarProfileHelper.GetProfileValue(); iss.Variables.Add(new SessionStateVariableEntry("PROFILE", profileValue, "The $PROFILE.")); var runspace = RunspaceFactory.CreateRunspace(_psHost, iss); runspace.Open(); var pwsh = PowerShell.Create(runspace); // Add Modules directory that contains the helper modules string psJupyterModulePath = Path.Join( Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location), "Modules"); AddModulePath(psJupyterModulePath); RegisterForDisposal(pwsh); return pwsh; } public void AddModulePath(string modulePath) { if (string.IsNullOrWhiteSpace(modulePath)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(modulePath)); } var psModulePath = Environment.GetEnvironmentVariable(PSModulePathEnvName); Environment.SetEnvironmentVariable( PSModulePathEnvName, $"{modulePath}{Path.PathSeparator}{psModulePath}"); } public void AddAccelerator(string name, Type type) { _addAccelerator?.Invoke(null, new object[] { name, type }); } public IReadOnlyCollection<KernelValueInfo> GetValueInfos() { var psObject = pwsh.Runspace.SessionStateProxy.InvokeProvider.Item.Get("variable:")?.FirstOrDefault(); if (psObject?.BaseObject is Dictionary<string, PSVariable>.ValueCollection valueCollection) { return valueCollection.Select(v => new KernelValueInfo( v.Name, v.Value?.GetType())).ToArray(); } return Array.Empty<KernelValueInfo>(); } public bool TryGetValue<T>(string name, out T value) { var variable = pwsh.Runspace.SessionStateProxy.PSVariable.Get(name); if (variable is not null) { object outVal = (variable.Value is PSObject psobject) ? psobject.Unwrap() : variable.Value; if (outVal is T tObj) { value = tObj; return true; } } value = default; return false; } public Task SetValueAsync(string name, object value, Type declaredType) { _lazyPwsh.Value.Runspace.SessionStateProxy.PSVariable.Set(name, value); return Task.CompletedTask; } public async Task HandleAsync( SubmitCode submitCode, KernelInvocationContext context) { // Acknowledge that we received the request. context.Publish(new CodeSubmissionReceived(submitCode)); var code = submitCode.Code; // Test is the code we got is actually able to run. if (IsCompleteSubmission(code, out ParseError[] parseErrors)) { context.Publish(new CompleteCodeSubmissionReceived(submitCode)); } else { context.Publish(new IncompleteCodeSubmissionReceived(submitCode)); } var formattedDiagnostics = parseErrors .Select(d => d.ToString()) .Select(text => new FormattedValue(PlainTextFormatter.MimeType, text)) .ToImmutableArray(); var diagnostics = parseErrors.Select(ToDiagnostic).ToImmutableArray(); context.Publish(new DiagnosticsProduced(diagnostics, submitCode, formattedDiagnostics)); // If there were parse errors, display them and return early. if (parseErrors.Length > 0) { var parseException = new ParseException(parseErrors); ReportError(parseException.ErrorRecord); return; } // Do nothing if we get a Diagnose type. if (submitCode.SubmissionType == SubmissionType.Diagnose) { return; } if (context.CancellationToken.IsCancellationRequested) { context.Fail(submitCode, null, "Command cancelled"); return; } if (AzShell is not null) { await RunSubmitCodeInAzShell(code); } else { RunSubmitCodeLocally(code); } } public Task HandleAsync( RequestCompletions requestCompletions, KernelInvocationContext context) { CompletionsProduced completion; if (AzShell is not null) { // Currently no tab completion when interacting with AzShell. completion = new CompletionsProduced(Array.Empty<CompletionItem>(), requestCompletions); } else { var results = CommandCompletion.CompleteInput( requestCompletions.Code, SourceUtilities.GetCursorOffsetFromPosition(requestCompletions.Code, requestCompletions.LinePosition), options: null, pwsh); var completionItems = results.CompletionMatches.Select( c => new CompletionItem( displayText: c.CompletionText, kind: c.ResultType.ToString(), documentation: c.ToolTip)); // The end index is the start index plus the length of the replacement. var endIndex = results.ReplacementIndex + results.ReplacementLength; completion = new CompletionsProduced( completionItems, requestCompletions, SourceUtilities.GetLinePositionSpanFromStartAndEndIndices(requestCompletions.Code, results.ReplacementIndex, endIndex)); } context.Publish(completion); return Task.CompletedTask; } public Task HandleAsync( RequestDiagnostics requestDiagnostics, KernelInvocationContext context) { var code = requestDiagnostics.Code; IsCompleteSubmission(code, out var parseErrors); var diagnostics = parseErrors.Select(ToDiagnostic); context.Publish(new DiagnosticsProduced(diagnostics, requestDiagnostics)); return Task.CompletedTask; } private async Task RunSubmitCodeInAzShell(string code) { code = code.Trim(); var shouldDispose = false; try { if (string.Equals(code, "exit", StringComparison.OrdinalIgnoreCase)) { await AzShell.ExitSession(); shouldDispose = true; } else { await AzShell.SendCommand(code); } } catch (IOException e) { ReportException(e); shouldDispose = true; } if (shouldDispose) { AzShell.Dispose(); AzShell = null; } } private void RunSubmitCodeLocally(string code) { try { pwsh.AddScript(code) .AddCommand(_outDefaultCommand) .Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); pwsh.InvokeAndClearCommands(); } catch (Exception e) { ReportException(e); } finally { ((PSKernelHostUserInterface)_psHost.UI).ResetProgress(); } } private static bool IsCompleteSubmission(string code, out ParseError[] errors) { // Parse the PowerShell script. If there are any parse errors, check if the input was incomplete. // We only need to check if the first ParseError has incomplete input. This is consistant with // what PowerShell itself does today. Parser.ParseInput(code, out _, out errors); return errors.Length == 0 || !errors[0].IncompleteInput; } private void ReportError(ErrorRecord error) { var psObject = PSObject.AsPSObject(error); _writeStreamProperty.SetValue(psObject, _errorStreamValue); pwsh.AddCommand(_outDefaultCommand) .AddParameter("InputObject", psObject) .InvokeAndClearCommands(); } private void ReportException(Exception e) { var error = e is IContainsErrorRecord icer ? icer.ErrorRecord : new ErrorRecord(e, "JupyterPSHost.ReportException", ErrorCategory.NotSpecified, targetObject: null); ReportError(error); } private static Diagnostic ToDiagnostic(ParseError parseError) { return new Diagnostic( new LinePositionSpan( new LinePosition(parseError.Extent.StartLineNumber - 1, parseError.Extent.StartColumnNumber), new LinePosition(parseError.Extent.EndLineNumber - 1, parseError.Extent.EndColumnNumber)), DiagnosticSeverity.Error, parseError.ErrorId, parseError.Message); } } }
37.277628
140
0.600145
[ "MIT" ]
tommymarto/interactive
src/Microsoft.DotNet.Interactive.PowerShell/PowerShellKernel.cs
13,832
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.ComponentModel.Composition.Factories; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Linq; using System.Reflection; using System.UnitTesting; using Xunit; namespace System.ComponentModel.Composition { public class ComposablePartExtensibilityTests { [Fact] public void PhaseTest() { CompositionContainer container = ContainerFactory.Create(); CompositionBatch batch = new CompositionBatch(); var part = new OrderingTestComposablePart(); part.AddImport("Import1", ImportCardinality.ExactlyOne, true, false); part.AddExport("Export1", 1); part.CallOrder.Enqueue("Import:Import1"); part.CallOrder.Enqueue("OnComposed"); batch.AddExportedValue("Import1", 20); batch.AddPart(part); container.Compose(batch); // Export shouldn't be called until it is pulled on by someone. var export = container.GetExport<object>("Export1"); part.CallOrder.Enqueue("Export:Export1"); Assert.Equal(1, export.Value); Assert.True(part.CallOrder.Count == 0); } [Fact] public void ImportTest() { var exporter = new TestExportBinder(); var importer = new TestImportBinder(); CompositionContainer container = ContainerFactory.Create(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(importer); batch.AddPart(exporter); container.Compose(batch); ExportsAssert.AreEqual(importer.SetImports["single"], 42); ExportsAssert.AreEqual(importer.SetImports["multi"], 1, 2, 3); } [Fact] public void ConstructorInjectionSimpleCase() { var container = ContainerFactory.Create(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new ConstructorInjectionComposablePart(typeof(Foo))); batch.AddExportedValue<IBar>(new Bar("Bar Value")); container.Compose(batch); var import = container.GetExport<Foo>(); var foo = import.Value; Assert.Equal("Bar Value", foo.Bar.Value); } [Fact] public void ConstructorInjectionCycle() { var container = ContainerFactory.Create(); CompositionBatch batch = new CompositionBatch(); batch.AddPart(new ConstructorInjectionComposablePart(typeof(AClass))); batch.AddPart(new ConstructorInjectionComposablePart(typeof(BClass))); CompositionAssert.ThrowsErrors( ErrorId.ImportEngine_PartCannotSetImport, ErrorId.ImportEngine_PartCannotSetImport, RetryMode.DoNotRetry, () => { container.Compose(batch); } ); } } internal class OrderingTestComposablePart : ConcreteComposablePart { public Queue<string> CallOrder = new Queue<string>(); public OrderingTestComposablePart() { } public new void AddExport(string contractName, object value) { var export = ExportFactory.Create( contractName, () => { this.OnGetExport(contractName); return value; } ); base.AddExport(export); } private void OnGetExport(string contractName) { Assert.Equal("Export:" + contractName, CallOrder.Dequeue()); } public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports) { ContractBasedImportDefinition contractBasedImportDefinition = (ContractBasedImportDefinition)definition; Assert.Equal( "Import:" + contractBasedImportDefinition.ContractName, CallOrder.Dequeue() ); base.SetImport(definition, exports); } public override void Activate() { Assert.Equal("OnComposed", CallOrder.Dequeue()); base.Activate(); } } internal class TestExportBinder : ConcreteComposablePart { public TestExportBinder() { AddExport("single", 42); AddExport("multi", 1); AddExport("multi", 2); AddExport("multi", 3); } } internal class TestImportBinder : ConcreteComposablePart { public TestImportBinder() { AddImport("single", ImportCardinality.ExactlyOne, true, false); AddImport("multi", ImportCardinality.ZeroOrMore, true, false); } } public class Foo { public Foo(IBar bar) { Bar = bar; } public IBar Bar { get; private set; } } public interface IBar { string Value { get; } } public class Bar : IBar { public Bar(string value) { Value = value; } public string Value { get; private set; } } public class FooBar { [Import("Foo")] public Foo Foo { get; set; } } public class AClass { public AClass(BClass b) { } public BClass B { get; private set; } } public class BClass { public BClass(AClass a) { this.A = a; } public AClass A { get; private set; } } internal class ConstructorInjectionComposablePart : ConcreteComposablePart { private Type _type; private ConstructorInfo _constructor; private Dictionary<ImportDefinition, object> _imports; public ConstructorInjectionComposablePart(Type type) { this._type = type; // Note that this just blindly takes the first constructor... this._constructor = this._type.GetConstructors().FirstOrDefault(); Assert.NotNull(this._constructor); foreach (var param in this._constructor.GetParameters()) { string name = AttributedModelServices.GetContractName(param.ParameterType); AddImport(name, ImportCardinality.ExactlyOne, true, true); } string contractName = AttributedModelServices.GetContractName(type); string typeIdentity = AttributedModelServices.GetTypeIdentity(type); var metadata = new Dictionary<string, object>(); metadata.Add(CompositionConstants.ExportTypeIdentityMetadataName, typeIdentity); Export composableExport = ExportFactory.Create(contractName, metadata, GetInstance); this.AddExport(composableExport); this._imports = new Dictionary<ImportDefinition, object>(); } private object GetInstance() { var result = CompositionResult.SucceededResult; // We only need this guard if we are pulling on the lazy exports during this call // but if we do the pulling in SetImport it isn't needed. //if (currentlyExecuting) //{ // var issue = CompositionError.Create("CM:CreationCycleDetected", // "This failed because there is a creation cycle"); // return result.MergeIssue(issue).ToResult<object>(null); //} try { List<object> constructorArgs = new List<object>(); foreach ( ImportDefinition import in this.ImportDefinitions.Where(i => i.IsPrerequisite) ) { object importValue; if (!this._imports.TryGetValue(import, out importValue)) { result = result.MergeError( CompositionError.Create( CompositionErrorId.ImportNotSetOnPart, "The import '{0}' is required for construction of '{1}'", import.ToString(), _type.FullName ) ); continue; } constructorArgs.Add(importValue); } if (!result.Succeeded) { throw new CompositionException(result.Errors); } object obj = this._constructor.Invoke(constructorArgs.ToArray()); return obj; } finally { } } public override void SetImport(ImportDefinition definition, IEnumerable<Export> exports) { _imports[definition] = exports.First().Value; } } }
31.193878
98
0.563188
[ "MIT" ]
belav/runtime
src/libraries/System.ComponentModel.Composition/tests/System/ComponentModel/Composition/ComposablePartExtensibilityTests.cs
9,171
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ClientCertificateTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ClientCertificateTests")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2f335ede-75fa-4c44-a6ea-f5aef31fe819")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.25
84
0.75236
[ "MIT" ]
davidsh/corefx-net-tls
ClientCertificateTests/ClientCertificateTests/Properties/AssemblyInfo.cs
1,380
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码已从模板生成手动更改此文件可能导致应用程序出现意外的行为。 // 如果重新生成代码,将覆盖对此文件的手动更改。 // author Taihe // </auto-generated> //------------------------------------------------------------------------------ using TaiheSystem.CBE.Api.Model; using TaiheSystem.CBE.Api.Model.Dto; using TaiheSystem.CBE.Api.Model.View; using System.Collections.Generic; using System.Threading.Tasks; using SqlSugar; using System.Linq; namespace TaiheSystem.CBE.Api.Interfaces { public class BaseFactoryService : BaseService<Base_Factory>, IBaseFactoryService { #region CustomInterface /// <summary> /// 查询工厂(分页) /// </summary> /// <param name="parm"></param> /// <param name="Async"></param> /// <returns></returns> public PagedInfo<FactoryVM> QueryFactoryPages(FactoryQueryDto parm) { var source = Db.Queryable<Base_Factory, Sys_DataRelation, Base_Company>((a, b, c) => new object[] { JoinType.Inner,a.ID == b.Form, JoinType.Inner,b.To == c.ID, }).WhereIF(!string.IsNullOrEmpty(parm.QueryText), (a, b, c) => a.FactoryName.Contains(parm.QueryText) || a.FactoryNo.Contains(parm.QueryText)) .Select((a, b, c) => new FactoryVM { ID = a.ID, FactoryNo = a.FactoryNo, FactoryName = a.FactoryName, Remark = a.Remark, Enable = a.Enable, CompanyUID = c.ID, CompanyNo = c.CompanyNo, CompanyName = c.CompanyName, CreateTime = a.CreateTime, UpdateTime = a.UpdateTime, CreateID = a.CreateID, CreateName = a.CreateName, UpdateID = a.UpdateID, UpdateName = a.UpdateName }) .MergeTable(); return source.ToPage(new PageParm { PageIndex = parm.PageIndex , PageSize = parm.PageSize, OrderBy = parm.OrderBy , Sort = parm.Sort}); } /// <summary> /// 根据ID查询工厂 /// </summary> /// <param name="id"></param> /// <param name="Async"></param> /// <returns></returns> public FactoryVM GetFactory(string id) { var source = Db.Queryable<Base_Factory, Sys_DataRelation, Base_Company>((a, b, c) => new object[] { JoinType.Inner,a.ID == b.Form, JoinType.Inner,b.To == c.ID, }).Where((a, b, c) => a.ID == id) .Select((a, b, c) => new FactoryVM { ID = a.ID, FactoryNo = a.FactoryNo, FactoryName = a.FactoryName, Remark = a.Remark, Enable = a.Enable, CompanyUID = c.ID, CompanyNo = c.CompanyNo, CompanyName = c.CompanyName, CreateTime = a.CreateTime, UpdateTime = a.UpdateTime, CreateID = a.CreateID, CreateName = a.CreateName, UpdateID = a.UpdateID, UpdateName = a.UpdateName }).MergeTable(); return source.First(); } /// <summary> /// 查询所有工厂 /// </summary> public List<FactoryVM> GetAllFactory(bool? enable = null) { var source = Db.Queryable<Base_Factory, Sys_DataRelation, Base_Company>((a, b, c) => new object[] { JoinType.Inner,a.ID == b.Form, JoinType.Inner,b.To == c.ID, }) .WhereIF(enable != null, (a, b, c) => a.Enable == enable) .Select((a, b, c) => new FactoryVM { ID = a.ID, FactoryNo = a.FactoryNo, FactoryName = a.FactoryName, Remark = a.Remark, Enable = a.Enable, CompanyUID = c.ID, CompanyNo = c.CompanyNo, CompanyName = c.CompanyName, CreateTime = a.CreateTime, UpdateTime = a.UpdateTime, CreateID = a.CreateID, CreateName = a.CreateName, UpdateID = a.UpdateID, UpdateName = a.UpdateName }).MergeTable().OrderBy(m => m.FactoryNo); return source.ToList(); } #endregion } }
36.235772
154
0.48665
[ "Apache-2.0" ]
AboutZld/Taihe.CBE.API
TaiheSystem.CBE.Api.Interfaces/Service/BaseFactoryService.cs
4,605
C#