content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; namespace WebApplication.Controls.ShoppingCart { public partial class AddToCartButton : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (!ShoppingCart.CurrentCart.CanRenderAddToCartButton(BasePage.CurrentMediaDetail)) AddToCartPanel.Visible = false; else AddToCartPanel.Visible = true; } protected void AddToCart_OnClick(object sender, EventArgs e) { if (BasePage.CurrentMediaDetail == null) return; BasePage.AddToCart(BasePage.CurrentMediaDetail); } public BasePage BasePage { get { return (BasePage)this.Page; } } } }
24.864865
96
0.566304
[ "Apache-2.0" ]
MacdonaldRobinson/FlexDotnetCMS
WebApplication/Controls/ShoppingCart/AddToCartButton.ascx.cs
922
C#
using EngineLayer; using IO.Mgf; using IO.MzML; using IO.ThermoRawFileReader; using MassSpectrometry; using mzPlot; using OxyPlot; using OxyPlot.Wpf; using Proteomics.Fragmentation; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; using System.Windows.Shapes; namespace GuiFunctions { public class MetaDrawLogic { public ObservableCollection<string> PsmResultFilePaths { get; private set; } public ObservableCollection<string> SpectraFilePaths { get; private set; } public ObservableCollection<string> SpectralLibraryPaths { get; private set; } public ObservableCollection<PsmFromTsv> FilteredListOfPsms { get; private set; } // filtered list of PSMs after q-value filter, etc. public Dictionary<string, ObservableCollection<PsmFromTsv>> PsmsGroupedByFile { get; private set; } public object ThreadLocker; public ICollectionView PeptideSpectralMatchesView; private List<PsmFromTsv> AllPsms; // all loaded PSMs private Dictionary<string, DynamicDataConnection> MsDataFiles; // key is file name without extension private List<PeptideSpectrumMatchPlot> CurrentlyDisplayedPlots; private Regex illegalInFileName = new Regex(@"[\\/:*?""<>|]"); private SpectralLibrary SpectralLibrary; public MetaDrawLogic() { PsmResultFilePaths = new ObservableCollection<string>(); SpectraFilePaths = new ObservableCollection<string>(); SpectralLibraryPaths = new ObservableCollection<string>(); FilteredListOfPsms = new ObservableCollection<PsmFromTsv>(); PsmsGroupedByFile = new Dictionary<string, ObservableCollection<PsmFromTsv>>(); AllPsms = new List<PsmFromTsv>(); MsDataFiles = new Dictionary<string, DynamicDataConnection>(); PeptideSpectralMatchesView = CollectionViewSource.GetDefaultView(FilteredListOfPsms); ThreadLocker = new object(); CurrentlyDisplayedPlots = new List<PeptideSpectrumMatchPlot>(); } public List<string> LoadFiles(bool loadSpectra, bool loadPsms) { List<string> errors = new List<string>(); lock (ThreadLocker) { FilteredListOfPsms.Clear(); PsmsGroupedByFile.Clear(); AllPsms.Clear(); MsDataFiles.Clear(); } // load MS data files if (loadSpectra) { LoadSpectraFiles(out var errors1); errors.AddRange(errors1); } // load PSMs if (loadPsms) { LoadPsms(out var errors2, loadSpectra); errors.AddRange(errors2); } // load spectral libraries LoadSpectralLibraries(out var errors3); errors.AddRange(errors3); return errors; } public void DisplaySpectrumMatch(PlotView plotView, Canvas canvas, PsmFromTsv psm, ParentChildScanPlotsView parentChildScanPlotsView, out List<string> errors) { errors = null; // clear old parent/child scans parentChildScanPlotsView.Plots.Clear(); CurrentlyDisplayedPlots.Clear(); // get the scan if (!MsDataFiles.TryGetValue(psm.FileNameWithoutExtension, out DynamicDataConnection spectraFile)) { errors = new List<string>(); errors.Add("The spectra file could not be found for this PSM: " + psm.FileNameWithoutExtension); return; } MsDataScan scan = spectraFile.GetOneBasedScanFromDynamicConnection(psm.Ms2ScanNumber); LibrarySpectrum librarySpectrum = null; // plot the annotated spectrum match PeptideSpectrumMatchPlot plot; //if not crosslinked if (psm.BetaPeptideBaseSequence == null) { // get the library spectrum if relevant if (SpectralLibrary != null) { SpectralLibrary.TryGetSpectrum(psm.FullSequence, psm.PrecursorCharge, out var librarySpectrum1); librarySpectrum = librarySpectrum1; } plot = new PeptideSpectrumMatchPlot(plotView, canvas, psm, scan, psm.MatchedIons, librarySpectrum: librarySpectrum); } else //crosslinked { plot = new CrosslinkSpectrumMatchPlot(plotView, canvas, psm, scan); } CurrentlyDisplayedPlots.Add(plot); // plot parent/child scans if (psm.ChildScanMatchedIons != null) { // draw parent scan string parentAnnotation = "Scan: " + scan.OneBasedScanNumber + " Dissociation Type: " + scan.DissociationType + " MsOrder: " + scan.MsnOrder + " Selected Mz: " + scan.SelectedIonMZ.Value.ToString("0.##") + " Retention Time: " + scan.RetentionTime.ToString("0.##"); var parentPlotView = new PlotView(); // placeholder var parentCanvas = new Canvas(); var item = new ParentChildScanPlotTemplate() { Plot = new PeptideSpectrumMatchPlot(parentPlotView, parentCanvas, psm, scan, psm.MatchedIons), SpectrumLabel = parentAnnotation, TheCanvas = parentCanvas }; parentChildScanPlotsView.Plots.Add(item); // remove model from placeholder (the model can only be referenced by 1 plotview at a time) parentPlotView.Model = null; // draw child scans HashSet<int> scansDrawn = new HashSet<int>(); var allChildScanMatchedIons = psm.ChildScanMatchedIons; if (psm.BetaPeptideChildScanMatchedIons != null) { allChildScanMatchedIons = allChildScanMatchedIons.Concat(psm.BetaPeptideChildScanMatchedIons) .GroupBy(p => p.Key) .ToDictionary(p => p.Key, q => q.SelectMany(p => p.Value).ToList()); } foreach (var childScanMatchedIons in allChildScanMatchedIons) { int childScanNumber = childScanMatchedIons.Key; if (scansDrawn.Contains(childScanNumber)) { continue; } scansDrawn.Add(childScanNumber); List<MatchedFragmentIon> matchedIons = childScanMatchedIons.Value; MsDataScan childScan = spectraFile.GetOneBasedScanFromDynamicConnection(childScanNumber); string childAnnotation = "Scan: " + childScan.OneBasedScanNumber + " Dissociation Type: " + childScan.DissociationType + " MsOrder: " + childScan.MsnOrder + " Selected Mz: " + childScan.SelectedIonMZ.Value.ToString("0.##") + " RetentionTime: " + childScan.RetentionTime.ToString("0.##"); Canvas childCanvas = new Canvas(); PlotView childPlotView = new PlotView(); // placeholder // make the plot var childPlot = new PeptideSpectrumMatchPlot(childPlotView, childCanvas, psm, childScan, matchedIons, annotateProperties: false); childPlot.Model.Title = null; childPlot.Model.Subtitle = null; item = new ParentChildScanPlotTemplate() { Plot = childPlot, SpectrumLabel = childAnnotation, TheCanvas = childCanvas }; // remove model from placeholder (the model can only be referenced by 1 plotview at a time) childPlotView.Model = null; parentChildScanPlotsView.Plots.Add(item); CurrentlyDisplayedPlots.Add(childPlot); } } } //draw the sequence coverage map: write out the sequence, overlay modifications, and display matched fragments public void DrawSequenceCoverageMap(PsmFromTsv psm, Canvas sequenceText, Canvas map) { map.Children.Clear(); sequenceText.Children.Clear(); int spacing = 20; const int textHeight = 140; const int heightIncrement = 5; const int xShift = 10; int peptideLength = psm.BaseSeq.Length; //intensity arrays for each ion type double[] nIntensityArray = new double[peptideLength - 1]; double[] cIntensityArray = new double[peptideLength - 1]; double[] internalIntensityArray = new double[peptideLength - 1]; //colors for annotation Color nColor = Colors.Blue; Color cColor = Colors.Red; Color internalColor = Colors.Purple; //draw sequence text for (int r = 0; r < psm.BaseSeq.Length; r++) { TextDrawing(sequenceText, new Point(r * spacing + xShift, textHeight - 30), (r + 1).ToString(), Brushes.Black, 8); TextDrawing(sequenceText, new Point(r * spacing + xShift, textHeight - 15), (psm.BaseSeq.Length - r).ToString(), Brushes.Black, 8); TextDrawing(sequenceText, new Point(r * spacing + xShift, textHeight), psm.BaseSeq[r].ToString(), Brushes.Black, 16); } //create circles for mods, if needed and able if (!psm.FullSequence.Contains("|")) //can't draw mods if not localized/identified { PeptideSpectrumMatchPlot.AnnotateModifications(psm, sequenceText, psm.FullSequence, textHeight-4, spacing, xShift+5); } //draw lines for each matched fragment List<bool[]> index = new List<bool[]>(); //N-terminal List<MatchedFragmentIon> nTermFragments = psm.MatchedIons.Where(x => x.NeutralTheoreticalProduct.Terminus == FragmentationTerminus.N).ToList(); //C-terminal in reverse order List<MatchedFragmentIon> cTermFragments = psm.MatchedIons.Where(x => x.NeutralTheoreticalProduct.Terminus == FragmentationTerminus.C).OrderByDescending(x => x.NeutralTheoreticalProduct.FragmentNumber).ToList(); //add internal fragments List<MatchedFragmentIon> internalFragments = psm.MatchedIons.Where(x => x.NeutralTheoreticalProduct.SecondaryProductType != null).OrderBy(x => x.NeutralTheoreticalProduct.FragmentNumber).ToList(); //indexes to navigate terminal ions int n = 0; int c = 0; int heightForThisFragment = 70; //location to draw a fragment //line up terminal fragments so that complementary ions are paired on the same line while (n < nTermFragments.Count && c < cTermFragments.Count) { MatchedFragmentIon nProduct = nTermFragments[n]; MatchedFragmentIon cProduct = cTermFragments[c]; int expectedComplementary = peptideLength - nProduct.NeutralTheoreticalProduct.FragmentNumber; //if complementary pair if (cProduct.NeutralTheoreticalProduct.FragmentNumber == expectedComplementary) { //plot sequences DrawHorizontalLine(0, nProduct.NeutralTheoreticalProduct.FragmentNumber, map, heightForThisFragment, nColor, spacing); DrawHorizontalLine(peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber, peptideLength, map, heightForThisFragment, cColor, spacing); //record intensities nIntensityArray[nProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += nProduct.Intensity; cIntensityArray[peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += cProduct.Intensity; //increment indexes n++; c++; } //if n-terminal ion is present without complementary else if (cProduct.NeutralTheoreticalProduct.FragmentNumber < expectedComplementary) { DrawHorizontalLine(0, nProduct.NeutralTheoreticalProduct.FragmentNumber, map, heightForThisFragment, nColor, spacing); nIntensityArray[nProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += nProduct.Intensity; n++; } //if c-terminal ion is present without complementary else { DrawHorizontalLine(peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber, peptideLength, map, heightForThisFragment, cColor, spacing); cIntensityArray[peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += cProduct.Intensity; c++; } heightForThisFragment += heightIncrement; } //wrap up leftover fragments without complementary pairs for (; n < nTermFragments.Count; n++) { MatchedFragmentIon nProduct = nTermFragments[n]; DrawHorizontalLine(0, nProduct.NeutralTheoreticalProduct.FragmentNumber, map, heightForThisFragment, nColor, spacing); nIntensityArray[nProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += nProduct.Intensity; heightForThisFragment += heightIncrement; } for (; c < cTermFragments.Count; c++) { MatchedFragmentIon cProduct = cTermFragments[c]; DrawHorizontalLine(peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber, peptideLength, map, heightForThisFragment, cColor, spacing); cIntensityArray[peptideLength - cProduct.NeutralTheoreticalProduct.FragmentNumber - 1] += cProduct.Intensity; heightForThisFragment += heightIncrement; } //internal fragments foreach (MatchedFragmentIon fragment in internalFragments) { DrawHorizontalLine(fragment.NeutralTheoreticalProduct.FragmentNumber, fragment.NeutralTheoreticalProduct.SecondaryFragmentNumber, map, heightForThisFragment, internalColor, spacing); internalIntensityArray[fragment.NeutralTheoreticalProduct.FragmentNumber - 1] += fragment.Intensity; internalIntensityArray[fragment.NeutralTheoreticalProduct.SecondaryFragmentNumber - 1] += fragment.Intensity; heightForThisFragment += heightIncrement; } map.Height = heightForThisFragment + 100; map.Width = spacing * psm.BaseSeq.Length + 100; sequenceText.Width = spacing * psm.BaseSeq.Length + 100; ////PLOT INTENSITY HISTOGRAM//// double[] intensityArray = new double[peptideLength - 1]; for (int i = 0; i < intensityArray.Length; i++) { intensityArray[i] = nIntensityArray[i] + cIntensityArray[i] + internalIntensityArray[i]; } double maxIntensity = intensityArray.Max(); //foreach cleavage site for (int i = 0; i < intensityArray.Length; i++) { //if anything if (intensityArray[i] > 0) { int x = (i + 1) * spacing + 7; //n-terminal int nY = 100 - (int)Math.Round(nIntensityArray[i] * 100 / maxIntensity, 0); if (nY != 100) { DrawVerticalLine(104, nY + 4, sequenceText, (i + 1) * spacing + 5, nColor); } //c-terminal int cY = nY - (int)Math.Round(cIntensityArray[i] * 100 / maxIntensity, 0); if (nY != cY) { DrawVerticalLine(nY + 2, cY + 2, sequenceText, (i + 1) * spacing + 5, cColor); } //internal int iY = cY - (int)Math.Round(internalIntensityArray[i] * 100 / maxIntensity, 0); if (cY != iY) { DrawVerticalLine(cY, iY, sequenceText, (i + 1) * spacing + 5, internalColor); } } } } public static void TextDrawing(Canvas sequenceText, Point loc, string txt, Brush clr, int fontSize) { TextBlock tb = new TextBlock(); tb.Foreground = clr; tb.Text = txt; tb.FontSize = fontSize; if (clr == Brushes.Black) { tb.FontWeight = System.Windows.FontWeights.Bold; } else { tb.FontWeight = System.Windows.FontWeights.ExtraBold; } tb.FontFamily = new FontFamily("Arial"); // monospaced font Canvas.SetTop(tb, loc.Y); Canvas.SetLeft(tb, loc.X); Panel.SetZIndex(tb, 2); //lower priority sequenceText.Children.Add(tb); sequenceText.UpdateLayout(); } public static void DrawHorizontalLine(int start, int end, Canvas map, int height, Color clr, int spacing) { DrawLine(map, new Point(start * spacing + 7, height), new Point(end * spacing + 4, height), clr); } public static void DrawVerticalLine(int start, int end, Canvas map, int x, Color clr) { DrawLine(map, new Point(x, start), new Point(x, end), clr); } public static void DrawLine(Canvas cav, Point start, Point end, Color clr) { Line line = new Line(); line.Stroke = new SolidColorBrush(clr); line.X1 = start.X; line.X2 = end.X; line.Y1 = start.Y; line.Y2 = end.Y; line.StrokeThickness = 3.25; line.StrokeStartLineCap = PenLineCap.Round; line.StrokeEndLineCap = PenLineCap.Round; cav.Children.Add(line); Canvas.SetZIndex(line, 1); //on top of any other things in canvas } public void ExportToPdf(PlotView plotView, Canvas canvas, List<PsmFromTsv> spectrumMatches, ParentChildScanPlotsView parentChildScanPlotsView, string directory, out List<string> errors) { errors = new List<string>(); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } foreach (var psm in spectrumMatches) { DisplaySpectrumMatch(plotView, canvas, psm, parentChildScanPlotsView, out var displayErrors); if (displayErrors != null) { errors.AddRange(displayErrors); } string sequence = illegalInFileName.Replace(psm.FullSequence, string.Empty); if (sequence.Length > 30) { sequence = sequence.Substring(0, 30); } foreach (var plot in CurrentlyDisplayedPlots) { string filePath = System.IO.Path.Combine(directory, plot.Scan.OneBasedScanNumber + "_" + sequence + ".pdf"); int i = 2; while (File.Exists(filePath)) { filePath = System.IO.Path.Combine(directory, plot.Scan.OneBasedScanNumber + "_" + sequence + "_" + i + ".pdf"); i++; } plot.ExportToPdf(filePath, plotView.ActualWidth, plotView.ActualHeight); } } DisplaySpectrumMatch(plotView, canvas, spectrumMatches.First(), parentChildScanPlotsView, out var moreDisplayErrors); } public void FilterPsms() { lock (ThreadLocker) { FilteredListOfPsms.Clear(); foreach (var psm in AllPsms.Where(p => MetaDrawSettings.FilterAcceptsPsm(p))) { FilteredListOfPsms.Add(psm); } } } public void FilterPsmsByString(string searchString) { if (searchString == "") { PeptideSpectralMatchesView.Filter = null; } else { PeptideSpectralMatchesView.Filter = obj => { PsmFromTsv psm = obj as PsmFromTsv; return ((psm.Ms2ScanNumber.ToString()).StartsWith(searchString) || psm.FullSequence.ToUpper().Contains(searchString.ToUpper())); }; } } public void CleanUpResources() { lock (ThreadLocker) { AllPsms.Clear(); FilteredListOfPsms.Clear(); PsmResultFilePaths.Clear(); SpectraFilePaths.Clear(); SpectralLibraryPaths.Clear(); foreach (var connection in MsDataFiles) { connection.Value.CloseDynamicConnection(); } MsDataFiles.Clear(); if (SpectralLibrary != null) { SpectralLibrary.CloseConnections(); } } } private void LoadPsms(out List<string> errors, bool haveLoadedSpectra) { errors = new List<string>(); HashSet<string> fileNamesWithoutExtension = new HashSet<string>( SpectraFilePaths.Select(p => System.IO.Path.GetFileName(p.Replace(GlobalVariables.GetFileExtension(p), string.Empty)))); List<PsmFromTsv> psmsThatDontHaveMatchingSpectraFile = new List<PsmFromTsv>(); try { foreach (var resultsFile in PsmResultFilePaths) { lock (ThreadLocker) { foreach (PsmFromTsv psm in PsmTsvReader.ReadTsv(resultsFile, out List<string> warnings)) { if (fileNamesWithoutExtension.Contains(psm.FileNameWithoutExtension) || !haveLoadedSpectra) { AllPsms.Add(psm); } else { psmsThatDontHaveMatchingSpectraFile.Add(psm); } if (PsmsGroupedByFile.TryGetValue(psm.FileNameWithoutExtension, out var psmsForThisFile)) { psmsForThisFile.Add(psm); } else { PsmsGroupedByFile.Add(psm.FileNameWithoutExtension, new ObservableCollection<PsmFromTsv> { psm }); } } } } } catch (Exception e) { errors.Add("Error reading PSM file:\n" + e.Message); } if (psmsThatDontHaveMatchingSpectraFile.Any()) { foreach (var file in psmsThatDontHaveMatchingSpectraFile.GroupBy(p => p.FileNameWithoutExtension)) { errors.Add(file.Count() + " PSMs from " + file.Key + " were not loaded because this spectra file was not found"); } } FilterPsms(); } private void LoadSpectraFiles(out List<string> errors) { errors = new List<string>(); foreach (var filepath in SpectraFilePaths) { lock (ThreadLocker) { var fileNameWithoutExtension = filepath.Replace(GlobalVariables.GetFileExtension(filepath), string.Empty); fileNameWithoutExtension = System.IO.Path.GetFileName(fileNameWithoutExtension); DynamicDataConnection spectraFile = null; string extension = GlobalVariables.GetFileExtension(filepath); if (extension.Equals(".mzML", StringComparison.OrdinalIgnoreCase)) { spectraFile = new MzmlDynamicData(filepath); } else if (extension.Equals(".mgf", StringComparison.OrdinalIgnoreCase)) { spectraFile = new MgfDynamicData(filepath); } else if (extension.Equals(".raw", StringComparison.OrdinalIgnoreCase)) { spectraFile = new ThermoDynamicData(filepath); } else { errors.Add("Unrecognized spectra file type: " + extension); continue; } if (!MsDataFiles.TryAdd(fileNameWithoutExtension, spectraFile)) { spectraFile.CloseDynamicConnection(); // print warning? but probably unnecessary. this means the data file was loaded twice. // which is an error but not an important one because the data is loaded } } } } private void LoadSpectralLibraries(out List<string> errors) { errors = new List<string>(); try { SpectralLibrary = new SpectralLibrary(SpectralLibraryPaths.ToList()); } catch (Exception e) { SpectralLibrary = null; errors.Add("Problem loading spectral library: " + e.Message); } } } }
42.621188
222
0.555154
[ "MIT" ]
Alexander-Sol/MetaMorpheus
GuiFunctions/MetaDraw/MetaDrawLogic.cs
26,555
C#
namespace LoyaltyProgramServiceTests.Mocks { using Microsoft.AspNetCore.Mvc; public class SpecialOffersMock : ControllerBase { [HttpGet("/specialoffers/events")] public ActionResult<object[]> GetEvents([FromQuery] int start, [FromQuery] int end) => new[] { new { SequenceNumber = 1, Name = "baz", Content = new { OfferName = "foo", Description = "bar", Item = new {ProductName = "name"} } } }; } }
22.583333
90
0.527675
[ "MIT" ]
horsdal/microservices-in-dotnet-book-second-edition
Chapter08/LoyaltyProgramServiceTests/Mocks/SpecialOffersMock.cs
542
C#
using System.Collections.Generic; using BrotliLib.Markers.Types; namespace BrotliLib.Markers.Builders{ public class MarkerRootBuilder : IMarkerBuilder{ public MarkerRoot Root { get; } private readonly Stack<MarkerNode> nodes = new Stack<MarkerNode>(); private readonly Stack<int> starts = new Stack<int>(); public MarkerRootBuilder(){ this.Root = new MarkerRoot(); } public void MarkStart(int index){ MarkerNode added = new MarkerNode{ Depth = nodes.Count }; if (nodes.Count == 0){ Root.AddChild(added); } else{ nodes.Peek().AddChildOrSibling(added); } starts.Push(index); nodes.Push(added); } public void MarkEnd(int index, IMarkerInfo info){ nodes.Pop().Marker = new Marker(starts.Pop(), index, info); } } }
27.588235
75
0.570362
[ "MIT" ]
chylex/Brotli-Builder
BrotliLib/Markers/Builders/MarkerRootBuilder.cs
940
C#
using System.Linq; using Abp.Configuration; using Abp.Localization; using Abp.Net.Mail; using Myproject.EntityFramework; namespace Myproject.Migrations.SeedData { public class DefaultSettingsCreator { private readonly MyprojectDbContext _context; public DefaultSettingsCreator(MyprojectDbContext context) { _context = context; } public void Create() { //Emailing AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com"); AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer"); //Languages AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en"); } private void AddSettingIfNotExists(string name, string value, int? tenantId = null) { if (_context.Settings.Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null)) { return; } _context.Settings.Add(new Setting(tenantId, null, name, value)); _context.SaveChanges(); } } }
28.825
105
0.627927
[ "MIT" ]
ahmetkursatesim/ASPNETProject
src/Myproject.EntityFramework/Migrations/SeedData/DefaultSettingsCreator.cs
1,155
C#
namespace Hexalith.Application.Queries { using System.Threading; using System.Threading.Tasks; using Hexalith.Application.Messages; using Microsoft.Extensions.Options; public abstract class SettingsQueryHandler<TQuery, TSettings> : QueryHandler<TQuery, TSettings> where TQuery : QueryBase<TSettings> where TSettings : class { private readonly IOptions<TSettings> _options; protected SettingsQueryHandler(IOptions<TSettings> options) { _options = options; } public override Task<TSettings> Handle(Envelope<TQuery> envelope, CancellationToken cancellationToken = default) { return Task.FromResult(_options.Value); } } }
27.962963
120
0.674172
[ "MIT" ]
Hexalith/Hexalith
src/Core/Application/Hexalith.Application/Queries/SettingsQueryHandler.cs
757
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class WeaponEventHandler : MonoBehaviour { public void SetAttackingBool(int state) { GetComponentInParent<Animator>().SetBool("isAttacking", Convert.ToBoolean(state)); } //where the actual attack gets executed private void OnTriggerEnter2D(Collider2D collision) { if(collision.tag != "Enemy") { return; } var stats = GetComponentInParent<CharacterStats>(); int damage = 0; bool isCrit = false; //check if it's a crit if (RNGUtil.Roll(stats.CritChance)) { damage = stats.AttackPower.Value * 2; isCrit = true; } else { damage = stats.AttackPower.Value; } collision.GetComponent<EnemyCombat>().TakeDamage(damage, 20, isCrit, GetComponentInParent<Transform>()); } }
25.315789
112
0.611227
[ "CC0-1.0" ]
MufasaDoodle/GMD-Project
Assets/Scripts/Player/WeaponEventHandler.cs
962
C#
using System; using System.Diagnostics; using Cirrious.CrossCore.Platform; namespace Kunicardus.Touch { public class DebugTrace : IMvxTrace { public void Trace(MvxTraceLevel level, string tag, Func<string> message) { Debug.WriteLine(tag + ":" + level + ":" + message()); } public void Trace(MvxTraceLevel level, string tag, string message) { Debug.WriteLine(tag + ":" + level + ":" + message); } public void Trace(MvxTraceLevel level, string tag, string message, params object[] args) { try { Debug.WriteLine(string.Format(tag + ":" + level + ":" + message, args)); } catch (FormatException) { Trace(MvxTraceLevel.Error, tag, "Exception during trace of {0} {1}", level, message); } } } }
28.21875
101
0.542636
[ "MIT" ]
nininea2/unicard_app_base
Kunicardus.Touch/DebugTrace.cs
903
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Microsoft.Psi.Common.Interpolators { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Implements a greedy interpolator that selects the first value from a specified window. The /// interpolator only considers messages available in the window on the secondary stream at /// the moment the primary stream message arrives. As such, it belongs to the class of greedy /// interpolators and does not guarantee reproducible results. /// </summary> /// <typeparam name="T">The type of messages.</typeparam> public sealed class FirstAvailableInterpolator<T> : GreedyInterpolator<T> { private readonly RelativeTimeInterval relativeTimeInterval; private readonly bool orDefault; private readonly T defaultValue; private readonly string name; /// <summary> /// Initializes a new instance of the <see cref="FirstAvailableInterpolator{T}"/> class. /// </summary> /// <param name="relativeTimeInterval">The relative time interval within which to search for the first message.</param> /// <param name="orDefault">Indicates whether to output a default value when no result is found.</param> /// <param name="defaultValue">An optional default value to use.</param> public FirstAvailableInterpolator(RelativeTimeInterval relativeTimeInterval, bool orDefault, T defaultValue = default) { if (!relativeTimeInterval.LeftEndpoint.Bounded) { throw new NotSupportedException($"{nameof(FirstAvailableInterpolator<T>)} does not support relative time intervals that are " + $"left-unbounded. The use of this interpolator in a fusion operation like Fuse or Join could lead to an incremental, " + $"continuous accumulation of messages on the secondary stream queue held by the fusion component. If you wish to interpolate " + $"by selecting the very first message in the secondary stream, please instead apply the First() operator on the " + $"secondary (with an unlimited delivery policy), and use the {nameof(NearestAvailableInterpolator<T>)}, as this " + $"will accomplish the same result."); } this.relativeTimeInterval = relativeTimeInterval; this.orDefault = orDefault; this.defaultValue = defaultValue; this.name = (this.orDefault ? $"{nameof(Available)}.{nameof(Available.FirstOrDefault)}" : $"{nameof(Available)}.{nameof(Available.First)}") + this.relativeTimeInterval.ToString(); } /// <inheritdoc/> public override InterpolationResult<T> Interpolate(DateTime interpolationTime, IEnumerable<Message<T>> messages, DateTime? closedOriginatingTime) { // If no messages available, if (messages.Count() == 0) { // Then depending on orDefault, either create a default value or return does not exist. return this.orDefault ? InterpolationResult<T>.Create(this.defaultValue, DateTime.MinValue) : InterpolationResult<T>.DoesNotExist(DateTime.MinValue); } Message<T> firstMessage = default; bool found = false; foreach (var message in messages) { var delta = message.OriginatingTime - interpolationTime; // Determine if the message is on the right side of the window start var messageIsAfterWindowStart = this.relativeTimeInterval.LeftEndpoint.Inclusive ? delta >= this.relativeTimeInterval.Left : delta > this.relativeTimeInterval.Left; // Only consider messages that occur within the lookback window. if (messageIsAfterWindowStart) { // Determine if the message is outside the window end var messageIsOutsideWindowEnd = this.relativeTimeInterval.RightEndpoint.Inclusive ? delta > this.relativeTimeInterval.Right : delta >= this.relativeTimeInterval.Right; // We stop searching either when we reach a message that is beyond the lookahead window if (messageIsOutsideWindowEnd) { break; } // keep track of message and exit the loop as we found the first one firstMessage = message; found = true; break; } } // If we found a first message in the window if (found) { // Return the matching message value as the matched result. // All messages before the matching message are obsolete. return InterpolationResult<T>.Create(firstMessage.Data, firstMessage.OriginatingTime); } else { // o/w, that means no match was found, which implies there was no message in the // window. In that case, either return DoesNotExist or the default value. var windowLeft = interpolationTime.BoundedAdd(this.relativeTimeInterval.Left); return this.orDefault ? InterpolationResult<T>.Create(this.defaultValue, windowLeft) : InterpolationResult<T>.DoesNotExist(windowLeft); } } /// <inheritdoc/> public override string ToString() => this.name; } }
50.761062
187
0.620293
[ "MIT" ]
Microsoft/psi
Sources/Runtime/Microsoft.Psi/Common/Interpolators/FirstAvailableInterpolator.cs
5,738
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace GameFramework { // Die eigentliche "Intelligenz" des Spiels. // Ausführliche Erklärung in c't 10/14, S. 176ff public class MinimaxBrain<TMove> : Brain<TMove> { protected Random _rnd; // So viele Halbzüge in die Zukunft wird der Spielbaum analysiert. public int Depth { get; set; } public MinimaxBrain() { _rnd = new Random(); } int _valueCount = 0; TimeSpan _valueTime; Func<Game<TMove>, int, int> _evaluator; public async override Task<TMove> SelectMoveAsync(Game<TMove> game, int player) { // Die Stellungsbewertungsfunktion _evaluator = game.GetEvaluator<Game<TMove>>(2); return await Task<TMove>.Run(() => { Stopwatch timer = Stopwatch.StartNew(); _valueCount = 0; int bestValue = -int.MaxValue; var bestMoves = new List<TMove>(); // Von den folgenden 2 Zeilen immer nur eine entkommentieren, // um zwischen paralleler oder serieller Analyse umzuschalten. // foreach(var move in game.MovesFor(player)) Parallel.ForEach(game.MovesFor(player), move => { // Von den folgenden 4 Zeilen ist immer nur eine zu entkommentieren! // int value = -MiniMax(game.MakeMove(move), 1 - player, Depth); // int value = -MiniMaxParallel(game.MakeMove(move), 1 - player, Depth); int value = -AlphaBeta(game.MakeMove(move), 1 - player, Depth, -int.MaxValue, -bestValue); // int value = -AlphaBetaParallel(game.MakeMove(move), 1 - player, Depth, -int.MaxValue, -bestValue, null); lock(bestMoves) { // Ist eigentlich nur bei paralleler Analyse nötig if(value > bestValue) { // Neuer bester Zug bestValue = value; bestMoves.Clear(); bestMoves.Add(move); } else if(value == bestValue) { // Ein Zug mit derselben Bewertung wie der bisher beste bestMoves.Add(move); } } }); // Parallel.ForEach() // } // foreach() timer.Stop(); _valueTime = timer.Elapsed; // Aus den gesammelten Zügen mit der besten Bewertung einen zufällig auswählen. return bestMoves[_rnd.Next(bestMoves.Count)]; }); } protected virtual int MiniMax(Game<TMove> game, int player, int depth) { if(depth == 0) return GameValue(game, player); int bestValue = -int.MaxValue; foreach(var move in game.MovesFor(player)) { int value = -MiniMax(game.MakeMove(move), 1 - player, depth - 1); if(value > bestValue) { bestValue = value; } } return bestValue; } protected virtual int MiniMaxParallel(Game<TMove> game, int player, int depth) { if(depth == 0) return GameValue(game, player); int bestValue = -int.MaxValue; object lockObject = new object(); Parallel.ForEach(game.MovesFor(player), move => { int value; // Auf den letzten Rekursionsstufen lohnt sich die Parallelisierung nicht mehr. if(depth > 2) value = -MiniMaxParallel(game.MakeMove(move), 1 - player, depth - 1); else value = -MiniMax(game.MakeMove(move), 1 - player, depth - 1); lock(lockObject) { if(value > bestValue) { bestValue = value; } } }); return bestValue; } protected virtual int AlphaBeta(Game<TMove> game, int player, int depth, int alpha, int beta) { if(depth == 0) return GameValue(game, player); int bestValue = -int.MaxValue; foreach(var move in game.MovesFor(player)) { int value = -AlphaBeta(game.MakeMove(move), 1 - player, depth - 1, -beta, -alpha); if(value > bestValue) { bestValue = value; } if(value > alpha) { alpha = value; if(alpha >= beta) { break; } } } return bestValue; } protected virtual int AlphaBetaParallel(Game<TMove> game, int player, int depth, int alpha, int beta, ParallelLoopState outerState) { if(depth == 0) return GameValue(game, player); int bestValue = -int.MaxValue; object lockObject = new object(); Parallel.ForEach(game.MovesFor(player), (move, loopState) => { // Abbrechen, wenn in einer höheren Etage geschnitten wurde. if(outerState != null && outerState.IsStopped) { loopState.Stop(); } else { int value; if(depth > 2) value = -AlphaBetaParallel(game.MakeMove(move), 1 - player, depth - 1, -beta, -alpha, loopState); else value = -AlphaBeta(game.MakeMove(move), 1 - player, depth - 1, -beta, -alpha); lock(lockObject) { if(value > bestValue) { bestValue = value; } if(value > alpha) { alpha = value; if(alpha >= beta) { loopState.Stop(); } } } } }); return bestValue; } protected virtual int GameValue(Game<TMove> game, int player) { Interlocked.Increment(ref _valueCount); return _evaluator(game, player); } public override string GetStatistics() { return string.Format("{0:n0} Stellungen in {1:%h}:{1:mm}:{1:ss},{1:%f} analysiert.", _valueCount, _valueTime); } } }
32.543353
135
0.575666
[ "Unlicense" ]
MartinNiemllerSchule/lk1314
othello/1410-176/cthello/cthello/GameFramework/MinimaxBrain.cs
5,640
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #nullable disable namespace StyleCop.Analyzers.Test.CSharp10.Lightup { using StyleCop.Analyzers.Test.CSharp9.Lightup; public class AccessorDeclarationSyntaxExtensionsTestsCSharp10 : AccessorDeclarationSyntaxExtensionsTestsCSharp9 { } }
29.928571
115
0.794749
[ "MIT" ]
RogerHowellDfE/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp10/Lightup/AccessorDeclarationSyntaxExtensionsTestsCSharp10.cs
421
C#
/* SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. * * Modifications Copyright OpenSearch Contributors. See * GitHub history for details. * * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Linq; using OpenSearch.Net; using FluentAssertions; using OpenSearch.Client; using Tests.Core.Extensions; using Tests.Core.ManagedOpenSearch.Clusters; using Tests.Domain; using Tests.Framework.EndpointTests; using Tests.Framework.EndpointTests.TestState; namespace Tests.Document.Multiple.MultiTermVectors { public class MultiTermVectorsIdsApiTests : ApiIntegrationTestBase<ReadOnlyCluster, MultiTermVectorsResponse, IMultiTermVectorsRequest, MultiTermVectorsDescriptor, MultiTermVectorsRequest> { public MultiTermVectorsIdsApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override object ExpectJson { get; } = new { ids = Developer.Developers.Select(p => p.Id).Take(2) }; protected override int ExpectStatusCode => 200; protected override Func<MultiTermVectorsDescriptor, IMultiTermVectorsRequest> Fluent => d => d .Index<Developer>() .Ids(Developer.Developers.Select(p => (Id)p.Id).Take(2)) .FieldStatistics() .Payloads() .TermStatistics() .Positions() .Offsets(); protected override HttpMethod HttpMethod => HttpMethod.POST; protected override MultiTermVectorsRequest Initializer => new MultiTermVectorsRequest(Infer.Index<Developer>()) { Ids = Developer.Developers.Select(p => (Id)p.Id).Take(2), FieldStatistics = true, Payloads = true, TermStatistics = true, Positions = true, Offsets = true }; protected override bool SupportsDeserialization => false; protected override string UrlPath => $"/devs/_mtermvectors?field_statistics=true&payloads=true&term_statistics=true&positions=true&offsets=true"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.MultiTermVectors(f), (client, f) => client.MultiTermVectorsAsync(f), (client, r) => client.MultiTermVectors(r), (client, r) => client.MultiTermVectorsAsync(r) ); protected override void ExpectResponse(MultiTermVectorsResponse response) { response.ShouldBeValid(); response.Documents.Should().NotBeEmpty().And.HaveCount(2).And.OnlyContain(d => d.Found); var termvectorDoc = response.Documents.FirstOrDefault(d => d.TermVectors.Count > 0); termvectorDoc.Should().NotBeNull(); termvectorDoc.Index.Should().NotBeNull(); termvectorDoc.Id.Should().NotBeNull(); termvectorDoc.TermVectors.Should().NotBeEmpty().And.ContainKey("firstName"); var vectors = termvectorDoc.TermVectors["firstName"]; AssertTermVectors(vectors); vectors = termvectorDoc.TermVectors[Infer.Field<Developer>(p => p.FirstName)]; AssertTermVectors(vectors); } private static void AssertTermVectors(TermVector vectors) { vectors.Terms.Should().NotBeEmpty(); foreach (var vectorTerm in vectors.Terms) { vectorTerm.Key.Should().NotBeNullOrWhiteSpace(); vectorTerm.Value.Should().NotBeNull(); vectorTerm.Value.TermFrequency.Should().BeGreaterThan(0); vectorTerm.Value.TotalTermFrequency.Should().BeGreaterThan(0); vectorTerm.Value.Tokens.Should().NotBeEmpty(); var token = vectorTerm.Value.Tokens.First(); token.EndOffset.Should().BeGreaterThan(0); } } } }
34.564516
123
0.752683
[ "Apache-2.0" ]
opensearch-project/opensearch-net
tests/Tests/Document/Multiple/MultiTermVectors/MultiTermVectorsIdsApiTests.cs
4,286
C#
using System.Collections.Generic; namespace _535_EncodeAndDecodeTinyURL { internal class Codec { private IDictionary<string, string> UrlMap = new Dictionary<string, string>(); // Encodes a URL to a shortened URL public string encode(string longUrl) { return encodeUrl(longUrl); } private string encodeUrl(string url) { var hash = string.Format("{0:X}", url.GetHashCode()); var hashedUrl = $"http://tinyurl.com/{hash}"; UrlMap[hashedUrl] = url; return hashedUrl; } // Decodes a shortened URL to its original URL. public string decode(string shortUrl) { return UrlMap[shortUrl]; } } }
24.0625
86
0.571429
[ "MIT" ]
kodoftw/LeetCode
LeetCode/535-EncodeAndDecodeTinyURL/Codec.cs
772
C#
namespace EA.Weee.RequestHandlers.AatfReturn.Specification { using EA.Weee.Domain.AatfReturn; using System; using System.Linq.Expressions; public class ReturnReportOnByReturnIdSpecification : Specification<ReturnReportOn> { public Guid ReturnId { get; private set; } public ReturnReportOnByReturnIdSpecification(Guid returnId) { ReturnId = returnId; } public override Expression<Func<ReturnReportOn, bool>> ToExpression() { return @returnReportOn => @returnReportOn.ReturnId == ReturnId; } } }
27.363636
86
0.667774
[ "Unlicense" ]
DEFRA/prsd-weee
src/EA.Weee.RequestHandlers/AatfReturn/Specification/ReturnReportOnByReturnIdSpecification.cs
604
C#
using Microsoft.EntityFrameworkCore; namespace RestWithAspNet.Model.Context { public class MySqlContext : DbContext { public MySqlContext(){} public MySqlContext(DbContextOptions<MySqlContext> options) : base(options) { } public DbSet<Person> People { get; set; } } }
17.210526
83
0.64526
[ "Apache-2.0" ]
PRicardo/RestWithAsp-Net5
RestWithAspNet/RestWithAspNet/RestWithAspNet/Model/Context/MySqlContext.cs
329
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 Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Tests { public class Directory_Delete_str : FileSystemTest { #region Utilities public virtual void Delete(string path) { Directory.Delete(path); } #endregion #region UniversalTests [Fact] public void NullParameters() { Assert.Throws<ArgumentNullException>(() => Delete(null)); } [Fact] public void InvalidParameters() { Assert.Throws<ArgumentException>(() => Delete(string.Empty)); } [Fact] public void ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName)); } Assert.True(testDir.Exists); } [Fact] public void ShouldThrowIOExceptionForDirectoryWithFiles() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] public void DirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [Fact] [OuterLoop] public void DeleteRoot() { Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory()))); } [Fact] public void PositiveTest() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName); Assert.False(testDir.Exists); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingFile_ThrowsDirectoryNotFound(char trailingChar) { string path = GetTestFilePath() + trailingChar; Assert.Throws<DirectoryNotFoundException>(() => Delete(path)); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar) { string path = Path.Combine(GetTestFilePath(), "file" + trailingChar); Assert.Throws<DirectoryNotFoundException>(() => Delete(path)); } [Fact] public void ShouldThrowIOExceptionDeletingCurrentDirectory() { Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory())); } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void DeletingSymLinkDoesntDeleteTarget() { var path = GetTestFilePath(); var linkPath = GetTestFilePath(); Directory.CreateDirectory(path); Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true)); // Both the symlink and the target exist Assert.True(Directory.Exists(path), "path should exist"); Assert.True(Directory.Exists(linkPath), "linkPath should exist"); // Delete the symlink Directory.Delete(linkPath); // Target should still exist Assert.True(Directory.Exists(path), "path should still exist"); Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist"); } [ConditionalFact(nameof(UsingNewNormalization))] public void ExtendedDirectoryWithSubdirectories() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.CreateSubdirectory(GetTestFileName()); Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); } [ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))] public void LongPathExtendedDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500)); Delete(testDir.FullName); Assert.False(testDir.Exists); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException public void WindowsDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException public void WindowsDeleteExtendedReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Assert.Throws<IOException>(() => Delete(testDir.FullName)); Assert.True(testDir.Exists); testDir.Attributes = FileAttributes.Normal; } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds public void UnixDeleteReadOnlyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.ReadOnly; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds public void WindowsShouldBeAbleToDeleteHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [ConditionalFact(nameof(UsingNewNormalization))] [PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath()); testDir.Attributes = FileAttributes.Hidden; Delete(testDir.FullName); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds public void UnixShouldBeAbleToDeleteHiddenDirectory() { string testDir = "." + GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, testDir)); Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden)); Delete(Path.Combine(TestDirectory, testDir)); Assert.False(Directory.Exists(testDir)); } [Fact] [OuterLoop("Needs sudo access")] [PlatformSpecific(TestPlatforms.Linux)] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void Unix_NotFoundDirectory_ReadOnlyVolume() { ReadOnly_FileSystemHelper(readOnlyDirectory => { Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(readOnlyDirectory, "DoesNotExist"))); }); } #endregion } public class Directory_Delete_str_bool : Directory_Delete_str { #region Utilities public override void Delete(string path) { Directory.Delete(path, false); } public virtual void Delete(string path, bool recursive) { Directory.Delete(path, recursive); } #endregion [Fact] public void RecursiveDelete() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose(); testDir.CreateSubdirectory(GetTestFileName()); Delete(testDir.FullName, true); Assert.False(testDir.Exists); } [Fact] public void RecursiveDeleteWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Delete(testDir.FullName + Path.DirectorySeparatorChar, true); Assert.False(testDir.Exists); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { Assert.Throws<IOException>(() => Delete(testDir.FullName, true)); } Assert.True(testDir.Exists); } } }
37.373585
144
0.631462
[ "MIT" ]
cydhaselton/cfx-android
src/System.IO.FileSystem/tests/Directory/Delete.cs
9,904
C#
namespace dp2Circulation { partial class RotateControl { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 组件设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RotateControl)); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.InitialImage"))); this.pictureBox1.Location = new System.Drawing.Point(3, 3); this.pictureBox1.Margin = new System.Windows.Forms.Padding(0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(100, 50); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; this.pictureBox1.SizeChanged += new System.EventHandler(this.pictureBox1_SizeChanged); this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click); // // RotateControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.pictureBox1); this.Name = "RotateControl"; this.Size = new System.Drawing.Size(103, 53); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBox1; } }
37.567164
145
0.59118
[ "Apache-2.0" ]
DigitalPlatform/dp2
dp2Circulation/Label/RotateControl.Designer.cs
2,669
C#
using System; using System.Linq; namespace equalArrays { class Program { static void Main(string[] args) { int[] firstArray = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToArray(); int[] secondArray = Console.ReadLine() .Split(' ') .Select(int.Parse) .ToArray(); int sum = 0; for (int i = 0; i < firstArray.Length; i++) { if (firstArray[i] == secondArray[i]) { sum += firstArray[i]; } else { Console.WriteLine($"Arrays are not identical. Found difference at {i} index"); return; } } Console.WriteLine($"Arrays are identical. Sum: {sum}"); } } }
24.447368
98
0.401507
[ "MIT" ]
BorislavVladimirov/C-Software-University
C# TechModule January 2019/Arrays 2019/Arrays/equalArrays/Program.cs
931
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V6.Resources; namespace Google.Ads.GoogleAds.V6.Services { public partial class GetCustomerManagerLinkRequest { /// <summary> /// <see cref="gagvr::CustomerManagerLinkName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> public gagvr::CustomerManagerLinkName ResourceNameAsCustomerManagerLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomerManagerLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
37.352941
135
0.698425
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
src/V6/Services/CustomerManagerLinkServiceResourceNames.g.cs
1,270
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.Globalization; using System.Speech.Synthesis; using System.Speech.Synthesis.TtsEngine; using System.Xml; namespace System.Speech.Internal.Synthesis { #region Internal Types internal interface ISsmlParser { object ProcessSpeak(string sVersion, string sBaseUri, CultureInfo culture, List<SsmlXmlAttribute> extraNamespace); void ProcessText(string text, object voice, ref FragmentState fragmentState, int position, bool fIgnore); void ProcessAudio(object voice, string sUri, string baseUri, bool fIgnore); void ProcessBreak(object voice, ref FragmentState fragmentState, EmphasisBreak eBreak, int time, bool fIgnore); void ProcessDesc(CultureInfo culture); void ProcessEmphasis(bool noLevel, EmphasisWord word); void ProcessMark(object voice, ref FragmentState fragmentState, string name, bool fIgnore); object ProcessTextBlock(bool isParagraph, object voice, ref FragmentState fragmentState, CultureInfo culture, bool newCulture, VoiceGender gender, VoiceAge age); void EndProcessTextBlock(bool isParagraph); void ProcessPhoneme(ref FragmentState fragmentState, AlphabetType alphabet, string ph, char[] phoneIds); void ProcessProsody(string pitch, string range, string rate, string volume, string duration, string points); void ProcessSayAs(string interpretAs, string format, string detail); void ProcessSub(string alias, object voice, ref FragmentState fragmentState, int position, bool fIgnore); object ProcessVoice(string name, CultureInfo culture, VoiceGender gender, VoiceAge age, int variant, bool fNewCulture, List<SsmlXmlAttribute> extraNamespace); void ProcessLexicon(Uri uri, string type); void EndElement(); void EndSpeakElement(); void ProcessUnknownElement(object voice, ref FragmentState fragmentState, XmlReader reader); void StartProcessUnknownAttributes(object voice, ref FragmentState fragmentState, string element, List<SsmlXmlAttribute> extraAttributes); void EndProcessUnknownAttributes(object voice, ref FragmentState fragmentState, string element, List<SsmlXmlAttribute> extraAttributes); // Prompt data used void ContainsPexml(string pexmlPrefix); // Prompt Engine tags bool BeginPromptEngineOutput(object voice); void EndPromptEngineOutput(object voice); // global elements bool ProcessPromptEngineDatabase(object voice, string fname, string delta, string idset); bool ProcessPromptEngineDiv(object voice); bool ProcessPromptEngineId(object voice, string id); // scoped elements bool BeginPromptEngineTts(object voice); void EndPromptEngineTts(object voice); bool BeginPromptEngineWithTag(object voice, string tag); void EndPromptEngineWithTag(object voice, string tag); bool BeginPromptEngineRule(object voice, string name); void EndPromptEngineRule(object voice, string name); // Properties string Ssml { get; } } internal class LexiconEntry { internal Uri _uri; internal string _mediaType; internal LexiconEntry(Uri uri, string mediaType) { _uri = uri; _mediaType = mediaType; } /// <summary> /// Tests whether two objects are equivalent /// </summary> public override bool Equals(object obj) { LexiconEntry entry = obj as LexiconEntry; return entry != null && _uri.Equals(entry._uri); } /// <summary> /// Overrides Object.GetHashCode() /// </summary> public override int GetHashCode() { return _uri.GetHashCode(); } } internal class SsmlXmlAttribute { internal SsmlXmlAttribute(string prefix, string name, string value, string ns) { _prefix = prefix; _name = name; _value = value; _ns = ns; } internal string _prefix; internal string _name; internal string _value; internal string _ns; } #endregion }
40.146789
169
0.688071
[ "MIT" ]
333fred/runtime
src/libraries/System.Speech/src/Internal/Synthesis/ISSmlParser.cs
4,376
C#
using System; using System.IO; using System.Linq; using System.Threading; using System.Collections.Generic; using NUnit.Framework; using Xamarin.MacDev; using Xamarin.MacDev.Tasks; using Xamarin.Utils; namespace Xamarin.iOS.Tasks { [TestFixture] public class UtilityTests { [Test] public void TestAbsoluteToRelativePath () { string rpath; rpath = PathUtils.AbsoluteToRelative ("/Users/user/source/Project", "/Users/user/Source/Project/Info.plist"); Assert.AreEqual ("Info.plist", rpath, "#1"); } } }
18.785714
112
0.737643
[ "BSD-3-Clause" ]
Therzok/xamarin-macios
tests/msbuild/Xamarin.MacDev.Tasks.Tests/UtilityTests.cs
528
C#
using CharacterGen.CharacterClasses; using CharacterGen.Domain.Tables; using NUnit.Framework; using System.Linq; namespace CharacterGen.Tests.Integration.Tables.Magics.Spells.Known.Sorcerers { [TestFixture] public class Level13SorcererKnownSpellsTests : AdjustmentsTests { protected override string tableName { get { return string.Format(TableNameConstants.Formattable.Adjustments.LevelXCLASSKnownSpells, 13, CharacterClassConstants.Sorcerer); } } [Test] public override void CollectionNames() { var names = Enumerable.Range(0, 7).Select(i => i.ToString()); AssertCollectionNames(names); } [TestCase(0, 9)] [TestCase(1, 5)] [TestCase(2, 5)] [TestCase(3, 4)] [TestCase(4, 4)] [TestCase(5, 3)] [TestCase(6, 2)] public void Adjustment(int spellLevel, int quantity) { base.Adjustment(spellLevel.ToString(), quantity); } } }
27.282051
142
0.601504
[ "MIT" ]
DnDGen/CharacterGen
CharacterGen.Tests.Integration.Tables/Magics/Spells/Known/Sorcerers/Level13SorcererKnownSpellsTests.cs
1,066
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 Ant.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; } } } }
36.2
152
0.563536
[ "Apache-2.0" ]
netstat133/Antenna-Length-Calculator
Ant/Ant/Properties/Settings.Designer.cs
1,088
C#
using System; namespace GCSample { class Program { static void Main(string[] args) { var gc = new StandardDispose(); gc.Close(); gc.Dispose(); gc.PublicMethod(); // 会抛出以释放资源的异常 Console.WriteLine("Hello World!"); } } }
18.588235
46
0.487342
[ "MIT" ]
jinjupeng/CodingTutorials
CSharpTutorials/GCSample/Program.cs
340
C#
namespace UiMetadataFramework.Basic.Input { using UiMetadataFramework.Core.Binding; public class StringInputFieldBinding : InputFieldBinding { public const string ControlName = "text"; public StringInputFieldBinding() : base(typeof(string), ControlName) { } } }
21.230769
70
0.768116
[ "MIT" ]
UNOPS/UiMetadataFramework
UiMetadataFramework.Basic/Input/StringInputFieldBinding.cs
278
C#
/* * virusapi * * The Cloudmersive Virus Scan API lets you scan files and content for viruses and identify security issues with content. * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Reflection; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Cloudmersive.APIClient.NETCore.VirusScan.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration : IReadableConfiguration { #region Constants /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.2.6"; /// <summary> /// Identifier for ISO 8601 DateTime Format /// </summary> /// <remarks>See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information.</remarks> // ReSharper disable once InconsistentNaming public const string ISO8601_DATETIME_FORMAT = "o"; #endregion Constants #region Static Members private static readonly object GlobalConfigSync = new { }; private static Configuration _globalConfiguration; /// <summary> /// Default creation of exceptions for a given method name and response object /// </summary> public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => { var status = (int)response.StatusCode; if (status >= 400) { return new ApiException(status, string.Format("Error calling {0}: {1}", methodName, response.Content), response.Content); } if (status == 0) { return new ApiException(status, string.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage); } return null; }; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default { get { return _globalConfiguration; } set { lock (GlobalConfigSync) { _globalConfiguration = value; } } } #endregion Static Members #region Private Members /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> private IDictionary<string, string> _apiKey = null; /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> private IDictionary<string, string> _apiKeyPrefix = null; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; private string _tempFolderPath = Path.GetTempPath(); #endregion Private Members #region Constructors static Configuration() { _globalConfiguration = new GlobalConfiguration(); } /// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class /// </summary> public Configuration() { UserAgent = "Swagger-Codegen/1.2.6/csharp"; BasePath = "https://api.cloudmersive.com"; DefaultHeader = new ConcurrentDictionary<string, string>(); ApiKey = new ConcurrentDictionary<string, string>(); ApiKeyPrefix = new ConcurrentDictionary<string, string>(); // Setting Timeout has side effects (forces ApiClient creation). Timeout = 100000; } /// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class /// </summary> public Configuration( IDictionary<string, string> defaultHeader, IDictionary<string, string> apiKey, IDictionary<string, string> apiKeyPrefix, string basePath = "https://api.cloudmersive.com") : this() { if (string.IsNullOrWhiteSpace(basePath)) throw new ArgumentException("The provided basePath is invalid.", "basePath"); if (defaultHeader == null) throw new ArgumentNullException("defaultHeader"); if (apiKey == null) throw new ArgumentNullException("apiKey"); if (apiKeyPrefix == null) throw new ArgumentNullException("apiKeyPrefix"); BasePath = basePath; foreach (var keyValuePair in defaultHeader) { DefaultHeader.Add(keyValuePair); } foreach (var keyValuePair in apiKey) { ApiKey.Add(keyValuePair); } foreach (var keyValuePair in apiKeyPrefix) { ApiKeyPrefix.Add(keyValuePair); } } /// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> [Obsolete("Use explicit object construction and setting of properties.", true)] public Configuration( // ReSharper disable UnusedParameter.Local ApiClient apiClient = null, IDictionary<string, string> defaultHeader = null, string username = null, string password = null, string accessToken = null, IDictionary<string, string> apiKey = null, IDictionary<string, string> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string userAgent = "Swagger-Codegen/1.2.6/csharp" // ReSharper restore UnusedParameter.Local ) { } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> [Obsolete("This constructor caused unexpected sharing of static data. It is no longer supported.", true)] // ReSharper disable once UnusedParameter.Local public Configuration(ApiClient apiClient) { } #endregion Constructors #region Properties private ApiClient _apiClient = null; /// <summary> /// Gets an instance of an ApiClient for this configuration /// </summary> public virtual ApiClient ApiClient { get { if (_apiClient == null) _apiClient = CreateApiClient(); return _apiClient; } } private String _basePath = null; /// <summary> /// Gets or sets the base path for API access. /// </summary> public virtual string BasePath { get { return _basePath; } set { _basePath = value; // pass-through to ApiClient if it's set. if(_apiClient != null) { _apiClient.RestClient.BaseUrl = new Uri(_basePath); } } } /// <summary> /// Gets or sets the default header. /// </summary> public virtual IDictionary<string, string> DefaultHeader { get; set; } /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> public virtual int Timeout { get { return ApiClient.RestClient.Timeout; } set { ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public virtual string UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public virtual string Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public virtual string Password { get; set; } /// <summary> /// Gets the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix(string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public virtual string AccessToken { get; set; } /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public virtual string TempFolderPath { get { return _tempFolderPath; } set { if (string.IsNullOrEmpty(value)) { // Possible breaking change since swagger-codegen 2.2.1, enforce a valid temporary path on set. _tempFolderPath = Path.GetTempPath(); return; } // create the directory if it does not exist if (!Directory.Exists(value)) { Directory.CreateDirectory(value); } // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) { _tempFolderPath = value; } else { _tempFolderPath = value + Path.DirectorySeparatorChar; } } } /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public virtual string DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public virtual IDictionary<string, string> ApiKeyPrefix { get { return _apiKeyPrefix; } set { if (value == null) { throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); } _apiKeyPrefix = value; } } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public virtual IDictionary<string, string> ApiKey { get { return _apiKey; } set { if (value == null) { throw new InvalidOperationException("ApiKey collection may not be null."); } _apiKey = value; } } #endregion Properties #region Methods /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { DefaultHeader[key] = value; } /// <summary> /// Creates a new <see cref="ApiClient" /> based on this <see cref="Configuration" /> instance. /// </summary> /// <returns></returns> public ApiClient CreateApiClient() { return new ApiClient(BasePath) { Configuration = this }; } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (Cloudmersive.APIClient.NETCore.VirusScan) Debug Report:\n"; report += " OS: " + System.Environment.OSVersion + "\n"; report += " .NET Framework Version: " + System.Environment.Version + "\n"; report += " Version of the API: v1\n"; report += " SDK Package Version: 1.2.6\n"; return report; } /// <summary> /// Add Api Key Header. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> /// <returns></returns> public void AddApiKey(string key, string value) { ApiKey[key] = value; } /// <summary> /// Sets the API key prefix. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> public void AddApiKeyPrefix(string key, string value) { ApiKeyPrefix[key] = value; } #endregion Methods } }
34.385463
130
0.542886
[ "Apache-2.0" ]
CloudmersiveSupport/Cloudmersive.APIClient.NETCore.VirusScan
client/src/Cloudmersive.APIClient.NETCore.VirusScan/Client/Configuration.cs
15,611
C#
using System.Collections; using System.Collections.Generic; using Unity.Mathematics; using UnityEngine; /** * Look up for where an entity is in the world of the game board */ public static class Board { // maximum z value public static float SpikeZone = 0f; public static float TrenchZone = -170f; public static float CastleZone = -270f; public static float[] zones = new[] {SpikeZone, TrenchZone, CastleZone}; }
24.333333
76
0.719178
[ "MIT" ]
DennisSSDev/CastleStorm
Assets/Mono/GameStatics/Board.cs
440
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityCollectionReferencesRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; /// <summary> /// The interface IDeviceMemberOfCollectionReferencesRequestBuilder. /// </summary> public partial interface IDeviceMemberOfCollectionReferencesRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> IDeviceMemberOfCollectionReferencesRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IDeviceMemberOfCollectionReferencesRequest Request(IEnumerable<Option> options); } }
40.060606
153
0.606657
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IDeviceMemberOfCollectionReferencesRequestBuilder.cs
1,322
C#
// Copyright 1998-2012 Epic Games, Inc. All Rights Reserved. using UnrealBuildTool; public class AudiokineticTools : ModuleRules { #if WITH_FORWARDED_MODULE_RULES_CTOR public AudiokineticTools(ReadOnlyTargetRules Target) : base(Target) #else public AudiokineticTools(TargetInfo Target) #endif { PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; PrivateIncludePaths.Add("AudiokineticTools/Private"); PrivateIncludePathModuleNames.AddRange( new string[] { "TargetPlatform", "MainFrame", "MovieSceneTools", "LevelEditor" }); PublicIncludePathModuleNames.AddRange( new string[] { "AssetTools", "ContentBrowser", "Matinee" }); PublicDependencyModuleNames.AddRange( new string[] { "AkAudio", "Core", "InputCore", "CoreUObject", "Engine", "UnrealEd", "Slate", "SlateCore", "Matinee", "EditorStyle", "Json", "XmlParser", "WorkspaceMenuStructure", "DirectoryWatcher", "Projects", "Sequencer", "PropertyEditor" }); PrivateDependencyModuleNames.AddRange( new string[] { "MovieScene", "MovieSceneTools", "MovieSceneTracks", "MatineeToLevelSequence", "RenderCore" }); } }
24.538462
71
0.517868
[ "MIT" ]
BeatItOtaku/Eclair3
Plugins/Wwise/Source/AudiokineticTools/AudiokineticTools.Build.cs
1,595
C#
namespace JohnLBevan.EventApp.BaseInterfaces { public interface IVenue { long? Id { get; set; } bool? IsBoxOffice { get; set; } bool? IsVenue { get; set; } long? LocationId { get; set; } string Name { get; set; } string UniqueName { get; set; } } }
22.142857
44
0.548387
[ "MIT" ]
JohnLBevan/EdinburghFringe
WebApplication/JohnLBevan.EventApp.BaseInterfaces/IVenue.cs
310
C#
// ----------------------------------------------------------------------- // <copyright file="ScenarioSettingsSection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Microsoft.Store.PartnerCenter.Samples.Configuration { /// <summary> /// Holds the scenario specific settings section. /// </summary> public class ScenarioSettingsSection : Section { /// <summary> /// Initializes a new instance of the <see cref="ScenarioSettingsSection"/> class. /// </summary> public ScenarioSettingsSection() : base("ScenarioSettings") { } /// <summary> /// Gets the customer domain suffix. /// </summary> public string CustomerDomainSuffix { get { return this.ConfigurationSection["CustomerDomainSuffix"]; } } /// <summary> /// Gets the ID of the customer to delete from the TIP account. /// </summary> public string CustomerIdToDelete { get { return this.ConfigurationSection["CustomerIdToDelete"]; } } /// <summary> /// Gets the ID of the customer user to delete. /// </summary> public string CustomerUserIdToDelete { get { return this.ConfigurationSection["CustomerUserIdToDelete"]; } } /// <summary> /// Gets the ID of the directory role whose details should be read. /// </summary> public string DefaultDirectoryRoleId { get { return this.ConfigurationSection["DefaultDirectoryRoleId"]; } } /// <summary> /// Gets the ID of the user member whose details should be read. /// </summary> public string DefaultUserMemberId { get { return this.ConfigurationSection["DefaultUserMemberId"]; } } /// <summary> /// Gets the ID of the customer whose details should be read. /// </summary> public string DefaultCustomerId { get { return this.ConfigurationSection["DefaultCustomerId"]; } } /// <summary> /// Gets the configured ID of the configuration policy. /// </summary> public string DefaultConfigurationPolicyId { get { return this.ConfigurationSection["DefaultConfigurationPolicyId"]; } } /// <summary> /// Gets the configured ID of the Devices Batch. /// </summary> public string DefaultDeviceBatchId { get { return this.ConfigurationSection["DefaultDeviceBatchId"]; } } /// <summary> /// Gets the configured ID of the Device. /// </summary> public string DefaultDeviceId { get { return this.ConfigurationSection["DefaultDeviceId"]; } } /// <summary> /// Gets the configured ID of the Batch Upload Status Tracking. /// </summary> public string DefaultBatchUploadStatusTrackingId { get { return this.ConfigurationSection["DefaultBatchUploadStatusTrackingId"]; } } /// <summary> /// Gets the ID of the indirect reseller id whose details should be read. /// </summary> public string DefaultIndirectResellerId { get { return this.ConfigurationSection["DefaultIndirectResellerId"]; } } /// <summary> /// Gets the ID of the default customer user. /// </summary> public string DefaultCustomerUserId { get { return this.ConfigurationSection["DefaultCustomerUserId"]; } } /// <summary> /// Gets the number of customers to return in each customer page. /// </summary> public int CustomerPageSize { get { return int.Parse(this.ConfigurationSection["CustomerPageSize"]); } } /// <summary> /// Gets the number of customer users to return in each customer user page. /// </summary> public string CustomerUserPageSize { get { return this.ConfigurationSection["CustomerUserPageSize"]; } } /// <summary> /// Gets the number of offers to return in each offer page. /// </summary> public int DefaultOfferPageSize { get { return int.Parse(this.ConfigurationSection["DefaultOfferPageSize"]); } } /// <summary> /// Gets the number of invoices to return in each invoice page. /// </summary> public int InvoicePageSize { get { return int.Parse(this.ConfigurationSection["InvoicePageSize"]); } } /// <summary> /// Gets the configured Invoice ID. /// </summary> public string DefaultInvoiceId { get { return this.ConfigurationSection["DefaultInvoiceId"]; } } /// <summary> /// Gets the configured Receipt ID. /// </summary> public string DefaultReceiptId { get { return this.ConfigurationSection["DefaultReceiptId"]; } } /// <summary> /// Gets the configured partner MPD ID. /// </summary> public string PartnerMpnId { get { return this.ConfigurationSection["PartnerMpnId"]; } } /// <summary> /// Gets the configured offer ID. /// </summary> public string DefaultOfferId { get { return this.ConfigurationSection["DefaultOfferId"]; } } /// <summary> /// Gets the configured product ID. /// </summary> public string DefaultProductId { get { return this.ConfigurationSection["DefaultProductId"]; } } /// <summary> /// Gets the configured SKU ID. /// </summary> public string DefaultSkuId { get { return this.ConfigurationSection["DefaultSkuId"]; } } /// <summary> /// Gets the configured availability ID. /// </summary> public string DefaultAvailabilityId { get { return this.ConfigurationSection["DefaultAvailabilityId"]; } } /// <summary> /// Gets the configured order ID. /// </summary> public string DefaultOrderId { get { return this.ConfigurationSection["DefaultOrderId"]; } } /// <summary> /// Gets the configured subscription ID. /// </summary> public string DefaultSubscriptionId { get { return this.ConfigurationSection["DefaultSubscriptionId"]; } } /// <summary> /// Gets the service request ID. /// </summary> public string DefaultServiceRequestId { get { return this.ConfigurationSection["DefaultServiceRequestId"]; } } /// <summary> /// Gets the number of service requests to return in each service request page. /// </summary> public int ServiceRequestPageSize { get { return int.Parse(this.ConfigurationSection["ServiceRequestPageSize"]); } } /// <summary> /// Gets the configured agreement template ID for create new customer agreements. /// </summary> public string DefaultAgreementTemplateId { get { return this.ConfigurationSection["DefaultAgreementTemplateId"]; } } /// <summary> /// Gets the partner's user ID for creating new customer agreement. /// </summary> public string DefaultPartnerUserId { get { return this.ConfigurationSection["DefaultPartnerUserId"]; } } /// <summary> /// Gets the cart Id for an existing cart /// </summary> public string DefaultCartId { get { return this.ConfigurationSection["DefaultCartId"]; } } /// <summary> /// Gets the Quantity for updating an existing cart /// </summary> public string DefaultQuantity { get { return this.ConfigurationSection["DefaultQuantity"]; } } /// <summary> /// Gets the Catalog Item Id for an item from catalog /// </summary> public string DefaultCatalogItemId { get { return this.ConfigurationSection["DefaultCatalogItemId"]; } } /// <summary> /// Gets the scope for provisioning status /// </summary> public string DefaultScope { get { return this.ConfigurationSection["DefaultScope"]; } } /// <summary> /// Gets the Azure Subscription Id for provision status /// </summary> public string DefaultAzureSubscriptionId { get { return this.ConfigurationSection["DefaultAzureSubscriptionId"]; } } /// <summary> /// Gets the BillingCycle for creating a cart /// </summary> public string DefaultBillingCycle { get { return this.ConfigurationSection["DefaultBillingCycle"]; } } /// <summary> /// Gets the customer agreements file name. /// </summary> public string DefaultCustomerAgreementCsvFileName { get { return this.ConfigurationSection["DefaultCustomerAgreementCsvFileName"]; } } /// <summary> /// Gets the configured Currency code. /// </summary> public string DefaultCurrencyCode { get { return this.ConfigurationSection["DefaultCurrencyCode"]; } } /// <summary> /// Gets the default renewal term duration. /// </summary> public string DefaultRenewalTermDuration { get { return this.ConfigurationSection["DefaultRenewalTermDuration"]; } } } }
26.531963
90
0.482489
[ "MIT" ]
FrankieTF/Partner-Center-DotNet-Samples
sdk/SdkSamples/Configuration/ScenarioSettingsSection.cs
11,623
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:00:43 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using go; #nullable enable namespace go { namespace cmd { namespace vendor { namespace golang.org { namespace x { namespace sys { public static partial class unix_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct BpfHdr { // Constructors public BpfHdr(NilType _) { this.Tstamp = default; this.Caplen = default; this.Datalen = default; this.Hdrlen = default; this.Pad_cgo_0 = default; } public BpfHdr(BpfTimeval Tstamp = default, uint Caplen = default, uint Datalen = default, ushort Hdrlen = default, array<byte> Pad_cgo_0 = default) { this.Tstamp = Tstamp; this.Caplen = Caplen; this.Datalen = Datalen; this.Hdrlen = Hdrlen; this.Pad_cgo_0 = Pad_cgo_0; } // Enable comparisons between nil and BpfHdr struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(BpfHdr value, NilType nil) => value.Equals(default(BpfHdr)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(BpfHdr value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, BpfHdr value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, BpfHdr value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator BpfHdr(NilType nil) => default(BpfHdr); } [GeneratedCode("go2cs", "0.1.0.0")] public static BpfHdr BpfHdr_cast(dynamic value) { return new BpfHdr(value.Tstamp, value.Caplen, value.Datalen, value.Hdrlen, value.Pad_cgo_0); } } }}}}}}
34.283784
159
0.579819
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/vendor/golang.org/x/sys/unix/ztypes_netbsd_386_BpfHdrStruct.cs
2,537
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.Cx.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTestCasesClientTest { [xunit::FactAttribute] public void BatchDeleteTestCasesRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCaseNames = { TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); client.BatchDeleteTestCases(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteTestCasesRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCaseNames = { TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }, }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteTestCasesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteTestCasesAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteTestCases() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); client.BatchDeleteTestCases(request.Parent); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteTestCasesAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteTestCasesAsync(request.Parent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteTestCasesAsync(request.Parent, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchDeleteTestCasesResourceNames() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCases(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); client.BatchDeleteTestCases(request.ParentAsAgentName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchDeleteTestCasesResourceNamesAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchDeleteTestCasesRequest request = new BatchDeleteTestCasesRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.BatchDeleteTestCasesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); await client.BatchDeleteTestCasesAsync(request.ParentAsAgentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.BatchDeleteTestCasesAsync(request.ParentAsAgentName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCaseRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.GetTestCase(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.GetTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.GetTestCaseAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCase() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.GetTestCase(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.GetTestCaseAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.GetTestCaseAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCaseResourceNames() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.GetTestCase(request.TestCaseName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseResourceNamesAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseRequest request = new GetTestCaseRequest { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.GetTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.GetTestCaseAsync(request.TestCaseName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.GetTestCaseAsync(request.TestCaseName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTestCaseRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.CreateTestCase(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTestCaseRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.CreateTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.CreateTestCaseAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTestCase() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.CreateTestCase(request.Parent, request.TestCase); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTestCaseAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.CreateTestCaseAsync(request.Parent, request.TestCase, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.CreateTestCaseAsync(request.Parent, request.TestCase, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTestCaseResourceNames() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.CreateTestCase(request.ParentAsAgentName, request.TestCase); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTestCaseResourceNamesAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTestCaseRequest request = new CreateTestCaseRequest { ParentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), TestCase = new TestCase(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.CreateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.CreateTestCaseAsync(request.ParentAsAgentName, request.TestCase, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.CreateTestCaseAsync(request.ParentAsAgentName, request.TestCase, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTestCaseRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTestCaseRequest request = new UpdateTestCaseRequest { TestCase = new TestCase(), UpdateMask = new wkt::FieldMask(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.UpdateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.UpdateTestCase(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTestCaseRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTestCaseRequest request = new UpdateTestCaseRequest { TestCase = new TestCase(), UpdateMask = new wkt::FieldMask(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.UpdateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.UpdateTestCaseAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.UpdateTestCaseAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTestCase() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTestCaseRequest request = new UpdateTestCaseRequest { TestCase = new TestCase(), UpdateMask = new wkt::FieldMask(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.UpdateTestCase(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase response = client.UpdateTestCase(request.TestCase, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTestCaseAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTestCaseRequest request = new UpdateTestCaseRequest { TestCase = new TestCase(), UpdateMask = new wkt::FieldMask(), }; TestCase expectedResponse = new TestCase { TestCaseName = TestCaseName.FromProjectLocationAgentTestCase("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]"), Tags = { "tags52c47ad5", }, DisplayName = "display_name137f65c2", Notes = "notes00b55843", TestCaseConversationTurns = { new ConversationTurn(), }, CreationTime = new wkt::Timestamp(), LastTestResult = new TestCaseResult(), TestConfig = new TestConfig(), }; mockGrpcClient.Setup(x => x.UpdateTestCaseAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCase>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCase responseCallSettings = await client.UpdateTestCaseAsync(request.TestCase, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCase responseCancellationToken = await client.UpdateTestCaseAsync(request.TestCase, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CalculateCoverageRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CalculateCoverageRequest request = new CalculateCoverageRequest { Type = CalculateCoverageRequest.Types.CoverageType.TransitionRouteGroup, AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; CalculateCoverageResponse expectedResponse = new CalculateCoverageResponse { IntentCoverage = new IntentCoverage(), TransitionCoverage = new TransitionCoverage(), AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), RouteGroupCoverage = new TransitionRouteGroupCoverage(), }; mockGrpcClient.Setup(x => x.CalculateCoverage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); CalculateCoverageResponse response = client.CalculateCoverage(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CalculateCoverageRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CalculateCoverageRequest request = new CalculateCoverageRequest { Type = CalculateCoverageRequest.Types.CoverageType.TransitionRouteGroup, AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), }; CalculateCoverageResponse expectedResponse = new CalculateCoverageResponse { IntentCoverage = new IntentCoverage(), TransitionCoverage = new TransitionCoverage(), AgentAsAgentName = AgentName.FromProjectLocationAgent("[PROJECT]", "[LOCATION]", "[AGENT]"), RouteGroupCoverage = new TransitionRouteGroupCoverage(), }; mockGrpcClient.Setup(x => x.CalculateCoverageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<CalculateCoverageResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); CalculateCoverageResponse responseCallSettings = await client.CalculateCoverageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); CalculateCoverageResponse responseCancellationToken = await client.CalculateCoverageAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCaseResultRequestObject() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult response = client.GetTestCaseResult(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseResultRequestObjectAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCaseResult() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult response = client.GetTestCaseResult(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseResultAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTestCaseResultResourceNames() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResult(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult response = client.GetTestCaseResult(request.TestCaseResultName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTestCaseResultResourceNamesAsync() { moq::Mock<TestCases.TestCasesClient> mockGrpcClient = new moq::Mock<TestCases.TestCasesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTestCaseResultRequest request = new GetTestCaseResultRequest { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), }; TestCaseResult expectedResponse = new TestCaseResult { TestCaseResultName = TestCaseResultName.FromProjectLocationAgentTestCaseResult("[PROJECT]", "[LOCATION]", "[AGENT]", "[TEST_CASE]", "[RESULT]"), EnvironmentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), ConversationTurns = { new ConversationTurn(), }, TestResult = TestResult.Failed, TestTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetTestCaseResultAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestCaseResult>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TestCasesClient client = new TestCasesClientImpl(mockGrpcClient.Object, null); TestCaseResult responseCallSettings = await client.GetTestCaseResultAsync(request.TestCaseResultName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestCaseResult responseCancellationToken = await client.GetTestCaseResultAsync(request.TestCaseResultName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
60.514484
242
0.636872
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Dialogflow.Cx.V3/Google.Cloud.Dialogflow.Cx.V3.Tests/TestCasesClientTest.g.cs
52,224
C#
using System; namespace ProcessorCSV.API { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.5625
69
0.606061
[ "MIT" ]
sinspeel/ProcessorCSV
ProcessorCSV.API/WeatherForecast.cs
297
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class InterractionManager : MonoBehaviour { public static InterractionManager instance; /* public delegate void acteurInScene(); protected static event acteurInScene OnActeurInScene; */ public bool actorIsInScene; private void Awake() { instance = this; } public virtual void SetChoicesRoom(List<int> choices) { } public virtual void LaunchNextScene() { } public virtual GameObject GetLeaves() { return null; } public virtual List<int> GetChoices() { return null; } public virtual void LaunchGoodOutro() { } public virtual void LaunchBadOutro() { } }
14.722222
57
0.631447
[ "Apache-2.0" ]
thomasjl/Contes_RVTeam
Unity/Contes_RVTeam/Assets/Props/InterractionManager.cs
797
C#
namespace _04AddMinion { using System; using System.Data.SqlClient; using System.Linq; using _01InitialSetup; public class StartUp { public static void Main() { var minionInfo = Console.ReadLine() .Split(new string[] { "Minion: ", " " }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); var minionName = minionInfo[0]; var minionAge = int.Parse(minionInfo[1]); var minionTown = minionInfo[2]; var villainName = Console.ReadLine() .Split("Villain: ", StringSplitOptions.RemoveEmptyEntries) .ToArray()[0]; using (var connection = new SqlConnection(Configuration.ConnectionString)) { connection.Open(); int? townId = GetTownIdByName(connection, minionTown); if (townId == null) { Insert(connection, Queries.InsertTown, "@townName", minionTown); Console.WriteLine($"Town {minionTown} was added to the database."); } townId = GetTownIdByName(connection, minionTown); InsertMinion(connection, minionName, minionAge, townId); int? villainId = GetVillainIdByName(connection, villainName); if (villainId == null) { Insert(connection, Queries.InsertVillain, "@villainName", villainName); Console.WriteLine($"Villain {villainName} was added to the database."); } villainId = GetVillainIdByName(connection, villainName); var minionId = GetMinionIdByName(connection, minionName); InsertMinionToVillain(connection, villainId, minionId); Console.WriteLine($"Successfully added {minionName} to be minion of {villainName}."); } } private static int GetMinionIdByName(SqlConnection connection, string minionName) { using var command = new SqlCommand(Queries.MinionId, connection); command.Parameters.AddWithValue("@Name", minionName); return (int)command.ExecuteScalar(); } private static int? GetVillainIdByName(SqlConnection connection, string villainName) { using var command = new SqlCommand(Queries.VillainId, connection); command.Parameters.AddWithValue("@Name", villainName); return (int?)command.ExecuteScalar(); } private static int? GetTownIdByName(SqlConnection connection, string minionTown) { using var command = new SqlCommand(Queries.TownId, connection); command.Parameters.AddWithValue("@townName", minionTown); return (int?)command.ExecuteScalar(); } private static void InsertMinionToVillain(SqlConnection connection, int? villainId, int minionId) { using var command = new SqlCommand(Queries.InsertMinionsVillains, connection); command.Parameters.AddWithValue("@villainId", villainId); command.Parameters.AddWithValue("@minionId", minionId); command.ExecuteNonQuery(); } private static void InsertMinion(SqlConnection connection, string minionName, int minionAge, int? townId) { using var command = new SqlCommand(Queries.InsertMinion, connection); command.Parameters.AddWithValue("@name", minionName); command.Parameters.AddWithValue("@age", minionAge); command.Parameters.AddWithValue("@townId", townId); command.ExecuteNonQuery(); } private static void Insert(SqlConnection connection, string query, string paramName, string paramValue) { using var command = new SqlCommand(query, connection); command.Parameters.AddWithValue(paramName, paramValue); command.ExecuteNonQuery(); } } }
34.726496
113
0.602757
[ "MIT" ]
kalintsenkov/SoftUni-Software-Engineering
CSharp-DB/Databases-Advanced/Homeworks/01AdoNetIntroduction/04AddMinion/StartUp.cs
4,065
C#
// Copyright 2013-2019 Automatak, LLC // // Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak // LLC (www.automatak.com) under one or more contributor license agreements. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. Green Energy Corp and Automatak LLC license // this file to you under the Apache License, Version 2.0 (the "License"); you // may not use this file except in compliance with the License. You may obtain // a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Automatak.DNP3.Interface { /// <summary> /// A communication channel to which DNP3 masters / outstation can be attached /// </summary> public interface IChannel { /// <summary> /// Retrieves the current log filters /// </summary> /// <returns>A structure representing the currently enabled filters</returns> LogFilter GetLogFilters(); /// <summary> /// Set the log filters to a new value /// </summary> /// <param name="filters">A structure representing the new set of enabled filters</param> void SetLogFilters(LogFilter filters); /// <summary> /// Read the channel statistics /// </summary> /// <returns>The current statistics for the channel</returns> IChannelStatistics GetChannelStatistics(); /// <summary> /// Adds a master stack to the channel /// </summary> /// <param name="id">name of the logger that will be assigned to this stack</param> /// <param name="publisher">Where measurements will be sent as they are received from the outstation</param> /// <param name="application">master application instance</param> /// <param name="config">configuration information for the master stack</param> /// <returns>reference to the created master</returns> IMaster AddMaster(String id, ISOEHandler publisher, IMasterApplication application, MasterStackConfig config); /// <summary> /// Adds an outstation to the channel /// </summary> /// <param name="id">name of the logger that will be assigned to this stack</param> /// <param name="commandHandler">where command requests are sent to be handled in application code</param> /// <param name="application">outstation application instance</param> /// <param name="config">configuration information for the outstation stack</param> /// <returns>reference to the created outstation</returns> IOutstation AddOutstation(String id, ICommandHandler commandHandler, IOutstationApplication application, OutstationStackConfig config); /// <summary> /// Shutdown the channel and all stacks that have been added. Calling shutdown more than once or /// continuing to use child objects (masters/outstations) after calling shutdown can cause a failure. /// </summary> void Shutdown(); } }
45.74026
145
0.681147
[ "Apache-2.0" ]
JakeChow/DNP
dotnet/CLRInterface/src/IChannel.cs
3,522
C#
using Meadow; using System.Threading; namespace ICs.IOExpanders.Pca9685_Sample { class Program { static IApp app; public static void Main(string[] args) { if (args.Length > 0 && args[0] == "--exitOnDebug") return; // instantiate and run new meadow app app = new MeadowApp(); Thread.Sleep(Timeout.Infinite); } } }
20.45
70
0.557457
[ "Apache-2.0" ]
WildernessLabs/Meadow.Foundation
Source/Meadow.Foundation.Peripherals/ICs.IOExpanders.Pca9685/Samples/ICs.IOExpanders.Pca9685_Sample/Program.cs
411
C#
using System; using UnityEngine; namespace HeathenEngineering.Scriptable { [Serializable] public class CameraReference : VariableReference<Camera> { public CameraPointerVariable Variable; public override IDataVariable<Camera> m_variable => Variable; public CameraReference(Camera value) : base(value) { } } }
22.5
69
0.7
[ "MIT" ]
TH3UNKN0WN-1337/Heathen-System-Core
Assets/_Heathen Engineering/SystemsCore/Framework/Scriptable/Data Types/Camera/CameraReference.cs
362
C#
using System; using System.Collections.Generic; using Hl7.Fhir.Introspection; using Hl7.Fhir.Validation; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Utility; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma warning disable 1591 // suppress XML summary warnings // // Generated for FHIR v1.0.2 // namespace Hl7.Fhir.Model { /// <summary> /// Prescription of medication to for patient /// </summary> [FhirType("MedicationOrder", IsResource=true)] [DataContract] public partial class MedicationOrder : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged { [NotMapped] public override ResourceType ResourceType { get { return ResourceType.MedicationOrder; } } [NotMapped] public override string TypeName { get { return "MedicationOrder"; } } /// <summary> /// A code specifying the state of the prescribing event. Describes the lifecycle of the prescription. /// (url: http://hl7.org/fhir/ValueSet/medication-order-status) /// </summary> [FhirEnumeration("MedicationOrderStatus")] public enum MedicationOrderStatus { /// <summary> /// The prescription is 'actionable', but not all actions that are implied by it have occurred yet. /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("active", "http://hl7.org/fhir/medication-order-status"), Description("Active")] Active, /// <summary> /// Actions implied by the prescription are to be temporarily halted, but are expected to continue later. May also be called "suspended". /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("on-hold", "http://hl7.org/fhir/medication-order-status"), Description("On Hold")] OnHold, /// <summary> /// All actions that are implied by the prescription have occurred. /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("completed", "http://hl7.org/fhir/medication-order-status"), Description("Completed")] Completed, /// <summary> /// The prescription was entered in error. /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("entered-in-error", "http://hl7.org/fhir/medication-order-status"), Description("Entered In Error")] EnteredInError, /// <summary> /// Actions implied by the prescription are to be permanently halted, before all of them occurred. /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("stopped", "http://hl7.org/fhir/medication-order-status"), Description("Stopped")] Stopped, /// <summary> /// The prescription is not yet 'actionable', i.e. it is a work in progress, requires sign-off or verification, and needs to be run through decision support process. /// (system: http://hl7.org/fhir/medication-order-status) /// </summary> [EnumLiteral("draft", "http://hl7.org/fhir/medication-order-status"), Description("Draft")] Draft, } [FhirType("DosageInstructionComponent")] [DataContract] public partial class DosageInstructionComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement { [NotMapped] public override string TypeName { get { return "DosageInstructionComponent"; } } /// <summary> /// Dosage instructions expressed as text /// </summary> [FhirElement("text", InSummary=true, Order=40)] [DataMember] public Hl7.Fhir.Model.FhirString TextElement { get { return _TextElement; } set { _TextElement = value; OnPropertyChanged("TextElement"); } } private Hl7.Fhir.Model.FhirString _TextElement; /// <summary> /// Dosage instructions expressed as text /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Text { get { return TextElement != null ? TextElement.Value : null; } set { if (value == null) TextElement = null; else TextElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Text"); } } /// <summary> /// Supplemental instructions - e.g. "with meals" /// </summary> [FhirElement("additionalInstructions", InSummary=true, Order=50)] [DataMember] public Hl7.Fhir.Model.CodeableConcept AdditionalInstructions { get { return _AdditionalInstructions; } set { _AdditionalInstructions = value; OnPropertyChanged("AdditionalInstructions"); } } private Hl7.Fhir.Model.CodeableConcept _AdditionalInstructions; /// <summary> /// When medication should be administered /// </summary> [FhirElement("timing", InSummary=true, Order=60)] [DataMember] public Hl7.Fhir.Model.Timing Timing { get { return _Timing; } set { _Timing = value; OnPropertyChanged("Timing"); } } private Hl7.Fhir.Model.Timing _Timing; /// <summary> /// Take "as needed" (for x) /// </summary> [FhirElement("asNeeded", InSummary=true, Order=70, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.FhirBoolean),typeof(Hl7.Fhir.Model.CodeableConcept))] [DataMember] public Hl7.Fhir.Model.Element AsNeeded { get { return _AsNeeded; } set { _AsNeeded = value; OnPropertyChanged("AsNeeded"); } } private Hl7.Fhir.Model.Element _AsNeeded; /// <summary> /// Body site to administer to /// </summary> [FhirElement("site", InSummary=true, Order=80, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.Element Site { get { return _Site; } set { _Site = value; OnPropertyChanged("Site"); } } private Hl7.Fhir.Model.Element _Site; /// <summary> /// How drug should enter body /// </summary> [FhirElement("route", InSummary=true, Order=90)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Route { get { return _Route; } set { _Route = value; OnPropertyChanged("Route"); } } private Hl7.Fhir.Model.CodeableConcept _Route; /// <summary> /// Technique for administering medication /// </summary> [FhirElement("method", InSummary=true, Order=100)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Method { get { return _Method; } set { _Method = value; OnPropertyChanged("Method"); } } private Hl7.Fhir.Model.CodeableConcept _Method; /// <summary> /// Amount of medication per dose /// </summary> [FhirElement("dose", InSummary=true, Order=110, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Range),typeof(Hl7.Fhir.Model.SimpleQuantity))] [DataMember] public Hl7.Fhir.Model.Element Dose { get { return _Dose; } set { _Dose = value; OnPropertyChanged("Dose"); } } private Hl7.Fhir.Model.Element _Dose; /// <summary> /// Amount of medication per unit of time /// </summary> [FhirElement("rate", InSummary=true, Order=120, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Ratio),typeof(Hl7.Fhir.Model.Range))] [DataMember] public Hl7.Fhir.Model.Element Rate { get { return _Rate; } set { _Rate = value; OnPropertyChanged("Rate"); } } private Hl7.Fhir.Model.Element _Rate; /// <summary> /// Upper limit on medication per unit of time /// </summary> [FhirElement("maxDosePerPeriod", InSummary=true, Order=130)] [DataMember] public Hl7.Fhir.Model.Ratio MaxDosePerPeriod { get { return _MaxDosePerPeriod; } set { _MaxDosePerPeriod = value; OnPropertyChanged("MaxDosePerPeriod"); } } private Hl7.Fhir.Model.Ratio _MaxDosePerPeriod; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as DosageInstructionComponent; if (dest != null) { base.CopyTo(dest); if(TextElement != null) dest.TextElement = (Hl7.Fhir.Model.FhirString)TextElement.DeepCopy(); if(AdditionalInstructions != null) dest.AdditionalInstructions = (Hl7.Fhir.Model.CodeableConcept)AdditionalInstructions.DeepCopy(); if(Timing != null) dest.Timing = (Hl7.Fhir.Model.Timing)Timing.DeepCopy(); if(AsNeeded != null) dest.AsNeeded = (Hl7.Fhir.Model.Element)AsNeeded.DeepCopy(); if(Site != null) dest.Site = (Hl7.Fhir.Model.Element)Site.DeepCopy(); if(Route != null) dest.Route = (Hl7.Fhir.Model.CodeableConcept)Route.DeepCopy(); if(Method != null) dest.Method = (Hl7.Fhir.Model.CodeableConcept)Method.DeepCopy(); if(Dose != null) dest.Dose = (Hl7.Fhir.Model.Element)Dose.DeepCopy(); if(Rate != null) dest.Rate = (Hl7.Fhir.Model.Element)Rate.DeepCopy(); if(MaxDosePerPeriod != null) dest.MaxDosePerPeriod = (Hl7.Fhir.Model.Ratio)MaxDosePerPeriod.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new DosageInstructionComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as DosageInstructionComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(TextElement, otherT.TextElement)) return false; if( !DeepComparable.Matches(AdditionalInstructions, otherT.AdditionalInstructions)) return false; if( !DeepComparable.Matches(Timing, otherT.Timing)) return false; if( !DeepComparable.Matches(AsNeeded, otherT.AsNeeded)) return false; if( !DeepComparable.Matches(Site, otherT.Site)) return false; if( !DeepComparable.Matches(Route, otherT.Route)) return false; if( !DeepComparable.Matches(Method, otherT.Method)) return false; if( !DeepComparable.Matches(Dose, otherT.Dose)) return false; if( !DeepComparable.Matches(Rate, otherT.Rate)) return false; if( !DeepComparable.Matches(MaxDosePerPeriod, otherT.MaxDosePerPeriod)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as DosageInstructionComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(TextElement, otherT.TextElement)) return false; if( !DeepComparable.IsExactly(AdditionalInstructions, otherT.AdditionalInstructions)) return false; if( !DeepComparable.IsExactly(Timing, otherT.Timing)) return false; if( !DeepComparable.IsExactly(AsNeeded, otherT.AsNeeded)) return false; if( !DeepComparable.IsExactly(Site, otherT.Site)) return false; if( !DeepComparable.IsExactly(Route, otherT.Route)) return false; if( !DeepComparable.IsExactly(Method, otherT.Method)) return false; if( !DeepComparable.IsExactly(Dose, otherT.Dose)) return false; if( !DeepComparable.IsExactly(Rate, otherT.Rate)) return false; if( !DeepComparable.IsExactly(MaxDosePerPeriod, otherT.MaxDosePerPeriod)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (TextElement != null) yield return TextElement; if (AdditionalInstructions != null) yield return AdditionalInstructions; if (Timing != null) yield return Timing; if (AsNeeded != null) yield return AsNeeded; if (Site != null) yield return Site; if (Route != null) yield return Route; if (Method != null) yield return Method; if (Dose != null) yield return Dose; if (Rate != null) yield return Rate; if (MaxDosePerPeriod != null) yield return MaxDosePerPeriod; } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (TextElement != null) yield return new ElementValue("text", TextElement); if (AdditionalInstructions != null) yield return new ElementValue("additionalInstructions", AdditionalInstructions); if (Timing != null) yield return new ElementValue("timing", Timing); if (AsNeeded != null) yield return new ElementValue("asNeeded", AsNeeded); if (Site != null) yield return new ElementValue("site", Site); if (Route != null) yield return new ElementValue("route", Route); if (Method != null) yield return new ElementValue("method", Method); if (Dose != null) yield return new ElementValue("dose", Dose); if (Rate != null) yield return new ElementValue("rate", Rate); if (MaxDosePerPeriod != null) yield return new ElementValue("maxDosePerPeriod", MaxDosePerPeriod); } } } [FhirType("DispenseRequestComponent")] [DataContract] public partial class DispenseRequestComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement { [NotMapped] public override string TypeName { get { return "DispenseRequestComponent"; } } /// <summary> /// Product to be supplied /// </summary> [FhirElement("medication", InSummary=true, Order=40, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.Element Medication { get { return _Medication; } set { _Medication = value; OnPropertyChanged("Medication"); } } private Hl7.Fhir.Model.Element _Medication; /// <summary> /// Time period supply is authorized for /// </summary> [FhirElement("validityPeriod", InSummary=true, Order=50)] [DataMember] public Hl7.Fhir.Model.Period ValidityPeriod { get { return _ValidityPeriod; } set { _ValidityPeriod = value; OnPropertyChanged("ValidityPeriod"); } } private Hl7.Fhir.Model.Period _ValidityPeriod; /// <summary> /// Number of refills authorized /// </summary> [FhirElement("numberOfRepeatsAllowed", InSummary=true, Order=60)] [DataMember] public Hl7.Fhir.Model.PositiveInt NumberOfRepeatsAllowedElement { get { return _NumberOfRepeatsAllowedElement; } set { _NumberOfRepeatsAllowedElement = value; OnPropertyChanged("NumberOfRepeatsAllowedElement"); } } private Hl7.Fhir.Model.PositiveInt _NumberOfRepeatsAllowedElement; /// <summary> /// Number of refills authorized /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public int? NumberOfRepeatsAllowed { get { return NumberOfRepeatsAllowedElement != null ? NumberOfRepeatsAllowedElement.Value : null; } set { if (!value.HasValue) NumberOfRepeatsAllowedElement = null; else NumberOfRepeatsAllowedElement = new Hl7.Fhir.Model.PositiveInt(value); OnPropertyChanged("NumberOfRepeatsAllowed"); } } /// <summary> /// Amount of medication to supply per dispense /// </summary> [FhirElement("quantity", InSummary=true, Order=70)] [DataMember] public Hl7.Fhir.Model.SimpleQuantity Quantity { get { return _Quantity; } set { _Quantity = value; OnPropertyChanged("Quantity"); } } private Hl7.Fhir.Model.SimpleQuantity _Quantity; /// <summary> /// Number of days supply per dispense /// </summary> [FhirElement("expectedSupplyDuration", InSummary=true, Order=80)] [DataMember] public Hl7.Fhir.Model.Duration ExpectedSupplyDuration { get { return _ExpectedSupplyDuration; } set { _ExpectedSupplyDuration = value; OnPropertyChanged("ExpectedSupplyDuration"); } } private Hl7.Fhir.Model.Duration _ExpectedSupplyDuration; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as DispenseRequestComponent; if (dest != null) { base.CopyTo(dest); if(Medication != null) dest.Medication = (Hl7.Fhir.Model.Element)Medication.DeepCopy(); if(ValidityPeriod != null) dest.ValidityPeriod = (Hl7.Fhir.Model.Period)ValidityPeriod.DeepCopy(); if(NumberOfRepeatsAllowedElement != null) dest.NumberOfRepeatsAllowedElement = (Hl7.Fhir.Model.PositiveInt)NumberOfRepeatsAllowedElement.DeepCopy(); if(Quantity != null) dest.Quantity = (Hl7.Fhir.Model.SimpleQuantity)Quantity.DeepCopy(); if(ExpectedSupplyDuration != null) dest.ExpectedSupplyDuration = (Hl7.Fhir.Model.Duration)ExpectedSupplyDuration.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new DispenseRequestComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as DispenseRequestComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Medication, otherT.Medication)) return false; if( !DeepComparable.Matches(ValidityPeriod, otherT.ValidityPeriod)) return false; if( !DeepComparable.Matches(NumberOfRepeatsAllowedElement, otherT.NumberOfRepeatsAllowedElement)) return false; if( !DeepComparable.Matches(Quantity, otherT.Quantity)) return false; if( !DeepComparable.Matches(ExpectedSupplyDuration, otherT.ExpectedSupplyDuration)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as DispenseRequestComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Medication, otherT.Medication)) return false; if( !DeepComparable.IsExactly(ValidityPeriod, otherT.ValidityPeriod)) return false; if( !DeepComparable.IsExactly(NumberOfRepeatsAllowedElement, otherT.NumberOfRepeatsAllowedElement)) return false; if( !DeepComparable.IsExactly(Quantity, otherT.Quantity)) return false; if( !DeepComparable.IsExactly(ExpectedSupplyDuration, otherT.ExpectedSupplyDuration)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Medication != null) yield return Medication; if (ValidityPeriod != null) yield return ValidityPeriod; if (NumberOfRepeatsAllowedElement != null) yield return NumberOfRepeatsAllowedElement; if (Quantity != null) yield return Quantity; if (ExpectedSupplyDuration != null) yield return ExpectedSupplyDuration; } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Medication != null) yield return new ElementValue("medication", Medication); if (ValidityPeriod != null) yield return new ElementValue("validityPeriod", ValidityPeriod); if (NumberOfRepeatsAllowedElement != null) yield return new ElementValue("numberOfRepeatsAllowed", NumberOfRepeatsAllowedElement); if (Quantity != null) yield return new ElementValue("quantity", Quantity); if (ExpectedSupplyDuration != null) yield return new ElementValue("expectedSupplyDuration", ExpectedSupplyDuration); } } } [FhirType("SubstitutionComponent")] [DataContract] public partial class SubstitutionComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged, IBackboneElement { [NotMapped] public override string TypeName { get { return "SubstitutionComponent"; } } /// <summary> /// generic | formulary + /// </summary> [FhirElement("type", InSummary=true, Order=40)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Type { get { return _Type; } set { _Type = value; OnPropertyChanged("Type"); } } private Hl7.Fhir.Model.CodeableConcept _Type; /// <summary> /// Why should (not) substitution be made /// </summary> [FhirElement("reason", InSummary=true, Order=50)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Reason { get { return _Reason; } set { _Reason = value; OnPropertyChanged("Reason"); } } private Hl7.Fhir.Model.CodeableConcept _Reason; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as SubstitutionComponent; if (dest != null) { base.CopyTo(dest); if(Type != null) dest.Type = (Hl7.Fhir.Model.CodeableConcept)Type.DeepCopy(); if(Reason != null) dest.Reason = (Hl7.Fhir.Model.CodeableConcept)Reason.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new SubstitutionComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as SubstitutionComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Type, otherT.Type)) return false; if( !DeepComparable.Matches(Reason, otherT.Reason)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as SubstitutionComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Type, otherT.Type)) return false; if( !DeepComparable.IsExactly(Reason, otherT.Reason)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (Type != null) yield return Type; if (Reason != null) yield return Reason; } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (Type != null) yield return new ElementValue("type", Type); if (Reason != null) yield return new ElementValue("reason", Reason); } } } /// <summary> /// External identifier /// </summary> [FhirElement("identifier", InSummary=true, Order=90)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Identifier> Identifier { get { if(_Identifier==null) _Identifier = new List<Hl7.Fhir.Model.Identifier>(); return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private List<Hl7.Fhir.Model.Identifier> _Identifier; /// <summary> /// When prescription was authorized /// </summary> [FhirElement("dateWritten", InSummary=true, Order=100)] [DataMember] public Hl7.Fhir.Model.FhirDateTime DateWrittenElement { get { return _DateWrittenElement; } set { _DateWrittenElement = value; OnPropertyChanged("DateWrittenElement"); } } private Hl7.Fhir.Model.FhirDateTime _DateWrittenElement; /// <summary> /// When prescription was authorized /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string DateWritten { get { return DateWrittenElement != null ? DateWrittenElement.Value : null; } set { if (value == null) DateWrittenElement = null; else DateWrittenElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("DateWritten"); } } /// <summary> /// active | on-hold | completed | entered-in-error | stopped | draft /// </summary> [FhirElement("status", InSummary=true, Order=110)] [DataMember] public Code<Hl7.Fhir.Model.MedicationOrder.MedicationOrderStatus> StatusElement { get { return _StatusElement; } set { _StatusElement = value; OnPropertyChanged("StatusElement"); } } private Code<Hl7.Fhir.Model.MedicationOrder.MedicationOrderStatus> _StatusElement; /// <summary> /// active | on-hold | completed | entered-in-error | stopped | draft /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.MedicationOrder.MedicationOrderStatus? Status { get { return StatusElement != null ? StatusElement.Value : null; } set { if (!value.HasValue) StatusElement = null; else StatusElement = new Code<Hl7.Fhir.Model.MedicationOrder.MedicationOrderStatus>(value); OnPropertyChanged("Status"); } } /// <summary> /// When prescription was stopped /// </summary> [FhirElement("dateEnded", InSummary=true, Order=120)] [DataMember] public Hl7.Fhir.Model.FhirDateTime DateEndedElement { get { return _DateEndedElement; } set { _DateEndedElement = value; OnPropertyChanged("DateEndedElement"); } } private Hl7.Fhir.Model.FhirDateTime _DateEndedElement; /// <summary> /// When prescription was stopped /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string DateEnded { get { return DateEndedElement != null ? DateEndedElement.Value : null; } set { if (value == null) DateEndedElement = null; else DateEndedElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("DateEnded"); } } /// <summary> /// Why prescription was stopped /// </summary> [FhirElement("reasonEnded", InSummary=true, Order=130)] [DataMember] public Hl7.Fhir.Model.CodeableConcept ReasonEnded { get { return _ReasonEnded; } set { _ReasonEnded = value; OnPropertyChanged("ReasonEnded"); } } private Hl7.Fhir.Model.CodeableConcept _ReasonEnded; /// <summary> /// Who prescription is for /// </summary> [FhirElement("patient", InSummary=true, Order=140)] [CLSCompliant(false)] [References("Patient")] [DataMember] public Hl7.Fhir.Model.ResourceReference Patient { get { return _Patient; } set { _Patient = value; OnPropertyChanged("Patient"); } } private Hl7.Fhir.Model.ResourceReference _Patient; /// <summary> /// Who ordered the medication(s) /// </summary> [FhirElement("prescriber", InSummary=true, Order=150)] [CLSCompliant(false)] [References("Practitioner")] [DataMember] public Hl7.Fhir.Model.ResourceReference Prescriber { get { return _Prescriber; } set { _Prescriber = value; OnPropertyChanged("Prescriber"); } } private Hl7.Fhir.Model.ResourceReference _Prescriber; /// <summary> /// Created during encounter/admission/stay /// </summary> [FhirElement("encounter", InSummary=true, Order=160)] [CLSCompliant(false)] [References("Encounter")] [DataMember] public Hl7.Fhir.Model.ResourceReference Encounter { get { return _Encounter; } set { _Encounter = value; OnPropertyChanged("Encounter"); } } private Hl7.Fhir.Model.ResourceReference _Encounter; /// <summary> /// Reason or indication for writing the prescription /// </summary> [FhirElement("reason", InSummary=true, Order=170, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [DataMember] public Hl7.Fhir.Model.Element Reason { get { return _Reason; } set { _Reason = value; OnPropertyChanged("Reason"); } } private Hl7.Fhir.Model.Element _Reason; /// <summary> /// Information about the prescription /// </summary> [FhirElement("note", InSummary=true, Order=180)] [DataMember] public Hl7.Fhir.Model.FhirString NoteElement { get { return _NoteElement; } set { _NoteElement = value; OnPropertyChanged("NoteElement"); } } private Hl7.Fhir.Model.FhirString _NoteElement; /// <summary> /// Information about the prescription /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Note { get { return NoteElement != null ? NoteElement.Value : null; } set { if (value == null) NoteElement = null; else NoteElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Note"); } } /// <summary> /// Medication to be taken /// </summary> [FhirElement("medication", InSummary=true, Order=190, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.CodeableConcept),typeof(Hl7.Fhir.Model.ResourceReference))] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Element Medication { get { return _Medication; } set { _Medication = value; OnPropertyChanged("Medication"); } } private Hl7.Fhir.Model.Element _Medication; /// <summary> /// How medication should be taken /// </summary> [FhirElement("dosageInstruction", InSummary=true, Order=200)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.MedicationOrder.DosageInstructionComponent> DosageInstruction { get { if(_DosageInstruction==null) _DosageInstruction = new List<Hl7.Fhir.Model.MedicationOrder.DosageInstructionComponent>(); return _DosageInstruction; } set { _DosageInstruction = value; OnPropertyChanged("DosageInstruction"); } } private List<Hl7.Fhir.Model.MedicationOrder.DosageInstructionComponent> _DosageInstruction; /// <summary> /// Medication supply authorization /// </summary> [FhirElement("dispenseRequest", InSummary=true, Order=210)] [DataMember] public Hl7.Fhir.Model.MedicationOrder.DispenseRequestComponent DispenseRequest { get { return _DispenseRequest; } set { _DispenseRequest = value; OnPropertyChanged("DispenseRequest"); } } private Hl7.Fhir.Model.MedicationOrder.DispenseRequestComponent _DispenseRequest; /// <summary> /// Any restrictions on medication substitution /// </summary> [FhirElement("substitution", InSummary=true, Order=220)] [DataMember] public Hl7.Fhir.Model.MedicationOrder.SubstitutionComponent Substitution { get { return _Substitution; } set { _Substitution = value; OnPropertyChanged("Substitution"); } } private Hl7.Fhir.Model.MedicationOrder.SubstitutionComponent _Substitution; /// <summary> /// An order/prescription that this supersedes /// </summary> [FhirElement("priorPrescription", InSummary=true, Order=230)] [CLSCompliant(false)] [References("MedicationOrder")] [DataMember] public Hl7.Fhir.Model.ResourceReference PriorPrescription { get { return _PriorPrescription; } set { _PriorPrescription = value; OnPropertyChanged("PriorPrescription"); } } private Hl7.Fhir.Model.ResourceReference _PriorPrescription; public override void AddDefaultConstraints() { base.AddDefaultConstraints(); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as MedicationOrder; if (dest != null) { base.CopyTo(dest); if(Identifier != null) dest.Identifier = new List<Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); if(DateWrittenElement != null) dest.DateWrittenElement = (Hl7.Fhir.Model.FhirDateTime)DateWrittenElement.DeepCopy(); if(StatusElement != null) dest.StatusElement = (Code<Hl7.Fhir.Model.MedicationOrder.MedicationOrderStatus>)StatusElement.DeepCopy(); if(DateEndedElement != null) dest.DateEndedElement = (Hl7.Fhir.Model.FhirDateTime)DateEndedElement.DeepCopy(); if(ReasonEnded != null) dest.ReasonEnded = (Hl7.Fhir.Model.CodeableConcept)ReasonEnded.DeepCopy(); if(Patient != null) dest.Patient = (Hl7.Fhir.Model.ResourceReference)Patient.DeepCopy(); if(Prescriber != null) dest.Prescriber = (Hl7.Fhir.Model.ResourceReference)Prescriber.DeepCopy(); if(Encounter != null) dest.Encounter = (Hl7.Fhir.Model.ResourceReference)Encounter.DeepCopy(); if(Reason != null) dest.Reason = (Hl7.Fhir.Model.Element)Reason.DeepCopy(); if(NoteElement != null) dest.NoteElement = (Hl7.Fhir.Model.FhirString)NoteElement.DeepCopy(); if(Medication != null) dest.Medication = (Hl7.Fhir.Model.Element)Medication.DeepCopy(); if(DosageInstruction != null) dest.DosageInstruction = new List<Hl7.Fhir.Model.MedicationOrder.DosageInstructionComponent>(DosageInstruction.DeepCopy()); if(DispenseRequest != null) dest.DispenseRequest = (Hl7.Fhir.Model.MedicationOrder.DispenseRequestComponent)DispenseRequest.DeepCopy(); if(Substitution != null) dest.Substitution = (Hl7.Fhir.Model.MedicationOrder.SubstitutionComponent)Substitution.DeepCopy(); if(PriorPrescription != null) dest.PriorPrescription = (Hl7.Fhir.Model.ResourceReference)PriorPrescription.DeepCopy(); return dest; } else throw new ArgumentException("Can only copy to an object of the same type", "other"); } public override IDeepCopyable DeepCopy() { return CopyTo(new MedicationOrder()); } public override bool Matches(IDeepComparable other) { var otherT = other as MedicationOrder; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(DateWrittenElement, otherT.DateWrittenElement)) return false; if( !DeepComparable.Matches(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.Matches(DateEndedElement, otherT.DateEndedElement)) return false; if( !DeepComparable.Matches(ReasonEnded, otherT.ReasonEnded)) return false; if( !DeepComparable.Matches(Patient, otherT.Patient)) return false; if( !DeepComparable.Matches(Prescriber, otherT.Prescriber)) return false; if( !DeepComparable.Matches(Encounter, otherT.Encounter)) return false; if( !DeepComparable.Matches(Reason, otherT.Reason)) return false; if( !DeepComparable.Matches(NoteElement, otherT.NoteElement)) return false; if( !DeepComparable.Matches(Medication, otherT.Medication)) return false; if( !DeepComparable.Matches(DosageInstruction, otherT.DosageInstruction)) return false; if( !DeepComparable.Matches(DispenseRequest, otherT.DispenseRequest)) return false; if( !DeepComparable.Matches(Substitution, otherT.Substitution)) return false; if( !DeepComparable.Matches(PriorPrescription, otherT.PriorPrescription)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as MedicationOrder; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(DateWrittenElement, otherT.DateWrittenElement)) return false; if( !DeepComparable.IsExactly(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.IsExactly(DateEndedElement, otherT.DateEndedElement)) return false; if( !DeepComparable.IsExactly(ReasonEnded, otherT.ReasonEnded)) return false; if( !DeepComparable.IsExactly(Patient, otherT.Patient)) return false; if( !DeepComparable.IsExactly(Prescriber, otherT.Prescriber)) return false; if( !DeepComparable.IsExactly(Encounter, otherT.Encounter)) return false; if( !DeepComparable.IsExactly(Reason, otherT.Reason)) return false; if( !DeepComparable.IsExactly(NoteElement, otherT.NoteElement)) return false; if( !DeepComparable.IsExactly(Medication, otherT.Medication)) return false; if( !DeepComparable.IsExactly(DosageInstruction, otherT.DosageInstruction)) return false; if( !DeepComparable.IsExactly(DispenseRequest, otherT.DispenseRequest)) return false; if( !DeepComparable.IsExactly(Substitution, otherT.Substitution)) return false; if( !DeepComparable.IsExactly(PriorPrescription, otherT.PriorPrescription)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return elem; } if (DateWrittenElement != null) yield return DateWrittenElement; if (StatusElement != null) yield return StatusElement; if (DateEndedElement != null) yield return DateEndedElement; if (ReasonEnded != null) yield return ReasonEnded; if (Patient != null) yield return Patient; if (Prescriber != null) yield return Prescriber; if (Encounter != null) yield return Encounter; if (Reason != null) yield return Reason; if (NoteElement != null) yield return NoteElement; if (Medication != null) yield return Medication; foreach (var elem in DosageInstruction) { if (elem != null) yield return elem; } if (DispenseRequest != null) yield return DispenseRequest; if (Substitution != null) yield return Substitution; if (PriorPrescription != null) yield return PriorPrescription; } } [NotMapped] internal override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return new ElementValue("identifier", elem); } if (DateWrittenElement != null) yield return new ElementValue("dateWritten", DateWrittenElement); if (StatusElement != null) yield return new ElementValue("status", StatusElement); if (DateEndedElement != null) yield return new ElementValue("dateEnded", DateEndedElement); if (ReasonEnded != null) yield return new ElementValue("reasonEnded", ReasonEnded); if (Patient != null) yield return new ElementValue("patient", Patient); if (Prescriber != null) yield return new ElementValue("prescriber", Prescriber); if (Encounter != null) yield return new ElementValue("encounter", Encounter); if (Reason != null) yield return new ElementValue("reason", Reason); if (NoteElement != null) yield return new ElementValue("note", NoteElement); if (Medication != null) yield return new ElementValue("medication", Medication); foreach (var elem in DosageInstruction) { if (elem != null) yield return new ElementValue("dosageInstruction", elem); } if (DispenseRequest != null) yield return new ElementValue("dispenseRequest", DispenseRequest); if (Substitution != null) yield return new ElementValue("substitution", Substitution); if (PriorPrescription != null) yield return new ElementValue("priorPrescription", PriorPrescription); } } } }
45.417279
177
0.577387
[ "BSD-3-Clause" ]
amitpuri/fhir-net-api
src/Hl7.Fhir.Core/Model/Generated/MedicationOrder.cs
49,416
C#
using System; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using MTF_Services.Model; using MTF_Services.WinForms.Data; using MTF_Services.WinForms.Extentions; using MTF_Services.WinForms.Properties; namespace MTF_Services.WinForms.Forms.SysAdmin.Services.Dictionary { /// <summary> /// Класс формы редактирования типов сервиса /// </summary> public partial class EditServiceTypeForm : Form { /// <summary> /// Объект для доступа к контекту данных. /// </summary> private readonly Context _ctx; /// <summary> /// Список типов сервиса /// </summary> public BindingList<ServiceType> ServiceTypes { get; set; } /// <summary> /// Текущий тип сервиса /// </summary> public ServiceType CurrentServiceType { get; set; } /// <summary> /// Наименование типа сервиса до изменения /// </summary> private string _serviceTypeNameBeforeEditing; /// <summary> /// Режим работы формы. /// </summary> private FormMode _formMode; /// <summary> /// Флаг редактирования типов сервиса /// </summary> public bool Edited { get; set; } /// <summary> /// Конструктор формы редактирования типов сервиса /// </summary> public EditServiceTypeForm() { InitializeComponent(); _formMode = FormMode.None; _ctx = new Context(); EnDisFields(false); BindCollection(); } /// <summary> /// Конструктор для выбора типа сервиса из списка /// </summary> /// <param name="findMode">Флаг поиска типа сервиса</param> public EditServiceTypeForm(bool findMode) : this() { if (!findMode) throw new ArgumentException("Неверное значение флага!"); _formMode = FormMode.None; but_Select.Visible = findMode; but_Select.Image = new Bitmap(Resources.camera_test, new Size(20, 20)); } /// <summary> /// Привязка коллекции /// </summary> private void BindCollection() { ServiceTypes = _ctx.GetServiceTypesBS(); serviceTypeBindingSource.DataSource = ServiceTypes; listBox1.DataSource = serviceTypeBindingSource; } /// <summary> /// Активация/деактивация полей для редактирования /// </summary> /// <param name="enabled">Флаг активации полей редактирования</param> private void EnDisFields(bool enabled) { textBox2.Enabled = enabled; btn_Save.Enabled = enabled; btn_Cancel.Enabled = enabled; textBox_ConditionToFind.Enabled = !enabled; listBox1.Enabled = !enabled; picBtn_FindByCondition.Enabled = !enabled; picBtn_ClearCondition.Enabled = !enabled; button2.Enabled = !enabled; button3.Enabled = !enabled; } /// <summary> /// Обработчик события изменения текущего элемента в источнике данных типов сервиса /// </summary> private void serviceTypeBindingSource_CurrentChanged(object sender, EventArgs e) { var selectedItem = ((BindingSource)sender).Current as ServiceType; if (selectedItem != null) CurrentServiceType = selectedItem; } /// <summary> /// Обработчик события нажатия клавиши мыши на кнопку, /// который совершает добавление нового типа сервиса /// </summary> private void button2_Click(object sender, EventArgs e) { ServiceTypes.AddNew(); serviceTypeBindingSource.MoveLast(); EnDisFields(true); _formMode = FormMode.Add; } /// <summary> /// Обработчик события нажатия клавиши мыши на кнопку, /// который совершает редактирование выбранного типа сервиса /// </summary> private void button3_Click(object sender, EventArgs e) { if (CurrentServiceType != null) { EnDisFields(true); _serviceTypeNameBeforeEditing = CurrentServiceType.Name; _formMode = FormMode.Edit; } else MessageBox.Show("Выберите тип сервиса из списка или добавьте новый!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Обработчик события нажатия клавиши мыши на кнопку, /// который выполняет сохранение изменений /// </summary> private async void btn_Save_Click(object sender, EventArgs e) { if (_formMode != FormMode.None) { try { if (string.IsNullOrWhiteSpace(CurrentServiceType.Name)) { MessageBox.Show("Введите наименование типа сервиса!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } bool existed = false; switch (_formMode) { case FormMode.Add: existed = await _ctx.CheckServiceTypeForDublicate(CurrentServiceType.Name); break; case FormMode.Edit: existed = await _ctx.CheckServiceTypeForDublicate(CurrentServiceType.Name) && !CurrentServiceType.Name.Equals(_serviceTypeNameBeforeEditing); break; } if (existed) { MessageBox.Show("Тип сервиса с таким наименованием уже существует!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (_formMode == FormMode.Add) ServiceTypes.EndNew(ServiceTypes.IndexOf(CurrentServiceType)); await _ctx.SaveChangesAsync(); EnDisFields(false); Edited = true; _formMode = FormMode.None; DialogResult = DialogResult.OK; MessageBox.Show("Изменения успешно сохранены!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch { MessageBox.Show("Изменения не удалось сохранить!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// <summary> /// Обработчик события нажатия клавиши мыши на кнопку, /// который производит отмену последнего добавления/редактирования /// </summary> private void btn_Cancel_Click(object sender, EventArgs e) { if (_formMode != FormMode.None) { var result = MessageBox.Show("Изменения не будут сохранены! Продолжить?", "Отмена изменений", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (result == DialogResult.Yes) { try { if (_formMode == FormMode.Edit) { int indexOfElement = ServiceTypes.IndexOf(CurrentServiceType); CurrentServiceType = _ctx.CancelChanges(CurrentServiceType); ServiceTypes[indexOfElement] = CurrentServiceType; } else ServiceTypes.CancelNew(ServiceTypes.IndexOf(CurrentServiceType)); EnDisFields(false); _formMode = FormMode.None; } catch { MessageBox.Show("Произошла ошибка при отмене изменений!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } /// <summary> /// Обработчик события нажатия клавиши мыши на кнопку, /// который совершает подтверждение выбранного типа сервиса /// </summary> private void but_Select_Click(object sender, EventArgs e) { if (CurrentServiceType != null) { DialogResult = DialogResult.OK; Close(); } else MessageBox.Show("Выберите тип сервиса из списка или добавьте новый!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Обработчик события закрытия формы /// </summary> private void EditServiceTypeForm_FormClosing(object sender, FormClosingEventArgs e) { if (_formMode != FormMode.None) { var result = MessageBox.Show("Изменения не будут сохранены! Продолжить?", "Отмена изменений", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk); if (result == DialogResult.No) e.Cancel = true; } } /// <summary> /// Ограничение ввода в наименовании добавляемого/редактируемого типа сервиса /// </summary> private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsControl(e.KeyChar) && !Char.IsLetter(e.KeyChar) && e.KeyChar != (int) Keys.Space) e.Handled = true; } /// <summary> /// Обработчик события нажатия клавиши мыши на графический объект, /// который производит очистку строки для поиска /// </summary> private void picBtn_ClearCondition_Click(object sender, EventArgs e) { textBox_ConditionToFind.Text = string.Empty; } /// <summary> /// Обработчик события нажатия клавиши мыши на графический объект, /// который производит поиск типа сервиса по наименованию /// </summary> private void picBtn_FindByCondition_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBox_ConditionToFind.Text)) { MessageBox.Show("Введите условие для поиска типа сервиса!", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var firstFoundedElement = ServiceTypes.FirstOrDefault(x => x.Name.ToUpper().Contains(textBox_ConditionToFind.Text.ToUpper())); if (firstFoundedElement != null) serviceTypeBindingSource.Position = ServiceTypes.IndexOf(firstFoundedElement); else MessageBox.Show("Не удалось найти тип сервиса по указанному условию!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Обработчик события нажатий клавиш клавиатуры на форме /// </summary> private void EditServiceTypeForm_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: btn_Cancel_Click(null, EventArgs.Empty); break; case Keys.Enter: btn_Save_Click(null, EventArgs.Empty); break; } } } }
37.528662
169
0.541158
[ "MIT" ]
NorthRebel/MTF_Services
Main/Source/MTF_Services.WinForms/Forms/SysAdmin/Services/Dictionary/EditServiceTypeForm.cs
13,552
C#
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using System.Collections.Generic; namespace VsChromium.Core.Files.PatternMatching { public class OpIsNoMatch : BaseOperator, IPrePassWontMatch { public bool PrePassWontMatch(MatchKind kind, string path, IPathComparer comparer) { return true; } public override int MatchWorker(MatchKind kind, IPathComparer comparer, IList<BaseOperator> operators, int operatorIndex, string path, int pathIndex) { return -1; } public override string ToString() { return "<no match>"; } } }
32.227273
156
0.708039
[ "BSD-3-Clause" ]
C-EO/vs-chromium
src/Core/Files/PatternMatching/OpIsNoMatch.cs
711
C#
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- using Microsoft.WindowsAzure.MobileServices; using Microsoft.WindowsAzure.MobileServices.Query; using MobileClient.Tests.Helpers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Xunit; namespace MobileClient.Tests.Table { public class ZumoQuery_Test { private MobileServiceTableQueryDescription Compile<T, U>(Func<IMobileServiceTable<T>, IMobileServiceTableQuery<U>> getQuery) { IMobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp); IMobileServiceTable<T> table = service.GetTable<T>(); IMobileServiceTableQuery<U> query = getQuery(table); MobileServiceTableQueryProvider provider = new MobileServiceTableQueryProvider(); MobileServiceTableQueryDescription compiledQuery = provider.Compile((MobileServiceTableQuery<U>)query); return compiledQuery; } [Fact] public void BasicQuery() { // Query syntax MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table select p); Assert.Equal("Product", query.TableName); Assert.Null(query.Filter); Assert.Equal(2, query.Selection.Count); Assert.Equal(0, query.Ordering.Count); } [Fact] public void Ordering() { // Query syntax MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table orderby p.Price ascending select p); Assert.Equal(1, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Ascending, query.Ordering[0].Direction); // Chaining query = Compile<Product, Product>(table => table.OrderBy(p => p.Price)); Assert.Equal(1, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Ascending, query.Ordering[0].Direction); // Query syntax descending query = Compile<Product, Product>(table => from p in table orderby p.Price descending select p); Assert.Equal(1, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Descending, query.Ordering[0].Direction); // Chaining descending query = Compile<Product, Product>(table => table.OrderByDescending(p => p.Price)); Assert.Equal(1, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Descending, query.Ordering[0].Direction); // Query syntax with multiple query = Compile<Product, Product>(table => from p in table orderby p.Price ascending, p.Name descending select p); Assert.Equal(2, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Ascending, query.Ordering[0].Direction); Assert.Equal("Name", ((MemberAccessNode)query.Ordering[1].Expression).MemberName); Assert.Equal(OrderByDirection.Descending, query.Ordering[1].Direction); // Chaining with multiple query = Compile<Product, Product>(table => table .OrderBy(p => p.Price) .ThenByDescending(p => p.Name)); Assert.Equal(2, query.Ordering.Count); Assert.Equal("Price", ((MemberAccessNode)query.Ordering[0].Expression).MemberName); Assert.Equal(OrderByDirection.Ascending, query.Ordering[0].Direction); Assert.Equal("Name", ((MemberAccessNode)query.Ordering[1].Expression).MemberName); Assert.Equal(OrderByDirection.Descending, query.Ordering[1].Direction); } [Fact] public void Projection() { // Query syntax MobileServiceTableQueryDescription query = Compile<Product, string>(table => from p in table select p.Name); Assert.Equal(3, query.Selection.Count); Assert.Equal("Name", query.Selection[0]); Assert.Equal("Weight", query.Selection[1]); Assert.Equal("WeightInKG", query.Selection[2]); Assert.Equal(typeof(Product), query.ProjectionArgumentType); Assert.Equal( "ZUMO", query.Projections.First().DynamicInvoke( new Product { Name = "ZUMO", Price = 0, InStock = true })); // Chaining query = Compile<Product, string>(table => table.Select(p => p.Name)); Assert.Equal(3, query.Selection.Count); Assert.Equal("Name", query.Selection[0]); Assert.Equal("Weight", query.Selection[1]); Assert.Equal("WeightInKG", query.Selection[2]); Assert.Equal(typeof(Product), query.ProjectionArgumentType); Assert.Equal( "ZUMO", query.Projections.First().DynamicInvoke( new Product { Name = "ZUMO", Price = 0, InStock = true })); // Verify that we don't blow up by trying to include the Foo // property in the compiled query Compile((IMobileServiceTable<Product> table) => from p in table select new { Foo = p.Name }); } [Fact] public void MutlipleProjection() { // Chaining MobileServiceTableQueryDescription query = Compile<Product, string>(table => table.Select(p => new { Foo = p.Name }) .Select(f => f.Foo.ToLower())); Assert.Equal(3, query.Selection.Count); Assert.Equal("Name", query.Selection[0]); Assert.Equal("Weight", query.Selection[1]); Assert.Equal("WeightInKG", query.Selection[2]); Assert.Equal(typeof(Product), query.ProjectionArgumentType); Assert.Equal( "zumo", query.Projections[1].DynamicInvoke( query.Projections[0].DynamicInvoke( new Product { Name = "ZUMO", Price = 0, InStock = true }))); // Verify that we don't blow up by trying to include the Foo // property in the compiled query Compile((IMobileServiceTable<Product> table) => table.Select(p => new { Foo = p.Name }) .Select(f => new { LowerFoo = f.Foo.ToLower() })); } [Fact] public void SkipTake() { // Query syntax MobileServiceTableQueryDescription query = Compile<Product, Product>(table => (from p in table select p).Skip(2).Take(5)); Assert.Equal(2, query.Skip); Assert.Equal(5, query.Top); // Chaining query = Compile<Product, Product>(table => table.Select(p => p).Skip(2).Take(5)); Assert.Equal(2, query.Skip); Assert.Equal(5, query.Top); // Allow New operations query = Compile<Product, Product>(table => table.Select(p => p).Skip(new Product() { SmallId = 2 }.SmallId).Take(5)); Assert.Equal(2, query.Skip); Assert.Equal(5, query.Top); } [Fact] public void WithParameters() { var userParmeters1 = new Dictionary<string, string>() { { "state", "PA" } }; var userParmeters2 = new Dictionary<string, string>() { { "country", "USA" } }; IMobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp); IMobileServiceTable<Product> t = service.GetTable<Product>(); IMobileServiceTableQuery<Product> originalQuery = from p in t select p; IMobileServiceTableQuery<Product> query = originalQuery.WithParameters(userParmeters1) .Skip(2) .WithParameters(userParmeters2); Assert.Equal("PA", originalQuery.Parameters["state"]); // , "original query should also have parameters" Assert.Equal("USA", originalQuery.Parameters["country"]); // , "original query should also have parameters" Assert.Equal("PA", query.Parameters["state"]); Assert.Equal("USA", query.Parameters["country"]); } [Fact] public void Filtering() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Price > 50 select p); AssertFilter(query.Filter, "(Price gt 50M)"); query = Compile<Product, Product>(table => table.Where(p => p.Price > 50)); AssertFilter(query.Filter, "(Price gt 50M)"); query = Compile<Product, Product>(table => from p in table where p.Weight <= 10 select p); AssertFilter(query.Filter, "(Weight le 10f)"); query = Compile<Product, Product>(table => table.Where(p => p.Weight <= 10)); AssertFilter(query.Filter, "(Weight le 10f)"); query = Compile<Product, Product>(table => from p in table where p.Weight <= 10 && p.InStock == true select p); AssertFilter(query.Filter, "((Weight le 10f) and (InStock eq true))"); query = Compile<Product, Product>(table => table.Where(p => p.Weight <= 10 && p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) and (InStock eq true))"); query = Compile<Product, Product>(table => from p in table where p.Weight <= 10 || p.InStock == true select p); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); query = Compile<Product, Product>(table => table.Where(p => p.Weight <= 10 || p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); query = Compile<Product, Product>(table => from p in table where !p.InStock select p); AssertFilter(query.Filter, "not(InStock)"); query = Compile<Product, Product>(table => table.Where(p => !p.InStock)); AssertFilter(query.Filter, "not(InStock)"); } [Fact] public void Filtering_PartialEval() { // Allow New Operations float foo = 10; var query = Compile<Product, Product>(table => table.Where(p => p.Weight <= new Product() { Weight = foo }.Weight || p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); query = Compile<Product, Product>(table => table.Where(p => p.Weight <= new Product(15) { Weight = foo }.Weight || p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); query = Compile<Product, Product>(table => table.Where(p => p.Weight <= new Product(15) { Weight = 10 }.Weight || p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); long id = 15; query = Compile<Product, Product>(table => table.Where(p => p.Weight <= new Product(id) { Weight = 10 }.Weight || p.InStock == true)); AssertFilter(query.Filter, "((Weight le 10f) or (InStock eq true))"); query = Compile<Product, Product>(table => table.Where(p => p.Created == new DateTime(1994, 10, 14, 0, 0, 0, DateTimeKind.Utc))); AssertFilter(query.Filter, "(Created eq datetime'1994-10-14T00%3A00%3A00.000Z')"); query = Compile<ProductWithDateTimeOffset, ProductWithDateTimeOffset>(table => table.Where(p => p.Created == new DateTimeOffset(1994, 10, 13, 17, 0, 0, TimeSpan.FromHours(7)))); AssertFilter(query.Filter, "(Created eq datetimeoffset'1994-10-13T17%3A00%3A00.0000000%2B07%3A00')"); } [Fact] public void CombinedQuery() { MobileServiceTableQueryDescription query = Compile((IMobileServiceTable<Product> table) => (from p in table where p.Price <= 10M && p.Weight > 10f where !p.InStock orderby p.Price descending, p.Name select new { p.Name, p.Price }) .Skip(20) .Take(10)); Assert.Equal("$filter=(((Price le 10M) and (Weight gt 10f)) and not(InStock))&$orderby=Price desc,Name&$skip=20&$top=10&$select=Name,Price,Weight,WeightInKG", query.ToODataString()); } [Fact] public void Bug466610UsingShorts() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => table.Where(p => p.DisplayAisle == 2)); AssertFilter(query.Filter, "(DisplayAisle eq 2)"); query = Compile<Product, Product>(table => from p in table where p.DisplayAisle == (short)3 select p); AssertFilter(query.Filter, "(DisplayAisle eq 3)"); short closedOverVariable = (short)5; query = Compile<Product, Product>(table => from p in table where p.DisplayAisle == closedOverVariable select p); AssertFilter(query.Filter, "(DisplayAisle eq 5)"); query = Compile<Product, Product>(table => table.Where(p => p.OptionFlags == 7)); AssertFilter(query.Filter, "(OptionFlags eq 7)"); // Verify non-numeric conversions still aren't supported Assert.Throws<NotSupportedException>(() => { object aisle = 12.0; Compile<Product, Product>(table => from p in table where (object)p.DisplayAisle == aisle select p ); }); } [Fact] public void Bug466610BareSkipTake() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => table.Skip(3)); Assert.Equal(3, query.Skip); Assert.False(query.Top.HasValue); query = Compile<Product, Product>(table => table.Take(5)); Assert.Equal(5, query.Top); Assert.False(query.Skip.HasValue); query = Compile<Product, Product>(table => table.Skip(7).Take(9)); Assert.Equal(7, query.Skip); Assert.Equal(9, query.Top); query = Compile<Product, Product>(table => table.Take(11).Skip(13)); Assert.Equal(13, query.Skip); Assert.Equal(11, query.Top); } [Fact] public void FilterOperators() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Name + "x" == "mx" select p); AssertFilter(query.Filter, "(concat(Name,'x') eq 'mx')"); query = Compile<Product, Product>(table => from p in table where p.Weight + 1.0 == 10.0 select p); AssertFilter(query.Filter, "((Weight add 1.0) eq 10.0)"); query = Compile<Product, Product>(table => from p in table where p.Weight + 1 == 10 select p); AssertFilter(query.Filter, "((Weight add 1f) eq 10f)"); query = Compile<Product, Product>(table => from p in table where p.Weight - 1.0 == 10.0 select p); AssertFilter(query.Filter, "((Weight sub 1.0) eq 10.0)"); query = Compile<Product, Product>(table => from p in table where p.Weight * 2.0 == 10.0 select p); AssertFilter(query.Filter, "((Weight mul 2.0) eq 10.0)"); query = Compile<Product, Product>(table => from p in table where p.Weight / 2.0 == 10.0 select p); AssertFilter(query.Filter, "((Weight div 2.0) eq 10.0)"); query = Compile<Product, Product>(table => from p in table where p.Id % 2 == 1 select p); AssertFilter(query.Filter, "((id mod 2L) eq 1L)"); query = Compile<Product, Product>(table => from p in table where (p.Weight * 2.0) / 3.0 + 1.0 == 10.0 select p); AssertFilter(query.Filter, "((((Weight mul 2.0) div 3.0) add 1.0) eq 10.0)"); } [Fact] public void FilterMethods_1() { // Methods that look like properties var query = Compile<Product, Product>(table => from p in table where p.Name.Length == 7 select p); AssertFilter(query.Filter, "(length(Name) eq 7)"); } [Fact] public void FilterMethods_2() { var query = Compile<Product, Product>(table => from p in table where p.Created.Day == 7 select p); AssertFilter(query.Filter, "(day(Created) eq 7)"); } [Fact] public void FilterMethods_3() { var query = Compile<Product, Product>(table => from p in table where p.Created.Month == 7 select p); AssertFilter(query.Filter, "(month(Created) eq 7)"); } [Fact] public void FilterMethods_4() { var query = Compile<Product, Product>(table => from p in table where p.Created.Year == 7 select p); AssertFilter(query.Filter, "(year(Created) eq 7)"); } [Fact] public void FilterMethods_5() { var query = Compile<Product, Product>(table => from p in table where p.Created.Hour == 7 select p); AssertFilter(query.Filter, "(hour(Created) eq 7)"); } [Fact] public void FilterMethods_6() { var query = Compile<Product, Product>(table => from p in table where p.Created.Minute == 7 select p); AssertFilter(query.Filter, "(minute(Created) eq 7)"); } [Fact] public void FilterMethods_7() { var query = Compile<Product, Product>(table => from p in table where p.Created.Second == 7 select p); AssertFilter(query.Filter, "(second(Created) eq 7)"); } [Fact] public void FilterMethods_8() { // Static methods var query = Compile<Product, Product>(table => from p in table where Math.Floor(p.Weight) == 10 select p); AssertFilter(query.Filter, "(floor(Weight) eq 10.0)"); } [Fact] public void FilterMethods_9() { var query = Compile<Product, Product>(table => from p in table where Decimal.Floor(p.Price) == 10 select p); AssertFilter(query.Filter, "(floor(Price) eq 10M)"); } [Fact] public void FilterMethods_10() { var query = Compile<Product, Product>(table => from p in table where Math.Ceiling(p.Weight) == 10 select p); AssertFilter(query.Filter, "(ceiling(Weight) eq 10.0)"); } [Fact] public void FilterMethods_11() { var query = Compile<Product, Product>(table => from p in table where Decimal.Ceiling(p.Price) == 10 select p); AssertFilter(query.Filter, "(ceiling(Price) eq 10M)"); } [Fact] public void FilterMethods_12() { var query = Compile<Product, Product>(table => from p in table where Math.Round(p.Weight) == 10 select p); AssertFilter(query.Filter, "(round(Weight) eq 10.0)"); } [Fact] public void FilterMethods_13() { var query = Compile<Product, Product>(table => from p in table where Math.Round(p.Price) == 10 select p); AssertFilter(query.Filter, "(round(Price) eq 10M)"); } [Fact] public void FilterMethods_14() { var query = Compile<Product, Product>(table => from p in table where string.Concat(p.Name, "x") == "mx" select p); AssertFilter(query.Filter, "(concat(Name,'x') eq 'mx')"); } #pragma warning disable RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_15() { // Instance methods var query = Compile<Product, Product>(table => from p in table where p.Name.ToLower() == "a" select p); AssertFilter(query.Filter, "(tolower(Name) eq 'a')"); } #pragma warning restore RCS1155 // Use StringComparison when comparing strings. #pragma warning disable RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_16() { // Instance methods var query = Compile<Product, Product>(table => from p in table where p.Name.ToLowerInvariant() == "a" select p); AssertFilter(query.Filter, "(tolower(Name) eq 'a')"); } #pragma warning restore RCS1155 // Use StringComparison when comparing strings. #pragma warning disable RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_17() { var query = Compile<Product, Product>(table => from p in table where p.Name.ToUpper() == "A" select p); AssertFilter(query.Filter, "(toupper(Name) eq 'A')"); } #pragma warning restore RCS1155 // Use StringComparison when comparing strings. #pragma warning disable RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_18() { var query = Compile<Product, Product>(table => from p in table where p.Name.ToUpperInvariant() == "A" select p); AssertFilter(query.Filter, "(toupper(Name) eq 'A')"); } #pragma warning restore RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_19() { var query = Compile<Product, Product>(table => from p in table where p.Name.Trim() == "A" select p); AssertFilter(query.Filter, "(trim(Name) eq 'A')"); } [Fact] public void FilterMethods_20() { var query = Compile<Product, Product>(table => from p in table where p.Name.StartsWith("x") select p); AssertFilter(query.Filter, "startswith(Name,'x')"); } [Fact] public void FilterMethods_21() { var query = Compile<Product, Product>(table => from p in table where p.Name.EndsWith("x") select p); AssertFilter(query.Filter, "endswith(Name,'x')"); } [Fact] public void FilterMethods_22() { var query = Compile<Product, Product>(table => from p in table where p.Name.IndexOf("x") == 2 select p); AssertFilter(query.Filter, "(indexof(Name,'x') eq 2)"); } [Fact] public void FilterMethods_23() { var query = Compile<Product, Product>(table => from p in table where p.Name.IndexOf('x') == 2 select p); AssertFilter(query.Filter, "(indexof(Name,'x') eq 2)"); } [Fact] public void FilterMethods_24() { var query = Compile<Product, Product>(table => from p in table where p.Name.Contains("x") select p); AssertFilter(query.Filter, "substringof('x',Name)"); } [Fact] public void FilterMethods_25() { var query = Compile<Product, Product>(table => from p in table where p.Name.Replace("a", "A") == "A" select p); AssertFilter(query.Filter, "(replace(Name,'a','A') eq 'A')"); } [Fact] public void FilterMethods_26() { var query = Compile<Product, Product>(table => from p in table where p.Name.Replace('a', 'A') == "A" select p); AssertFilter(query.Filter, "(replace(Name,'a','A') eq 'A')"); } [Fact] public void FilterMethods_27() { var query = Compile<Product, Product>(table => from p in table where p.Name.Substring(2) == "A" select p); AssertFilter(query.Filter, "(substring(Name,2) eq 'A')"); } [Fact] public void FilterMethods_28() { var query = Compile<Product, Product>(table => from p in table where p.Name.Substring(2, 3) == "A" select p); AssertFilter(query.Filter, "(substring(Name,2,3) eq 'A')"); } [Fact] public void FilterMethods_29() { // Verify each type works on nested expressions too var query = Compile<Product, Product>(table => from p in table where (p.Name + "x").Length == 7 select p); AssertFilter(query.Filter, "(length(concat(Name,'x')) eq 7)"); } [Fact] public void FilterMethods_30() { var query = Compile<Product, Product>(table => from p in table where string.Concat(p.Name + "x", "x") == "mx" select p); AssertFilter(query.Filter, "(concat(concat(Name,'x'),'x') eq 'mx')"); } #pragma warning disable RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterMethods_31() { var query = Compile<Product, Product>(table => from p in table where (p.Name + "x").ToLower() == "ax" select p); AssertFilter(query.Filter, "(tolower(concat(Name,'x')) eq 'ax')"); } #pragma warning restore RCS1155 // Use StringComparison when comparing strings. [Fact] public void FilterContainsMethod() { string[] names = new[] { "name1", "name2" }; MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where names.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name2'))"); IEnumerable<string> namesEnum = new[] { "name1", "name2" }; query = Compile<Product, Product>(table => from p in table where namesEnum.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name2'))"); IEnumerable<string> empty = Enumerable.Empty<string>(); query = Compile<Product, Product>(table => from p in table where empty.Contains(p.Name) select p); AssertFilter(query.Filter, string.Empty); //test Contains on List<T> List<string> namesList = new List<string>() { "name1", "name2" }; query = Compile<Product, Product>(table => from p in table where namesList.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name2'))"); //test Contains on Collection<T> Collection<string> coll = new Collection<string>() { "name1", "name2" }; query = Compile<Product, Product>(table => from p in table where coll.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name2'))"); //test duplicates namesList = new List<string>() { "name1", "name1" }; query = Compile<Product, Product>(table => from p in table where namesList.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name1'))"); //test single namesList = new List<string>() { "name1" }; query = Compile<Product, Product>(table => from p in table where namesList.Contains(p.Name) select p); AssertFilter(query.Filter, "(Name eq 'name1')"); //test multiples namesList = new List<string>() { "name1", "name2", "name3" }; query = Compile<Product, Product>(table => from p in table where namesList.Contains(p.Name) select p); AssertFilter(query.Filter, "(((Name eq 'name1') or (Name eq 'name2')) or (Name eq 'name3'))"); IEnumerable<string> productNames = new Product[] { new Product { Name = "name1" }, new Product { Name = "name2" } }.Select(pr => pr.Name); query = Compile<Product, Product>(table => from p in table where productNames.Contains(p.Name) select p); AssertFilter(query.Filter, "((Name eq 'name1') or (Name eq 'name2'))"); IEnumerable<bool> booleans = new[] { false, true }; query = Compile<Product, Product>(table => from p in table where booleans.Contains(p.InStock) select p); AssertFilter(query.Filter, "((InStock eq false) or (InStock eq true))"); IEnumerable<int> numbers = new[] { 13, 6 }; query = Compile<Product, Product>(table => from p in table where numbers.Contains(p.DisplayAisle) select p); AssertFilter(query.Filter, "((DisplayAisle eq 13) or (DisplayAisle eq 6))"); IEnumerable<double> doubles = new[] { 4.6, 3.9089 }; query = Compile<Product, Product>(table => from p in table where doubles.Contains(p.Weight) select p); AssertFilter(query.Filter, "((Weight eq 4.6) or (Weight eq 3.9089))"); } [Fact] public void FilterContainsMethodNegative() { Assert.Throws<NotSupportedException>(() => { //Contains on parameter members is not supported Compile<Product, Product>(table => from p in table where p.Tags.Contains(p.Name) select p); }); } [Fact] public void TestSelectInsideWhere() { Assert.Throws<NotSupportedException>(() => { //test Select inside Where IEnumerable<Product> products = new Product[] { new Product { Name = "name1" }, new Product { Name = "name2" } }; Compile<Product, Product>(table => from p in table where products.Select(pr => pr.Name).Contains(p.Name) select p); }); } [Fact] public void MultipleParameterExpressionsThrowInContains() { Assert.Throws<NotSupportedException>(() => { IEnumerable<int> numbers = new[] { 13, 6, 5 }; //multiple parameter expressions throw in Contains Compile<Product, Product>(table => from p in table where numbers.Select(n => p.Id).Contains(p.DisplayAisle) select p); }); } [Fact] public void ContainsOnListOfTWhereTNotMember() { Assert.Throws<InvalidOperationException>(() => { IEnumerable<object> objects = new object[] { 4.6, "string" }; //Contains on list of T where T != typeof(p.Member) Compile<Product, Product>(table => from p in table where objects.Contains(p.Weight) select p); }); } [Fact] public void FilterEnums() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Type == ProductType.Food select p); AssertFilter(query.Filter, "(Type eq 'Food')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum1 == Enum1.Enum1Value2 select p); AssertFilter(query.Filter, "(Enum1 eq 'Enum1Value2')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum2 == Enum2.Enum2Value2 select p); AssertFilter(query.Filter, "(Enum2 eq 'Enum2Value2')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum3 == (Enum3.Enum3Value2 | Enum3.Enum3Value1) select p); AssertFilter(query.Filter, "(Enum3 eq 'Enum3Value1%2C%20Enum3Value2')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum4 == Enum4.Enum4Value2 select p); AssertFilter(query.Filter, "(Enum4 eq 'Enum4Value2')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum5 == Enum5.Enum5Value2 select p); AssertFilter(query.Filter, "(Enum5 eq 'Enum5Value2')"); query = Compile<EnumType, EnumType>(table => from p in table where p.Enum6 == Enum6.Enum6Value1 select p); AssertFilter(query.Filter, "(Enum6 eq 'Enum6Value1')"); //check if toString works query = Compile<EnumType, EnumType>(table => from p in table where p.Enum6.ToString() == Enum6.Enum6Value1.ToString() select p); AssertFilter(query.Filter, "(Enum6 eq 'Enum6Value1')"); } [Fact] public void ToStringTest() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Tags.ToString() == "Test" select p); AssertFilter(query.Filter, "(Tags eq 'Test')"); query = Compile<Product, Product>(table => from p in table where p.Price.ToString() == "1.56" select p); AssertFilter(query.Filter, "(Price eq '1.56')"); query = Compile<Product, Product>(table => from p in table where p.Created.ToString() == "January 23" select p); AssertFilter(query.Filter, "(Created eq 'January%2023')"); IList<string> namesList = new List<string>() { "name1", "name1" }; query = Compile<Product, Product>(table => from p in table where namesList.Contains(p.DisplayAisle.ToString()) select p); AssertFilter(query.Filter, "((DisplayAisle eq 'name1') or (DisplayAisle eq 'name1'))"); } [Fact] public void FilterReturnsTrueConstant() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where true select p); AssertFilter(query.Filter, "true"); query = Compile<Product, Product>(table => table.Where(p => true)); AssertFilter(query.Filter, "true"); query = Compile<Product, Product>(table => table.Where(item => !item.InStock || item.InStock)); AssertFilter(query.Filter, "(not(InStock) or InStock)"); } [Fact] public void FilterNullable() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Updated == null select p); AssertFilter(query.Filter, "(Updated eq null)"); var minDate = new DateTime(1, 1, 1, 8, 0, 0, DateTimeKind.Utc); query = Compile<Product, Product>(table => from p in table where p.Updated == minDate select p); AssertFilter(query.Filter, "(Updated eq datetime'0001-01-01T08%3A00%3A00.000Z')"); query = Compile<Product, Product>(table => from p in table where p.WeightInKG == null select p); AssertFilter(query.Filter, "(WeightInKG eq null)"); query = Compile<Product, Product>(table => from p in table where p.WeightInKG == 4.0 select p); AssertFilter(query.Filter, "(WeightInKG eq 4.0)"); } [Fact] public void MultipleSkipShouldAddUp() { // Query syntax MobileServiceTableQueryDescription query = Compile<Product, Product>(table => (from p in table select p).Skip(2).Skip(5)); Assert.Equal(7, query.Skip); query = Compile<Product, Product>(table => (from p in table select p).Skip(5).Skip(5)); Assert.Equal(10, query.Skip); query = Compile<Product, Product>(table => (from p in table select p).Skip(20).Skip(6).Skip(5).Skip(2).Skip(9).Skip(5)); Assert.Equal(47, query.Skip); } [Fact] public void MultipleTakeShouldChooseSmallest() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => (from p in table select p).Take(2).Take(5)); Assert.Equal(2, query.Top); query = Compile<Product, Product>(table => (from p in table select p).Take(5).Take(2)); Assert.Equal(2, query.Top); query = Compile<Product, Product>(table => (from p in table select p).Take(5).Take(5)); Assert.Equal(5, query.Top); } [Fact] public void TableNameShouldPropagateCorrectly() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table select p); Assert.Equal("Product", query.TableName); Assert.Null(query.Filter); Assert.Equal(2, query.Selection.Count); Assert.Equal(0, query.Ordering.Count); query = Compile<Product, string>(table => from p in table select p.Name); Assert.Equal("Product", query.TableName); Assert.Null(query.Filter); Assert.Equal(3, query.Selection.Count); Assert.Equal(0, query.Ordering.Count); } [Fact] public void BooleanMemberValuesShouldBeHandled() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.InStock select p); Assert.Equal("Product", query.TableName); AssertFilter(query.Filter, "InStock"); Assert.Equal(0, query.Selection.Count); Assert.Equal(0, query.Ordering.Count); } [Fact] public void UnsignedDataTypesTest() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.UnsignedId == 12UL select p); Assert.Equal("Product", query.TableName); AssertFilter(query.Filter, "(UnsignedId eq 12L)"); //unsigned ints should be sent as long query = Compile<Product, Product>(table => from p in table where p.UnsignedSmallId == 12U //uint select p); Assert.Equal("Product", query.TableName); AssertFilter(query.Filter, "(UnsignedSmallId eq 12L)"); query = Compile<Product, Product>(table => from p in table where p.UnsignedDisplayAisle == (ushort)12 select p); Assert.Equal("Product", query.TableName); AssertFilter(query.Filter, "(UnsignedDisplayAisle eq 12)"); } [Fact] public void FilterBasedOnTimeSpanShouldResultInString() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.AvailableTime > TimeSpan.FromDays(1) select p); Assert.Equal("Product", query.TableName); AssertFilter(query.Filter, "(AvailableTime gt '1.00%3A00%3A00')"); Assert.Equal(0, query.Selection.Count); Assert.Equal(0, query.Ordering.Count); } [Fact] public void SkipZero() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => table.Skip(0)); Assert.Equal("Product", query.TableName); Assert.Equal(0, query.Skip); Assert.False(query.Top.HasValue); Assert.Equal("$skip=0", query.ToODataString()); } [Fact] public void TopZero() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => table.Take(0)); Assert.Equal("Product", query.TableName); Assert.Equal(0, query.Top); Assert.False(query.Skip.HasValue); Assert.Equal("$top=0", query.ToODataString()); } [Fact] public void DoublesSerializedUsingInvariantCulture() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where p.Weight > 1.3f select p); AssertFilter(query.Filter, "(Weight gt 1.3f)"); } [Fact] public void DoublesSerializedAsDoubles() { MobileServiceTableQueryDescription query = Compile<Product, Product>(table => from p in table where (p.SmallId / 100.0) == 2 select p); AssertFilter(query.Filter, "((SmallId div 100.0) eq 2.0)"); query = Compile<Product, Product>(table => from p in table where (p.Weight * 31.213) == 60200000000000000000000000.0 select p); AssertFilter(query.Filter, "((Weight mul 31.213) eq 6.02E+25)"); } private static void AssertFilter(QueryNode filter, string expectedFilterStr) { string filterStr = ODataExpressionVisitor.ToODataString(filter); Assert.Equal(expectedFilterStr, filterStr); } } }
39.08441
194
0.523701
[ "Apache-2.0" ]
Atlas-LiftTech/azure-mobile-apps-net-client
unittests/MobileClient.Tests/Table/ZumoQuery.Test.cs
45,379
C#
using System.Text; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; using DiscordBoats.Internal; using DiscordBoats.Models; namespace DiscordBoats { public class BoatClient : BaseBoatClient { public BoatClient(ulong botId, string token) { BotId = botId; Client.DefaultRequestHeaders.Add("Authorization", token); } protected ulong BotId { get; } public async Task<IBoatBot> GetSelfAsync() { return await GetBotAsync(BotId); } public string GetWidgetUrl(WidgetImageFormat imageFormat = WidgetImageFormat.Svg) { return GetWidgetUrl(BotId, imageFormat); } public async Task<bool> HasVotedAsync(ulong userId) { return await HasVotedAsync(BotId, userId); } public async Task<bool> UpdateGuildCountAsync(int guildCount) { string url = $"{Api.GetBaseUrl()}/{Api.BotEndpoint}/{BotId}"; string json = JsonConvert.SerializeObject(new CountObject(guildCount)); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await Client.PostAsync(url, content); return response.IsSuccessStatusCode; } } }
28.891304
89
0.635816
[ "MIT" ]
DiscordBoats/Boats.NET
DiscordBoats/BoatClient.cs
1,329
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="ElementGroupingType.cs" company="RHEA System S.A."> // // Copyright 2022 RHEA System S.A. // // 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. // // </copyright> // ------------------------------------------------------------------------------------------------ namespace Kalliope.Core { using Kalliope.Common; /// <summary> /// A type for a group. Each Group is associated with a new instance of each of its GroupTypes, allowing individual settings per group /// </summary> [Description("A type for a group. Each Group is associated with a new instance of each of its GroupTypes, allowing individual settings per group")] [Domain(isAbstract: true, general: "ModelThing")] [Container(typeName: "ElementGrouping", propertyName: "GroupingTypes")] [Ignore("This class derives from ModelThing and therefore has no Id property and is an abstract class that has no subclasses defined in the domain model")] public abstract class ElementGroupingType : ModelThing { } }
46.944444
160
0.619527
[ "Apache-2.0" ]
RHEAGROUP/Kalliope
Kalliope/Core/ElementGroupingType.cs
1,692
C#
using Commun; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace InterfaceGraphique { public partial class OpenCard : Form { private delegate void AddCardCallBack(string xml, string name, string password, string score); public OpenCard() { InitializeComponent(); Program.SDispatcher.EditionConnectionM.CardPlusReceived += AddCard; } void AddCard(string xml, string name, string password , string score) { if (InvokeRequired) { Invoke(new AddCardCallBack(AddCard),xml, name, password, score); } else { Panel panel = new Panel(); PictureBox pictureBox = new PictureBox(); Label nameLabel = new Label(); Label statusLabel = new Label(); Label scoreLabel = new Label(); ComboBox comboBox = new ComboBox(); /*this.m_flowLayout.SuspendLayout(); panel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(pictureBox)).BeginInit(); this.SuspendLayout();*/ // m_flowLayout.Controls.Add(panel); // panel.Controls.Add(nameLabel); panel.Controls.Add(statusLabel); panel.Controls.Add(scoreLabel); panel.Controls.Add(pictureBox); panel.Controls.Add(comboBox); panel.Font = new System.Drawing.Font("Sitka Small", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); //////panel.Location = new System.Drawing.Point(300, 3); //panel.Name = "panel1"; panel.Size = new Size(184, 193); panel.TabIndex = 0; // pictureBox.Location = new Point(15, 28); pictureBox.SizeMode = PictureBoxSizeMode.Zoom; pictureBox.BackColor = Color.Black; //pictureBox.Name = "pictureBox1"; pictureBox.Size = new Size(152, 114); pictureBox.TabIndex = 0; pictureBox.TabStop = false; Card card = Card.ReadFromString(xml); Bitmap bitmap = card.GetBitmap(6); pictureBox.Image = (Bitmap)bitmap.Clone(); // if (password != "") { TextBox passwordText = new TextBox(); Button open = new Button(); panel.Controls.Add(passwordText); panel.Controls.Add(open); passwordText.Size = new Size(152, 14); passwordText.Location = new Point(15, 28); passwordText.PasswordChar = '*'; passwordText.Visible = false; open.Size = new Size(67, 30); open.Location = new Point(14, 118); open.Text = "Ouvrir"; open.Visible = false; passwordText.BringToFront(); open.BringToFront(); pictureBox.Click += (sender, e) => { passwordText.Visible = true; open.Visible = true; passwordText.Focus(); }; open.Click += (sender, e) => { if (passwordText.Text != password) { MessageBox.Show("Le mot de passe saisi est incorrect"); } else { string option = (string)comboBox.SelectedItem; Program.IsSpectator = (option == "Editeur" ? false : true); Program.SDispatcher.EditionConnectionM.GetCard(name); Close(); } }; } else { pictureBox.Click += (sender, e) => { string option = (string)comboBox.SelectedItem; Program.IsSpectator = (option == "Editeur" ? false : true); Program.SDispatcher.EditionConnectionM.GetCard(name); Close(); }; } // comboBox1 // comboBox.FormattingEnabled = true; comboBox.Font = new Font("Sitka Small", 10.8F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0))); comboBox.Items.AddRange(new object[] { "Editeur", "Spectateur"}); comboBox.Location = new Point(81, 119); comboBox.DropDownStyle = ComboBoxStyle.DropDownList; comboBox.SelectedIndex = 0; //comboBox.Name = "comboBox1"; comboBox.Size = new Size(87, 21); comboBox.TabIndex = 0; comboBox.BringToFront(); //comboBox.ItemHeight = 15; // nameLabel.AutoSize = true; nameLabel.Location = new Point(15, 3); //nameLabel.Name = "label1"; nameLabel.Size = new Size(90, 23); nameLabel.TabIndex = 1; nameLabel.Text = name; // statusLabel.AutoSize = true; statusLabel.Location = new Point(15, 148); //statusLabel.Name = "label2"; statusLabel.Size = new Size(115, 23); statusLabel.TabIndex = 2; statusLabel.Text = (password != "") ? "Privée" : "Public"; // // label3 // scoreLabel.AutoSize = true; scoreLabel.Location = new Point(15, 168); scoreLabel.Name = "label3"; scoreLabel.Size = new Size(52, 23); scoreLabel.TabIndex = 3; scoreLabel.Text = "Score : " + score; // /*this.m_flowLayout.ResumeLayout(false); panel.ResumeLayout(false); panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(pictureBox)).EndInit(); this.ResumeLayout(false);*/ } } private void OpenCard_FormClosing(object sender, FormClosingEventArgs e) { Program.SDispatcher.EditionConnectionM.CardPlusReceived -= AddCard; } } }
40.745562
158
0.476038
[ "MIT" ]
samirov78/MultiplayerRobotSimulator
ClientLourd/Code/Sources/InterfaceGraphique/Forms/OpenCard.cs
6,889
C#
namespace MultipleDbContextDemo.MigrationsSecond { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<MultipleDbContextDemo.EntityFramework.MySecondDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; MigrationsDirectory = @"MigrationsSecond"; } protected override void Seed(MultipleDbContextDemo.EntityFramework.MySecondDbContext context) { context.Courses.AddOrUpdate(c => c.CourseName, new Course("Mathematics"), new Course("Physics") ); } } }
29.56
124
0.645467
[ "MIT" ]
Jimmey-Jiang/aspnetboilerplate-samples
MultipleDbContextDemo/MultipleDbContextDemo.EntityFramework/MigrationsSecond/Configuration.cs
739
C#
using System; using System.Net; using System.Net.Http; using System.Web.Http; using Nyan.Core.Settings; namespace Nyan.Modules.Web.REST.tools { [RoutePrefix("stack/proxy")] public class ProxyController : ApiController { [Route("")] [HttpGet] public object Search([FromUri] string url) { try { var client = new HttpClient(); var result = client.GetStringAsync(url).Result; var resp = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain") }; return resp; } catch (Exception e) { Current.Log.Add(e); throw; } } } }
24.542857
96
0.50291
[ "MIT" ]
bucknellu/Nyan
Modules/Web/REST/tools/Proxy.cs
861
C#
#nullable enable using System; using Content.Server.Holiday.Celebrate; using Content.Server.Holiday.Greet; using Content.Server.Holiday.Interfaces; using Content.Server.Holiday.ShouldCelebrate; using Robust.Shared.Prototypes; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; using YamlDotNet.RepresentationModel; namespace Content.Server.Holiday { [Prototype("holiday")] public class HolidayPrototype : IPrototype { [ViewVariables] public string Name { get; private set; } = string.Empty; [ViewVariables] public string ID { get; private set; } = string.Empty; [ViewVariables] public byte BeginDay { get; set; } = 1; [ViewVariables] public Month BeginMonth { get; set; } = Month.Invalid; /// <summary> /// Day this holiday will end. Zero means it lasts a single day. /// </summary> [ViewVariables] public byte EndDay { get; set; } = 0; /// <summary> /// Month this holiday will end in. Invalid means it lasts a single month. /// </summary> [ViewVariables] public Month EndMonth { get; set; } = Month.Invalid; [ViewVariables] private IHolidayShouldCelebrate _shouldCelebrate = new DefaultHolidayShouldCelebrate(); [ViewVariables] private IHolidayGreet _greet = new DefaultHolidayGreet(); [ViewVariables] private IHolidayCelebrate _celebrate = new DefaultHolidayCelebrate(); public void LoadFrom(YamlMappingNode mapping) { var serializer = YamlObjectSerializer.NewReader(mapping); ExposeData(serializer); } public void ExposeData(ObjectSerializer serializer) { serializer.DataField(this, x => x.ID, "id", string.Empty); serializer.DataField(this, x => x.Name, "name", string.Empty); serializer.DataField(this, x => x.BeginDay, "beginDay", (byte)1); serializer.DataField(this, x => x.BeginMonth, "beginMonth", Month.Invalid); serializer.DataField(this, x => x.EndDay, "endDay", (byte)0); serializer.DataField(this, x => x.EndMonth, "endMonth", Month.Invalid); serializer.DataField(ref _shouldCelebrate, "shouldCelebrate", new DefaultHolidayShouldCelebrate()); serializer.DataField(ref _greet, "greet", new DefaultHolidayGreet()); serializer.DataField(ref _celebrate, "celebrate", new DefaultHolidayCelebrate()); } public bool ShouldCelebrate(DateTime date) { return _shouldCelebrate.ShouldCelebrate(date, this); } public string Greet() { return _greet.Greet(this); } /// <summary> /// Called before the round starts to set up any festive shenanigans. /// </summary> public void Celebrate() { _celebrate.Celebrate(this); } } }
37.189873
111
0.63887
[ "MIT" ]
TheOneAndMightyRed/space-station-14
Content.Server/Holiday/HolidayPrototype.cs
2,938
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpGLTF.Animations { /// <summary> /// Wraps a collection of samplers split over time to speed up key retrieval. /// </summary> /// <typeparam name="T">The value sampled at any offset</typeparam> readonly struct FastCurveSampler<T> : ICurveSampler<T> { /// <summary> /// Creates a new, read only <see cref="ICurveSampler{T}"/> that has been optimized for fast sampling. /// </summary> /// <remarks> /// Sampling a raw curve with a large number of keys can be underperformant. This code splits the keys into 1 second /// chunks that can be accessed at much faster speed. /// </remarks> /// <typeparam name="TKey">The value of a key (may include tangents)</typeparam> /// <param name="sequence">A sequence of Time-Key entries, ordered by Time.</param> /// <param name="chunkFactory">A curve chunk factory function.</param> /// <returns>The new, optimized curve sampler.</returns> public static ICurveSampler<T> CreateFrom<TKey>(IEnumerable<(float, TKey)> sequence, Func<(float, TKey)[], ICurveSampler<T>> chunkFactory) { // not enough keys, or not worth optimizing it. if (!sequence.Skip(3).Any()) return null; var split = sequence .SplitByTime() .Select(item => chunkFactory.Invoke(item)) .Cast<ICurveSampler<T>>(); return new FastCurveSampler<T>(split); } private FastCurveSampler(IEnumerable<ICurveSampler<T>> samplers) { _Samplers = samplers.ToArray(); } private readonly ICurveSampler<T>[] _Samplers; public T GetPoint(float offset) { if (offset < 0) offset = 0; var index = (int)offset; if (index >= _Samplers.Length) index = _Samplers.Length - 1; return _Samplers[index].GetPoint(offset); } } }
37.122807
147
0.587429
[ "MIT" ]
ptasev/SharpGLTF
src/SharpGLTF.Core/Animations/FastCurveSampler.cs
2,118
C#
#nullable enable using System; using System.IO; using System.Threading.Tasks; using GovUk.Education.ExploreEducationStatistics.Common.Cache.Interfaces; using GovUk.Education.ExploreEducationStatistics.Common.Model; using GovUk.Education.ExploreEducationStatistics.Common.Services.Interfaces; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace GovUk.Education.ExploreEducationStatistics.Common.Services { public class BlobCacheService : IBlobCacheService { private readonly IBlobStorageService _blobStorageService; private readonly ILogger<BlobCacheService> _logger; public BlobCacheService(IBlobStorageService blobStorageService, ILogger<BlobCacheService> logger) { _blobStorageService = blobStorageService; _logger = logger; } public async Task DeleteItem(IBlobCacheKey cacheKey) { await _blobStorageService.DeleteBlob(cacheKey.Container, cacheKey.Key); } public async Task<TItem> GetItem<TItem>( IBlobCacheKey cacheKey, Func<TItem> itemSupplier) where TItem : class { // Attempt to read blob from the cache container var cachedEntity = await GetItem<TItem>(cacheKey); if (cachedEntity != null) { return cachedEntity; } // Cache miss - invoke provider instead var entity = itemSupplier(); // Write result to cache as a json blob before returning await SetItem(cacheKey, entity); return entity; } public async Task<TItem> GetItem<TItem>( IBlobCacheKey cacheKey, Func<Task<TItem>> itemSupplier) where TItem : class { // Attempt to read blob from the cache container var cachedEntity = await GetItem<TItem>(cacheKey); if (cachedEntity != null) { return cachedEntity; } // Cache miss - invoke provider instead var entity = await itemSupplier(); // Write result to cache as a json blob before returning await SetItem(cacheKey, entity); return entity; } public async Task<Either<ActionResult, TItem>> GetItem<TItem>( IBlobCacheKey cacheKey, Func<Task<Either<ActionResult, TItem>>> itemSupplier) where TItem : class { // Attempt to read blob from the cache container var cachedEntity = await GetItem<TItem>(cacheKey); if (cachedEntity != null) { return cachedEntity; } // Cache miss - invoke provider instead return await itemSupplier().OnSuccessDo(async entity => { // Write result to cache as a json blob before returning await SetItem(cacheKey, entity); }); } public async Task<TItem?> GetItem<TItem>(IBlobCacheKey cacheKey) where TItem : class { return (TItem?) await GetItem(cacheKey, typeof(TItem)); } public async Task<object?> GetItem(IBlobCacheKey cacheKey, Type targetType) { var blobContainer = cacheKey.Container; var key = cacheKey.Key; // Attempt to read blob from the storage container try { return await _blobStorageService.GetDeserializedJson(cacheKey.Container, cacheKey.Key, targetType); } catch (JsonException) { // If there's an error deserializing the blob, we should // assume it's not salvageable and delete it so that it's re-built. await _blobStorageService.DeleteBlob(blobContainer, key); } catch (FileNotFoundException) { // Do nothing as the blob just doesn't exist } catch (Exception e) { _logger.LogError(e, $"Caught error fetching cache entry from: {blobContainer}/{key}"); } return default; } public async Task SetItem<TItem>( IBlobCacheKey cacheKey, TItem item) { // Write result to cache as a json blob before returning await _blobStorageService.UploadAsJson(cacheKey.Container, cacheKey.Key, item); } } }
33.588235
115
0.588004
[ "MIT" ]
dfe-analytical-services/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Common/Services/BlobCacheService.cs
4,570
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows; using GenshinPlayerQuery.View; namespace GenshinPlayerQuery.Core { internal static class MessageBus { private const int COOKIE_HTTP_ONLY = 0x00002000; private const string COOKIE_NAME_LOGIN_TICKET = "login_ticket"; private const string COOKIE_URL = "https://user.mihoyo.com/"; private const string LOGIN_TICKET_FILE = "ticket.txt"; private const string QUERY_HISTORY_FILE = "history.txt"; private const int MAX_QUERY_HISTORY_COUNT = 10; static MessageBus() { new Thread(UpdateChecker.CheckUpdate).Start(); if (File.Exists(LOGIN_TICKET_FILE)) { LoginTicket = File.ReadAllText(LOGIN_TICKET_FILE); SetBrowserLoginTicket(LoginTicket); } if (File.Exists(QUERY_HISTORY_FILE)) { try { string queryHistory = File.ReadAllText(QUERY_HISTORY_FILE); QueryHistory.AddRange(Regex.Split(queryHistory.Trim(), "\r\n|\r|\n")); } catch { MessageBox.Show("查询历史记录解析失败"); } } } public static string LoginTicket { get; set; } public static List<string> QueryHistory { get; set; } = new List<string>(); public static LoginWindow LoginWindow { get; set; } public static MainWindow MainWindow { get; set; } public static void AddQueryHistory(string uid) { if (!QueryHistory.Contains(uid)) { MainWindow.ComboBoxUserId.Items.Add(uid); QueryHistory.Add(uid); if (QueryHistory.Count > MAX_QUERY_HISTORY_COUNT) { MainWindow.ComboBoxUserId.Items.RemoveAt(0); QueryHistory.RemoveAt(0); } } } public static void Exit() { StringBuilder queryHistory = new StringBuilder(); foreach (string uid in QueryHistory) { queryHistory.AppendLine(uid); } File.WriteAllText(QUERY_HISTORY_FILE, queryHistory.ToString()); Environment.Exit(0); } public static void Login() { MainWindow.Visibility = Visibility.Hidden; new LoginWindow().Show(); } public static void AfterLoginSuccessful() { LoginTicket = GetBrowserLoginTicket(); File.WriteAllText(LOGIN_TICKET_FILE, LoginTicket); LoginWindow.Close(); MainWindow.Visibility = Visibility.Visible; } public static void AfterLoginFailed() { MessageBox.Show("工具需要您的米游社Cookie来调用查询接口\r\n此操作不会泄露您的账号信息", "提示", MessageBoxButton.OK); Exit(); } public static void ShowRoleDetails(string uid, string server, string roleId) { new RoleWindow(uid, server, roleId).Show(); } public static string GetBrowserLoginTicket() { const string url = COOKIE_URL; StringBuilder loginTicket = new StringBuilder(); uint size = 256; InternetGetCookieEx(url, COOKIE_NAME_LOGIN_TICKET, loginTicket, ref size, COOKIE_HTTP_ONLY, IntPtr.Zero); return loginTicket.ToString(); } public static void SetBrowserLoginTicket(string loginTicket) { if (loginTicket.StartsWith(COOKIE_NAME_LOGIN_TICKET + "=")) { loginTicket = loginTicket.Split('=')[1]; } const string url = COOKIE_URL; InternetSetCookieEx(url, COOKIE_NAME_LOGIN_TICKET, loginTicket, COOKIE_HTTP_ONLY, IntPtr.Zero); } [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetGetCookieEx( string url, string cookieName, StringBuilder cookieData, ref uint cookieSize, int flags, IntPtr reversed); [DllImport("wininet.dll", SetLastError = true)] private static extern int InternetSetCookieEx( string url, string cookieName, string cookieData, int flags, IntPtr reversed); } }
33.766917
117
0.586284
[ "Apache-2.0" ]
GengGode/GenshinPlayerQuery
src/Core/MessageBus.cs
4,575
C#
namespace Serenity.Data { using System; using System.Text; /// <summary> /// An object that is used to create criterias by employing operator overloading /// features of C# language, instead of using string based criterias.</summary> #if !COREFX [Serializable] #endif public class Criteria : BaseCriteria { public static readonly BaseCriteria Empty = new Criteria(); public static readonly BaseCriteria False = new Criteria("0=1"); public static readonly BaseCriteria True = new Criteria("1=1"); private string expression; /// <summary> /// Creates an empty criteria</summary> private Criteria() { } /// <summary> /// Creates a new criteria with given condition. This condition is usually a /// field name, but it can also be a criteria text pre-generated.</summary> /// <remarks> /// Usually used like: <c>new Criteria("fieldname") >= 5</c>.</remarks> /// <param name="text"> /// A field name or criteria condition (can be null)</param> public Criteria(string text) { this.expression = text; } /// <summary> /// Creates a new criteria that contains field name of the metafield.</summary> /// <param name="field"> /// Field (required).</param> public Criteria(IField field) { if (field == null) throw new ArgumentNullException("field"); this.expression = field.Expression; } /// <summary> /// Belirtilen tablo alias'ı ve alan adını aralarına nokta koyarak içeren yeni bir /// kriter oluşturur.</summary> /// <param name="alias"> /// Tablo alias'ı. Null ya da boş olursa önemsenmez.</param> /// <param name="field"> /// Alan adı (zorunlu).</param> public Criteria(string alias, string field) { if (String.IsNullOrEmpty(field)) throw new ArgumentNullException("field"); if (String.IsNullOrEmpty(alias)) throw new ArgumentNullException("alias"); this.expression = alias + "." + SqlSyntax.AutoBracketValid(field); } /// <summary> /// Belirtilen numerik tablo alias'ı (başına T konarak) ve alan adını aralarına /// nokta koyarak içeren yeni bir kriter oluşturur.</summary> /// <param name="joinNumber"> /// Join numarası (T1 gibi kullanılır). Değer sıfırdan küçükse alan adı tek başına /// kullanılır.</param> /// <param name="field"> /// Alan adı (zorunlu).</param> public Criteria(int joinNumber, string field) { if (String.IsNullOrEmpty(field)) throw new ArgumentNullException("field"); if (joinNumber < 0) throw new ArgumentOutOfRangeException("joinNumber"); this.expression = joinNumber.TableAliasDot() + SqlSyntax.AutoBracketValid(field); } /// <summary> /// Belirtilen numerik tablo alias'ı (başına T konarak) ve alanın adını aralarına /// nokta koyarak içeren yeni bir kriter oluşturur.</summary> /// <param name="alias"> /// Join aliası (T1 gibi kullanılır)</param> /// <param name="field"> /// Alan nesnesi (zorunlu).</param> public Criteria(IAlias alias, IField field) : this(alias.Name, field.Name) { } /// <summary> /// Belirtilen numerik tablo alias'ı (başına T konarak) ve alanın adını aralarına /// nokta koyarak içeren yeni bir kriter oluşturur.</summary> /// <param name="alias"> /// Join aliası (T1 gibi kullanılır)</param> /// <param name="field"> /// Alan nesnesi (zorunlu).</param> public Criteria(IAlias alias, string field) : this(alias.Name, field) { } /// <summary> /// Belirtilen numerik tablo alias'ı (başına T konarak) ve alanın adını aralarına /// nokta koyarak içeren yeni bir kriter oluşturur.</summary> /// <param name="joinNumber"> /// Join numarası (T1 gibi kullanılır)</param> /// <param name="field"> /// Alan nesnesi (zorunlu).</param> public Criteria(int joinNumber, IField field) : this(joinNumber, field.Name) { } /// <summary> /// Belirtilen join ve meta alanın adını aralarına nokta koyarak içeren yeni bir /// kriter oluşturur.</summary> /// <param name="join"> /// Tablo alias bilgisini içeren LeftJoin nesnesi (zorunlu).</param> /// <param name="field"> /// Field alan (zorunlu).</param> public Criteria(string join, IField field) : this(join, field.Name) { } /// <summary> /// Belirtilen SqlQuery i içeren yeni bir /// kriter oluşturur.</summary> /// <param name="query"> /// Query nesnesi (genellikle sub query).</param> public Criteria(ISqlQuery query) : this(query.ToString()) { } /// <summary> /// Verilen alan adını köşeli parantez içine alarak yeni bir kriter oluşturur. /// SQL'de boşluk içeren ya da keyword olan alan adlarının kullanılabilmesi /// için gerekebilir.</summary> /// <param name="fieldName"> /// Köşeli parantez içine alınıp kriterye çevrilecek alan adı (zorunlu).</param> /// <returns> /// Alan adını köşeli parantez içinde içeren yeni bir kriter.</returns> public static Criteria Bracket(string fieldName) { if (String.IsNullOrEmpty(fieldName)) throw new ArgumentNullException("fieldName"); return new Criteria("[" + fieldName + "]"); } /// <summary> /// Creates a new EXISTS criteria</summary> /// <param name="query"> /// Expression</param> /// <returns></returns> public static BaseCriteria Exists(ISqlQuery query) { return new UnaryCriteria(CriteriaOperator.Exists, new Criteria(query)); } /// <summary> /// Creates a new EXISTS criteria</summary> /// <param name="expression"> /// Expression</param> /// <returns></returns> public static BaseCriteria Exists(string expression) { return new UnaryCriteria(CriteriaOperator.Exists, new Criteria(expression)); } /// <summary> /// Gets if criteria is empty.</summary> public override bool IsEmpty { get { return String.IsNullOrEmpty(expression); } } public override void ToString(StringBuilder sb, IQueryWithParams query) { sb.Append(this.expression); } public string Expression { get { return expression; } } } }
35.597015
93
0.559888
[ "MIT" ]
davidzhang9990/SimpleProject
Serenity.Data/Criteria/Criteria.cs
7,260
C#
// ***************************************************************************** // 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.490) // Version 5.490.0.0 www.ComponentFactory.com // ***************************************************************************** using System; namespace Krypton.Docking { /// <summary> /// Event arguments for a AutoHiddenGroupPanelAdding/AutoHiddenGroupPanelRemoved events. /// </summary> public class AutoHiddenGroupPanelEventArgs : EventArgs { #region Instance Fields #endregion #region Identity /// <summary> /// Initialize a new instance of the AutoHiddenGroupPanelEventArgs class. /// </summary> /// <param name="autoHiddenPanel">Reference to auto hidden panel control instance.</param> /// <param name="element">Reference to docking auto hidden edge element that is managing the panel.</param> public AutoHiddenGroupPanelEventArgs(KryptonAutoHiddenPanel autoHiddenPanel, KryptonDockingEdgeAutoHidden element) { AutoHiddenPanelControl = autoHiddenPanel; EdgeAutoHiddenElement = element; } #endregion #region Public /// <summary> /// Gets a reference to the KryptonAutoHiddenPanel control. /// </summary> public KryptonAutoHiddenPanel AutoHiddenPanelControl { get; } /// <summary> /// Gets a reference to the KryptonDockingEdgeAutoHidden that is managing the edge. /// </summary> public KryptonDockingEdgeAutoHidden EdgeAutoHiddenElement { get; } #endregion } }
41
157
0.623102
[ "BSD-3-Clause" ]
Carko/Krypton-Toolkit-Suite-NET-Core
Source/Truncated Namespaces/Source/Krypton Components/Krypton.Docking/Event Args/AutoHiddenGroupPanelEventArgs.cs
2,176
C#
using YAF.Lucene.Net.Analysis.TokenAttributes; namespace YAF.Lucene.Net.Analysis.Ckb { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A <see cref="TokenFilter"/> that applies <see cref="SoraniStemmer"/> to stem Sorani words. /// <para> /// To prevent terms from being stemmed use an instance of /// <see cref="Miscellaneous.SetKeywordMarkerFilter"/> or a custom <see cref="TokenFilter"/> that sets /// the <see cref="KeywordAttribute"/> before this <see cref="TokenStream"/>. /// </para> /// </summary> /// <seealso cref="Miscellaneous.SetKeywordMarkerFilter"/> public sealed class SoraniStemFilter : TokenFilter { private readonly SoraniStemmer stemmer = new SoraniStemmer(); private readonly ICharTermAttribute termAtt; private readonly IKeywordAttribute keywordAttr; public SoraniStemFilter(TokenStream input) : base(input) { termAtt = AddAttribute<ICharTermAttribute>(); keywordAttr = AddAttribute<IKeywordAttribute>(); } public override bool IncrementToken() { if (m_input.IncrementToken()) { if (!keywordAttr.IsKeyword) { int newlen = stemmer.Stem(termAtt.Buffer, termAtt.Length); termAtt.Length = newlen; } return true; } else { return false; } } } }
38.737705
107
0.617435
[ "Apache-2.0" ]
AlbertoP57/YAFNET
yafsrc/Lucene.Net/Lucene.Net.Analysis.Common/Analysis/Ckb/SoraniStemFilter.cs
2,305
C#
using System; using System.Collections.Generic; using Newtonsoft.Json; using Xunit.Abstractions; namespace Xunit { internal class SerializedList<T> : List<T>, IXunitSerializable { private const string CountField = "Count"; private const string ItemTypeFieldPrefix = "ItemType"; private const string ItemFieldPrefix = "Item"; public SerializedList() { } public SerializedList(List<T> values) { this.AddRange(values); } public void Deserialize(IXunitSerializationInfo info) { int count = info.GetValue<int>(CountField); this.Capacity = count; for (int i = 0; i < count; i++) { string typeName = info.GetValue<string>(ItemTypeFieldPrefix + i); Type type = Type.GetType(typeName); this.Add((T)JsonConvert.DeserializeObject(info.GetValue<string>(ItemFieldPrefix + i), type)); } } public void Serialize(IXunitSerializationInfo info) { info.AddValue(CountField, this.Count, typeof(int)); for (int i = 0; i < this.Count; i++) { info.AddValue(ItemTypeFieldPrefix + i, this[i].GetType().AssemblyQualifiedName, typeof(string)); info.AddValue(ItemFieldPrefix + i, JsonConvert.SerializeObject(this[i]), typeof(string)); } } } }
26.733333
100
0.705736
[ "MIT" ]
davidwengier/Xunit.SerializedTheoryData
src/SerializedList.cs
1,205
C#
using UnityEngine; using System.Collections; public class GoalGOB { public string name; public float value; public float change; public virtual float GetDiscontentment(float newValue) { return newValue * newValue; } public virtual float GetChange() { return 0f; } }
16.3
58
0.644172
[ "MIT" ]
PacktPublishing/Complete-Unity-2018-Game-Development
UAIPC/Assets/_UnityAIPC/Scripts/Ch03DecisionMaking/GoalGOB.cs
328
C#
// Copyright 2020 Andreas Atteneder // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; namespace GLTFast { using Schema; public interface IMaterialGenerator { UnityEngine.Material GetPbrMetallicRoughnessMaterial(bool doubleSided=false); UnityEngine.Material GenerateMaterial( Material gltfMaterial, ref Schema.Texture[] textures, ref Schema.Image[] schemaImages, ref Dictionary<int,UnityEngine.Texture2D>[] imageVariants, string url, int id =0 ); } }
33.69697
85
0.695144
[ "Apache-2.0" ]
Gfi-Innovation/UMI3D-Desktop-Browser
UMI3D-Browser-Desktop/Assets/UMI3D SDK/Dependencies/Runtime/GltFast/Runtime/Scripts/IMaterialGenerator.cs
1,114
C#
using System; using System.Reactive.Linq; using System.Threading.Tasks; using GitHub.Api; using GitHub.Factories; using GitHub.Models; using GitHub.Primitives; using GitHub.Services; using GitHub.ViewModels; using GitHub.ViewModels.GitHubPane; using NSubstitute; using Octokit; using UnitTests; using NUnit.Framework; using IConnection = GitHub.Models.IConnection; /// <summary> /// All the tests in this class are split in subclasses so that when they run /// in parallel the temp dir is set up uniquely for each test /// </summary> public class PullRequestCreationViewModelTests : TestBaseClass { static LibGit2Sharp.IRepository SetupLocalRepoMock(IGitClient gitClient, IGitService gitService, string remote, string head, bool isTracking) { var l2remote = Substitute.For<LibGit2Sharp.Remote>(); l2remote.Name.Returns(remote); gitClient.GetHttpRemote(Args.LibGit2Repo, Args.String).Returns(Task.FromResult(l2remote)); var l2repo = Substitute.For<LibGit2Sharp.IRepository>(); var l2branchcol = Substitute.For<LibGit2Sharp.BranchCollection>(); var l2branch = Substitute.For<LibGit2Sharp.Branch>(); l2branch.FriendlyName.Returns(head); l2branch.IsTracking.Returns(isTracking); l2branchcol[Args.String].Returns(l2branch); l2repo.Branches.Returns(l2branchcol); l2repo.Head.Returns(l2branch); gitService.GetRepository(Args.String).Returns(l2repo); return l2repo; } struct TestData { public IServiceProvider ServiceProvider; public ILocalRepositoryModel ActiveRepo; public LibGit2Sharp.IRepository L2Repo; public IRepositoryModel SourceRepo; public IRepositoryModel TargetRepo; public IBranch SourceBranch; public IBranch TargetBranch; public IGitClient GitClient; public IGitService GitService; public INotificationService NotificationService; public IConnection Connection; public IApiClient ApiClient; public IModelService ModelService; public IModelServiceFactory GetModelServiceFactory() { var result = Substitute.For<IModelServiceFactory>(); result.CreateAsync(Connection).Returns(ModelService); result.CreateBlocking(Connection).Returns(ModelService); return result; } } static TestData PrepareTestData( string repoName, string sourceRepoOwner, string sourceBranchName, string targetRepoOwner, string targetBranchName, string remote, bool repoIsFork, bool sourceBranchIsTracking) { var serviceProvider = Substitutes.ServiceProvider; var gitService = serviceProvider.GetGitService(); var gitClient = Substitute.For<IGitClient>(); var notifications = Substitute.For<INotificationService>(); var connection = Substitute.For<IConnection>(); var api = Substitute.For<IApiClient>(); var ms = Substitute.For<IModelService>(); connection.HostAddress.Returns(HostAddress.Create("https://github.com")); // this is the local repo instance that is available via TeamExplorerServiceHolder and friends var activeRepo = Substitute.For<ILocalRepositoryModel>(); activeRepo.LocalPath.Returns(""); activeRepo.Name.Returns(repoName); activeRepo.CloneUrl.Returns(new UriString("http://github.com/" + sourceRepoOwner + "/" + repoName)); activeRepo.Owner.Returns(sourceRepoOwner); Repository githubRepoParent = null; if (repoIsFork) githubRepoParent = CreateRepository(targetRepoOwner, repoName, id: 1); var githubRepo = CreateRepository(sourceRepoOwner, repoName, id: 2, parent: githubRepoParent); var sourceBranch = new BranchModel(sourceBranchName, activeRepo); var sourceRepo = new RemoteRepositoryModel(githubRepo); var targetRepo = targetRepoOwner == sourceRepoOwner ? sourceRepo : sourceRepo.Parent; var targetBranch = targetBranchName != targetRepo.DefaultBranch.Name ? new BranchModel(targetBranchName, targetRepo) : targetRepo.DefaultBranch; activeRepo.CurrentBranch.Returns(sourceBranch); api.GetRepository(Args.String, Args.String).Returns(Observable.Return(githubRepo)); ms.ApiClient.Returns(api); // sets up the libgit2sharp repo and branch objects var l2repo = SetupLocalRepoMock(gitClient, gitService, remote, sourceBranchName, sourceBranchIsTracking); return new TestData { ServiceProvider = serviceProvider, ActiveRepo = activeRepo, L2Repo = l2repo, SourceRepo = sourceRepo, SourceBranch = sourceBranch, TargetRepo = targetRepo, TargetBranch = targetBranch, GitClient = gitClient, GitService = gitService, NotificationService = notifications, Connection = connection, ApiClient = api, ModelService = ms }; } [Test] public void TargetBranchDisplayNameIncludesRepoOwnerWhenFork() { var data = PrepareTestData("octokit.net", "shana", "master", "octokit", "master", "origin", true, true); var prservice = new PullRequestService(data.GitClient, data.GitService, Substitute.For<IVSGitExt>(), data.ServiceProvider.GetOperatingSystem(), Substitute.For<IUsageTracker>()); prservice.GetPullRequestTemplate(data.ActiveRepo).Returns(Observable.Empty<string>()); var vm = new PullRequestCreationViewModel(data.GetModelServiceFactory(), prservice, data.NotificationService); vm.InitializeAsync(data.ActiveRepo, data.Connection).Wait(); Assert.That("octokit/master", Is.EqualTo(vm.TargetBranch.DisplayName)); } [TestCase("repo-name-1", "source-repo-owner", "source-branch", true, true, "target-repo-owner", "target-branch", "title", null)] [TestCase("repo-name-2", "source-repo-owner", "source-branch", true, true, "target-repo-owner", "master", "title", "description")] [TestCase("repo-name-3", "source-repo-owner", "master", true, true, "target-repo-owner", "master", "title", "description")] [TestCase("repo-name-4", "source-repo-owner", "source-branch", false, true, "source-repo-owner", "target-branch", "title", null)] [TestCase("repo-name-5", "source-repo-owner", "source-branch", false, true, "source-repo-owner", "master", "title", "description")] [TestCase("repo-name-6", "source-repo-owner", "source-branch", true, false, "target-repo-owner", "target-branch", "title", null)] [TestCase("repo-name-7", "source-repo-owner", "source-branch", true, false, "target-repo-owner", "master", "title", "description")] [TestCase("repo-name-8", "source-repo-owner", "master", true, false, "target-repo-owner", "master", "title", "description")] [TestCase("repo-name-9", "source-repo-owner", "source-branch", false, false, "source-repo-owner", "target-branch", "title", null)] [TestCase("repo-name-10", "source-repo-owner", "source-branch", false, false, "source-repo-owner", "master", "title", "description")] [TestCase("repo-name-11", "source-repo-owner", "source-branch", false, false, "source-repo-owner", "master", null, null)] public async Task CreatingPRs( string repoName, string sourceRepoOwner, string sourceBranchName, bool repoIsFork, bool sourceBranchIsTracking, string targetRepoOwner, string targetBranchName, string title, string body) { var remote = "origin"; var data = PrepareTestData(repoName, sourceRepoOwner, sourceBranchName, targetRepoOwner, targetBranchName, "origin", repoIsFork, sourceBranchIsTracking); var targetRepo = data.TargetRepo; var gitClient = data.GitClient; var l2repo = data.L2Repo; var activeRepo = data.ActiveRepo; var sourceBranch = data.SourceBranch; var targetBranch = data.TargetBranch; var ms = data.ModelService; var prservice = new PullRequestService(data.GitClient, data.GitService, Substitute.For<IVSGitExt>(), data.ServiceProvider.GetOperatingSystem(), Substitute.For<IUsageTracker>()); var vm = new PullRequestCreationViewModel(data.GetModelServiceFactory(), prservice, data.NotificationService); await vm.InitializeAsync(data.ActiveRepo, data.Connection); // the TargetBranch property gets set to whatever the repo default is (we assume master here), // so we only set it manually to emulate the user selecting a different target branch if (targetBranchName != "master") vm.TargetBranch = new BranchModel(targetBranchName, targetRepo); if (title != null) vm.PRTitle = title; // this is optional if (body != null) vm.Description = body; ms.CreatePullRequest(activeRepo, targetRepo, sourceBranch, targetBranch, Arg.Any<string>(), Arg.Any<string>()) .Returns(x => { var pr = Substitute.For<IPullRequestModel>(); pr.Base.Returns(new GitReferenceModel("ref", "label", "sha", "https://clone.url")); return Observable.Return(pr); }); await vm.CreatePullRequest.ExecuteAsync(); var unused2 = gitClient.Received().Push(l2repo, sourceBranchName, remote); if (!sourceBranchIsTracking) unused2 = gitClient.Received().SetTrackingBranch(l2repo, sourceBranchName, remote); else unused2 = gitClient.DidNotReceiveWithAnyArgs().SetTrackingBranch(Args.LibGit2Repo, Args.String, Args.String); var unused = ms.Received().CreatePullRequest(activeRepo, targetRepo, sourceBranch, targetBranch, title ?? "Source branch", body ?? String.Empty); } [Test] public void TemplateIsUsedIfPresent() { var data = PrepareTestData("stuff", "owner", "master", "owner", "master", "origin", false, true); var prservice = Substitute.For<IPullRequestService>(); prservice.GetPullRequestTemplate(data.ActiveRepo).Returns(Observable.Return("Test PR template")); var vm = new PullRequestCreationViewModel(data.GetModelServiceFactory(), prservice, data.NotificationService); vm.InitializeAsync(data.ActiveRepo, data.Connection).Wait(); Assert.That("Test PR template", Is.EqualTo(vm.Description)); } }
49.018779
185
0.685567
[ "MIT" ]
eladsnacj/VisualStudio
test/UnitTests/GitHub.App/ViewModels/Dialog/PullRequestCreationViewModelTests.cs
10,443
C#
using System; using System.Diagnostics; using Lucene.Net.Documents; namespace Lucene.Net.Search { using Lucene.Net.Index; using NUnit.Framework; using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DirectoryReader = Lucene.Net.Index.DirectoryReader; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using FloatField = FloatField; using IndexReader = Lucene.Net.Index.IndexReader; using IntField = IntField; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MultiFields = Lucene.Net.Index.MultiFields; using NumericUtils = Lucene.Net.Util.NumericUtils; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using TestNumericUtils = Lucene.Net.Util.TestNumericUtils; // NaN arrays using TestUtil = Lucene.Net.Util.TestUtil; [TestFixture] public class TestNumericRangeQuery32 : LuceneTestCase { // distance of entries private static int Distance; // shift the starting of the values to the left, to also have negative values: private static readonly int StartOffset = -1 << 15; // number of docs to generate for testing private static int NoDocs; private static Directory Directory = null; private static IndexReader Reader = null; private static IndexSearcher Searcher = null; [TestFixtureSetUp] public static void BeforeClass() { NoDocs = AtLeast(4096); Distance = (1 << 30) / NoDocs; Directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 100, 1000)).SetMergePolicy(NewLogMergePolicy())); FieldType storedInt = new FieldType(IntField.TYPE_NOT_STORED); storedInt.Stored = true; storedInt.Freeze(); FieldType storedInt8 = new FieldType(storedInt); storedInt8.NumericPrecisionStep = 8; FieldType storedInt4 = new FieldType(storedInt); storedInt4.NumericPrecisionStep = 4; FieldType storedInt2 = new FieldType(storedInt); storedInt2.NumericPrecisionStep = 2; FieldType storedIntNone = new FieldType(storedInt); storedIntNone.NumericPrecisionStep = int.MaxValue; FieldType unstoredInt = IntField.TYPE_NOT_STORED; FieldType unstoredInt8 = new FieldType(unstoredInt); unstoredInt8.NumericPrecisionStep = 8; FieldType unstoredInt4 = new FieldType(unstoredInt); unstoredInt4.NumericPrecisionStep = 4; FieldType unstoredInt2 = new FieldType(unstoredInt); unstoredInt2.NumericPrecisionStep = 2; IntField field8 = new IntField("field8", 0, storedInt8), field4 = new IntField("field4", 0, storedInt4), field2 = new IntField("field2", 0, storedInt2), fieldNoTrie = new IntField("field" + int.MaxValue, 0, storedIntNone), ascfield8 = new IntField("ascfield8", 0, unstoredInt8), ascfield4 = new IntField("ascfield4", 0, unstoredInt4), ascfield2 = new IntField("ascfield2", 0, unstoredInt2); Document doc = new Document(); // add fields, that have a distance to test general functionality doc.Add(field8); doc.Add(field4); doc.Add(field2); doc.Add(fieldNoTrie); // add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive doc.Add(ascfield8); doc.Add(ascfield4); doc.Add(ascfield2); // Add a series of noDocs docs with increasing int values for (int l = 0; l < NoDocs; l++) { int val = Distance * l + StartOffset; field8.IntValue = val; field4.IntValue = val; field2.IntValue = val; fieldNoTrie.IntValue = val; val = l - (NoDocs / 2); ascfield8.IntValue = val; ascfield4.IntValue = val; ascfield2.IntValue = val; writer.AddDocument(doc); } Reader = writer.Reader; Searcher = NewSearcher(Reader); writer.Dispose(); } [TestFixtureTearDown] public static void AfterClass() { Searcher = null; Reader.Dispose(); Reader = null; Directory.Dispose(); Directory = null; } [SetUp] public override void SetUp() { base.SetUp(); // set the theoretical maximum term count for 8bit (see docs for the number) // super.tearDown will restore the default BooleanQuery.MaxClauseCount = 3 * 255 * 2 + 255; } /// <summary> /// test for both constant score and boolean query, the other tests only use the constant score mode </summary> private void TestRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; int lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3); NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, true); NumericRangeFilter<int> f = NumericRangeFilter.NewIntRange(field, precisionStep, lower, upper, true, true); for (sbyte i = 0; i < 3; i++) { TopDocs topDocs; string type; switch (i) { case 0: type = " (constant score filter rewrite)"; q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); break; case 1: type = " (constant score boolean rewrite)"; q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); break; case 2: type = " (filter)"; topDocs = Searcher.Search(new MatchAllDocsQuery(), f, NoDocs, Sort.INDEXORDER); break; default: return; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count" + type); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(2 * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "First doc" + type); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((1 + count) * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "Last doc" + type); } } [Test] public virtual void TestRange_8bit() { TestRange(8); } [Test] public virtual void TestRange_4bit() { TestRange(4); } [Test] public virtual void TestRange_2bit() { TestRange(2); } [Test] public virtual void TestInverseRange() { AtomicReaderContext context = (AtomicReaderContext)SlowCompositeReaderWrapper.Wrap(Reader).Context; NumericRangeFilter<int> f = NumericRangeFilter.NewIntRange("field8", 8, 1000, -1000, true, true); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A inverse range should return the null instance"); f = NumericRangeFilter.NewIntRange("field8", 8, int.MaxValue, null, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range starting with Integer.MAX_VALUE should return the null instance"); f = NumericRangeFilter.NewIntRange("field8", 8, null, int.MinValue, false, false); Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range ending with Integer.MIN_VALUE should return the null instance"); } [Test] public virtual void TestOneMatchQuery() { NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange("ascfield8", 8, 1000, 1000, true, true); TopDocs topDocs = Searcher.Search(q, NoDocs); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(1, sd.Length, "Score doc count"); } private void TestLeftOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; int upper = (count - 1) * Distance + (Distance / 3) + StartOffset; NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, null, upper, true, true); TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(StartOffset, (int)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "Last doc"); q = NumericRangeQuery.NewIntRange(field, precisionStep, null, upper, false, true); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(count, sd.Length, "Score doc count"); doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(StartOffset, (int)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((count - 1) * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "Last doc"); } [Test] public virtual void TestLeftOpenRange_8bit() { TestLeftOpenRange(8); } [Test] public virtual void TestLeftOpenRange_4bit() { TestLeftOpenRange(4); } [Test] public virtual void TestLeftOpenRange_2bit() { TestLeftOpenRange(2); } private void TestRightOpenRange(int precisionStep) { string field = "field" + precisionStep; int count = 3000; int lower = (count - 1) * Distance + (Distance / 3) + StartOffset; NumericRangeQuery<int> q = NumericRangeQuery.NewIntRange(field, precisionStep, lower, null, true, true); TopDocs topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count"); Document doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(count * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "Last doc"); q = NumericRangeQuery.NewIntRange(field, precisionStep, lower, null, true, false); topDocs = Searcher.Search(q, null, NoDocs, Sort.INDEXORDER); sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); Assert.AreEqual(NoDocs - count, sd.Length, "Score doc count"); doc = Searcher.Doc(sd[0].Doc); Assert.AreEqual(count * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "First doc"); doc = Searcher.Doc(sd[sd.Length - 1].Doc); Assert.AreEqual((NoDocs - 1) * Distance + StartOffset, (int)doc.GetField(field).NumericValue, "Last doc"); } [Test] public virtual void TestRightOpenRange_8bit() { TestRightOpenRange(8); } [Test] public virtual void TestRightOpenRange_4bit() { TestRightOpenRange(4); } public virtual void TestRightOpenRange_2bit() { TestRightOpenRange(2); } [Test] public virtual void TestInfiniteValues() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(new FloatField("float", float.NegativeInfinity, Field.Store.NO)); doc.Add(new IntField("int", int.MinValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new FloatField("float", float.PositiveInfinity, Field.Store.NO)); doc.Add(new IntField("int", int.MaxValue, Field.Store.NO)); writer.AddDocument(doc); doc = new Document(); doc.Add(new FloatField("float", 0.0f, Field.Store.NO)); doc.Add(new IntField("int", 0, Field.Store.NO)); writer.AddDocument(doc); foreach (float f in TestNumericUtils.FLOAT_NANs) { doc = new Document(); doc.Add(new FloatField("float", f, Field.Store.NO)); writer.AddDocument(doc); } writer.Dispose(); IndexReader r = DirectoryReader.Open(dir); IndexSearcher s = NewSearcher(r); Query q = NumericRangeQuery.NewIntRange("int", null, null, true, true); TopDocs topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewIntRange("int", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewIntRange("int", int.MinValue, int.MaxValue, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewIntRange("int", int.MinValue, int.MaxValue, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewFloatRange("float", null, null, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewFloatRange("float", null, null, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewFloatRange("float", float.NegativeInfinity, float.PositiveInfinity, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewFloatRange("float", float.NegativeInfinity, float.PositiveInfinity, false, false); topDocs = s.Search(q, 10); Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count"); q = NumericRangeQuery.NewFloatRange("float", float.NaN, float.NaN, true, true); topDocs = s.Search(q, 10); Assert.AreEqual(TestNumericUtils.FLOAT_NANs.Length, topDocs.ScoreDocs.Length, "Score doc count"); r.Dispose(); dir.Dispose(); } private void TestRandomTrieAndClassicRangeQuery(int precisionStep) { string field = "field" + precisionStep; int totalTermCountT = 0, totalTermCountC = 0, termCountT, termCountC; int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { int lower = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset; int upper = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset; if (lower > upper) { int a = lower; lower = upper; upper = a; } BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_INT), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_INT); NumericUtils.IntToPrefixCodedBytes(lower, 0, lowerBytes); NumericUtils.IntToPrefixCodedBytes(upper, 0, upperBytes); // test inclusive range NumericRangeQuery<int> tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, true); TermRangeQuery cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); TopDocs cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, false, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, false); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test left exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, false, true); cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, true); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); // test right exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, false); cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, false); tTopDocs = Searcher.Search(tq, 1); cTopDocs = Searcher.Search(cq, 1); Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal"); totalTermCountT += termCountT = CountTerms(tq); totalTermCountC += termCountC = CountTerms(cq); CheckTermCounts(precisionStep, termCountT, termCountC); } CheckTermCounts(precisionStep, totalTermCountT, totalTermCountC); if (VERBOSE && precisionStep != int.MaxValue) { Console.WriteLine("Average number of terms during random search on '" + field + "':"); Console.WriteLine(" Numeric query: " + (((double)totalTermCountT) / (num * 4))); Console.WriteLine(" Classical query: " + (((double)totalTermCountC) / (num * 4))); } } [Test] public virtual void TestEmptyEnums() { int count = 3000; int lower = (Distance * 3 / 2) + StartOffset, upper = lower + count * Distance + (Distance / 3); // test empty enum Debug.Assert(lower < upper); Assert.IsTrue(0 < CountTerms(NumericRangeQuery.NewIntRange("field4", 4, lower, upper, true, true))); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewIntRange("field4", 4, upper, lower, true, true))); // test empty enum outside of bounds lower = Distance * NoDocs + StartOffset; upper = 2 * lower; Debug.Assert(lower < upper); Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewIntRange("field4", 4, lower, upper, true, true))); } private int CountTerms(MultiTermQuery q) { Terms terms = MultiFields.GetTerms(Reader, q.Field); if (terms == null) { return 0; } TermsEnum termEnum = q.GetTermsEnum(terms); Assert.IsNotNull(termEnum); int count = 0; BytesRef cur, last = null; while ((cur = termEnum.Next()) != null) { count++; if (last != null) { Assert.IsTrue(last.CompareTo(cur) < 0); } last = BytesRef.DeepCopyOf(cur); } // LUCENE-3314: the results after next() already returned null are undefined, // Assert.IsNull(termEnum.Next()); return count; } private void CheckTermCounts(int precisionStep, int termCountT, int termCountC) { if (precisionStep == int.MaxValue) { Assert.AreEqual(termCountC, termCountT, "Number of terms should be equal for unlimited precStep"); } else { Assert.IsTrue(termCountT <= termCountC, "Number of terms for NRQ should be <= compared to classical TRQ"); } } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_8bit() { TestRandomTrieAndClassicRangeQuery(8); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_4bit() { TestRandomTrieAndClassicRangeQuery(4); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_2bit() { TestRandomTrieAndClassicRangeQuery(2); } [Test] public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie() { TestRandomTrieAndClassicRangeQuery(int.MaxValue); } private void TestRangeSplit(int precisionStep) { string field = "ascfield" + precisionStep; // 10 random tests int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { int lower = (int)(Random().NextDouble() * NoDocs - NoDocs / 2); int upper = (int)(Random().NextDouble() * NoDocs - NoDocs / 2); if (lower > upper) { int a = lower; lower = upper; upper = a; } // test inclusive range Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); // test exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, false, false); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length"); // test left exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, false, true); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); // test right exclusive range tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, false); tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length"); } } [Test] public virtual void TestRangeSplit_8bit() { TestRangeSplit(8); } [Test] public virtual void TestRangeSplit_4bit() { TestRangeSplit(4); } [Test] public virtual void TestRangeSplit_2bit() { TestRangeSplit(2); } /// <summary> /// we fake a float test using int2float conversion of NumericUtils </summary> private void TestFloatRange(int precisionStep) { string field = "ascfield" + precisionStep; const int lower = -1000, upper = +2000; Query tq = NumericRangeQuery.NewFloatRange(field, precisionStep, NumericUtils.SortableIntToFloat(lower), NumericUtils.SortableIntToFloat(upper), true, true); TopDocs tTopDocs = Searcher.Search(tq, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length"); Filter tf = NumericRangeFilter.NewFloatRange(field, precisionStep, NumericUtils.SortableIntToFloat(lower), NumericUtils.SortableIntToFloat(upper), true, true); tTopDocs = Searcher.Search(new MatchAllDocsQuery(), tf, 1); Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length"); } [Test] public virtual void TestFloatRange_8bit() { TestFloatRange(8); } [Test] public virtual void TestFloatRange_4bit() { TestFloatRange(4); } [Test] public virtual void TestFloatRange_2bit() { TestFloatRange(2); } private void TestSorting(int precisionStep) { string field = "field" + precisionStep; // 10 random tests, the index order is ascending, // so using a reverse sort field should retun descending documents int num = TestUtil.NextInt(Random(), 10, 20); for (int i = 0; i < num; i++) { int lower = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset; int upper = (int)(Random().NextDouble() * NoDocs * Distance) + StartOffset; if (lower > upper) { int a = lower; lower = upper; upper = a; } Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, lower, upper, true, true); TopDocs topDocs = Searcher.Search(tq, null, NoDocs, new Sort(new SortField(field, SortField.Type_e.INT, true))); if (topDocs.TotalHits == 0) { continue; } ScoreDoc[] sd = topDocs.ScoreDocs; Assert.IsNotNull(sd); int last = (int)Searcher.Doc(sd[0].Doc).GetField(field).NumericValue; for (int j = 1; j < sd.Length; j++) { int act = (int)Searcher.Doc(sd[j].Doc).GetField(field).NumericValue; Assert.IsTrue(last > act, "Docs should be sorted backwards"); last = act; } } } [Test] public virtual void TestSorting_8bit() { TestSorting(8); } [Test] public virtual void TestSorting_4bit() { TestSorting(4); } [Test] public virtual void TestSorting_2bit() { TestSorting(2); } [Test] public virtual void TestEqualsAndHash() { QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test1", 4, 10, 20, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test2", 4, 10, 20, false, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test3", 4, 10, 20, true, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test4", 4, 10, 20, false, false)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test5", 4, 10, null, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test6", 4, null, 20, true, true)); QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test7", 4, null, null, true, true)); QueryUtils.CheckEqual(NumericRangeQuery.NewIntRange("test8", 4, 10, 20, true, true), NumericRangeQuery.NewIntRange("test8", 4, 10, 20, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test9", 4, 10, 20, true, true), NumericRangeQuery.NewIntRange("test9", 8, 10, 20, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test10a", 4, 10, 20, true, true), NumericRangeQuery.NewIntRange("test10b", 4, 10, 20, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test11", 4, 10, 20, true, true), NumericRangeQuery.NewIntRange("test11", 4, 20, 10, true, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test12", 4, 10, 20, true, true), NumericRangeQuery.NewIntRange("test12", 4, 10, 20, false, true)); QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test13", 4, 10, 20, true, true), NumericRangeQuery.NewFloatRange("test13", 4, 10f, 20f, true, true)); // the following produces a hash collision, because Long and Integer have the same hashcode, so only test equality: Query q1 = NumericRangeQuery.NewIntRange("test14", 4, 10, 20, true, true); Query q2 = NumericRangeQuery.NewLongRange("test14", 4, 10L, 20L, true, true); Assert.IsFalse(q1.Equals(q2)); Assert.IsFalse(q2.Equals(q1)); } } }
45.921429
402
0.588676
[ "Apache-2.0" ]
CerebralMischief/lucenenet
src/Lucene.Net.Tests/core/Search/TestNumericRangeQuery32.cs
32,145
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace YoukaiFox.Audio { public class AudioSettingsMenu : MonoBehaviour { #region Actions #endregion #region Serialized fields [SerializeField] private Slider _musicVolumeSlider; [SerializeField] private Slider _sfxVolumeSlider; [SerializeField] private Toggle _muteSoundToggle; [SerializeField] private bool _updateOnValueChanged = true; // [SerializeField] // [Tooltip("An audio clip to play when adjusting the volume.")] // private AudioClip _audioTestClip; #endregion #region Non-serialized fields private AudioManager _audioManager; #endregion #region Constant fields #endregion #region Unity events private void Start() { _audioManager = FindObjectOfType<AudioManager>(); SetUpListeners(); } private void OnEnable() { LoadSettings(); } #endregion #region Public methods public void UpdateSoundSettings() { if (AudioManager.Instance == null) { return; } var settings = new AudioManager.AudioSettings(); settings.IsMuted = _muteSoundToggle.isOn; settings.BgmVolume = _musicVolumeSlider.value; settings.SfxVolume = _sfxVolumeSlider.value; AudioManager.Instance.UpdateSettings(settings); } #endregion #region Protected methods #endregion #region Private methods private void LoadSettings() { if (AudioManager.Instance == null) { return; } var settings = AudioManager.Instance.GetCurrentSettings(); _muteSoundToggle.isOn = settings.IsMuted; _musicVolumeSlider.value = settings.BgmVolume; _sfxVolumeSlider.value = settings.SfxVolume; } private void SetUpListeners() { if (_updateOnValueChanged) { _muteSoundToggle.onValueChanged.AddListener(delegate {UpdateSoundSettings();}); _musicVolumeSlider.onValueChanged.AddListener(delegate {UpdateSoundSettings();}); _sfxVolumeSlider.onValueChanged.AddListener(delegate {UpdateSoundSettings();}); } } #endregion } }
24.11215
97
0.585271
[ "MIT" ]
YoukaiFox/YoukaiAudioManager
AudioSettingsMenu.cs
2,582
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KryptPadCSApp.Collections { class RefreshableCollection<T> : ObservableCollection<T> { public void RefreshItem(T item) { // Get current item index var index = IndexOf(item); // Remove item Remove(item); // Add item Insert(index, item); } } }
20.72
60
0.608108
[ "MIT" ]
KryptPad/KryptPad
KryptPadCSApp/Collections/RefreshableCollection.cs
520
C#
using PNN.Entities; public class Battleground_OnEntityDespawnedArgs { public readonly Entity affectedEntity; public Battleground_OnEntityDespawnedArgs(Entity affectedEntity) { this.affectedEntity = affectedEntity; } }
20.416667
68
0.763265
[ "MIT" ]
Kalystee/TacticalTurnedBase
Assets/Scripts/Game/Battleground/Events/Battleground_OnEntityDespawnedArgs.cs
247
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using Squidex.Domain.Apps.Core.Assets; using Squidex.Infrastructure; namespace Squidex.Domain.Apps.Core { public interface IUrlGenerator { bool CanGenerateAssetSourceUrl { get; } string? AssetSource(NamedId<DomainId> appId, DomainId assetId, long fileVersion); string? AssetThumbnail(NamedId<DomainId> appId, DomainId assetId, AssetType assetType); string AppSettingsUI(NamedId<DomainId> appId); string AssetsUI(NamedId<DomainId> appId); string AssetsUI(NamedId<DomainId> appId, string? query = null); string AssetContent(NamedId<DomainId> appId, DomainId assetId); string BackupsUI(NamedId<DomainId> appId); string ClientsUI(NamedId<DomainId> appId); string ContentsUI(NamedId<DomainId> appId); string ContentsUI(NamedId<DomainId> appId, NamedId<DomainId> schemaId); string ContentUI(NamedId<DomainId> appId, NamedId<DomainId> schemaId, DomainId contentId); string ContributorsUI(NamedId<DomainId> appId); string DashboardUI(NamedId<DomainId> appId); string LanguagesUI(NamedId<DomainId> appId); string PatternsUI(NamedId<DomainId> appId); string PlansUI(NamedId<DomainId> appId); string RolesUI(NamedId<DomainId> appId); string RulesUI(NamedId<DomainId> appId); string SchemasUI(NamedId<DomainId> appId); string SchemaUI(NamedId<DomainId> appId, NamedId<DomainId> schemaId); string WorkflowsUI(NamedId<DomainId> appId); string UI(); } }
31.080645
98
0.616502
[ "MIT" ]
SpyRefused/chthonianex
backend/src/Squidex.Domain.Apps.Core.Operations/IUrlGenerator.cs
1,929
C#
using System; using System.Windows.Forms; namespace ArchiveIntegrityChecker { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmMain()); } } }
22.05
65
0.582766
[ "MIT" ]
GridProtectionAlliance/openHistorian
Source/Tools/ArchiveIntegrityChecker/Program.cs
443
C#
using System; using System.Collections.Generic; using System.Reflection.Emit; using Inception.Proxying.Metadata; namespace Inception.Proxying.Generators { internal class FieldMetadataFieldBuilderMap : Dictionary<FieldMetadata, FieldBuilder> { public FieldMetadataFieldBuilderMap(int capacity) : base(capacity) { } } }
22.411765
89
0.692913
[ "BSD-2-Clause" ]
bradleyjford/inception
src/Inception/Proxying/Generators/FieldMetadataFieldBuilderMap.cs
383
C#
namespace Bloom.TeamCollection { /// <summary> /// Arguments for the DeleteRepoBookFile event in TeamCollection. /// </summary> /// <remarks>Don't confuse with the higher-level BookDeletedEventArgs. No new /// behavior in this class, but we do need to be able to distinguish them</remarks> public class DeleteRepoBookFileEventArgs : BookRepoChangeEventArgs { } }
31
84
0.752688
[ "MIT" ]
BloomBooks/BloomDesktop
src/BloomExe/TeamCollection/DeleteRepoBookFileEventArgs.cs
374
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using RentApp.Models.Entities; using RentApp.Persistance; using RentApp.Persistance.UnitOfWork; using System.Web; using RentApp.Models; using System.Threading.Tasks; namespace RentApp.Controllers { [RoutePrefix("api/AdditionalUserOps")] public class AppUsersController : ApiController { private readonly IUnitOfWork unitOfWork; private object locker = new object(); public AppUsersController(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } [Authorize(Roles = "Admin")] [Route("GetUnbannedManagers")] public IEnumerable<AppUser> GetUnbannedManagers() { return unitOfWork.AppUserRepository.GetUnbannedManagers(); } [Route("GetAllUsers")] public IEnumerable<AppUser> GetAllUsers() { return unitOfWork.AppUserRepository.GetAll(); } [Route("GetUser")] public AppUser GetUser(string email) { AppUser user = unitOfWork.AppUserRepository.Find(u => u.Email == email).FirstOrDefault(); return user; } [Authorize(Roles = "Admin")] [Route("GetBannedManagers")] public IEnumerable<AppUser> GetBannedManagers() { return unitOfWork.AppUserRepository.GetBannedManagers(); } [Authorize(Roles =("Admin"))] [Route("GetAwaitingClients")] public IEnumerable<AppUser> GetAwaitingClients() { return unitOfWork.AppUserRepository.GetAwaitingClients(); } [Authorize(Roles = "Admin")] [Route("AuthorizeUser")] public string AuthorizeUser([FromBody]string Id) { lock (locker) { if (!ModelState.IsValid) { return BadRequest(ModelState).ToString(); } //Get user data, and update activated to true AppUser current = unitOfWork.AppUserRepository.Get(Int32.Parse(Id)); current.Activated = true; try { unitOfWork.AppUserRepository.Update(current); unitOfWork.Complete(); string subject = "Account approval"; string desc = $"Dear {current.FullName}, Your account has been approved. Block 8 team."; unitOfWork.AppUserRepository.NotifyViaEmail(current.Email, subject, desc); } catch (DbUpdateConcurrencyException) { return BadRequest().ToString(); } return "Ok"; } } } }
30.163265
108
0.584574
[ "MIT" ]
ognjengt/PUSGS2018-SOM
initialApp-master/RentApp/Controllers/AppUsersController.cs
2,958
C#
#nullable enable using Microsoft; using Microsoft.VisualStudio.Shell; using System; using System.Windows.Input; using Task = System.Threading.Tasks.Task; namespace CopyGitLink.CodeLens.ViewModels { public sealed class ActionCommand : ICommand { private readonly Action _execute; public event EventHandler? CanExecuteChanged; internal ActionCommand(Action execute) { _execute = Requires.NotNull(execute, nameof(execute)); } public bool CanExecute(object? parameter) { return true; } public void Execute(object? parameter) { if (!CanExecute(parameter)) { return; } try { _execute(); } catch { // Fail silently. } RaiseCanExecuteChanged(); } public async Task ExecuteAsync() { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Execute(null); } private void RaiseCanExecuteChanged() { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } } }
21.37931
77
0.542742
[ "MIT" ]
GrahamTheCoder/CopyGitLink
src/Impl/CopyGitLink/CodeLens/ViewModels/ActionCommand.cs
1,242
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// Interface IFileExportConverters /// SupportByVersion Excel, 14,15,16 ///</summary> [SupportByVersionAttribute("Excel", 14,15,16)] [EntityTypeAttribute(EntityType.IsInterface)] public class IFileExportConverters : COMObject ,IEnumerable<NetOffice.ExcelApi.FileExportConverter> { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(IFileExportConverters); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public IFileExportConverters(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public IFileExportConverters(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); ICOMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Excel 14, 15, 16 /// Get /// </summary> /// <param name="index">object Index</param> [SupportByVersionAttribute("Excel", 14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public NetOffice.ExcelApi.FileExportConverter this[object index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray); NetOffice.ExcelApi.FileExportConverter newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.FileExportConverter.LateBindingApiWrapperType) as NetOffice.ExcelApi.FileExportConverter; return newObject; } } #endregion #region Methods #endregion #region IEnumerable<NetOffice.ExcelApi.FileExportConverter> Member /// <summary> /// SupportByVersionAttribute Excel, 14,15,16 /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] public IEnumerator<NetOffice.ExcelApi.FileExportConverter> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.ExcelApi.FileExportConverter item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Excel, 14,15,16 /// </summary> [SupportByVersionAttribute("Excel", 14,15,16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this); } #endregion #pragma warning restore } }
31.511211
216
0.69603
[ "MIT" ]
brunobola/NetOffice
Source/Excel/Interfaces/IFileExportConverters.cs
7,029
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.WritingSystems; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSFontControl : UserControl { private WritingSystemSetupModel _model; private string _defaultFontName; private float _defaultFontSize; private IKeyboardDefinition _defaultKeyboard; public WSFontControl() { InitializeComponent(); _defaultFontName = _testArea.Font.Name; _defaultFontSize = _testArea.Font.SizeInPoints; _fontComboBox.Text = _defaultFontName; _fontSizeComboBox.Text = _defaultFontSize.ToString(); _promptForFontTestArea.SetPrompt(_testArea, "Use this area to type something to test out your font."); if (KeyboardController.IsInitialized) KeyboardController.Register(_testArea); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelSelectionChanged; _model.CurrentItemUpdated -= ModelCurrentItemUpdated; } _model = model; _model.SelectionChanged += ModelSelectionChanged; _model.CurrentItemUpdated += ModelCurrentItemUpdated; PopulateFontList(); UpdateFromModel(); this.Disposed += OnDisposed; } void OnDisposed(object sender, EventArgs e) { if (_model != null) _model.SelectionChanged -= ModelSelectionChanged; } private void ModelSelectionChanged(object sender, EventArgs e) { UpdateFromModel(); } private void ModelCurrentItemUpdated(object sender, EventArgs e) { UpdateFromModel(); } private void UpdateFromModel() { if (!_model.HasCurrentSelection) { Enabled = false; return; } Enabled = true; float currentSize; if (!float.TryParse(_fontSizeComboBox.Text, out currentSize)) { currentSize = float.NaN; } if (_model.CurrentDefaultFontName != _fontComboBox.Text) { if (string.IsNullOrEmpty(_model.CurrentDefaultFontName)) { _fontComboBox.Text = _defaultFontName; } else { _fontComboBox.Text = _model.CurrentDefaultFontName; } _fontComboBox.SelectAll(); } if (_model.CurrentDefaultFontSize != currentSize) { if (_model.CurrentDefaultFontSize == 0) { _fontSizeComboBox.Text = _defaultFontSize.ToString(); } else { _fontSizeComboBox.Text = _model.CurrentDefaultFontSize.ToString(); } _fontSizeComboBox.SelectAll(); } if (_rightToLeftCheckBox.Checked != _model.CurrentRightToLeftScript) { _rightToLeftCheckBox.Checked = _model.CurrentRightToLeftScript; } SetTestAreaFont(); } private void PopulateFontList() { // For clearing the list was resizing the combo box, so we save the original size and then reset it Rectangle originalBounds = _fontComboBox.Bounds; List<string> fontitems = new List<string>(); _fontComboBox.Items.Clear(); if (_model == null) { return; } foreach (FontFamily fontFamily in WritingSystemSetupModel.FontFamilies) { if (!fontFamily.IsStyleAvailable(FontStyle.Regular)) { continue; } fontitems.Add(fontFamily.Name); } fontitems.Sort(); foreach (string fontname in fontitems) { _fontComboBox.Items.Add(fontname); } _fontComboBox.Bounds = originalBounds; } private void SetTestAreaFont() { float fontSize; if (!float.TryParse(_fontSizeComboBox.Text, out fontSize)) { fontSize = _defaultFontSize; } if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize)) { fontSize = _defaultFontSize; } string fontName = _fontComboBox.Text; if (!_fontComboBox.Items.Contains(fontName)) { fontName = _defaultFontName; } _testArea.Font = new Font(fontName, fontSize); _testArea.ForeColor = Color.Black; if (_testArea.Font.Name != _fontComboBox.Text.Trim()) { _testArea.ForeColor = Color.Gray; } _testArea.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No; } private void FontComboBox_TextChanged(object sender, EventArgs e) { if (_model == null) { return; } if (_model.HasCurrentSelection && _model.CurrentDefaultFontName != _fontComboBox.Text) { _model.CurrentDefaultFontName = _fontComboBox.Text; } SetTestAreaFont(); } private void FontSizeComboBox_TextChanged(object sender, EventArgs e) { if (_model == null) { return; } float newSize; if (!float.TryParse(_fontSizeComboBox.Text, out newSize)) { return; } if (_model.HasCurrentSelection && _model.CurrentDefaultFontSize != newSize) { _model.CurrentDefaultFontSize = newSize; } SetTestAreaFont(); } private void _testArea_Enter(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard = Keyboard.Controller.ActiveKeyboard; _model.ActivateCurrentKeyboard(); } private void _testArea_Leave(object sender, EventArgs e) { if (_model == null) { return; } _defaultKeyboard.Activate(); } private void RightToLeftCheckBox_CheckedChanged(object sender, EventArgs e) { if (_model == null) { return; } if (_model.HasCurrentSelection && _model.CurrentRightToLeftScript != _rightToLeftCheckBox.Checked) { _model.CurrentRightToLeftScript = _rightToLeftCheckBox.Checked; } SetTestAreaFont(); } } }
24.725225
105
0.707779
[ "MIT" ]
darcywong00/libpalaso
PalasoUIWindowsForms/WritingSystems/WSFontControl.cs
5,489
C#
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion // Aknowledgments // This module borrows code and ideas from TinyPG framework by Herre Kuijpers, // specifically TextMarker.cs and TextHighlighter.cs classes. // http://www.codeproject.com/KB/recipes/TinyPG.aspx // using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using Irony.Parsing; namespace Irony.GrammarExplorer { public class TokenColorTable : Dictionary<TokenColor, Color> { } public class RichTextBoxHighlighter : NativeWindow, IDisposable, IUIThreadInvoker { public RichTextBox TextBox; public readonly TokenColorTable TokenColors = new TokenColorTable(); public readonly EditorAdapter Adapter; public readonly EditorViewAdapter ViewAdapter; private IntPtr _savedEventMask = IntPtr.Zero; bool _colorizing; bool _disposed; #region constructor, initialization and disposing public RichTextBoxHighlighter(RichTextBox textBox, LanguageData language) { TextBox = textBox; Adapter = new EditorAdapter(language); ViewAdapter = new EditorViewAdapter(Adapter, this); InitColorTable(); Connect(); UpdateViewRange(); ViewAdapter.SetNewText(TextBox.Text); } private void Connect() { TextBox.MouseMove += TextBox_MouseMove; TextBox.TextChanged += TextBox_TextChanged; TextBox.KeyDown += TextBox_KeyDown; TextBox.VScroll += TextBox_ScrollResize; TextBox.HScroll += TextBox_ScrollResize; TextBox.SizeChanged += TextBox_ScrollResize; TextBox.Disposed += TextBox_Disposed; ViewAdapter.ColorizeTokens += Adapter_ColorizeTokens; this.AssignHandle(TextBox.Handle); } private void Disconnect() { if (TextBox != null) { TextBox.MouseMove -= TextBox_MouseMove; TextBox.TextChanged -= TextBox_TextChanged; TextBox.KeyDown -= TextBox_KeyDown; TextBox.Disposed -= TextBox_Disposed; TextBox.VScroll -= TextBox_ScrollResize; TextBox.HScroll -= TextBox_ScrollResize; TextBox.SizeChanged -= TextBox_ScrollResize; } TextBox = null; } public void Dispose() { Adapter.Stop(); _disposed = true; Disconnect(); this.ReleaseHandle(); GC.SuppressFinalize(this); } private void InitColorTable() { TokenColors[TokenColor.Comment] = Color.Green; TokenColors[TokenColor.Identifier] = Color.Black; TokenColors[TokenColor.Keyword] = Color.Blue; TokenColors[TokenColor.Number] = Color.DarkRed; TokenColors[TokenColor.String] = Color.DarkSlateGray; TokenColors[TokenColor.Text] = Color.Black; } #endregion #region TextBox event handlers void TextBox_MouseMove(object sender, MouseEventArgs e) { //TODO: implement showing tip } void TextBox_KeyDown(object sender, KeyEventArgs e) { //TODO: implement showing intellisense hints or drop-downs } void TextBox_TextChanged(object sender, EventArgs e) { //if we are here while colorizing, it means the "change" event is a result of our coloring action if (_colorizing) return; ViewAdapter.SetNewText(TextBox.Text); } void TextBox_ScrollResize(object sender, EventArgs e) { UpdateViewRange(); } void TextBox_Disposed(object sender, EventArgs e) { Dispose(); } private void UpdateViewRange() { int minpos = TextBox.GetCharIndexFromPosition(new Point(0, 0)); int maxpos = TextBox.GetCharIndexFromPosition(new Point(TextBox.ClientSize.Width, TextBox.ClientSize.Height)); ViewAdapter.SetViewRange(minpos, maxpos); } #endregion #region WinAPI // some winapís required [DllImport("user32", CharSet = CharSet.Auto)] private extern static IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern bool PostMessageA(IntPtr hWnd, int nBar, int wParam, int lParam); [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetScrollPos(int hWnd, int nBar); [DllImport("user32.dll")] private static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); private const int WM_SETREDRAW = 0x000B; private const int WM_USER = 0x400; private const int EM_GETEVENTMASK = (WM_USER + 59); private const int EM_SETEVENTMASK = (WM_USER + 69); private const int SB_HORZ = 0x0; private const int SB_VERT = 0x1; private const int WM_HSCROLL = 0x114; private const int WM_VSCROLL = 0x115; private const int SB_THUMBPOSITION = 4; const int WM_PAINT = 0x000F; private int HScrollPos { get { //sometimes explodes with null reference exception return GetScrollPos((int)TextBox.Handle, SB_HORZ); } set { SetScrollPos((IntPtr)TextBox.Handle, SB_HORZ, value, true); PostMessageA((IntPtr)TextBox.Handle, WM_HSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0); } } private int VScrollPos { get { return GetScrollPos((int)TextBox.Handle, SB_VERT); } set { SetScrollPos((IntPtr)TextBox.Handle, SB_VERT, value, true); PostMessageA((IntPtr)TextBox.Handle, WM_VSCROLL, SB_THUMBPOSITION + 0x10000 * value, 0); } } #endregion #region Colorizing tokens public void LockTextBox() { // Stop redrawing: SendMessage(TextBox.Handle, WM_SETREDRAW, 0, IntPtr.Zero ); // Stop sending of events: _savedEventMask = SendMessage(TextBox.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero); //SendMessage(TextBox.Handle, EM_SETEVENTMASK, 0, IntPtr.Zero); } public void UnlockTextBox() { // turn on events SendMessage(TextBox.Handle, EM_SETEVENTMASK, 0, _savedEventMask); // turn on redrawing SendMessage(TextBox.Handle, WM_SETREDRAW, 1, IntPtr.Zero); } void Adapter_ColorizeTokens(object sender, ColorizeEventArgs args) { if (_disposed) return; //Debug.WriteLine("Coloring " + args.Tokens.Count + " tokens."); _colorizing = true; int hscroll = HScrollPos; int vscroll = VScrollPos; int selstart = TextBox.SelectionStart; int selLength = TextBox.SelectionLength; LockTextBox(); try { foreach (Token tkn in args.Tokens) { Color color = GetTokenColor(tkn); TextBox.Select(tkn.Location.Position, tkn.Length); TextBox.SelectionColor = color; } } finally { TextBox.Select(selstart, selLength); HScrollPos = hscroll; VScrollPos = vscroll; UnlockTextBox(); _colorizing = false; } TextBox.Invalidate(); } private Color GetTokenColor(Token token) { if (token.EditorInfo == null) return Color.Black; //Right now we scan source, not parse; initially all keywords are recognized as Identifiers; then they are "backpatched" // by parser when it detects that it is in fact keyword from Grammar. So now this backpatching does not happen, // so we have to detect keywords here var colorIndex = token.EditorInfo.Color; if (token.KeyTerm != null && token.KeyTerm.EditorInfo != null && token.KeyTerm.FlagIsSet(TermFlags.IsKeyword)) { colorIndex = token.KeyTerm.EditorInfo.Color; }//if Color result; if (TokenColors.TryGetValue(colorIndex, out result)) return result; return Color.Black; } #endregion #region IUIThreadInvoker Members public void InvokeOnUIThread(ColorizeMethod colorize) { TextBox.BeginInvoke(new MethodInvoker(colorize)); } #endregion }//class }//namespace
34.592593
126
0.672377
[ "MIT" ]
Aggror/Stride
sources/shaders/Irony.GrammarExplorer/Highlighter/RichTextBoxHighlighter.cs
8,409
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 kms-2014-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.KeyManagementService.Model { /// <summary> /// The request was rejected because the specified CMK is not enabled. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class DisabledException : AmazonKeyManagementServiceException { /// <summary> /// Constructs a new DisabledException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public DisabledException(string message) : base(message) {} /// <summary> /// Construct instance of DisabledException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public DisabledException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of DisabledException /// </summary> /// <param name="innerException"></param> public DisabledException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of DisabledException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DisabledException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of DisabledException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DisabledException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the DisabledException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected DisabledException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
47.532258
179
0.662029
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/KeyManagementService/Generated/Model/DisabledException.cs
5,894
C#
/* * Copyright 2002-2020 Raphael Mudge * Copyrigth 2020 Sebastian Ritter * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using java = biz.ritter.javapi; using sleep.engine; using sleep.engine.types; using sleep.engine.atoms; using sleep.runtime; using sleep.interfaces; namespace sleep.taint{ /** A replacement factory that generates Sleep interpreter instructions that honor and spread the taint mode. */ public class TaintModeGeneratedSteps : GeneratedSteps { public Step Call(String function) { return new TaintCall(function, base.Call(function)); } public Step PLiteral(java.util.List<Object> doit) { return new PermeableStep(base.PLiteral(doit)); } public Step Operate(String oper) { return new TaintOperate(oper, base.Operate(oper)); } public Step ObjectNew(Type name) { return new PermeableStep(base.ObjectNew(name)); } public Step ObjectAccess(String name) { return new TaintObjectAccess(base.ObjectAccess(name), name, null); } public override Step ObjectAccessStatic(Type aClass, String name) { return new TaintObjectAccess(base.ObjectAccessStatic(aClass, name), name, aClass); } } }
36.27027
112
0.747019
[ "BSD-3-Clause" ]
bastie/sleep-vampire
csharp/src/sleep/taint/TaintModeGeneratedSteps.cs
2,684
C#
using System; using Elmish.WPF.Samples.FileDialogs; using static Elmish.WPF.Samples.FileDialogs.Program; namespace FileDialogs.Views { public static class Program { [STAThread] public static void Main() => main(new MainWindow()); } }
21.166667
52
0.720472
[ "Apache-2.0" ]
MicaelMor/Elmish.WPF
src/Samples/FileDialogs.Views/Program.cs
256
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.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Security.Authentication; namespace System.Net.Security { // Implements SSL session caching mechanism based on a static table of SSL credentials. internal static class SslSessionsCache { private const int CheckExpiredModulo = 32; private static readonly ConcurrentDictionary<SslCredKey, SafeCredentialReference> s_cachedCreds = new ConcurrentDictionary<SslCredKey, SafeCredentialReference>(); // // Uses certificate thumb-print comparison. // private readonly struct SslCredKey : IEquatable<SslCredKey> { private readonly byte[] _thumbPrint; private readonly int _allowedProtocols; private readonly EncryptionPolicy _encryptionPolicy; private readonly bool _isServerMode; // // SECURITY: X509Certificate.GetCertHash() is virtual hence before going here, // the caller of this ctor has to ensure that a user cert object was inspected and // optionally cloned. // internal SslCredKey(byte[] thumbPrint, int allowedProtocols, bool isServerMode, EncryptionPolicy encryptionPolicy) { _thumbPrint = thumbPrint ?? Array.Empty<byte>(); _allowedProtocols = allowedProtocols; _encryptionPolicy = encryptionPolicy; _isServerMode = isServerMode; } public override int GetHashCode() { int hashCode = 0; if (_thumbPrint.Length > 0) { hashCode ^= _thumbPrint[0]; if (1 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[1] << 8); } if (2 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[2] << 16); } if (3 < _thumbPrint.Length) { hashCode ^= (_thumbPrint[3] << 24); } } hashCode ^= _allowedProtocols; hashCode ^= (int)_encryptionPolicy; hashCode ^= _isServerMode ? 0x10000 : 0x20000; return hashCode; } public override bool Equals(object obj) => (obj is SslCredKey && Equals((SslCredKey)obj)); public bool Equals(SslCredKey other) { byte[] thumbPrint = _thumbPrint; byte[] otherThumbPrint = other._thumbPrint; if (thumbPrint.Length != otherThumbPrint.Length) { return false; } if (_encryptionPolicy != other._encryptionPolicy) { return false; } if (_allowedProtocols != other._allowedProtocols) { return false; } if (_isServerMode != other._isServerMode) { return false; } for (int i = 0; i < thumbPrint.Length; ++i) { if (thumbPrint[i] != otherThumbPrint[i]) { return false; } } return true; } } // // Returns null or previously cached cred handle. // // ATTN: The returned handle can be invalid, the callers of InitializeSecurityContext and AcceptSecurityContext // must be prepared to execute a back-out code if the call fails. // internal static SafeFreeCredentials TryCachedCredential(byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (s_cachedCreds.Count == 0) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Not found, Current Cache Count = {s_cachedCreds.Count}"); return null; } var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached; if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed || cached.Target.IsInvalid) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Not found or invalid, Current Cache Coun = {s_cachedCreds.Count}"); return null; } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Found a cached Handle = {cached.Target}"); return cached.Target; } // // The app is calling this method after starting an SSL handshake. // // ATTN: The thumbPrint must be from inspected and possibly cloned user Cert object or we get a security hole in SslCredKey ctor. // internal static void CacheCredential(SafeFreeCredentials creds, byte[] thumbPrint, SslProtocols sslProtocols, bool isServer, EncryptionPolicy encryptionPolicy) { if (creds == null) { NetEventSource.Fail(null, "creds == null"); } if (creds.IsInvalid) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Refused to cache an Invalid Handle {creds}, Current Cache Count = {s_cachedCreds.Count}"); return; } var key = new SslCredKey(thumbPrint, (int)sslProtocols, isServer, encryptionPolicy); SafeCredentialReference cached; if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed || cached.Target.IsInvalid) { lock (s_cachedCreds) { if (!s_cachedCreds.TryGetValue(key, out cached) || cached.IsClosed) { cached = SafeCredentialReference.CreateReference(creds); if (cached == null) { // Means the handle got closed in between, return it back and let caller deal with the issue. return; } s_cachedCreds[key] = cached; if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Caching New Handle = {creds}, Current Cache Count = {s_cachedCreds.Count}"); // // A simplest way of preventing infinite cache grows. // // Security relief (DoS): // A number of active creds is never greater than a number of _outstanding_ // security sessions, i.e. SSL connections. // So we will try to shrink cache to the number of active creds once in a while. // // We won't shrink cache in the case when NO new handles are coming to it. // if ((s_cachedCreds.Count % CheckExpiredModulo) == 0) { KeyValuePair<SslCredKey, SafeCredentialReference>[] toRemoveAttempt = s_cachedCreds.ToArray(); for (int i = 0; i < toRemoveAttempt.Length; ++i) { cached = toRemoveAttempt[i].Value; if (cached != null) { creds = cached.Target; cached.Dispose(); if (!creds.IsClosed && !creds.IsInvalid && (cached = SafeCredentialReference.CreateReference(creds)) != null) { s_cachedCreds[toRemoveAttempt[i].Key] = cached; } else { s_cachedCreds.TryRemove(toRemoveAttempt[i].Key, out cached); } } } if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"Scavenged cache, New Cache Count = {s_cachedCreds.Count}"); } } else if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"CacheCredential() (locked retry) Found already cached Handle = {cached.Target}"); } } } else if (NetEventSource.IsEnabled) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, $"CacheCredential() Ignoring incoming handle = {creds} since found already cached Handle = {cached.Target}"); } } } }
41.46696
181
0.505152
[ "MIT" ]
2E0PGS/corefx
src/System.Net.Security/src/System/Net/Security/SslSessionsCache.cs
9,413
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RemoteDebuggingDemo { public partial class _Default { /// <summary> /// Button1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button Button1; } }
30.44
84
0.465177
[ "Apache-2.0" ]
noopman/RemoteDebuggingDemo
RemoteDebuggingDemo/Default.aspx.designer.cs
763
C#
/* https://www.codewars.com/kata/56c2acc8c44a3ad6e400050a/csharp 7 kyu Monkey's MATH 01: How many "ZERO"s? Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0". In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two). So, a is a "0",b is a "0",6 is also a "0",and 8 have two "0" ,etc... Now, write some code to count how many "0"s in the text. Let us see who is smarter? You ? or monkey? Input always be a string(including words numbers and symbols), You don't need to verify it, but pay attention to the difference between uppercase and lowercase letters. Here is a table of characters: one zero abdegopq069DOPQR () <-- A pair of braces as a zero two zero %&B8 Output will be a number of "0". */ using System.Linq; using System.Text.RegularExpressions; namespace CodeWars { public class MonkeysMATH01 { public static int CountZero(string s) { return s.Replace("()", "a").Sum(c => "abdegopq069DOPQR".Contains(c) ? 1 : "%&B8".Contains(c) ? 2 : 0); // return Regex.Matches(s, @"[abdegopq069DOPQR]|(\(\))").Count + 2 * Regex.Matches(s, "[%&B8]").Count; // return s.Replace("()", "a").Count(x => "abdegopq069DOPQR".Contains(x)) + s.Count(x => "%&B8".Contains(x)) * 2; // s = s.Replace("()", "0"); // return s.Count(c => "abdegopq069DOPQR".Contains(c)) * 1 + // s.Count(c => "%&B8".Contains(c)) * 2; } } }
32.361702
125
0.619987
[ "MIT" ]
a-kozhanov/codewars-csharp
CodeWars/7kyu/MonkeysMATH01.cs
1,529
C#
namespace Jopalesha.CheckWhenDoIt.Conditions { public class BoolCondition : ICondition { public BoolCondition(bool value) { IsTrue = value; } public bool IsTrue { get; } } }
17.846154
45
0.573276
[ "MIT" ]
jopalesha/CheckWhenDoIt
src/CheckWhenDoIt/Conditions/BoolCondition.cs
234
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amaranth.Util { /// <summary> /// Extension methods on <c>string</c>. /// </summary> public static class StringExtensions { public static string FormatNames(this string format, IDictionary<string, object> properties) { string result = format; foreach (KeyValuePair<string, object> pair in properties) { result = result.Replace("{" + pair.Key + "}", pair.Value.ToString()); } return result; } public static string[] CharacterWrap(this string text, int lineWidth) { List<string> lines = new List<string>(); while (text.Length > lineWidth) { lines.Add(text.Substring(0, lineWidth)); text = text.Substring(lineWidth); } if (text.Length > 0) { lines.Add(text); } return lines.ToArray(); } public static string[] WordWrap(this string text, int lineWidth) { List<string> lines = new List<string>(); string line; int lastWrapPoint = 0; int thisLineStart = 0; for (int i = 0; i < text.Length; i++) { char c = text[i]; if (c == ' ') { lastWrapPoint = i; } // wrap if we got too long if (i - thisLineStart >= lineWidth) { if (lastWrapPoint != 0) { // have a recent point to wrap at, so word wrap line = text.Substring(thisLineStart, lastWrapPoint - thisLineStart); thisLineStart = lastWrapPoint; } else { // no convenient point to word wrap, so character wrap line = text.Substring(thisLineStart, i - thisLineStart); thisLineStart = i; } line = line.Trim(); lines.Add(line); } } // add the last bit line = text.Substring(thisLineStart); line = line.Trim(); lines.Add(line); return lines.ToArray(); } } }
28.955556
101
0.433615
[ "MIT" ]
LambdaSix/Amaranth
Amaranth.Util/Extension Classes/StringExtensions.cs
2,608
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("FyDoxaDelegeEventUcakSimulasyonu")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FyDoxaDelegeEventUcakSimulasyonu")] [assembly: AssemblyCopyright("Copyright © 2009")] [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("dc8e28f4-ca4d-4b63-b8c3-bb8a81635793")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.837838
84
0.752262
[ "MIT" ]
fatihyildizhan/csharp-2010-older-projects
FyDoxaDelegeEventUcakSimulasyonu/FyDoxaDelegeEventUcakSimulasyonu/Properties/AssemblyInfo.cs
1,440
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------ using System; using Microsoft.OData.Edm; using Microsoft.OpenApi.OData.Edm; using Microsoft.OpenApi.OData.Tests; using Xunit; namespace Microsoft.OpenApi.OData.Generator.Tests { public class OpenApiComponentsGeneratorTest { [Fact] public void CreateComponentsThrowArgumentNullContext() { // Arrange ODataContext context = null; // Act & Assert Assert.Throws<ArgumentNullException>("context", () => context.CreateComponents()); } [Fact] public void CreateComponentsReturnsForEmptyModel() { // Arrange IEdmModel model = EdmModelHelper.EmptyModel; ODataContext context = new ODataContext(model); // Act var components = context.CreateComponents(); // Assert Assert.NotNull(components); Assert.NotNull(components.Schemas); Assert.NotNull(components.Parameters); Assert.NotNull(components.Responses); Assert.Null(components.RequestBodies); } } }
30.911111
95
0.570812
[ "MIT" ]
Bhaskers-Blu-Org2/OpenAPI.NET.OData
test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiComponentsGeneratorTests.cs
1,393
C#
namespace Oddin.OddsFeedSdk { internal static class SdkDefaults { internal const string ProductionHost = "mq.oddin.gg"; internal const string ProductionApiHost = "api-mq.oddin.gg"; internal const string IntegrationHost = "mq.integration.oddin.gg"; internal const string IntegrationApiHost = "api-mq.integration.oddin.gg"; internal const int DefaultPort = 5672; internal const int UnknownProducerId = 99; internal const int StatefulRecoveryWindowInMinutes = 4320; internal const int MinInactivitySeconds = 11; internal const int DefaultInactivitySeconds = 15; internal const int MaxInactivitySeconds = 30; internal const int MinRecoveryExecutionInSeconds = 600; internal const int MaxRecoveryExecutionInSeconds = 21600; internal const int MinHttpClientTimeout = 10; internal const int MaxHttpClientTimeout = 60; internal const int DefaultHttpClientTimeout = 30; } }
36.785714
82
0.68932
[ "BSD-3-Clause" ]
oddin-gg/netcoresdk
src/Oddin.OddsFeedSdk/Oddin.OddsFeedSdk/SdkDefaults.cs
1,030
C#
using UnityEngine.Assertions; using UnityEngine.Rendering; #if HAS_URP using UnityEngine.Rendering.Universal; #elif HAS_HDRP using UnityEngine.Rendering.HighDefinition; #endif namespace ImGuiNET.Unity { static class RenderUtils { public enum RenderType { Mesh = 0, Procedural = 1, } public static IImGuiRenderer Create(RenderType type, ShaderResourcesAsset shaders, TextureManager textures) { Assert.IsNotNull(shaders, "Shaders not assigned."); switch (type) { case RenderType.Mesh: return new ImGuiRendererMesh(shaders, textures); case RenderType.Procedural: return new ImGuiRendererProcedural(shaders, textures); default: return null; } } public static bool IsUsingURP() { var currentRP = GraphicsSettings.currentRenderPipeline; #if HAS_URP return currentRP is UniversalRenderPipelineAsset; #else return false; #endif } public static bool IsUsingHDRP() { var currentRP = GraphicsSettings.currentRenderPipeline; #if HAS_HDRP return currentRP is HDRenderPipelineAsset; #else return false; #endif } public static CommandBuffer GetCommandBuffer(string name) { #if HAS_URP || HAS_HDRP return CommandBufferPool.Get(name); #else return new CommandBuffer { name = name }; #endif } public static void ReleaseCommandBuffer(CommandBuffer cmd) { #if HAS_URP || HAS_HDRP CommandBufferPool.Release(cmd); #else cmd.Release(); #endif } } }
26.140845
115
0.574892
[ "MIT" ]
Ethan13310/dear-imgui-unity
ImGuiNET.Unity/Renderer/RenderUtils.cs
1,858
C#
using NServiceBus; public class BookingChangePolicyData : ContainSagaData { public string BookingReferenceId { get; set; } public bool IsCancelled { get; set; } public bool IsFlightChanged { get; set; } public bool CanCompleteSaga() { return IsCancelled && IsFlightChanged; } }
19.705882
51
0.644776
[ "MIT" ]
indualagarsamy/Presentations
practical-ddd-bounded-contexts-events-microservices/src/first-model/AircraftTypeChangePolicy/BookingChangePolicyData.cs
337
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 iam-2010-05-08.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.IdentityManagement.Model { /// <summary> /// Container for the parameters to the CreatePolicyVersion operation. /// Creates a new version of the specified managed policy. To update a managed policy, /// you create a new policy version. A managed policy can have up to five versions. If /// the policy has five versions, you must delete an existing version using <a>DeletePolicyVersion</a> /// before you create a new version. /// /// /// <para> /// Optionally, you can set the new version as the policy's default version. The default /// version is the version that is in effect for the IAM users, groups, and roles to which /// the policy is attached. /// </para> /// /// <para> /// For more information about managed policy versions, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning /// for Managed Policies</a> in the <i>IAM User Guide</i>. /// </para> /// </summary> public partial class CreatePolicyVersionRequest : AmazonIdentityManagementServiceRequest { private string _policyArn; private string _policyDocument; private bool? _setAsDefault; /// <summary> /// Gets and sets the property PolicyArn. /// <para> /// The Amazon Resource Name (ARN) of the IAM policy to which you want to add a new version. /// </para> /// /// <para> /// For more information about ARNs, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon /// Resource Names (ARNs) and AWS Service Namespaces</a> in the <i>AWS General Reference</i>. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=2048)] public string PolicyArn { get { return this._policyArn; } set { this._policyArn = value; } } // Check to see if PolicyArn property is set internal bool IsSetPolicyArn() { return this._policyArn != null; } /// <summary> /// Gets and sets the property PolicyDocument. /// <para> /// The JSON policy document that you want to use as the content for this new version /// of the policy. /// </para> /// /// <para> /// You must provide policies in JSON format in IAM. However, for AWS CloudFormation templates /// formatted in YAML, you can provide the policy in JSON or YAML format. AWS CloudFormation /// always converts a YAML policy to JSON format before submitting it to IAM. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this /// parameter is a string of characters consisting of the following: /// </para> /// <ul> <li> /// <para> /// Any printable ASCII character ranging from the space character (\u0020) through the /// end of the ASCII character range /// </para> /// </li> <li> /// <para> /// The printable characters in the Basic Latin and Latin-1 Supplement character set (through /// \u00FF) /// </para> /// </li> <li> /// <para> /// The special characters tab (\u0009), line feed (\u000A), and carriage return (\u000D) /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true, Min=1, Max=131072)] public string PolicyDocument { get { return this._policyDocument; } set { this._policyDocument = value; } } // Check to see if PolicyDocument property is set internal bool IsSetPolicyDocument() { return this._policyDocument != null; } /// <summary> /// Gets and sets the property SetAsDefault. /// <para> /// Specifies whether to set this version as the policy's default version. /// </para> /// /// <para> /// When this parameter is <code>true</code>, the new policy version becomes the operative /// version. That is, it becomes the version that is in effect for the IAM users, groups, /// and roles that the policy is attached to. /// </para> /// /// <para> /// For more information about managed policy versions, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning /// for Managed Policies</a> in the <i>IAM User Guide</i>. /// </para> /// </summary> public bool SetAsDefault { get { return this._setAsDefault.GetValueOrDefault(); } set { this._setAsDefault = value; } } // Check to see if SetAsDefault property is set internal bool IsSetSetAsDefault() { return this._setAsDefault.HasValue; } } }
38.348387
168
0.604307
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/IdentityManagement/Generated/Model/CreatePolicyVersionRequest.cs
5,944
C#
using System; using System.Collections.Generic; using System.Linq; using ByteBank.Modelos; using ByteBank.SistemaAgencia.Comparadores; using ByteBank.SistemaAgencia.Extensoes; namespace ByteBank.SistemaAgencia { class Program { static void Main(string[] args) { // "Que dahora cara kkkkkk".AsConsoleError(); var contas = new List<ContaCorrente>() { new ContaCorrente(123, 97381), null, new ContaCorrente(122, 32346), new ContaCorrente(353, 23534), new ContaCorrente(236, 34923), }; // contas.Sort(); ~~> Implementação em IComparable // contas.Sort(new ComparadorContaCorrentePorAgencia()); var contasOrdenadas = contas .Where(conta => conta != null) .OrderBy(conta => conta.Numero); foreach (var conta in contasOrdenadas) { Console.WriteLine($"Conta número {conta.Numero}, ag. {conta.Agencia}"); } Console.ReadLine(); } static int SomarVarios(params int[] numeros) { int acumulador = 0; foreach (int numero in numeros) { acumulador += numero; } return acumulador; } static void TestaSort() { List<int> numeros = new List<int>(); numeros.Add(5); numeros.Add(6); numeros.Add(9); numeros.Add(0); numeros.Add(2); numeros.Add(4); numeros.Add(3); numeros.Add(8); numeros.Add(7); numeros.Add(1); numeros.AdicionarVarios(30, 40, 10, 20, -1234); // ListExtensoes.AdicionarVarios(numeros, 10, 20, 30, 40); numeros.Sort(); foreach (var numero in numeros) Console.WriteLine(numero); } static void TestaListaContaCorrente() { ListaDeContaCorrente lista = new ListaDeContaCorrente(); ContaCorrente contaDoGui = new ContaCorrente(11111, 1111111); ContaCorrente[] contas = new ContaCorrente[] { contaDoGui, new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679754) }; lista.AdicionarVarios(contas); lista.AdicionarVarios( contaDoGui, new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787), new ContaCorrente(874, 5679787) ); for (int i = 0; i < lista.Tamanho; i++) { ContaCorrente itemAtual = lista[i]; Console.WriteLine($"Item na posição {i} = Conta {itemAtual.Numero}/{itemAtual.Agencia}"); } } public static void TestaArrayContaCorrente() { ContaCorrente[] contas = new ContaCorrente[] { new ContaCorrente(874, 5679787), new ContaCorrente(874, 4456668), new ContaCorrente(874, 7781438) }; for (int indice = 0; indice < contas.Length; indice++) { ContaCorrente contaAtual = contas[indice]; Console.WriteLine($"Conta {indice} {contaAtual.Numero}"); } } public static void TestaArrayInt() { // ARRAY de inteiros, com 5 posições! int[] idades = null; idades = new int[3]; idades[0] = 15; idades[1] = 28; idades[2] = 35; //idades[3] = 50; //idades[4] = 28; Console.WriteLine(idades.Length); int acumulador = 0; for (int indice = 0; indice < idades.Length; indice++) { int idade = idades[indice]; Console.WriteLine($"Acessando o array idades no índice {indice}"); Console.WriteLine($"Valor de idades[{indice}] = {idade}"); acumulador += idade; } int media = acumulador / idades.Length; Console.WriteLine($"Média de idades = {media}"); } } }
25.012987
97
0.595275
[ "MIT" ]
angeloevangelista/alura
csharp/orientacao-objetos/08-list-lambda-linq/ByteBank.SistemaAgencia/Program.cs
3,863
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Atma.Math.Members; using Atma.Math.Tests; namespace Atma.Math.Types { abstract class AbstractType { /// <summary> /// true iff test generation is active /// </summary> public static bool TestMode { get; set; } /// <summary> /// Random /// </summary> public static Random Random = new Random(1234); /// <summary> /// All known types /// </summary> public static readonly Dictionary<string, AbstractType> Types = new Dictionary<string, AbstractType>(); /// <summary> /// Math class prefix /// </summary> public virtual string MathClass => BaseType?.MathClass; /// <summary> /// Currently active version /// </summary> public static int Version { get; set; } /// <summary> /// Base name (e.g. vec, mat, quat) /// </summary> public string BaseName { get; set; } = "vec"; /// <summary> /// Name of the base type /// </summary> public string BaseTypeName => BaseType.Name; /// <summary> /// Cast to basetype /// </summary> public string BaseTypeCast => "(" + BaseTypeName + ")"; /// <summary> /// Actual name of the type (e.g. the C# class name) /// </summary> public abstract string Name { get; } /// <summary> /// Name used for parameter types (for generics has T) /// </summary> public string NameThat => Name + GenericSuffix; /// <summary> /// Suffix for generic types /// </summary> public virtual string GenericSuffix => BaseType?.Generic ?? false ? (TestMode ? "<string>" : "<T>") : ""; /// <summary> /// Reference to base type /// </summary> public BuiltinType BaseType { get; set; } /// <summary> /// Namespace of this type /// </summary> public virtual string Namespace { get; } = Program.Namespace; /// <summary> /// Additional arg for data contracts /// </summary> public virtual string DataContractArg { get; } = ""; /// <summary> /// Folder for this type /// </summary> public virtual string Folder { get; } = ""; /// <summary> /// Class name for tests /// </summary> public virtual string TestClassName => BaseTypeName.Capitalized() + Folder + "Test"; /// <summary> /// Folder with trailing / /// </summary> public string PathOf(string basePath) => string.IsNullOrEmpty(Folder) ? Path.Combine(basePath, Name + ".cs") : Path.Combine(basePath, Folder, Name + ".cs"); public string GlmPathOf(string basePath) => string.IsNullOrEmpty(Folder) ? Path.Combine(basePath, Name + ".cs") : Path.Combine(basePath, Folder, Name + ".glm.cs"); public string TestPathOf(string basePath) => string.IsNullOrEmpty(Folder) ? Path.Combine(basePath, Name + ".cs") : Path.Combine(basePath, Folder, Name + ".Test.cs"); /// <summary> /// Comment of this type /// </summary> public abstract string TypeComment { get; } /// <summary> /// List of C# base classes (mostly interfaces) /// </summary> public virtual IEnumerable<string> BaseClasses { get { yield break; } } /// <summary> /// All members /// </summary> private Member[] members; private Field[] fields; private Constructor[] constructors; private Property[] properties; private Property[] staticProperties; private ImplicitOperator[] implicitOperators; private ExplicitOperator[] explicitOperators; private Operator[] operators; private Function[] functions; private Function[] staticFunctions; private Indexer[] indexer; private ComponentWiseStaticFunction[] componentWiseStaticFunctions; private ComponentWiseOperator[] componentWiseOp; private Member[] glmMembers; /// <summary> /// Generate all members /// </summary> public abstract IEnumerable<Member> GenerateMembers(); /// <summary> /// Generates type members and sorts them /// </summary> public void Generate() { members = GenerateMembers().ToArray(); if (members.Any(m => string.IsNullOrEmpty(m.Comment))) throw new InvalidOperationException("Missing comment"); foreach (var member in members) member.OriginalType = this; fields = members.OfType<Field>().ToArray(); constructors = members.OfType<Constructor>().ToArray(); properties = members.Where(m => !m.Static).OfType<Property>().ToArray(); staticProperties = members.Where(m => m.Static).OfType<Property>().ToArray(); implicitOperators = members.OfType<ImplicitOperator>().ToArray(); explicitOperators = members.OfType<ExplicitOperator>().ToArray(); operators = members.OfType<Operator>().ToArray(); functions = members.Where(m => !m.Static && m.GetType() == typeof(Function)).OfType<Function>().ToArray(); staticFunctions = members.Where(m => m.Static && m.GetType() == typeof(Function)).OfType<Function>().ToArray(); indexer = members.OfType<Indexer>().ToArray(); componentWiseStaticFunctions = members.OfType<ComponentWiseStaticFunction>().ToArray(); componentWiseOp = members.OfType<ComponentWiseOperator>().ToArray(); glmMembers = members.SelectMany(m => m.GlmMembers()).ToArray(); } /// <summary> /// Constructs an object of a given type /// </summary> public string Construct(AbstractType type, IEnumerable<string> args) => $"new {type.NameThat}({args.CommaSeparated()})"; /// <summary> /// Constructs an object of a given type /// </summary> public string Construct(AbstractType type, params string[] args) => $"new {type.NameThat}({args.CommaSeparated()})"; /// <summary> /// Generate tests for this class /// </summary> public virtual IEnumerable<TestFunc> GenerateTests() { yield break; } public void ResetRandom(int x) { Random = new Random(x + TestClassName.GetHashCode()); } public IEnumerable<string> TestFile { get { if (string.IsNullOrEmpty(Folder)) throw new NotSupportedException(); yield return "using System;"; yield return "using System.Collections;"; yield return "using System.Collections.Generic;"; yield return "using System.Globalization;"; yield return "using System.Runtime.InteropServices;"; yield return "using System.Runtime.Serialization;"; if (Version >= 40) { yield return "using System.Numerics;"; yield return "using System.Linq;"; } yield return "using NUnit.Framework;"; yield return "using Newtonsoft.Json;"; yield return "using " + Namespace + ";"; yield return ""; yield return "// ReSharper disable InconsistentNaming"; yield return ""; yield return "namespace " + Namespace + ".Generated." + Folder; yield return "{"; yield return " [TestFixture]"; yield return " public class " + TestClassName; yield return " {"; TestMode = true; ResetRandom(1234); foreach (var test in GenerateTests()) { yield return ""; yield return "[Test]".Indent(2); yield return $"public void {test.Name}()".Indent(2); yield return "{".Indent(2); foreach (var line in test.Code) yield return line.Indent(3); yield return "}".Indent(2); } TestMode = false; yield return ""; yield return " }"; yield return "}"; } } public IEnumerable<string> GlmSharpFile { get { yield return "using System;"; yield return "using System.Collections;"; yield return "using System.Collections.Generic;"; yield return "using System.Globalization;"; yield return "using System.Runtime.InteropServices;"; yield return "using System.Runtime.Serialization;"; if (Version >= 40) { yield return "using System.Numerics;"; yield return "using System.Linq;"; } yield return "using " + Program.Namespace + ".Swizzle;"; yield return ""; yield return "// ReSharper disable InconsistentNaming"; yield return ""; yield return "namespace " + Namespace; yield return "{"; yield return " /// <summary>"; yield return " /// Static class that contains static glm functions"; yield return " /// </summary>"; yield return " public static partial class glm"; yield return " {"; foreach (var member in glmMembers) foreach (var line in member.Lines) yield return line.Indent(2); yield return ""; yield return " }"; yield return "}"; } } public IEnumerable<string> CSharpFile { get { var baseclasses = BaseClasses.ToArray(); yield return "using System;"; yield return "using System.Collections;"; yield return "using System.Collections.Generic;"; yield return "using System.Globalization;"; yield return "using System.Runtime.InteropServices;"; yield return "using System.Runtime.Serialization;"; if (Version >= 40) { yield return "using System.Numerics;"; yield return "using System.Linq;"; } yield return "using " + Program.Namespace + ".Swizzle;"; yield return ""; yield return "// ReSharper disable InconsistentNaming"; yield return ""; yield return "namespace " + Namespace; yield return "{"; foreach (var line in TypeComment.AsComment()) yield return line.Indent(); yield return " [Serializable]"; if (Version >= 40) yield return $" [DataContract{DataContractArg}]"; yield return " [StructLayout(LayoutKind.Sequential)]"; yield return " public struct " + Name + GenericSuffix + (baseclasses.Length == 0 ? "" : " : " + baseclasses.CommaSeparated()); yield return " {"; if (fields.Length > 0) { yield return ""; yield return " #region Fields"; foreach (var field in fields) foreach (var line in field.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (constructors.Length > 0) { yield return ""; yield return " #region Constructors"; foreach (var ctor in constructors) foreach (var line in ctor.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (implicitOperators.Length > 0) { yield return ""; yield return " #region Implicit Operators"; foreach (var op in implicitOperators) foreach (var line in op.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (explicitOperators.Length > 0) { yield return ""; yield return " #region Explicit Operators"; foreach (var op in explicitOperators) foreach (var line in op.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (indexer.Length > 0) { yield return ""; yield return " #region Indexer"; foreach (var index in indexer) foreach (var line in index.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (properties.Length > 0) { yield return ""; yield return " #region Properties"; foreach (var prop in properties) foreach (var line in prop.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (staticProperties.Length > 0) { yield return ""; yield return " #region Static Properties"; foreach (var prop in staticProperties) foreach (var line in prop.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (operators.Length > 0) { yield return ""; yield return " #region Operators"; foreach (var op in operators) foreach (var line in op.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (functions.Length > 0) { yield return ""; yield return " #region Functions"; foreach (var func in functions) foreach (var line in func.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (staticFunctions.Length > 0) { yield return ""; yield return " #region Static Functions"; foreach (var func in staticFunctions) foreach (var line in func.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (componentWiseStaticFunctions.Length > 0) { yield return ""; yield return " #region Component-Wise Static Functions"; foreach (var func in componentWiseStaticFunctions) foreach (var line in func.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } if (componentWiseOp.Length > 0) { yield return ""; yield return " #region Component-Wise Operator Overloads"; foreach (var op in componentWiseOp) foreach (var line in op.Lines) yield return line.Indent(2); yield return ""; yield return " #endregion"; yield return ""; } foreach (var line in Body) yield return line.Indent(2); yield return " }"; yield return "}"; } } protected virtual IEnumerable<string> Body { get { yield break; } } public string Comparer(string val) => BaseType.Generic ? string.Format("EqualityComparer<T>.Default.Equals({0}, rhs.{0})", val) : string.Format("{0}.Equals(rhs.{0})", val); public virtual string ZeroValue => BaseType.ZeroValue; public virtual string OneValue => BaseType.OneValue; public string HashCodeOf(string val) => BaseType.Generic ? $"EqualityComparer<T>.Default.GetHashCode({val})" : $"{val}.GetHashCode()"; public string SqrOf(string s) => BaseType.IsComplex ? s + ".LengthSqr()" : s + "*" + s; public string SqrOf(char s) => SqrOf(s.ToString()); public string SqrtOf(string s) => BaseType.Decimal ? "(" + s + ").Sqrt()" : $"System.Math.Sqrt({s})"; public string SqrtOf(char s) => SqrOf(s.ToString()); public string DotFormatString => BaseType.IsComplex ? "lhs.{0} * Complex.Conjugate(rhs.{0})" : "lhs.{0} * rhs.{0}"; public string AbsString(string s) => BaseType.IsSigned ? (BaseType.IsComplex ? s + ".Magnitude" : MathClass + $".Abs({s})") : s; public string AbsString(char s) => BaseType.IsSigned ? (BaseType.IsComplex ? s + ".Magnitude" : MathClass + $".Abs({s})") : s.ToString(); public string ConstantSuffixFor(string s) { var type = BaseType ?? this; if (type.Name == "float") return s + "f"; if (type.Name == "bool") return s; if (type.Name == "Complex") return s; if (type.Name == "Half") return $"new Half({s})"; if (type.Name == "double") return s + "d"; if (type.Name == "decimal") return s + "m"; if (type.Name == "int") return s + ""; if (type.Name == "uint") return s + "u"; if (type.Name == "long") return s + "L"; throw new InvalidOperationException("unknown type " + this + ", " + type.Name); } public string ConstantStringFor(string s) { var type = BaseType ?? this; if (type.Name == "Half") return $"new Half({s})"; return s; } public IEnumerable<string> SwitchIndex(IEnumerable<string> cases) { yield return "switch (index)"; yield return "{"; foreach (var @case in cases) yield return @case.Indent(); yield return " default: throw new ArgumentOutOfRangeException(\"index\");"; yield return "}"; } public static void InitTypes() { Types.Clear(); // vectors foreach (var type in BuiltinType.BaseTypes) for (var comp = 2; comp <= 4; ++comp) { var vect = new VectorType(type, comp); var swizzler = vect.SwizzleType; Types.Add(vect.Name, vect); Types.Add(swizzler.Name, swizzler); } // quat foreach (var type in BuiltinType.BaseTypes) { var quat = new QuaternionType(type); Types.Add(quat.Name, quat); } // matrices foreach (var type in BuiltinType.BaseTypes) for (var rows = 2; rows <= 4; ++rows) for (var cols = 2; cols <= 4; ++cols) { var matt = new MatrixType(type, cols, rows); Types.Add(matt.Name, matt); } // generate types foreach (var type in Types.Values) type.Generate(); } private static string NestedSymmetricFunction(IReadOnlyList<string> fields, string funcFormat, int start, int end) { if (start == end) return fields[start]; var mid = (start + end) / 2; return string.Format(funcFormat, NestedSymmetricFunction(fields, funcFormat, start, mid), NestedSymmetricFunction(fields, funcFormat, mid + 1, end)); } public static string NestedSymmetricFunction(IEnumerable<string> ffs, string funcFormat) { var fs = ffs.ToArray(); return NestedSymmetricFunction(fs, funcFormat, 0, fs.Length - 1); } public string TypeCast(BuiltinType otherType, string c) { if (otherType.HasArithmetics && BaseType.IsBool) return $"{c} ? {otherType.OneValue} : {otherType.ZeroValue}"; if (otherType.IsBool && BaseType.HasArithmetics) return $"{c} != {BaseType.ZeroValue}"; return $"({otherType.Name}){c}"; } protected static string ToRgba(string xyzw) { var s = ""; foreach (var c in xyzw) { switch (c) { case 'x': s += 'r'; break; case 'y': s += 'g'; break; case 'z': s += 'b'; break; case 'w': s += 'a'; break; } } return s; } } }
38.836425
173
0.480373
[ "MIT" ]
xposure/Atma.Math
generator/Types/AbstractType.cs
23,032
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; namespace PhonePong.GameScreens { class SinglePlayerTitleScreen : TitleScreen { public override void Initialize() { base.Initialize(); } public override void Update(GameTime gameTime) { base.Update(gameTime); UpdateBallPosition(); CheckNaturalBallCollisions(); TouchCollection tc = TouchPanel.GetState(); Rectangle bounds = ScreenManager.PongGame.GraphicsDevice.Viewport.Bounds; foreach (TouchLocation tl in tc) { if (tl.Position.X < bounds.Width - 150 && tl.Position.X > bounds.Width - 250 && tl.Position.Y > 300 && tl.Position.Y < 600) { this.CurrStatus = ScreenStatus.Hidden; ScreenManager.AddScreen(new SinglePlayerGameScreen()); this.ExitScreen(); } else if (tl.Position.X < bounds.Width - 250 && tl.Position.X > bounds.Width - 350 && tl.Position.Y > 300 && tl.Position.Y < 600) { this.CurrStatus = ScreenStatus.Hidden; ScreenManager.AddScreen(new TwoPlayerGameScreen()); this.ExitScreen(); } } } public override void Draw(GameTime gameTime) { Game game = ScreenManager.PongGame; Rectangle ballSrc = new Rectangle(64, 0, 32, 32); game.GraphicsDevice.Clear(Color.Black); ScreenManager.Batch.Begin(); ScreenManager.Batch.Draw(ScreenManager.SpriteSheet, this._ball, ballSrc, Color.White); ScreenManager.Batch.DrawString(ScreenManager.ChoiceFont, "PONG", new Vector2(game.GraphicsDevice.Viewport.Bounds.Width - 50, 300), Color.Red, (float)Math.PI / 2, new Vector2(0, 0), new Vector2(1, 1), SpriteEffects.None, 0.0f); ScreenManager.Batch.DrawString(ScreenManager.ChoiceFont, "One Player", new Vector2(game.GraphicsDevice.Viewport.Bounds.Width - 150, 300), Color.Red, (float)Math.PI / 2, new Vector2(0, 0), new Vector2(1, 1), SpriteEffects.None, 0.0f); ScreenManager.Batch.DrawString(ScreenManager.ChoiceFont, "Two Players", new Vector2(game.GraphicsDevice.Viewport.Bounds.Width - 250, 300), Color.Red, (float)Math.PI / 2, new Vector2(0, 0), new Vector2(1, 1), SpriteEffects.None, 0.0f); ScreenManager.Batch.End(); base.Draw(gameTime); } } }
36.615385
152
0.690336
[ "Apache-2.0" ]
davidov541/WP7Pong
PhonePong/PhonePong/SinglePlayerTitleScreen.cs
2,380
C#
using Waf.NewsReader.Applications.Views; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Waf.NewsReader.Presentation.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SettingsView : TabbedPage, ISettingsView { public SettingsView() { InitializeComponent(); } public object? DataContext { get => BindingContext; set => BindingContext = value; } } }
23.238095
65
0.631148
[ "MIT" ]
jbe2277/waf
src/NewsReader/NewsReader.Presentation/Views/SettingsView.xaml.cs
490
C#
namespace Asp { using System.Threading.Tasks; public class ASPV_testfiles_input_injectwithmodel_cshtml : Microsoft.AspNet.Mvc.Razor.RazorPage<MyModel> { private static object @__o; private void @__RazorDesignTimeHelpers__() { #pragma warning disable 219 #line 1 "testfiles/input/injectwithmodel.cshtml" var __modelHelper = default(MyModel); #line default #line hidden #pragma warning restore 219 } #line hidden public ASPV_testfiles_input_injectwithmodel_cshtml() { } #line hidden [Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute] public #line 2 "testfiles/input/injectwithmodel.cshtml" MyApp MyPropertyName #line default #line hidden { get; private set; } [Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute] public #line 3 "testfiles/input/injectwithmodel.cshtml" MyService<MyModel> Html #line default #line hidden { get; private set; } [Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute] public Microsoft.AspNet.Mvc.IUrlHelper Url { get; private set; } [Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute] public Microsoft.AspNet.Mvc.IViewComponentHelper Component { get; private set; } [Microsoft.AspNet.Mvc.Razor.Internal.RazorInjectAttribute] public Microsoft.AspNet.Mvc.Rendering.IJsonHelper Json { get; private set; } #line hidden #pragma warning disable 1998 public override async Task ExecuteAsync() { } #pragma warning restore 1998 } }
30.054545
108
0.676951
[ "Apache-2.0" ]
VGGeorgiev/Mvc
test/Microsoft.AspNet.Mvc.Razor.Host.Test/TestFiles/Output/DesignTime/InjectWithModel.cs
1,653
C#
using EF.ComponentData.Services; using SimpleInjector; namespace ComputerComponentsWeb.DI { public static class CompDIRegistration { public static void Register(Container container) { container.Register<IComponentCategoryService, ComponentCategoryService>(); container.Register<IComponentItemService, ComponentItemService>(); } } }
29.571429
86
0.676329
[ "MIT" ]
dimitad/MvcComputerComponents
ComputerComponents/DI/CompDIRegistration.cs
416
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 CSharpMath.Utils.NuGet.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.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; } } } }
39.888889
151
0.58403
[ "MIT" ]
hflexgrig/CSharpMath
CSharpMath.Utils.NuGet/Properties/Settings.Designer.cs
1,079
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Markup; using System.Windows.Media; namespace ControlsAndLayout { public partial class Scene { public bool RealTimeUpdate = true; private void HandleSelectionChanged(object sender, SelectionChangedEventArgs args) { if (sender == null) return; Details.DataContext = (sender as ListBox).DataContext; } protected void HandleTextChanged(object sender, TextChangedEventArgs me) { if (RealTimeUpdate) ParseCurrentBuffer(); } private void ParseCurrentBuffer() { try { var ms = new MemoryStream(); var sw = new StreamWriter(ms); var str = TextBox1.Text; sw.Write(str); sw.Flush(); ms.Flush(); ms.Position = 0; try { var content = XamlReader.Load(ms); if (content != null) { cc.Children.Clear(); cc.Children.Add((UIElement) content); } TextBox1.Foreground = Brushes.Black; ErrorText.Text = ""; } catch (XamlParseException xpe) { TextBox1.Foreground = Brushes.Red; TextBox1.TextWrapping = TextWrapping.Wrap; ErrorText.Text = xpe.Message; } } catch (Exception) { // ignored } } protected void OnClickParseButton(object sender, RoutedEventArgs args) { ParseCurrentBuffer(); } protected void ShowPreview(object sender, RoutedEventArgs args) { PreviewRow.Height = new GridLength(1, GridUnitType.Star); CodeRow.Height = new GridLength(0); } protected void ShowCode(object sender, RoutedEventArgs args) { PreviewRow.Height = new GridLength(0); CodeRow.Height = new GridLength(1, GridUnitType.Star); } protected void ShowSplit(object sender, RoutedEventArgs args) { PreviewRow.Height = new GridLength(1, GridUnitType.Star); CodeRow.Height = new GridLength(1, GridUnitType.Star); } } }
30.213483
104
0.523615
[ "MIT" ]
21pages/WPF-Samples
Getting Started/ControlsAndLayout/ControlsAndLayout/Scene.xaml.cs
2,691
C#
using System; namespace IoT.Solutions.SmartIndustrialApplications.CrackDetection { class ModelInput { public byte[] Image { get; set; } public UInt32 LabelAsKey { get; set; } public string ImagePath { get; set; } public string Label { get; set; } } }
22.846154
66
0.62963
[ "MIT" ]
Apress/designing-iot-solutions-ms-azure
Nirnay_Ch07_SourceCode/CrackDetection/DataView/ModelInput.cs
299
C#
using Hamakaze; using SharpChat.Sessions; using SharpChat.Users; using SharpChat.Users.Bump; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.Json; namespace SharpChat.DataProvider.Misuzu.Users.Bump { public class MisuzuUserBumpClient : IUserBumpClient { private MisuzuDataProvider DataProvider { get; } private HttpClient HttpClient { get; } private const string URL = @"/bump"; public MisuzuUserBumpClient(MisuzuDataProvider dataProvider, HttpClient httpClient) { DataProvider = dataProvider ?? throw new ArgumentNullException(nameof(dataProvider)); HttpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } public void SubmitBumpUsers( SessionManager sessions, IEnumerable<IUser> users, Action onSuccess = null, Action<Exception> onFailure = null ) { if(users == null) throw new ArgumentNullException(nameof(users)); if(!users.Any()) return; List<MisuzuUserBumpInfo> infos = new List<MisuzuUserBumpInfo>(); foreach(IUser user in users) { IPAddress addr = sessions.GetRemoteAddresses(user).FirstOrDefault(); if(addr == default) continue; infos.Add(new MisuzuUserBumpInfo(user, addr)); } byte[] data = JsonSerializer.SerializeToUtf8Bytes(infos); HttpRequestMessage request = new HttpRequestMessage(HttpRequestMessage.POST, DataProvider.GetURL(URL)); request.SetHeader(@"X-SharpChat-Signature", DataProvider.GetSignedHash(data)); request.SetBody(data); HttpClient.SendRequest( request, disposeRequest: false, onComplete: (t, r) => { request.Dispose(); onSuccess?.Invoke(); }, onError: (t, e) => { Logger.Write(@"User bump request failed. Retrying once..."); Logger.Debug(e); HttpClient.SendRequest( request, onComplete: (t, r) => { Logger.Write(@"Second user bump attempt succeeded!"); onSuccess?.Invoke(); }, onError: (t, e) => { Logger.Write(@"User bump request failed again."); Logger.Debug(e); onFailure?.Invoke(e); } ); } ); } } }
37.260274
115
0.542647
[ "MIT" ]
hnjm/sharp-chat
SharpChat.DataProvider.Misuzu/Users/Bump/MisuzuUserBumpClient.cs
2,722
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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal partial class MethodDebugInfo<TTypeSymbol, TLocalSymbol> { private readonly struct LocalNameAndScope : IEquatable<LocalNameAndScope> { internal readonly string LocalName; internal readonly int ScopeStart; internal readonly int ScopeEnd; internal LocalNameAndScope(string localName, int scopeStart, int scopeEnd) { LocalName = localName; ScopeStart = scopeStart; ScopeEnd = scopeEnd; } public bool Equals(LocalNameAndScope other) { return ScopeStart == other.ScopeStart && ScopeEnd == other.ScopeEnd && string.Equals(LocalName, other.LocalName, StringComparison.Ordinal); } public override bool Equals(object obj) { throw new NotImplementedException(); } public override int GetHashCode() { return Hash.Combine(Hash.Combine(ScopeStart, ScopeEnd), LocalName.GetHashCode()); } } internal const int S_OK = 0x0; internal const int E_FAIL = unchecked((int)0x80004005); internal const int E_NOTIMPL = unchecked((int)0x80004001); private static readonly IntPtr s_ignoreIErrorInfo = new IntPtr(-1); public static unsafe MethodDebugInfo<TTypeSymbol, TLocalSymbol> ReadMethodDebugInfo( ISymUnmanagedReader3? symReader, EESymbolProvider<TTypeSymbol, TLocalSymbol>? symbolProvider, // TODO: only null in DTEE case where we looking for default namesapace int methodToken, int methodVersion, int ilOffset, bool isVisualBasicMethod ) { // no symbols if (symReader == null) { return None; } if (symReader is ISymUnmanagedReader5 symReader5) { int hr = symReader5.GetPortableDebugMetadataByVersion( methodVersion, out byte* metadata, out int size ); ThrowExceptionForHR(hr); if (hr == S_OK) { var mdReader = new MetadataReader(metadata, size); try { return ReadFromPortable( mdReader, methodToken, ilOffset, symbolProvider, isVisualBasicMethod ); } catch (BadImageFormatException) { // bad CDI, ignore return None; } } } var allScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); var containingScopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); try { var symMethod = symReader.GetMethodByVersion(methodToken, methodVersion); if (symMethod != null) { symMethod.GetAllScopes( allScopes, containingScopes, ilOffset, isScopeEndInclusive: isVisualBasicMethod ); } ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups; ImmutableArray<ExternAliasRecord> externAliasRecords; string defaultNamespaceName; if (isVisualBasicMethod) { ReadVisualBasicImportsDebugInfo( symReader, methodToken, methodVersion, out importRecordGroups, out defaultNamespaceName ); externAliasRecords = ImmutableArray<ExternAliasRecord>.Empty; } else { RoslynDebug.AssertNotNull(symbolProvider); ReadCSharpNativeImportsInfo( symReader, symbolProvider, methodToken, methodVersion, out importRecordGroups, out externAliasRecords ); defaultNamespaceName = ""; } // VB should read hoisted scope information from local variables: var hoistedLocalScopeRecords = isVisualBasicMethod ? default : ImmutableArray<HoistedLocalScopeRecord>.Empty; ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap = null; ImmutableDictionary<string, ImmutableArray<bool>>? dynamicLocalConstantMap = null; ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap = null; ImmutableDictionary< LocalNameAndScope, ImmutableArray<string?> >? tupleLocalConstantMap = null; byte[]? customDebugInfo = GetCustomDebugInfoBytes( symReader, methodToken, methodVersion ); if (customDebugInfo != null) { if (!isVisualBasicMethod) { var customDebugInfoRecord = CustomDebugInfoReader.TryGetCustomDebugInfoRecord( customDebugInfo, CustomDebugInfoKind.StateMachineHoistedLocalScopes ); if (!customDebugInfoRecord.IsDefault) { hoistedLocalScopeRecords = CustomDebugInfoReader .DecodeStateMachineHoistedLocalScopesRecord(customDebugInfoRecord) .SelectAsArray( s => new HoistedLocalScopeRecord(s.StartOffset, s.Length) ); } GetCSharpDynamicLocalInfo( customDebugInfo, allScopes, out dynamicLocalMap, out dynamicLocalConstantMap ); } GetTupleElementNamesLocalInfo( customDebugInfo, out tupleLocalMap, out tupleLocalConstantMap ); } var constantsBuilder = ArrayBuilder<TLocalSymbol>.GetInstance(); if (symbolProvider != null) // TODO { GetConstants( constantsBuilder, symbolProvider, containingScopes, dynamicLocalConstantMap, tupleLocalConstantMap ); } var reuseSpan = GetReuseSpan(allScopes, ilOffset, isVisualBasicMethod); return new MethodDebugInfo<TTypeSymbol, TLocalSymbol>( hoistedLocalScopeRecords, importRecordGroups, externAliasRecords, dynamicLocalMap, tupleLocalMap, defaultNamespaceName, containingScopes.GetLocalNames(), constantsBuilder.ToImmutableAndFree(), reuseSpan ); } catch (InvalidOperationException) { // bad CDI, ignore return None; } finally { allScopes.Free(); containingScopes.Free(); } } private static void ThrowExceptionForHR(int hr) { // E_FAIL indicates "no info". // E_NOTIMPL indicates a lack of ISymUnmanagedReader support (in a particular implementation). if (hr < 0 && hr != E_FAIL && hr != E_NOTIMPL) { Marshal.ThrowExceptionForHR(hr, s_ignoreIErrorInfo); } } /// <summary> /// Get the blob of binary custom debug info for a given method. /// </summary> private static byte[]? GetCustomDebugInfoBytes( ISymUnmanagedReader3 reader, int methodToken, int methodVersion ) { try { return reader.GetCustomDebugInfo(methodToken, methodVersion); } catch (ArgumentOutOfRangeException) { // Sometimes the debugger returns the HRESULT for ArgumentOutOfRangeException, rather than E_FAIL, // for methods without custom debug info (https://github.com/dotnet/roslyn/issues/4138). return null; } } /// <summary> /// Get the (unprocessed) import strings for a given method. /// </summary> /// <remarks> /// Doesn't consider forwarding. /// /// CONSIDER: Dev12 doesn't just check the root scope - it digs around to find the best /// match based on the IL offset and then walks up to the root scope (see PdbUtil::GetScopeFromOffset). /// However, it's not clear that this matters, since imports can't be scoped in VB. This is probably /// just based on the way they were extracting locals and constants based on a specific scope. /// /// Returns empty array if there are no import strings for the specified method. /// </remarks> private static ImmutableArray<string> GetImportStrings( ISymUnmanagedReader reader, int methodToken, int methodVersion ) { var method = reader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { // In rare circumstances (only bad PDBs?) GetMethodByVersion can return null. // If there's no debug info for the method, then no import strings are available. return ImmutableArray<string>.Empty; } var rootScope = method.GetRootScope(); if (rootScope == null) { Debug.Assert(false, "Expected a root scope."); return ImmutableArray<string>.Empty; } var childScopes = rootScope.GetChildren(); if (childScopes.Length == 0) { // It seems like there should always be at least one child scope, but we've // seen PDBs where that is not the case. return ImmutableArray<string>.Empty; } // As in NamespaceListWrapper::Init, we only consider namespaces in the first // child of the root scope. var firstChildScope = childScopes[0]; var namespaces = firstChildScope.GetNamespaces(); if (namespaces.Length == 0) { // It seems like there should always be at least one namespace (i.e. the global // namespace), but we've seen PDBs where that is not the case. return ImmutableArray<string>.Empty; } return ImmutableArray.CreateRange(namespaces.Select(n => n.GetName())); } private static void ReadCSharpNativeImportsInfo( ISymUnmanagedReader3 reader, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, int methodToken, int methodVersion, out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, out ImmutableArray<ExternAliasRecord> externAliasRecords ) { ImmutableArray<string> externAliasStrings; var importStringGroups = CustomDebugInfoReader.GetCSharpGroupedImportStrings( methodToken, KeyValuePairUtil.Create(reader, methodVersion), getMethodCustomDebugInfo: (token, arg) => GetCustomDebugInfoBytes(arg.Key, token, arg.Value), getMethodImportStrings: (token, arg) => GetImportStrings(arg.Key, token, arg.Value), externAliasStrings: out externAliasStrings ); Debug.Assert(importStringGroups.IsDefault == externAliasStrings.IsDefault); ArrayBuilder<ImmutableArray<ImportRecord>>? importRecordGroupBuilder = null; ArrayBuilder<ExternAliasRecord>? externAliasRecordBuilder = null; if (!importStringGroups.IsDefault) { importRecordGroupBuilder = ArrayBuilder<ImmutableArray<ImportRecord>>.GetInstance( importStringGroups.Length ); foreach (var importStringGroup in importStringGroups) { var groupBuilder = ArrayBuilder<ImportRecord>.GetInstance( importStringGroup.Length ); foreach (var importString in importStringGroup) { if ( TryCreateImportRecordFromCSharpImportString( symbolProvider, importString, out var record ) ) { groupBuilder.Add(record); } else { Debug.WriteLine($"Failed to parse import string {importString}"); } } importRecordGroupBuilder.Add(groupBuilder.ToImmutableAndFree()); } if (!externAliasStrings.IsDefault) { externAliasRecordBuilder = ArrayBuilder<ExternAliasRecord>.GetInstance( externAliasStrings.Length ); foreach (var externAliasString in externAliasStrings) { if ( !CustomDebugInfoReader.TryParseCSharpImportString( externAliasString, out var alias, out var externAlias, out var target, out var kind ) ) { Debug.WriteLine($"Unable to parse extern alias '{externAliasString}'"); continue; } Debug.Assert( kind == ImportTargetKind.Assembly, "Programmer error: How did a non-assembly get in the extern alias list?" ); RoslynDebug.Assert(alias != null); // Name of the extern alias. RoslynDebug.Assert(externAlias == null); // Not used. RoslynDebug.Assert(target != null); // Name of the target assembly. if (!AssemblyIdentity.TryParseDisplayName(target, out var targetIdentity)) { Debug.WriteLine( $"Unable to parse target of extern alias '{externAliasString}'" ); continue; } externAliasRecordBuilder.Add(new ExternAliasRecord(alias, targetIdentity)); } } } importRecordGroups = importRecordGroupBuilder?.ToImmutableAndFree() ?? ImmutableArray<ImmutableArray<ImportRecord>>.Empty; externAliasRecords = externAliasRecordBuilder?.ToImmutableAndFree() ?? ImmutableArray<ExternAliasRecord>.Empty; } private static bool TryCreateImportRecordFromCSharpImportString( EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, string importString, out ImportRecord record ) { string? targetString; if ( CustomDebugInfoReader.TryParseCSharpImportString( importString, out var alias, out var externAlias, out targetString, out var targetKind ) ) { ITypeSymbolInternal? type = null; if (targetKind == ImportTargetKind.Type) { type = symbolProvider.GetTypeSymbolForSerializedType(targetString); targetString = null; } record = new ImportRecord( targetKind: targetKind, alias: alias, targetType: type, targetString: targetString, targetAssembly: null, targetAssemblyAlias: externAlias ); return true; } record = default; return false; } /// <exception cref="InvalidOperationException">Bad data.</exception> private static void GetCSharpDynamicLocalInfo( byte[] customDebugInfo, IEnumerable<ISymUnmanagedScope> scopes, out ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap, out ImmutableDictionary<string, ImmutableArray<bool>>? dynamicLocalConstantMap ) { dynamicLocalMap = null; dynamicLocalConstantMap = null; var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord( customDebugInfo, CustomDebugInfoKind.DynamicLocals ); if (record.IsDefault) { return; } var localKindsByName = PooledDictionary<string, LocalKind>.GetInstance(); GetLocalKindByName(localKindsByName, scopes); ImmutableDictionary<int, ImmutableArray<bool>>.Builder? localBuilder = null; ImmutableDictionary<string, ImmutableArray<bool>>.Builder? constantBuilder = null; var dynamicLocals = CustomDebugInfoReader.DecodeDynamicLocalsRecord(record); foreach (var dynamicLocal in dynamicLocals) { int slot = dynamicLocal.SlotId; var flags = dynamicLocal.Flags; if (slot == 0) { LocalKind kind; var name = dynamicLocal.LocalName; localKindsByName.TryGetValue(name, out kind); switch (kind) { case LocalKind.DuplicateName: // Drop locals with ambiguous names. continue; case LocalKind.ConstantName: constantBuilder ??= ImmutableDictionary.CreateBuilder< string, ImmutableArray<bool> >(); constantBuilder[name] = flags; continue; } } localBuilder ??= ImmutableDictionary.CreateBuilder<int, ImmutableArray<bool>>(); localBuilder[slot] = flags; } if (localBuilder != null) { dynamicLocalMap = localBuilder.ToImmutable(); } if (constantBuilder != null) { dynamicLocalConstantMap = constantBuilder.ToImmutable(); } localKindsByName.Free(); } private enum LocalKind { DuplicateName, VariableName, ConstantName } /// <summary> /// Dynamic CDI encodes slot id and name for each dynamic local variable, but only name for a constant. /// Constants have slot id set to 0. As a result there is a potential for ambiguity. If a variable in a slot 0 /// and a constant defined anywhere in the method body have the same name we can't say which one /// the dynamic flags belong to (if there is a dynamic record for at least one of them). /// /// This method returns the local kind (variable, constant, or duplicate) based on name. /// </summary> private static void GetLocalKindByName( Dictionary<string, LocalKind> localNames, IEnumerable<ISymUnmanagedScope> scopes ) { Debug.Assert(localNames.Count == 0); var localSlot0 = scopes .SelectMany(scope => scope.GetLocals()) .FirstOrDefault(variable => variable.GetSlot() == 0); if (localSlot0 != null) { localNames.Add(localSlot0.GetName(), LocalKind.VariableName); } foreach (var scope in scopes) { foreach (var constant in scope.GetConstants()) { string name = constant.GetName(); localNames[name] = localNames.ContainsKey(name) ? LocalKind.DuplicateName : LocalKind.ConstantName; } } } private static void GetTupleElementNamesLocalInfo( byte[] customDebugInfo, out ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalMap, out ImmutableDictionary< LocalNameAndScope, ImmutableArray<string?> >? tupleLocalConstantMap ) { tupleLocalMap = null; tupleLocalConstantMap = null; var record = CustomDebugInfoReader.TryGetCustomDebugInfoRecord( customDebugInfo, CustomDebugInfoKind.TupleElementNames ); if (record.IsDefault) { return; } ImmutableDictionary<int, ImmutableArray<string?>>.Builder? localBuilder = null; ImmutableDictionary< LocalNameAndScope, ImmutableArray<string?> >.Builder? constantBuilder = null; var tuples = CustomDebugInfoReader.DecodeTupleElementNamesRecord(record); foreach (var tuple in tuples) { var slotIndex = tuple.SlotIndex; var elementNames = tuple.ElementNames; if (slotIndex < 0) { constantBuilder ??= ImmutableDictionary.CreateBuilder< LocalNameAndScope, ImmutableArray<string?> >(); var localAndScope = new LocalNameAndScope( tuple.LocalName, tuple.ScopeStart, tuple.ScopeEnd ); constantBuilder[localAndScope] = elementNames; } else { localBuilder ??= ImmutableDictionary.CreateBuilder< int, ImmutableArray<string?> >(); localBuilder[slotIndex] = elementNames; } } if (localBuilder != null) { tupleLocalMap = localBuilder.ToImmutable(); } if (constantBuilder != null) { tupleLocalConstantMap = constantBuilder.ToImmutable(); } } private static void ReadVisualBasicImportsDebugInfo( ISymUnmanagedReader reader, int methodToken, int methodVersion, out ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups, out string defaultNamespaceName ) { importRecordGroups = ImmutableArray<ImmutableArray<ImportRecord>>.Empty; var importStrings = CustomDebugInfoReader.GetVisualBasicImportStrings( methodToken, KeyValuePairUtil.Create(reader, methodVersion), (token, arg) => GetImportStrings(arg.Key, token, arg.Value) ); if (importStrings.IsDefault) { defaultNamespaceName = ""; return; } string? lazyDefaultNamespaceName = null; var projectLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance(); var fileLevelImportRecords = ArrayBuilder<ImportRecord>.GetInstance(); foreach (var importString in importStrings) { RoslynDebug.AssertNotNull(importString); if (importString.Length > 0 && importString[0] == '*') { string? alias = null; string? target = null; if ( !CustomDebugInfoReader.TryParseVisualBasicImportString( importString, out alias, out target, out var kind, out var scope ) ) { Debug.WriteLine($"Unable to parse import string '{importString}'"); continue; } else if (kind == ImportTargetKind.Defunct) { continue; } Debug.Assert(alias == null); // The default namespace is never aliased. Debug.Assert(target != null); Debug.Assert(kind == ImportTargetKind.DefaultNamespace); // We only expect to see one of these, but it looks like ProcedureContext::LoadImportsAndDefaultNamespaceNormal // implicitly uses the last one if there are multiple. Debug.Assert(lazyDefaultNamespaceName == null); lazyDefaultNamespaceName = target; } else { ImportRecord importRecord; VBImportScopeKind scope = 0; if ( TryCreateImportRecordFromVisualBasicImportString( importString, out importRecord, out scope ) ) { if (scope == VBImportScopeKind.Project) { projectLevelImportRecords.Add(importRecord); } else { Debug.Assert( scope == VBImportScopeKind.File || scope == VBImportScopeKind.Unspecified ); fileLevelImportRecords.Add(importRecord); } } else { Debug.WriteLine($"Failed to parse import string {importString}"); } } } importRecordGroups = ImmutableArray.Create( fileLevelImportRecords.ToImmutableAndFree(), projectLevelImportRecords.ToImmutableAndFree() ); defaultNamespaceName = lazyDefaultNamespaceName ?? ""; } private static bool TryCreateImportRecordFromVisualBasicImportString( string importString, out ImportRecord record, out VBImportScopeKind scope ) { ImportTargetKind targetKind; string alias; string targetString; if ( CustomDebugInfoReader.TryParseVisualBasicImportString( importString, out alias, out targetString, out targetKind, out scope ) ) { record = new ImportRecord( targetKind: targetKind, alias: alias, targetType: null, targetString: targetString, targetAssembly: null, targetAssemblyAlias: null ); return true; } record = default; return false; } private static ILSpan GetReuseSpan( ArrayBuilder<ISymUnmanagedScope> scopes, int ilOffset, bool isEndInclusive ) { return MethodContextReuseConstraints.CalculateReuseSpan( ilOffset, ILSpan.MaxValue, scopes.Select( scope => new ILSpan( (uint)scope.GetStartOffset(), (uint)(scope.GetEndOffset() + (isEndInclusive ? 1 : 0)) ) ) ); } private static void GetConstants( ArrayBuilder<TLocalSymbol> builder, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, ArrayBuilder<ISymUnmanagedScope> scopes, ImmutableDictionary<string, ImmutableArray<bool>>? dynamicLocalConstantMap, ImmutableDictionary<LocalNameAndScope, ImmutableArray<string?>>? tupleLocalConstantMap ) { foreach (var scope in scopes) { foreach (var constant in scope.GetConstants()) { string name = constant.GetName(); object rawValue = constant.GetValue(); var signature = constant.GetSignature().ToImmutableArray(); TTypeSymbol type; try { type = symbolProvider.DecodeLocalVariableType(signature); } catch (Exception e) when (e is UnsupportedSignatureContent || e is BadImageFormatException) { // ignore continue; } if (type.Kind == SymbolKind.ErrorType) { continue; } ConstantValue constantValue = PdbHelpers.GetSymConstantValue(type, rawValue); // TODO (https://github.com/dotnet/roslyn/issues/1815): report error properly when the symbol is used if (constantValue.IsBad) { continue; } var dynamicFlags = default(ImmutableArray<bool>); if (dynamicLocalConstantMap != null) { dynamicLocalConstantMap.TryGetValue(name, out dynamicFlags); } var tupleElementNames = default(ImmutableArray<string?>); if (tupleLocalConstantMap != null) { int scopeStart = scope.GetStartOffset(); int scopeEnd = scope.GetEndOffset(); tupleLocalConstantMap.TryGetValue( new LocalNameAndScope(name, scopeStart, scopeEnd), out tupleElementNames ); } builder.Add( symbolProvider.GetLocalConstant( name, type, constantValue, dynamicFlags, tupleElementNames ) ); } } } /// <summary> /// Returns symbols for the locals emitted in the original method, /// based on the local signatures from the IL and the names and /// slots from the PDB. The actual locals are needed to ensure the /// local slots in the generated method match the original. /// </summary> public static void GetLocals( ArrayBuilder<TLocalSymbol> builder, EESymbolProvider<TTypeSymbol, TLocalSymbol> symbolProvider, ImmutableArray<string> names, ImmutableArray<LocalInfo<TTypeSymbol>> localInfo, ImmutableDictionary<int, ImmutableArray<bool>>? dynamicLocalMap, ImmutableDictionary<int, ImmutableArray<string?>>? tupleLocalConstantMap ) { if (localInfo.Length == 0) { // When debugging a .dmp without a heap, localInfo will be empty although // names may be non-empty if there is a PDB. Since there's no type info, the // locals are dropped. Note this means the local signature of any generated // method will not match the original signature, so new locals will overlap // original locals. That is ok since there is no live process for the debugger // to update (any modified values exist in the debugger only). return; } Debug.Assert(localInfo.Length >= names.Length); for (int i = 0; i < localInfo.Length; i++) { string? name = (i < names.Length) ? names[i] : null; var dynamicFlags = default(ImmutableArray<bool>); dynamicLocalMap?.TryGetValue(i, out dynamicFlags); var tupleElementNames = default(ImmutableArray<string?>); tupleLocalConstantMap?.TryGetValue(i, out tupleElementNames); builder.Add( symbolProvider.GetLocalVariable( name, i, localInfo[i], dynamicFlags, tupleElementNames ) ); } } } }
38.679612
144
0.492442
[ "MIT" ]
belav/roslyn
src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/MethodDebugInfo.Native.cs
35,858
C#
using System; using System.Web; using Kudu.Core.Test; using Kudu.Services.ServiceHookHandlers; using Moq; using Newtonsoft.Json.Linq; using Xunit; namespace Kudu.Services.Test { public class KilnHgHandlerFacts { [Fact] public void KilnHgHandlerIgnoresNonKilnPayloads() { // Arrange var payload = JObject.Parse(@"{ ""repository"":{ ""repourl"":""http://test.codebasehq.com/projects/test-repositories/repositories/git1/commit/840daf31f4f87cb5cafd295ef75de989095f415b"" } }"); var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: payload, targetBranch: null, deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.UnknownPayload, result); } [Fact] public void KilnHgHandlerReturnsNoOpForCommitsThatAreNotTheTargetBranch() { // Arrange const string payload = @" { ""commits"": [ { ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""default"", ""id"": ""771363bfb8e6e2b76a3da8d156c6a3db0ea9a9c4"", ""message"": ""did a commit"", ""revision"": 1, ""timestamp"": ""1/7/2013 6:54:25 AM"" } ], ""repository"": { ""url"": ""https://kudutest.kilnhg.com/Code/Test/Group/KuduApp"" } } "; var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: JObject.Parse(payload), targetBranch: "not-default", deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.NoOp, result); Assert.Null(deploymentInfo); } [Theory] [InlineData("http://kudutest.kilnhg.com/Code/Test/Group/KuduApp")] [InlineData("https://kudutest.kilnhg.com/Code/Test/Group/KuduApp")] public void KilnHgHandlerParsesKilnPayloads(string repositoryUrl) { // Arrange string payload = @"{ ""commits"": [ { ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""default"", ""id"": ""f1525c29206072f6565e6ba70831afb65b55e9a0"", ""message"": ""commit message"", ""revision"": 14, ""timestamp"": ""1/15/2013 2:23:37 AM"" } ], ""repository"": { ""url"": """ + repositoryUrl + @""" } }"; var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: JObject.Parse(payload), targetBranch: "default", deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.ProcessDeployment, result); Assert.Equal("Kiln", deploymentInfo.Deployer); Assert.Equal(repositoryUrl, deploymentInfo.RepositoryUrl); Assert.Equal("Brian Surowiec", deploymentInfo.TargetChangeset.AuthorName); Assert.Equal("xtorted@optonline.net", deploymentInfo.TargetChangeset.AuthorEmail); Assert.Equal("f1525c29206072f6565e6ba70831afb65b55e9a0", deploymentInfo.TargetChangeset.Id); Assert.Equal("commit message", deploymentInfo.TargetChangeset.Message); Assert.Equal(new DateTimeOffset(2013, 1, 15, 2, 23, 37, TimeSpan.Zero), deploymentInfo.TargetChangeset.Timestamp); } [Fact] public void KilnHgHandlerParsesKilnPayloadsWithAccessTokenCommit() { // Arrange const string payload = @"{ ""commits"": [ { ""author"": ""a1444778-8d5d-413d-83f7-6dbf9e2cd77d"", ""branch"": ""default"", ""id"": ""f1525c29206072f6565e6ba70831afb65b55e9a0"", ""message"": ""commit message"", ""revision"": 14, ""timestamp"": ""1/15/2013 2:23:37 AM"" } ], ""repository"": { ""url"": ""https://kudutest.kilnhg.com/Code/Test/Group/KuduApp"" } }"; var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: JObject.Parse(payload), targetBranch: "default", deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.ProcessDeployment, result); Assert.Equal("Kiln", deploymentInfo.Deployer); Assert.Equal("https://kudutest.kilnhg.com/Code/Test/Group/KuduApp", deploymentInfo.RepositoryUrl); Assert.Equal("System Account", deploymentInfo.TargetChangeset.AuthorName); Assert.Null(deploymentInfo.TargetChangeset.AuthorEmail); Assert.Equal("f1525c29206072f6565e6ba70831afb65b55e9a0", deploymentInfo.TargetChangeset.Id); Assert.Equal("commit message", deploymentInfo.TargetChangeset.Message); Assert.Equal(new DateTimeOffset(2013, 1, 15, 2, 23, 37, TimeSpan.Zero), deploymentInfo.TargetChangeset.Timestamp); } [Theory] [InlineData("http://kudutest.kilnhg.com/Code/Test/Group/KuduApp")] [InlineData("https://kudutest.kilnhg.com/Code/Test/Group/KuduApp")] public void KilnHgHandlerParsesKilnPayloadsForPrivateRepositories(string repositoryUrl) { // Arrange string payload = @"{ ""commits"": [ { ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""default"", ""id"": ""771363bfb8e6e2b76a3da8d156c6a3db0ea9a9c4"", ""message"": ""commit message"", ""revision"": 1, ""timestamp"": ""1/7/2013 6:54:25 AM"" } ], ""repository"": { ""url"": """ + repositoryUrl + @""" } } "; var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); settingsManager.SetValue("kiln.accesstoken", "hg-user"); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: JObject.Parse(payload), targetBranch: "default", deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.ProcessDeployment, result); Assert.Equal("Kiln", deploymentInfo.Deployer); Assert.Equal("https://hg-user:kudu@kudutest.kilnhg.com/Code/Test/Group/KuduApp", deploymentInfo.RepositoryUrl); Assert.Equal("Brian Surowiec", deploymentInfo.TargetChangeset.AuthorName); Assert.Equal("xtorted@optonline.net", deploymentInfo.TargetChangeset.AuthorEmail); Assert.Equal("771363bfb8e6e2b76a3da8d156c6a3db0ea9a9c4", deploymentInfo.TargetChangeset.Id); Assert.Equal("commit message", deploymentInfo.TargetChangeset.Message); Assert.Equal(new DateTimeOffset(2013, 1, 7, 6, 54, 25, TimeSpan.Zero), deploymentInfo.TargetChangeset.Timestamp); } [Fact] public void KilnHgHandlerParsesKilnPayloadsForRepositoriesWithMultipleCommitsAccrossBranches() { // Arrange const string payload = @"{ ""commits"": [" + @"{ ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""non-default"", ""id"": ""f1525c29206072f6565e6ba70831afb65b55e9a0"", ""message"": ""commit message 14"", ""revision"": 14, ""timestamp"": ""1/15/2013 2:23:37 AM"" }," + @"{ ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""default"", ""id"": ""58df029b9891bed6be1516971b50dc0eda58ce38"", ""message"": ""commit message 13"", ""revision"": 13, ""timestamp"": ""1/15/2013 2:23:20 AM"" }," + @"{ ""author"": ""Brian Surowiec <xtorted@optonline.net>"", ""branch"": ""default"", ""id"": ""cb6ea738f5ec16d53c06a2f5823c34b396922c13"", ""message"": ""commit message 12"", ""revision"": 12, ""timestamp"": ""1/15/2013 2:23:04 AM"" }" + @"], ""repository"": { ""url"": ""https://kudutest.kilnhg.com/Code/Test/Group/KuduApp"" } }"; var httpRequest = new Mock<HttpRequestBase>(); var settingsManager = new MockDeploymentSettingsManager(); settingsManager.SetValue("kiln.accesstoken", "hg-user"); var kilnHandler = new KilnHgHandler(settingsManager); // Act DeploymentInfo deploymentInfo; DeployAction result = kilnHandler.TryParseDeploymentInfo(httpRequest.Object, payload: JObject.Parse(payload), targetBranch: "default", deploymentInfo: out deploymentInfo); // Assert Assert.Equal(DeployAction.ProcessDeployment, result); Assert.Equal("Kiln", deploymentInfo.Deployer); Assert.Equal("https://hg-user:kudu@kudutest.kilnhg.com/Code/Test/Group/KuduApp", deploymentInfo.RepositoryUrl); Assert.Equal("Brian Surowiec", deploymentInfo.TargetChangeset.AuthorName); Assert.Equal("xtorted@optonline.net", deploymentInfo.TargetChangeset.AuthorEmail); Assert.Equal("58df029b9891bed6be1516971b50dc0eda58ce38", deploymentInfo.TargetChangeset.Id); Assert.Equal("commit message 13", deploymentInfo.TargetChangeset.Message); Assert.Equal(new DateTimeOffset(2013, 1, 15, 2, 23, 20, TimeSpan.Zero), deploymentInfo.TargetChangeset.Timestamp); } [Theory] [InlineData(@"{ ""repo"": { ""repo_url"": ""https://kudutest.kilnhg.com/Code/Test/Group/KuduApp"" } } ")] [InlineData(@"{ ""repository"": { ""repo_url"": ""https://kudutest.kilnhg.com/Code/Test/Group/KuduApp"" } } ")] public void IsKilnRequestWithoutRepositoryUrl(string payloadContent) { // Arrange var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act bool result = kilnHandler.IsKilnRequest(JObject.Parse(payloadContent)); // Assert Assert.False(result); } [Theory] [InlineData(true, @"\.kilnhg\.com")] [InlineData(false, @"\.github\.com")] public void IsKilnRequestWithCustomDomainPatterns(bool expectedResult, string domainPattern) { // Arrange const string payload = @"{ ""repository"": { ""url"": ""https://kudu.kilnhg.com/Code/Test/Group/KuduApp"" } } "; var settingsManager = new MockDeploymentSettingsManager(); settingsManager.SetValue("kiln.domain", domainPattern); var kilnHandler = new KilnHgHandler(settingsManager); // Act bool result = kilnHandler.IsKilnRequest(JObject.Parse(payload)); // Assert Assert.Equal(expectedResult, result); } [Theory] [InlineData(true, @"kilnhg.com")] [InlineData(false, @"github.com")] public void IsKilnRequestWithDefaultDomainPatterns(bool expectedResult, string domain) { // Arrange var payload = string.Format(@"{{ ""repository"": {{ ""url"": ""https://kudu.{0}/Code/Test/Group/KuduApp"" }} }} ", domain); var settingsManager = new MockDeploymentSettingsManager(); var kilnHandler = new KilnHgHandler(settingsManager); // Act bool result = kilnHandler.IsKilnRequest(JObject.Parse(payload)); // Assert Assert.Equal(expectedResult, result); } [Theory] [InlineData("Test User <test@user.com>")] // full, correct, format [InlineData(" <test@user.com>")] // missing first & last name, with spaces [InlineData("Test <test@user.com>")] // only first name [InlineData(" User <test@user.com>")] // only last name, with spaces [InlineData("<test@user.com>")] // only email, no spaces [InlineData("test@user.com")] // only email, no other formatting public void ParseEmailFromAuthorWithEmailAddress(string author) { Assert.Equal("test@user.com", KilnHgHandler.ParseEmailFromAuthor(author)); } [Theory] [InlineData("Test User")] [InlineData("Test User <>")] [InlineData("Test User <email>")] [InlineData(null)] [InlineData("")] [InlineData("\t")] [InlineData(" ")] public void ParseEmailFromAuthorWithoutEmailAddress(string author) { Assert.Null(KilnHgHandler.ParseEmailFromAuthor(author)); } [Theory] [InlineData("Test User", "Test User <test@user.com>")] // full, correct, format [InlineData("<test@user.com>", " <test@user.com>")] // missing first & last name, with spaces [InlineData("Test", "Test <test@user.com>")] // only first name [InlineData("User", " User <test@user.com>")] // only last name, with spaces [InlineData("<test@user.com>", "<test@user.com>")] // only email, no spaces [InlineData("test@user.com", "test@user.com")] // only email, no other formatting [InlineData("Test User", " Test User ")] [InlineData("Test User", "Test User <>")] [InlineData("Test User", "Test User <email>")] [InlineData(null, null)] [InlineData(null, "")] [InlineData(null, "\t")] [InlineData(null, " ")] public void ParseNameFromAuthor(string expectedResult, string author) { Assert.Equal(expectedResult, KilnHgHandler.ParseNameFromAuthor(author)); } } }
56.166667
373
0.630776
[ "Apache-2.0" ]
DiogenesPolanco/kudu
Kudu.Services.Test/KilnHgHandlerFacts.cs
14,156
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace CleanArch.Infra.Data.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Courses", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Name = table.Column<string>(nullable: true), Description = table.Column<string>(nullable: true), ImageUrl = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Courses", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Courses"); } } }
32.5
71
0.516346
[ "Apache-2.0" ]
maxchn/CleanArchitectureDemo
CleanArch/CleanArch.Infra.Data/Migrations/20200823172949_InitialMigration.cs
1,042
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; namespace Adyen.Model.MarketPay { /// <summary> /// AccountContainer /// </summary> [DataContract] public partial class GetAccountHolderStatusResponse : IEquatable<AccountContainer>, IValidatableObject { /// <summary> /// account. /// </summary> /// <value>account.</value> [DataMember(Name = "Account", EmitDefaultValue = false)] public Account account { get; set; } /// <summary> /// Initializes a new instance of the <see cref="AccountContainer" /> class. /// </summary> /// <param name="account">account.</param> public AccountContainer(Account account = default(Account)) { this.account = account; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class AccountContainer {\n"); sb.Append(" account: ").Append(account).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as AccountContainer); } /// <summary> /// Returns true if MerchantDevice instances are equal /// </summary> /// <param name="input">Instance of MerchantDevice to be compared</param> /// <returns>Boolean</returns> public bool Equals(AccountContainer input) { if (input == null) return false; return ( this.account == input.account || (this.account != null && this.account.Equals(input.account)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.account != null) hashCode = hashCode * 59 + this.account.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
31.981982
141
0.530704
[ "MIT" ]
Ganesh-Chavan/adyen-dotnet-api-library
Adyen/Model/MarketPay/GetAccountHolderStatusResponse.cs
3,552
C#