content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using AutoFixture.Xunit2; using FluentAssertions; using Xunit; namespace SkillManagement.Domain.Tests { public class SkillTests { [Theory] [AutoData] public void GivenTitleIsNull_ThrowsArgumentNullException(string anyDescription) { Action action = () => _ = new Skill(null!, anyDescription); action.Should().ThrowExactly<ArgumentNullException>().And.ParamName.Should().Be("title"); } [Theory] [AutoData] public void GivenTitleIsEmpty_ThrowsArgumentNullException(string anyDescription) { Action action = () => _ = new Skill(string.Empty, anyDescription); action.Should().ThrowExactly<ArgumentNullException>().And.ParamName.Should().Be("title"); } [Theory] [AutoData] public void GivenIdIsDefault_ThrowsArgumentNullException(string anyTitle, string anyDescription) { Action action = () => _ = new Skill(Guid.Empty, anyTitle, anyDescription); action.Should().ThrowExactly<ArgumentNullException>().And.ParamName.Should().Be("id"); } [Theory] [AutoData] public void GivenValidTitleAndDescription_NewObjectIsCreatedSuccessfullyWithGeneratedId(string title, string description) { var skill = new Skill(title, description); skill.Id.Should().NotBe(default(Guid)); skill.Title.Should().Be(title); skill.Description.Should().Be(description); } [Theory] [AutoData] public void GivenValidIdAndTitleAndDescription_NewObjectIsCreatedSuccessfully(Guid id, string title, string description) { var skill = new Skill(id, title, description); skill.Id.Should().Be(id); skill.Title.Should().Be(title); skill.Description.Should().Be(description); } [Theory, AutoData] public void GivenTwoSkillObjectsWithSameId_TheyAreConsideredEqual(Guid id, string titleLeft, string descriptionLeft, string titleRight, string descriptionRight) { var left = new Skill(id, titleLeft, descriptionLeft); var right = new Skill(id, titleRight, descriptionRight); left.Equals(right).Should().Be(true); } [Theory, AutoData] public void GivenTwoSkillObjectsWithSameTitle_TheyAreConsideredEqual( string title, string descriptionLeft, string descriptionRight) { var left = new Skill(title, descriptionLeft); var right = new Skill(title, descriptionRight); left.Equals(right).Should().BeTrue(); (left == right).Should().BeTrue(); (left != right).Should().BeFalse(); left.GetHashCode().Should().Be(left.Id.GetHashCode()); } } }
32.626374
109
0.608286
[ "MIT" ]
Code-FC/skill-management-api
test/SkillManagement.Domain.Tests/SkillTests.cs
2,971
C#
using DNTFrameworkCore.Application; namespace DNTFrameworkCore.TestAPI.Application.Identity.Models { public class RoleReadModel : ReadModel<long> { public string Name { get; set; } public string Description { get; set; } } }
25.3
62
0.699605
[ "Apache-2.0" ]
amir-ashy/DNTFrameworkCore
test/DNTFrameworkCore.TestAPI/Application/Identity/Models/RoleReadModel.cs
253
C#
/* * Copyright (c) 2018, FusionAuth, All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ namespace FusionAuth.Domain { public class IntegrationRequest { public Integrations integrations; public IntegrationRequest(Integrations integrations) { this.integrations = integrations; } } }
30.035714
68
0.73365
[ "Apache-2.0" ]
FusionAuth/fusionauth-csharp-client
src/main/csharp/domain/api/IntegrationRequest.cs
843
C#
#if !UNIX // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Microsoft.PackageManagement.PackageSourceListProvider { using System; using System.IO; using System.Net; using System.Threading; using Directory = System.IO.Directory; using File = System.IO.File; using System.Threading.Tasks; using Microsoft.PackageManagement.Provider.Utility; using System.Security.Cryptography; using System.Linq; using ErrorCategory = PackageManagement.Internal.ErrorCategory; public class WebDownloader { /// <summary> /// Download data from remote via uri query. /// </summary> /// <param name="fileName">A file to store the downloaded data.</param> /// <param name="query">Uri query</param> /// <param name="request">An object passed in from the PackageManagement platform that contains APIs that can be used to interact with it </param> /// <param name="networkCredential">Credential to pass along to get httpclient</param> /// <param name="progressTracker">Utility class to help track progress</param> /// <returns></returns> internal static async Task<long> DownloadDataToFileAsync(string fileName, string query, PackageSourceListRequest request, NetworkCredential networkCredential, ProgressTracker progressTracker) { request.Verbose(Resources.Messages.DownloadingPackage, query); // try downloading for 3 times int remainingTry = 3; long totalDownloaded = 0; CancellationTokenSource cts; Stream input = null; FileStream output = null; while (remainingTry > 0) { // if user cancel the request, no need to do anything if (request.IsCanceled) { break; } input = null; output = null; cts = new CancellationTokenSource(); totalDownloaded = 0; try { // decrease try by 1 remainingTry -= 1; var httpClient = request.Client; httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "text/html; charset=iso-8859-1"); input = await httpClient.GetStreamAsync(query); // buffer size of 64 KB, this seems to be preferable buffer size, not too small and not too big byte[] bytes = new byte[1024 * 64]; output = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); int current = 0; // here we read content that we got from the http response stream into the bytes array current = await input.ReadAsync(bytes, 0, bytes.Length, cts.Token); int progressPercentage = progressTracker.StartPercent; // report initial progress request.Progress(progressTracker.ProgressID, progressPercentage, Resources.Messages.BytesRead, current); int i = progressTracker.StartPercent; while (current > 0) { totalDownloaded += current; // here we write out the bytes array into the file await output.WriteAsync(bytes, 0, current, cts.Token); // report the progress request.Progress(progressTracker.ProgressID, progressPercentage<progressTracker.EndPercent?progressPercentage++:progressTracker.EndPercent, Resources.Messages.BytesRead, totalDownloaded); // continue reading from the stream current = await input.ReadAsync(bytes, 0, bytes.Length, cts.Token); } if (totalDownloaded > 0) { // report that we finished the download request.Progress(progressTracker.ProgressID, progressTracker.EndPercent, Resources.Messages.BytesRead, totalDownloaded); request.CompleteProgress(progressTracker.ProgressID, true); return totalDownloaded; } // if request is canceled, don't retry if (request.IsCanceled) { return 0; } } catch (Exception ex) { request.CompleteProgress(progressTracker.ProgressID, true); request.Verbose(ex.Message); request.Debug(ex.StackTrace); } finally { // dispose input and output stream if (input != null) { input.Dispose(); } // dispose it if (output != null) { output.Dispose(); } // delete the file if created and nothing has downloaded if (totalDownloaded == 0 && File.Exists(fileName)) { fileName.TryHardToDelete(); } if (cts != null) { cts.Dispose(); } } // we have to retry again request.Verbose(Resources.Messages.RetryingDownload, query, remainingTry); } return totalDownloaded; } internal static string DownloadFile(string queryUrl, string destination, PackageSourceListRequest request, ProgressTracker progressTracker) { try { request.Debug(Resources.Messages.DebugInfoCallMethod, Constants.ProviderName, string.Format(System.Globalization.CultureInfo.InvariantCulture, "DownloadFile - url='{0}', destination='{1}'", queryUrl, destination)); if (string.IsNullOrWhiteSpace(destination)) { throw new ArgumentNullException("destination"); } // make sure that the parent folder is created first. var folder = Path.GetDirectoryName(destination); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } if (File.Exists(destination)) { destination.TryHardToDelete(); } if (progressTracker == null) { progressTracker = new ProgressTracker(request.StartProgress(0, Resources.Messages.DownloadingPackage, queryUrl)); } Uri uri; if (!Uri.TryCreate(queryUrl, UriKind.Absolute, out uri)) { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.UnsupportedUriFormat, Constants.ProviderName, queryUrl); return null; } if (uri.IsFile) { // downloading from a file share using (var input = File.OpenRead(queryUrl)) { using (var output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.Read)) { request.Progress(progressTracker.ProgressID, progressTracker.StartPercent, Resources.Messages.Downloading); input.CopyTo(output); } } request.CompleteProgress(progressTracker.ProgressID, true); } else { //Downloading from url var result = DownloadDataToFileAsync(destination, queryUrl, request, PathUtility.GetNetworkCredential(request.CredentialUsername, request.CredentialPassword), progressTracker).Result; } if (File.Exists(destination)) { request.Verbose(Resources.Messages.CompletedDownload, queryUrl); return destination; } else { request.Error(Internal.ErrorCategory.InvalidOperation, Resources.Messages.FailedToDownload, Constants.ProviderName, queryUrl, destination); return null; } } catch (Exception ex) { ex.Dump(request); request.Warning(ex.Message); return null; } } internal static bool VerifyHash(string fileFullPath,PackageJson package, PackageSourceListRequest request) { //skip in case the skip switch is specified if (request.SkipHashValidation.Value) { request.Verbose(Resources.Messages.SkipHashValidation); return true; } PackageHash packageHash = package.Hash; if (packageHash==null || string.IsNullOrWhiteSpace(packageHash.algorithm) || string.IsNullOrWhiteSpace(packageHash.hashCode)) { request.WriteError(ErrorCategory.InvalidArgument, Constants.ProviderName, Resources.Messages.HashNotSpecified, package.Name); return false; } try { HashAlgorithm hashAlgorithm = null; switch (packageHash.algorithm.ToLowerInvariant()) { case "sha256": hashAlgorithm = SHA256.Create(); break; case "md5": hashAlgorithm = MD5.Create(); break; case "sha512": hashAlgorithm = SHA512.Create(); break; default: request.WriteError(ErrorCategory.InvalidArgument, Constants.ProviderName, Resources.Messages.InvalidHashAlgorithm, packageHash.algorithm); return false; } using (FileStream stream = File.OpenRead(fileFullPath)) { // compute the hash byte[] computedHash = hashAlgorithm.ComputeHash(stream); // convert the original hash we got from json byte[] hashFromJSON = Convert.FromBase64String(package.Hash.hashCode); if (!Enumerable.SequenceEqual(computedHash, hashFromJSON)) { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.HashVerificationFailed, package.Name, package.Source); return false; } else { request.Verbose(Resources.Messages.HashValidationSuccessful); } } } catch { request.WriteError(ErrorCategory.InvalidOperation, Constants.ProviderName, Resources.Messages.HashVerificationFailed, package.Name, package.Source); return false; } return true; } } } #endif
40.303922
230
0.528825
[ "Apache-2.0", "MIT" ]
adbertram/PowerShell
src/Microsoft.PackageManagement.PackageSourceListProvider/PackageList/WebDownloader.cs
12,335
C#
using Codevos.Net.Caching.Attributes; namespace Codevos.Net.Caching.Tests.Infrastructure { public class CacheableUserService { private readonly CallCounter<CacheableUserService> CallCounter; public CacheableUserService( CallCounter<CacheableUserService> callCounter ) { CallCounter = callCounter; } [Cache] public virtual string GetFullName(int userId) { CallCounter.Increment(); return Constants.FullName; } } }
23.826087
71
0.624088
[ "MIT" ]
codevos/Codevos.Net.Caching
Codevos.Net.Caching.Tests/Infrastructure/CacheableUserService.cs
550
C#
/* * @author Valentin Simonov / http://va.lent.in/ */ using HutongGames.PlayMaker; using TouchScript.Gestures; using UnityEngine; namespace TouchScript.Modules.Playmaker.Actions { [ActionCategory("TouchScript")] [HutongGames.PlayMaker.Tooltip("Sends events when a gesture changes state.")] public class GestureStateChanged : FsmStateAction { [HutongGames.PlayMaker.Tooltip("The GameObject that owns the Gesture.")] public FsmOwnerDefault GameObject; [UIHint(UIHint.Behaviour)] [HutongGames.PlayMaker.Tooltip("The name of the Gesture.")] public FsmString Gesture; [HutongGames.PlayMaker.Tooltip("Optionally drag a component directly into this field (gesture name will be ignored).")] public Component Component; public Gesture.GestureState TargetState = Gestures.Gesture.GestureState.Recognized; public FsmEvent SendEvent; private Gesture gesture; public override void Reset() { TargetState = Gestures.Gesture.GestureState.Recognized; GameObject = null; Gesture = null; Component = null; SendEvent = null; } public override void OnEnter() { gesture = GestureUtils.GetGesture<Gesture>(Fsm, GameObject, Gesture, Component, false); if (gesture == null) { LogError("Gesture is missing"); return; } gesture.StateChanged += gestureStateChangedHandler; } public override void OnExit() { if (gesture == null) return; gesture.StateChanged -= gestureStateChangedHandler; } public override string ErrorCheck() { if (GestureUtils.GetGesture<Gesture>(Fsm, GameObject, Gesture, Component, false) == null) return "Gesture is missing"; return null; } private void gestureStateChangedHandler(object sender, GestureStateChangeEventArgs e) { if (e.State != TargetState) return; if (SendEvent == null) return; Fsm.Event(SendEvent); } } }
30.816901
130
0.617459
[ "MIT" ]
mioboo/TouchScript
UnityPackages/PlayMaker/Assets/TouchScript/Modules/PlayMaker/Actions/GestureStateChanged.cs
2,190
C#
using System.Collections.Generic; using Orchard.ContentManagement; namespace Orchard.Localization.ViewModels { public class EditLocalizationViewModel { public string SelectedCulture { get; set; } public IEnumerable<string> SiteCultures { get; set; } public IContent ContentItem { get; set; } public IContent MasterContentItem { get; set; } public ContentLocalizationsViewModel ContentLocalizations { get; set; } } }
38.833333
79
0.718884
[ "BSD-3-Clause" ]
ArsenShnurkov/OrchardCMS-1.7.3-for-mono
src/Orchard.Web/Modules/Orchard.Localization/ViewModels/EditLocalizationViewModel.cs
468
C#
namespace ClassLib054 { public class Class034 { public static string Property => "ClassLib054"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib054/Class034.cs
120
C#
using System; using System.Collections.Generic; using System.Text; namespace DDD_Aggregates.v1.Domain { public class PurchaseOrderLineItem { public PurchaseOrderLineItem(Product product, double quantity) : this(Guid.NewGuid().ToString(), product, quantity) { } public PurchaseOrderLineItem(string id, Product product, double quantity) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id"); } this.Id = id; this.Product = product; this.UpdateQuantity(quantity); } public string Id { get; } public Product Product { get; } public double Quantity { get; set; } private void EnsureLimit(Product product, double quantity) { var total = product.Price * quantity; if (total > 5000) { throw new Exception("Line item cannot exceep 5000"); } } public void UpdateQuantity(double newQuantity) { this.EnsureLimit(this.Product, newQuantity); this.Quantity = newQuantity; } } }
21.459016
81
0.517189
[ "MIT" ]
milannankov/ddd-aggregates-quickstart
source/DDD-Aggregates.Domain/v1/PurchaseOrderLineItem.cs
1,311
C#
// --------------------------------------------------------------------- // // Copyright (c) 2018-present, Magic Leap, Inc. All Rights Reserved. // Use of this file is governed by the Creator Agreement, located // here: https://id.magicleap.com/terms/developer // // --------------------------------------------------------------------- namespace MagicLeapTools { public interface IDirectManipulation { #if PLATFORM_LUMIN void GrabBegan(InteractionPoint interactionPoint); void GrabUpdate(InteractionPoint interactionPoint); void GrabEnd(InteractionPoint interactionPoint); #endif } }
33.736842
74
0.546022
[ "Apache-2.0" ]
ENDROLL-Gallery/magicleap-unity_0.24.1
Assets/MagicLeap-Tools/Code/Input/Hands/Interfaces/IDirectManipulation.cs
643
C#
using Newtonsoft.Json.Linq; namespace Clarifai.DTOs { /// <summary> /// The geographical location of an input. /// </summary> public class GeoPoint { /// <summary> /// The longitude - X axis. /// </summary> public decimal Longitude { get; } /// <summary> /// The latitude - Y axis. /// </summary> public decimal Latitude { get; } /// <summary> /// Ctor. /// </summary> /// <param name="longitude">the longitude - longitude axis</param> /// <param name="latitude">the latitude - latitude axis</param> public GeoPoint(decimal longitude, decimal latitude) { Latitude = latitude; Longitude = longitude; } /// <summary> /// Returns a new point moved by the new coordinates. /// </summary> /// <param name="longitude">the longitude to translate by</param> /// <param name="latitude">the latitude to translate by</param> /// <returns>a translated geographical point</returns> public GeoPoint Translated(decimal longitude, decimal latitude) { return new GeoPoint(Longitude + longitude, Latitude + latitude); } public JObject Serialize() { return new JObject( new JProperty("longitude", Longitude), new JProperty("latitude", Latitude)); } public static GeoPoint Deserialize(dynamic jsonObject) { dynamic point = jsonObject.geo_point; return new GeoPoint((decimal)point.longitude, (decimal)point.latitude); } public override bool Equals(object obj) { return obj is GeoPoint point && Longitude == point.Longitude && Latitude == point.Latitude; } public override int GetHashCode() { var hashCode = 1861411795; hashCode = hashCode * -1521134295 + Longitude.GetHashCode(); hashCode = hashCode * -1521134295 + Latitude.GetHashCode(); return hashCode; } public override string ToString() { return string.Format("[GeoPoint: (longitude: {0}, latitude: {0})]", Longitude, Latitude); } } }
30.571429
83
0.54503
[ "Apache-2.0" ]
Clarifai/clarifai-csharp
Clarifai/DTOs/GeoPoint.cs
2,356
C#
 using System; using System.Globalization; using Logger.Models.Contracts; using Logger.Models.Enumerations; namespace Logger.Models.Appenders { public class FileAppender : IAppender { public FileAppender(ILayout layout, Level level, IFile file) { this.Layout = layout; this.Level = level; this.File = file; } public ILayout Layout { get; private set; } public Level Level { get; private set; } public IFile File { get; private set; } public long MessagesAppended { get; private set; } public void Append(IError error) { string formattedMessage = this.File.Write(this.Layout, error); System.IO.File.AppendAllText(this.File.Path, formattedMessage); this.MessagesAppended++; } public override string ToString() { return $"Appender type: {this.GetType().Name}, Layout type: {this.Layout.GetType().Name}," + $" Report level: {this.Level.ToString().ToUpper()}, Messages appended: {this.MessagesAppended}, File size: {this.File.Size}"; } } }
28.95
140
0.608808
[ "MIT" ]
DeyanDanailov/SoftUni-OOP
SolidExercise/Logger/Models/Appenders/FileAppender.cs
1,160
C#
using FVI.Funcionarios.API.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FVI.Funcionarios.API.Data.Mappings { public class EnderecoMappings : IEntityTypeConfiguration<Endereco> { public void Configure(EntityTypeBuilder<Endereco> builder) { builder.HasKey(c => c.Id); builder.Property(c => c.Logradouro) .IsRequired() .HasColumnType("varchar(200)"); builder.Property(c => c.Numero) .IsRequired() .HasColumnType("varchar(50)"); builder.Property(c => c.Cep) .IsRequired() .HasColumnType("varchar(20)"); builder.Property(c => c.Complemento) .HasColumnType("varchar(250)"); builder.Property(c => c.Bairro) .IsRequired() .HasColumnType("varchar(100)"); builder.Property(c => c.Cidade) .IsRequired() .HasColumnType("varchar(100)"); builder.Property(c => c.Estado) .IsRequired() .HasColumnType("varchar(50)"); builder.ToTable("Enderecos"); } } }
28.354167
70
0.562087
[ "MIT" ]
Viliane/FaturaVI
src/services/FVI.Funcionarios.API/Data/Mappings/EnderecoMappings.cs
1,363
C#
using DarkUI.Config; using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using DarkUI.Icons; namespace DarkUI.Controls { public class DarkDropdownList : Control { #region Event Region public event EventHandler SelectedItemChanged; #endregion #region Field Region private DarkDropdownItem _selectedItem; private readonly DarkContextMenu _menu = new DarkContextMenu(); private bool _menuOpen; private bool _showBorder = true; private int _itemHeight = 22; private int _maxHeight = 130; private const int IconSize = 16; private ToolStripDropDownDirection _dropdownDirection = ToolStripDropDownDirection.Default; #endregion #region Property Region [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ObservableCollection<DarkDropdownItem> Items { get; } = new ObservableCollection<DarkDropdownItem>(); [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DarkDropdownItem SelectedItem { get { return _selectedItem; } set { _selectedItem = value; SelectedItemChanged?.Invoke(this, new EventArgs()); } } [Category("Appearance")] [Description("Determines whether a border is drawn around the control.")] [DefaultValue(true)] public bool ShowBorder { get { return _showBorder; } set { _showBorder = value; Invalidate(); } } protected override Size DefaultSize { get { return new Size(100, 26); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DarkControlState ControlState { get; private set; } = DarkControlState.Normal; [Category("Appearance")] [Description("Determines the height of the individual list view items.")] [DefaultValue(22)] public int ItemHeight { get { return _itemHeight; } set { _itemHeight = value; ResizeMenu(); } } [Category("Appearance")] [Description("Determines the maximum height of the dropdown panel.")] [DefaultValue(130)] public int MaxHeight { get { return _maxHeight; } set { _maxHeight = value; ResizeMenu(); } } [Category("Behavior")] [Description("Determines what location the dropdown list appears.")] [DefaultValue(ToolStripDropDownDirection.Default)] public ToolStripDropDownDirection DropdownDirection { get { return _dropdownDirection; } set { _dropdownDirection = value; } } #endregion #region Constructor Region public DarkDropdownList() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.Selectable | ControlStyles.UserMouse, true); _menu.AutoSize = false; _menu.Closed += Menu_Closed; Items.CollectionChanged += Items_CollectionChanged; SelectedItemChanged += DarkDropdownList_SelectedItemChanged; SetControlState(DarkControlState.Normal); } #endregion #region Method Region private ToolStripMenuItem GetMenuItem(DarkDropdownItem item) { foreach (ToolStripMenuItem menuItem in _menu.Items) { if ((DarkDropdownItem)menuItem.Tag == item) return menuItem; } return null; } private void SetControlState(DarkControlState controlState) { if (_menuOpen) return; if (ControlState != controlState) { ControlState = controlState; Invalidate(); } } private void ShowMenu() { if (_menu.Visible) return; SetControlState(DarkControlState.Pressed); _menuOpen = true; var pos = new Point(0, ClientRectangle.Bottom); if (_dropdownDirection == ToolStripDropDownDirection.AboveLeft || _dropdownDirection == ToolStripDropDownDirection.AboveRight) pos.Y = 0; _menu.Show(this, pos, _dropdownDirection); if (SelectedItem != null) { var selectedItem = GetMenuItem(SelectedItem); selectedItem.Select(); } } private void ResizeMenu() { var width = ClientRectangle.Width; var height = _menu.Items.Count * _itemHeight + 4; if (height > _maxHeight) height = _maxHeight; // Dirty: Check what the autosized items are foreach (ToolStripMenuItem item in _menu.Items) { item.AutoSize = true; if (item.Size.Width > width) width = item.Size.Width; item.AutoSize = false; } // Force the size foreach (ToolStripMenuItem item in _menu.Items) item.Size = new Size(width - 1, _itemHeight); _menu.Size = new Size(width, height); } #endregion #region Event Handler Region private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (DarkDropdownItem item in e.NewItems) { var menuItem = new ToolStripMenuItem(item.Text) { Image = item.Icon, AutoSize = false, Height = _itemHeight, Font = Font, Tag = item, TextAlign = ContentAlignment.MiddleLeft }; _menu.Items.Add(menuItem); menuItem.Click += Item_Select; if (SelectedItem == null) SelectedItem = item; } break; case NotifyCollectionChangedAction.Remove: foreach (DarkDropdownItem item in e.OldItems) { foreach (ToolStripMenuItem menuItem in _menu.Items) { if ((DarkDropdownItem)menuItem.Tag == item) _menu.Items.Remove(menuItem); } } break; } ResizeMenu(); } private void Item_Select(object sender, EventArgs e) { var menuItem = sender as ToolStripMenuItem; if (menuItem == null) return; var dropdownItem = (DarkDropdownItem)menuItem.Tag; if (_selectedItem != dropdownItem) SelectedItem = dropdownItem; } private void DarkDropdownList_SelectedItemChanged(object sender, EventArgs e) { foreach (ToolStripMenuItem item in _menu.Items) { if ((DarkDropdownItem)item.Tag == SelectedItem) { item.BackColor = Colors.DarkBlueBackground; item.Font = new Font(Font, FontStyle.Bold); } else { item.BackColor = Colors.GreyBackground; item.Font = new Font(Font, FontStyle.Regular); } } Invalidate(); } protected override void OnResize(EventArgs e) { base.OnResize(e); ResizeMenu(); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.Button == MouseButtons.Left) { if (ClientRectangle.Contains(e.Location)) SetControlState(DarkControlState.Pressed); else SetControlState(DarkControlState.Hover); } else { SetControlState(DarkControlState.Hover); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); ShowMenu(); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); SetControlState(DarkControlState.Normal); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); SetControlState(DarkControlState.Normal); } protected override void OnMouseCaptureChanged(EventArgs e) { base.OnMouseCaptureChanged(e); var location = Cursor.Position; if (!ClientRectangle.Contains(location)) SetControlState(DarkControlState.Normal); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); var location = Cursor.Position; if (!ClientRectangle.Contains(location)) SetControlState(DarkControlState.Normal); else SetControlState(DarkControlState.Hover); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.KeyCode == Keys.Space) ShowMenu(); } private void Menu_Closed(object sender, ToolStripDropDownClosedEventArgs e) { _menuOpen = false; if (!ClientRectangle.Contains(MousePosition)) SetControlState(DarkControlState.Normal); else SetControlState(DarkControlState.Hover); } #endregion #region Render Region protected override void OnPaint(PaintEventArgs e) { var g = e.Graphics; // Draw background using (var b = new SolidBrush(Colors.MediumBackground)) { g.FillRectangle(b, ClientRectangle); } // Draw normal state switch (ControlState) { case DarkControlState.Normal: if (ShowBorder) { using (var p = new Pen(Colors.LightBorder, 1)) { var modRect = new Rectangle(ClientRectangle.Left, ClientRectangle.Top, ClientRectangle.Width - 1, ClientRectangle.Height - 1); g.DrawRectangle(p, modRect); } } break; case DarkControlState.Hover: using (var b = new SolidBrush(Colors.DarkBorder)) { g.FillRectangle(b, ClientRectangle); } using (var b = new SolidBrush(Colors.DarkBackground)) { var arrowRect = new Rectangle(ClientRectangle.Right - DropdownIcons.small_arrow.Width - 8, ClientRectangle.Top, DropdownIcons.small_arrow.Width + 8, ClientRectangle.Height); g.FillRectangle(b, arrowRect); } using (var p = new Pen(Colors.BlueSelection, 1)) { var modRect = new Rectangle(ClientRectangle.Left, ClientRectangle.Top, ClientRectangle.Width - 1 - DropdownIcons.small_arrow.Width - 8, ClientRectangle.Height - 1); g.DrawRectangle(p, modRect); } break; case DarkControlState.Pressed: using (var b = new SolidBrush(Colors.DarkBorder)) { g.FillRectangle(b, ClientRectangle); } using (var b = new SolidBrush(Colors.BlueSelection)) { var arrowRect = new Rectangle(ClientRectangle.Right - DropdownIcons.small_arrow.Width - 8, ClientRectangle.Top, DropdownIcons.small_arrow.Width + 8, ClientRectangle.Height); g.FillRectangle(b, arrowRect); } break; } // Draw hover state // Draw pressed state // Draw dropdown arrow using (var img = DropdownIcons.small_arrow) { g.DrawImage(img, ClientRectangle.Right - img.Width - 4, ClientRectangle.Top + ClientRectangle.Height / 2 - img.Height / 2); } // Draw selected item if (SelectedItem == null) return; // Draw Icon var hasIcon = SelectedItem.Icon != null; if (hasIcon) { g.DrawImage(SelectedItem.Icon, new Point(ClientRectangle.Left + 5, ClientRectangle.Top + ClientRectangle.Height / 2 - IconSize / 2)); } // Draw Text using (var b = new SolidBrush(Colors.LightText)) { var stringFormat = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center }; var rect = new Rectangle(ClientRectangle.Left + 2, ClientRectangle.Top, ClientRectangle.Width - 16, ClientRectangle.Height); if (hasIcon) { rect.X += IconSize + 7; rect.Width -= IconSize + 7; } g.DrawString(SelectedItem.Text, Font, b, rect, stringFormat); } } #endregion } }
30.612705
138
0.508133
[ "MIT" ]
ActuallyaDeviloper/DarkUI
DarkUI/Controls/DarkDropdownList.cs
14,941
C#
namespace EShopOnAbp.BasketService.Entities; public class BasketItem { public Guid ProductId { get; private set; } public int Count { get; internal set; } private BasketItem() { } public BasketItem(Guid productId, int count = 1) { ProductId = productId; Count = count; } }
18.5
52
0.612613
[ "MIT" ]
271943794/eShopOnAbp
services/basket/src/EShopOnAbp.BasketService/Entities/BasketItem.cs
335
C#
namespace UtttApi.ObjectModel.Enums { public enum MarkType { EMPTY, PLAYER1, PLAYER2, DRAW } }
24.5
58
0.744898
[ "MIT" ]
Ian-Gilbert/UTTT-SVC
aspnet/UtttApi.ObjectModel/Enums/MarkType.cs
98
C#
#region Apache License Version 2.0 /*---------------------------------------------------------------- Copyright 2019 Suzhou Senparc Network Technology Co.,Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Detail: https://github.com/Senparc/Senparc.CO2NET/blob/master/LICENSE ----------------------------------------------------------------*/ #endregion Apache License Version 2.0 /*---------------------------------------------------------------- Copyright (C) 2020 Senparc 文件名:RedisManager.cs 文件功能描述:Redis连接及数据库管理接口。 创建标识:Senparc - 20160309 修改标识:Senparc - 20150319 修改描述:文件Manager.cs改名为RedisManager.cs(类名没有改动); 使用新的单例做法。 ----------------------------------------------------------------*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using StackExchange.Redis; namespace Senparc.CO2NET.Cache.Redis { /// <summary> /// Redis 链接管理 /// </summary> public class RedisManager { #region ConnectionMultiplexer 单例 /// <summary> /// _redis(ConnectionMultiplexer)单例 /// </summary> internal static ConnectionMultiplexer _redis { get { return NestedRedis.instance;//返回Nested类中的静态成员instance } } class NestedRedis { static NestedRedis() { } //将instance设为一个初始化的ConnectionMultiplexer新实例 internal static readonly ConnectionMultiplexer instance = GetManager(); } #endregion /// <summary> /// 链接设置字符串 /// </summary> public static string ConfigurationOption { get; set; } /// <summary> /// ConnectionMultiplexer /// </summary> public static ConnectionMultiplexer Manager { get { return _redis; } } /// <summary> /// 默认连接字符串 /// </summary> /// <returns></returns> private static string GetDefaultConnectionString() { return "localhost"; } private static ConnectionMultiplexer GetManager(string connectionString = null) { if (string.IsNullOrEmpty(connectionString)) { if (ConfigurationOption == null) { connectionString = GetDefaultConnectionString(); } else { return ConnectionMultiplexer.Connect(ConfigurationOptions.Parse(ConfigurationOption)); } } // var redisConfigInfo = RedisConfigInfo.GetConfig(); // #region options 设置说明 // /* //abortConnect : 当为true时,当没有可用的服务器时则不会创建一个连接 //allowAdmin : 当为true时 ,可以使用一些被认为危险的命令 //channelPrefix:所有pub/sub渠道的前缀 //connectRetry :重试连接的次数 //connectTimeout:超时时间 //configChannel: Broadcast channel name for communicating configuration changes //defaultDatabase : 默认0到-1 //keepAlive : 保存x秒的活动连接 //name:ClientName //password:password //proxy:代理 比如 twemproxy //resolveDns : 指定dns解析 //serviceName : Not currently implemented (intended for use with sentinel) //ssl={bool} : 使用sll加密 //sslHost={string} : 强制服务器使用特定的ssl标识 //syncTimeout={int} : 异步超时时间 //tiebreaker={string}:Key to use for selecting a server in an ambiguous master scenario //version={string} : Redis version level (useful when the server does not make this available) //writeBuffer={int} : 输出缓存区的大小 // */ // #endregion // var options = new ConfigurationOptions() // { // ServiceName = redisConfigInfo.ServerList, // }; return ConnectionMultiplexer.Connect(connectionString); } } }
31.376712
106
0.547915
[ "Apache-2.0" ]
HelloDBA/Senparc.CO2NET
src/Senparc.CO2NET.Cache.Redis/StackExchange.Redis/RedisManager.cs
5,043
C#
using System; using WebAssembly; namespace WebAssembly.Browser.DOM { [Export("HTMLTableCellElement", typeof(JSObject))] public class HTMLTableCellElement : HTMLElement { internal HTMLTableCellElement(JSObject handle) : base(handle) { } //public HTMLTableCellElement() { } [Export("abbr")] public string Abbr { get => GetProperty<string>("abbr"); set => SetProperty<string>("abbr", value); } [Export("align")] public string Align { get => GetProperty<string>("align"); set => SetProperty<string>("align", value); } [Export("axis")] public string Axis { get => GetProperty<string>("axis"); set => SetProperty<string>("axis", value); } [Export("bgColor")] public Object BgColor { get => GetProperty<Object>("bgColor"); set => SetProperty<Object>("bgColor", value); } [Export("cellIndex")] public double CellIndex => GetProperty<double>("cellIndex"); [Export("colSpan")] public double ColSpan { get => GetProperty<double>("colSpan"); set => SetProperty<double>("colSpan", value); } [Export("headers")] public string Headers { get => GetProperty<string>("headers"); set => SetProperty<string>("headers", value); } [Export("height")] public Object Height { get => GetProperty<Object>("height"); set => SetProperty<Object>("height", value); } [Export("noWrap")] public bool NoWrap { get => GetProperty<bool>("noWrap"); set => SetProperty<bool>("noWrap", value); } [Export("rowSpan")] public double RowSpan { get => GetProperty<double>("rowSpan"); set => SetProperty<double>("rowSpan", value); } [Export("scope")] public string Scope { get => GetProperty<string>("scope"); set => SetProperty<string>("scope", value); } [Export("width")] public string Width { get => GetProperty<string>("width"); set => SetProperty<string>("width", value); } [Export("ch")] public string Ch { get => GetProperty<string>("ch"); set => SetProperty<string>("ch", value); } [Export("chOff")] public string ChOff { get => GetProperty<string>("chOff"); set => SetProperty<string>("chOff", value); } [Export("vAlign")] public string VAlign { get => GetProperty<string>("vAlign"); set => SetProperty<string>("vAlign", value); } } }
52.777778
118
0.614316
[ "MIT" ]
kjpou1/wasm-dom
WebAssembly.Browser/DOM/HTMLTableCellElement.cs
2,377
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; namespace Grove.Variables { public delegate void Callback(); public interface IObservable { bool IsChanging(); void Subscribe(Callback callback); void Unsubscribe(Callback callback); } public class Observable : IObservable { private Dictionary<Callback, int> m_Observers; private bool m_IsChanging; public bool HasObservers() { return m_Observers != null; } public bool IsChanging() { return m_IsChanging; } public void Change() { Assert.IsFalse(m_IsChanging, "Loop detected"); if (m_Observers != null) { m_IsChanging = true; foreach (var callback in m_Observers.Keys) { try { callback(); } catch (Exception e) { Debug.LogException(e); } } m_IsChanging = false; } } public void Subscribe(Callback callback) { Assert.IsFalse(m_IsChanging, "Cannot Subscribe while Observable is changing"); if (m_Observers == null) { m_Observers = new Dictionary<Callback, int>() { { callback, 1 }, }; } else if (m_Observers.TryGetValue(callback, out var count)) { m_Observers[callback] = count + 1; } else { m_Observers.Add(callback, 1); } } public void Unsubscribe(Callback callback) { Assert.IsFalse(m_IsChanging, "Cannot Unsubscribe while Observable is changing"); int count = m_Observers[callback]; if (count > 1) { m_Observers[callback] = count - 1; } else { m_Observers.Remove(callback); if (m_Observers.Count == 0) { m_Observers = null; } } } } }
17.298969
83
0.640644
[ "MIT" ]
edohe/grove
Assets/Grove/Runtime/Common/Observable.cs
1,680
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace ExceptionMiddleware.Extensions; public class NotImplementedObjectResult : ObjectResult { public NotImplementedObjectResult(object value) : base(value) { this.StatusCode = StatusCodes.Status501NotImplemented; } }
23.769231
65
0.783172
[ "MIT" ]
LarsBehl/exceptionMiddleware
Extensions/NotImplementedObjectResult.cs
309
C#
using System; using System.Collections.Generic; using System.Text; namespace LionFire.Assets { public static class HAssetExtensions { public static HAsset<AssetType> ToHAsset<AssetType>(this string assetTypePath) where AssetType : class => new HAsset<AssetType>(assetTypePath); } }
23.428571
86
0.695122
[ "MIT" ]
LionFire/Core
src/LionFire.Assets.Old/Handles/HAssetExtensions.cs
330
C#
using System; using System.Collections; using System.Collections.Generic; namespace Metaheuristics { public abstract class DiscreteMA { public int PopulationSize { get; protected set; } public int[] LowerBounds { get; protected set; } public int[] UpperBounds { get; protected set; } public bool RepairEnabled { get; protected set; } public bool LocalSearchEnabled { get; protected set; } public double MutationProbability { get; protected set; } public int[] BestIndividual { get; protected set; } public double BestFitness { get; protected set; } public DiscreteMA (int popSize, double mutationProbability, int[] lowerBounds, int[] upperBounds) { PopulationSize = popSize + (popSize % 2); LowerBounds = lowerBounds; UpperBounds = upperBounds; RepairEnabled = false; LocalSearchEnabled = false; BestIndividual = null; BestFitness = 0; MutationProbability = mutationProbability; } // Evaluate an individual of the population. protected abstract double Fitness(int[] individual); // Generate the initial solution. protected abstract int[] InitialSolution(); // Generate the initial meme. protected bool[] InitialMeme() { bool[] meme = new bool[LowerBounds.Length]; int points = Statistics.RandomDiscreteUniform(LowerBounds.Length / 3, (2*LowerBounds.Length) / 3); for (int i = 0; i < points; i++) { meme[Statistics.RandomDiscreteUniform(0, LowerBounds.Length-1)] = true; } return meme; } // Repairing method to handle constraints. protected virtual void Repair(int[] individual) { } // Local search method. protected virtual void LocalSearch(int[] individual) { } public void Run(int timeLimit) { int startTime = Environment.TickCount; int iterationStartTime = 0; int iterationTime = 0; int maxIterationTime = 0; int numVariables = LowerBounds.Length; KeyValuePair<int[], bool[]>[] population = new KeyValuePair<int[], bool[]>[PopulationSize]; double[] evaluation = new double[PopulationSize]; int parent1 = 0; int parent2 = 0; KeyValuePair<int[], bool[]> descend = new KeyValuePair<int[], bool[]>(null,null); KeyValuePair<int[], bool[]>[] iterationPopulation = new KeyValuePair<int[], bool[]>[PopulationSize]; double[] iterationEvaluation = new double[PopulationSize]; KeyValuePair<int[], bool[]>[] newPopulation = null; double[] newEvaluation = null; // Generate the initial random population. for (int k = 0; k < PopulationSize; k++) { population[k] = new KeyValuePair<int[], bool[]>(InitialSolution(),InitialMeme()); } // Run a local search method for each individual in the population. if (LocalSearchEnabled) { for (int k = 0; k < PopulationSize; k++) { LocalSearch(population[k].Key); } } // Evaluate the population. for (int k = 0; k < PopulationSize; k++) { evaluation[k] = Fitness(population[k].Key); } Array.Sort(evaluation, population); BestIndividual = population[0].Key; BestFitness = evaluation[0]; maxIterationTime = Environment.TickCount - startTime; while (Environment.TickCount - startTime < timeLimit - maxIterationTime) { iterationStartTime = Environment.TickCount; newPopulation = new KeyValuePair<int[], bool[]>[PopulationSize]; newEvaluation = new double[PopulationSize]; // Apply the selection method. if (BestIndividual == null || evaluation[0] < BestFitness) { BestIndividual = population[0].Key; BestFitness = evaluation[0]; } // Mutation points. int mut1stPoint = Statistics.RandomDiscreteUniform(0, numVariables - 1); int mut2ndPoint = Statistics.RandomDiscreteUniform(0, numVariables - 1); for (int i = 0; i < PopulationSize; i++) { // Selection (four individual tournament). parent1 = Math.Min(Math.Min(Statistics.RandomDiscreteUniform(0,PopulationSize-1), Statistics.RandomDiscreteUniform(0,PopulationSize-1)), Math.Min(Statistics.RandomDiscreteUniform(0,PopulationSize-1), Statistics.RandomDiscreteUniform(0,PopulationSize-1))); parent2 = Math.Min(Math.Min(Statistics.RandomDiscreteUniform(0,PopulationSize-1), Statistics.RandomDiscreteUniform(0,PopulationSize-1)), Math.Min(Statistics.RandomDiscreteUniform(0,PopulationSize-1), Statistics.RandomDiscreteUniform(0,PopulationSize-1))); if (parent1 > parent2) { int tmp = parent1; parent1 = parent2; parent2 = tmp; } // Crossover with the meme of the best parent. descend = new KeyValuePair<int[], bool[]>(new int[numVariables], population[parent1].Value); for (int j = 0; j < numVariables; j++) { if (descend.Value[j]) { descend.Key[j] = population[parent1].Key[j]; } else { descend.Key[j] = population[parent1].Key[j]; } } // Mutation. if (Statistics.RandomUniform() < MutationProbability) { descend.Key[mut1stPoint] = Statistics.RandomDiscreteUniform(LowerBounds[mut1stPoint], UpperBounds[mut1stPoint]); descend.Key[mut2ndPoint] = Statistics.RandomDiscreteUniform(LowerBounds[mut2ndPoint], UpperBounds[mut2ndPoint]); } iterationPopulation[i] = descend; } // Handle constraints using a repairing method. if (RepairEnabled) { for (int k = 0; k < PopulationSize; k++) { Repair(iterationPopulation[k].Key); } } // Run a local search method for each individual in the population. if (LocalSearchEnabled && Environment.TickCount - startTime < timeLimit) { for (int k = 0; k < PopulationSize; k++) { LocalSearch(iterationPopulation[k].Key); } } // Evaluate the population. for (int k = 0; k < PopulationSize; k++) { iterationEvaluation[k] = Fitness(iterationPopulation[k].Key); } Array.Sort(iterationEvaluation, iterationPopulation); // Merge the new populations. int iterationIndex = 0; int existingIndex = 0; for (int k = 0; k < PopulationSize; k++) { if (evaluation[existingIndex] < iterationEvaluation[iterationIndex]) { newPopulation[k] = population[existingIndex]; newEvaluation[k] = evaluation[existingIndex]; existingIndex++; } else { newPopulation[k] = iterationPopulation[iterationIndex]; newEvaluation[k] = iterationEvaluation[iterationIndex]; iterationIndex++; } } population = newPopulation; evaluation = newEvaluation; iterationTime = Environment.TickCount - iterationStartTime; maxIterationTime = (maxIterationTime < iterationTime) ? iterationTime : maxIterationTime; } } } }
35.615385
127
0.651692
[ "MIT" ]
yasserglez/metaheuristics
Common/DiscreteMA.cs
6,945
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under MIT X11 license (for details please see \doc\license.txt) using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using ICSharpCode.NRefactory.PatternMatching; using ICSharpCode.NRefactory.VB.Ast; namespace ICSharpCode.NRefactory.VB { /// <summary> /// Description of OutputVisitor. /// </summary> public class OutputVisitor : IAstVisitor<object, object> { readonly IOutputFormatter formatter; readonly VBFormattingOptions policy; readonly Stack<AstNode> containerStack = new Stack<AstNode>(); readonly Stack<AstNode> positionStack = new Stack<AstNode>(); /// <summary> /// Used to insert the minimal amount of spaces so that the lexer recognizes the tokens that were written. /// </summary> LastWritten lastWritten; enum LastWritten { Whitespace, Other, KeywordOrIdentifier } public OutputVisitor(TextWriter textWriter, VBFormattingOptions formattingPolicy) { if (textWriter == null) throw new ArgumentNullException("textWriter"); if (formattingPolicy == null) throw new ArgumentNullException("formattingPolicy"); this.formatter = new TextWriterOutputFormatter(textWriter); this.policy = formattingPolicy; } public OutputVisitor(IOutputFormatter formatter, VBFormattingOptions formattingPolicy) { if (formatter == null) throw new ArgumentNullException("formatter"); if (formattingPolicy == null) throw new ArgumentNullException("formattingPolicy"); this.formatter = formatter; this.policy = formattingPolicy; } public object VisitCompilationUnit(CompilationUnit compilationUnit, object data) { // don't do node tracking as we visit all children directly foreach (AstNode node in compilationUnit.Children) node.AcceptVisitor(this, data); return null; } public object VisitBlockStatement(BlockStatement blockStatement, object data) { // prepare new block NewLine(); Indent(); StartNode(blockStatement); foreach (var stmt in blockStatement) { stmt.AcceptVisitor(this, data); NewLine(); } // finish block Unindent(); return EndNode(blockStatement); } public object VisitPatternPlaceholder(AstNode placeholder, Pattern pattern, object data) { throw new NotImplementedException(); } public object VisitTypeParameterDeclaration(TypeParameterDeclaration typeParameterDeclaration, object data) { StartNode(typeParameterDeclaration); switch (typeParameterDeclaration.Variance) { case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Invariant: break; case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Covariant: WriteKeyword("Out"); break; case ICSharpCode.NRefactory.TypeSystem.VarianceModifier.Contravariant: WriteKeyword("In"); break; default: throw new Exception("Invalid value for VarianceModifier"); } WriteIdentifier(typeParameterDeclaration.Name); if (typeParameterDeclaration.Constraints.Any()) { WriteKeyword("As"); if (typeParameterDeclaration.Constraints.Count > 1) WriteToken("{", TypeParameterDeclaration.Roles.LBrace); WriteCommaSeparatedList(typeParameterDeclaration.Constraints); if (typeParameterDeclaration.Constraints.Count > 1) WriteToken("}", TypeParameterDeclaration.Roles.RBrace); } return EndNode(typeParameterDeclaration); } public object VisitParameterDeclaration(ParameterDeclaration parameterDeclaration, object data) { StartNode(parameterDeclaration); WriteAttributes(parameterDeclaration.Attributes); WriteModifiers(parameterDeclaration.ModifierTokens); WriteIdentifier(parameterDeclaration.Name.Name); if (!parameterDeclaration.Type.IsNull) { WriteKeyword("As"); parameterDeclaration.Type.AcceptVisitor(this, data); } if (!parameterDeclaration.OptionalValue.IsNull) { WriteToken("=", ParameterDeclaration.Roles.Assign); parameterDeclaration.OptionalValue.AcceptVisitor(this, data); } return EndNode(parameterDeclaration); } public object VisitVBTokenNode(VBTokenNode vBTokenNode, object data) { var mod = vBTokenNode as VBModifierToken; if (mod != null) { StartNode(vBTokenNode); WriteKeyword(VBModifierToken.GetModifierName(mod.Modifier)); return EndNode(vBTokenNode); } else { throw new NotSupportedException("Should never visit individual tokens"); } } public object VisitAliasImportsClause(AliasImportsClause aliasImportsClause, object data) { throw new NotImplementedException(); } public object VisitAttribute(ICSharpCode.NRefactory.VB.Ast.Attribute attribute, object data) { StartNode(attribute); if (attribute.Target != AttributeTarget.None) { switch (attribute.Target) { case AttributeTarget.None: break; case AttributeTarget.Assembly: WriteKeyword("Assembly"); break; case AttributeTarget.Module: WriteKeyword("Module"); break; default: throw new Exception("Invalid value for AttributeTarget"); } WriteToken(":", Ast.Attribute.Roles.Colon); Space(); } attribute.Type.AcceptVisitor(this, data); WriteCommaSeparatedListInParenthesis(attribute.Arguments, false); return EndNode(attribute); } public object VisitAttributeBlock(AttributeBlock attributeBlock, object data) { StartNode(attributeBlock); WriteToken("<", AttributeBlock.Roles.LChevron); WriteCommaSeparatedList(attributeBlock.Attributes); WriteToken(">", AttributeBlock.Roles.RChevron); if (attributeBlock.Parent is ParameterDeclaration) Space(); else NewLine(); return EndNode(attributeBlock); } public object VisitImportsStatement(ImportsStatement importsStatement, object data) { StartNode(importsStatement); WriteKeyword("Imports", AstNode.Roles.Keyword); Space(); WriteCommaSeparatedList(importsStatement.ImportsClauses); NewLine(); return EndNode(importsStatement); } public object VisitMemberImportsClause(MemberImportsClause memberImportsClause, object data) { StartNode(memberImportsClause); memberImportsClause.Member.AcceptVisitor(this, data); return EndNode(memberImportsClause); } public object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data) { StartNode(namespaceDeclaration); NewLine(); WriteKeyword("Namespace"); bool isFirst = true; foreach (Identifier node in namespaceDeclaration.Identifiers) { if (isFirst) { isFirst = false; } else { WriteToken(".", NamespaceDeclaration.Roles.Dot); } node.AcceptVisitor(this, null); } NewLine(); WriteMembers(namespaceDeclaration.Members); WriteKeyword("End"); WriteKeyword("Namespace"); NewLine(); return EndNode(namespaceDeclaration); } public object VisitOptionStatement(OptionStatement optionStatement, object data) { throw new NotImplementedException(); } public object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) { StartNode(typeDeclaration); WriteAttributes(typeDeclaration.Attributes); WriteModifiers(typeDeclaration.ModifierTokens); WriteClassTypeKeyword(typeDeclaration); WriteIdentifier(typeDeclaration.Name.Name); WriteTypeParameters(typeDeclaration.TypeParameters); MarkFoldStart(); NewLine(); if (!typeDeclaration.InheritsType.IsNull) { Indent(); WriteKeyword("Inherits"); typeDeclaration.InheritsType.AcceptVisitor(this, data); Unindent(); NewLine(); } if (typeDeclaration.ImplementsTypes.Any()) { Indent(); WriteImplementsClause(typeDeclaration.ImplementsTypes); Unindent(); NewLine(); } if (!typeDeclaration.InheritsType.IsNull || typeDeclaration.ImplementsTypes.Any()) NewLine(); WriteMembers(typeDeclaration.Members); WriteKeyword("End"); WriteClassTypeKeyword(typeDeclaration); MarkFoldEnd(); NewLine(); return EndNode(typeDeclaration); } void WriteClassTypeKeyword(TypeDeclaration typeDeclaration) { switch (typeDeclaration.ClassType) { case ClassType.Class: WriteKeyword("Class"); break; case ClassType.Interface: WriteKeyword("Interface"); break; case ClassType.Struct: WriteKeyword("Structure"); break; case ClassType.Module: WriteKeyword("Module"); break; default: throw new Exception("Invalid value for ClassType"); } } public object VisitXmlNamespaceImportsClause(XmlNamespaceImportsClause xmlNamespaceImportsClause, object data) { throw new NotImplementedException(); } public object VisitEnumDeclaration(EnumDeclaration enumDeclaration, object data) { StartNode(enumDeclaration); WriteAttributes(enumDeclaration.Attributes); WriteModifiers(enumDeclaration.ModifierTokens); WriteKeyword("Enum"); WriteIdentifier(enumDeclaration.Name.Name); if (!enumDeclaration.UnderlyingType.IsNull) { Space(); WriteKeyword("As"); enumDeclaration.UnderlyingType.AcceptVisitor(this, data); } MarkFoldStart(); NewLine(); Indent(); foreach (var member in enumDeclaration.Members) { member.AcceptVisitor(this, null); } Unindent(); WriteKeyword("End"); WriteKeyword("Enum"); MarkFoldEnd(); NewLine(); return EndNode(enumDeclaration); } public object VisitEnumMemberDeclaration(EnumMemberDeclaration enumMemberDeclaration, object data) { StartNode(enumMemberDeclaration); WriteAttributes(enumMemberDeclaration.Attributes); WriteIdentifier(enumMemberDeclaration.Name.Name); if (!enumMemberDeclaration.Value.IsNull) { Space(); WriteToken("=", EnumMemberDeclaration.Roles.Assign); Space(); enumMemberDeclaration.Value.AcceptVisitor(this, data); } NewLine(); return EndNode(enumMemberDeclaration); } public object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) { StartNode(delegateDeclaration); WriteAttributes(delegateDeclaration.Attributes); WriteModifiers(delegateDeclaration.ModifierTokens); WriteKeyword("Delegate"); if (delegateDeclaration.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); WriteIdentifier(delegateDeclaration.Name.Name); WriteTypeParameters(delegateDeclaration.TypeParameters); WriteCommaSeparatedListInParenthesis(delegateDeclaration.Parameters, false); if (!delegateDeclaration.IsSub) { Space(); WriteKeyword("As"); WriteAttributes(delegateDeclaration.ReturnTypeAttributes); delegateDeclaration.ReturnType.AcceptVisitor(this, data); } NewLine(); return EndNode(delegateDeclaration); } public object VisitIdentifier(Identifier identifier, object data) { StartNode(identifier); WriteIdentifier(identifier.Name); WriteTypeCharacter(identifier.TypeCharacter); return EndNode(identifier); } public object VisitXmlIdentifier(XmlIdentifier xmlIdentifier, object data) { throw new NotImplementedException(); } public object VisitXmlLiteralString(XmlLiteralString xmlLiteralString, object data) { throw new NotImplementedException(); } public object VisitSimpleNameExpression(SimpleNameExpression simpleNameExpression, object data) { StartNode(simpleNameExpression); simpleNameExpression.Identifier.AcceptVisitor(this, data); WriteTypeArguments(simpleNameExpression.TypeArguments); return EndNode(simpleNameExpression); } public object VisitPrimitiveExpression(PrimitiveExpression primitiveExpression, object data) { StartNode(primitiveExpression); if (lastWritten == LastWritten.KeywordOrIdentifier) Space(); WritePrimitiveValue(primitiveExpression.Value); return EndNode(primitiveExpression); } public object VisitInstanceExpression(InstanceExpression instanceExpression, object data) { StartNode(instanceExpression); switch (instanceExpression.Type) { case InstanceExpressionType.Me: WriteKeyword("Me"); break; case InstanceExpressionType.MyBase: WriteKeyword("MyBase"); break; case InstanceExpressionType.MyClass: WriteKeyword("MyClass"); break; default: throw new Exception("Invalid value for InstanceExpressionType"); } return EndNode(instanceExpression); } public object VisitParenthesizedExpression(ParenthesizedExpression parenthesizedExpression, object data) { StartNode(parenthesizedExpression); LPar(); parenthesizedExpression.Expression.AcceptVisitor(this, data); RPar(); return EndNode(parenthesizedExpression); } public object VisitGetTypeExpression(GetTypeExpression getTypeExpression, object data) { StartNode(getTypeExpression); WriteKeyword("GetType"); LPar(); getTypeExpression.Type.AcceptVisitor(this, data); RPar(); return EndNode(getTypeExpression); } public object VisitTypeOfIsExpression(TypeOfIsExpression typeOfIsExpression, object data) { StartNode(typeOfIsExpression); WriteKeyword("TypeOf"); typeOfIsExpression.TypeOfExpression.AcceptVisitor(this, data); WriteKeyword("Is"); typeOfIsExpression.Type.AcceptVisitor(this, data); return EndNode(typeOfIsExpression); } public object VisitGetXmlNamespaceExpression(GetXmlNamespaceExpression getXmlNamespaceExpression, object data) { throw new NotImplementedException(); } public object VisitMemberAccessExpression(MemberAccessExpression memberAccessExpression, object data) { StartNode(memberAccessExpression); memberAccessExpression.Target.AcceptVisitor(this, data); WriteToken(".", MemberAccessExpression.Roles.Dot); memberAccessExpression.MemberName.AcceptVisitor(this, data); WriteTypeArguments(memberAccessExpression.TypeArguments); return EndNode(memberAccessExpression); } public object VisitTypeReferenceExpression(TypeReferenceExpression typeReferenceExpression, object data) { StartNode(typeReferenceExpression); typeReferenceExpression.Type.AcceptVisitor(this, data); return EndNode(typeReferenceExpression); } public object VisitEventMemberSpecifier(EventMemberSpecifier eventMemberSpecifier, object data) { StartNode(eventMemberSpecifier); eventMemberSpecifier.Target.AcceptVisitor(this, data); WriteToken(".", EventMemberSpecifier.Roles.Dot); eventMemberSpecifier.Member.AcceptVisitor(this, data); return EndNode(eventMemberSpecifier); } public object VisitInterfaceMemberSpecifier(InterfaceMemberSpecifier interfaceMemberSpecifier, object data) { StartNode(interfaceMemberSpecifier); interfaceMemberSpecifier.Target.AcceptVisitor(this, data); WriteToken(".", EventMemberSpecifier.Roles.Dot); interfaceMemberSpecifier.Member.AcceptVisitor(this, data); return EndNode(interfaceMemberSpecifier); } #region TypeMembers public object VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration, object data) { StartNode(constructorDeclaration); WriteAttributes(constructorDeclaration.Attributes); WriteModifiers(constructorDeclaration.ModifierTokens); WriteKeyword("Sub"); WriteKeyword("New"); WriteCommaSeparatedListInParenthesis(constructorDeclaration.Parameters, false); MarkFoldStart(); WriteBlock(constructorDeclaration.Body); WriteKeyword("End"); WriteKeyword("Sub"); MarkFoldEnd(); NewLine(); return EndNode(constructorDeclaration); } public object VisitMethodDeclaration(MethodDeclaration methodDeclaration, object data) { StartNode(methodDeclaration); WriteAttributes(methodDeclaration.Attributes); WriteModifiers(methodDeclaration.ModifierTokens); if (methodDeclaration.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); methodDeclaration.Name.AcceptVisitor(this, data); WriteTypeParameters(methodDeclaration.TypeParameters); WriteCommaSeparatedListInParenthesis(methodDeclaration.Parameters, false); if (!methodDeclaration.IsSub && !methodDeclaration.ReturnType.IsNull) { Space(); WriteKeyword("As"); WriteAttributes(methodDeclaration.ReturnTypeAttributes); methodDeclaration.ReturnType.AcceptVisitor(this, data); } WriteHandlesClause(methodDeclaration.HandlesClause); WriteImplementsClause(methodDeclaration.ImplementsClause); if (!methodDeclaration.Body.IsNull) { MarkFoldStart(); WriteBlock(methodDeclaration.Body); WriteKeyword("End"); if (methodDeclaration.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); MarkFoldEnd(); } NewLine(); return EndNode(methodDeclaration); } public object VisitFieldDeclaration(FieldDeclaration fieldDeclaration, object data) { StartNode(fieldDeclaration); WriteAttributes(fieldDeclaration.Attributes); WriteModifiers(fieldDeclaration.ModifierTokens); WriteCommaSeparatedList(fieldDeclaration.Variables); NewLine(); return EndNode(fieldDeclaration); } public object VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration, object data) { StartNode(propertyDeclaration); WriteAttributes(propertyDeclaration.Attributes); WriteModifiers(propertyDeclaration.ModifierTokens); WriteKeyword("Property"); WriteIdentifier(propertyDeclaration.Name.Name); WriteCommaSeparatedListInParenthesis(propertyDeclaration.Parameters, false); if (!propertyDeclaration.ReturnType.IsNull) { Space(); WriteKeyword("As"); WriteAttributes(propertyDeclaration.ReturnTypeAttributes); propertyDeclaration.ReturnType.AcceptVisitor(this, data); } bool needsBody = !propertyDeclaration.Getter.Body.IsNull || !propertyDeclaration.Setter.Body.IsNull; if (needsBody) { MarkFoldStart(); NewLine(); Indent(); if (!propertyDeclaration.Getter.Body.IsNull) { propertyDeclaration.Getter.AcceptVisitor(this, data); } if (!propertyDeclaration.Setter.Body.IsNull) { propertyDeclaration.Setter.AcceptVisitor(this, data); } Unindent(); WriteKeyword("End"); WriteKeyword("Property"); MarkFoldEnd(); } NewLine(); return EndNode(propertyDeclaration); } #endregion #region TypeName public object VisitPrimitiveType(PrimitiveType primitiveType, object data) { StartNode(primitiveType); WriteKeyword(primitiveType.Keyword); return EndNode(primitiveType); } public object VisitQualifiedType(QualifiedType qualifiedType, object data) { StartNode(qualifiedType); qualifiedType.Target.AcceptVisitor(this, data); WriteToken(".", AstNode.Roles.Dot); WriteIdentifier(qualifiedType.Name); WriteTypeArguments(qualifiedType.TypeArguments); return EndNode(qualifiedType); } public object VisitComposedType(ComposedType composedType, object data) { StartNode(composedType); composedType.BaseType.AcceptVisitor(this, data); if (composedType.HasNullableSpecifier) WriteToken("?", ComposedType.Roles.QuestionMark); WriteArraySpecifiers(composedType.ArraySpecifiers); return EndNode(composedType); } public object VisitArraySpecifier(ArraySpecifier arraySpecifier, object data) { StartNode(arraySpecifier); LPar(); for (int i = 0; i < arraySpecifier.Dimensions - 1; i++) { WriteToken(",", ArraySpecifier.Roles.Comma); } RPar(); return EndNode(arraySpecifier); } public object VisitSimpleType(SimpleType simpleType, object data) { StartNode(simpleType); WriteIdentifier(simpleType.Identifier); WriteTypeArguments(simpleType.TypeArguments); return EndNode(simpleType); } #endregion #region StartNode/EndNode void StartNode(AstNode node) { // Ensure that nodes are visited in the proper nested order. // Jumps to different subtrees are allowed only for the child of a placeholder node. Debug.Assert(containerStack.Count == 0 || node.Parent == containerStack.Peek()); if (positionStack.Count > 0) WriteSpecialsUpToNode(node); containerStack.Push(node); positionStack.Push(node.FirstChild); formatter.StartNode(node); } object EndNode(AstNode node) { Debug.Assert(node == containerStack.Peek()); AstNode pos = positionStack.Pop(); Debug.Assert(pos == null || pos.Parent == node); WriteSpecials(pos, null); containerStack.Pop(); formatter.EndNode(node); return null; } #endregion #region WriteSpecials /// <summary> /// Writes all specials from start to end (exclusive). Does not touch the positionStack. /// </summary> void WriteSpecials(AstNode start, AstNode end) { for (AstNode pos = start; pos != end; pos = pos.NextSibling) { if (pos.Role == AstNode.Roles.Comment) { pos.AcceptVisitor(this, null); } } } /// <summary> /// Writes all specials between the current position (in the positionStack) and the next /// node with the specified role. Advances the current position. /// </summary> void WriteSpecialsUpToRole(Role role) { for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) { if (pos.Role == role) { WriteSpecials(positionStack.Pop(), pos); positionStack.Push(pos); break; } } } /// <summary> /// Writes all specials between the current position (in the positionStack) and the specified node. /// Advances the current position. /// </summary> void WriteSpecialsUpToNode(AstNode node) { for (AstNode pos = positionStack.Peek(); pos != null; pos = pos.NextSibling) { if (pos == node) { WriteSpecials(positionStack.Pop(), pos); positionStack.Push(pos); break; } } } void WriteSpecialsUpToRole(Role role, AstNode nextNode) { // Look for the role between the current position and the nextNode. for (AstNode pos = positionStack.Peek(); pos != null && pos != nextNode; pos = pos.NextSibling) { if (pos.Role == AstNode.Roles.Comma) { WriteSpecials(positionStack.Pop(), pos); positionStack.Push(pos); break; } } } #endregion #region Comma /// <summary> /// Writes a comma. /// </summary> /// <param name="nextNode">The next node after the comma.</param> /// <param name="noSpacesAfterComma">When set prevents printing a space after comma.</param> void Comma(AstNode nextNode, bool noSpaceAfterComma = false) { WriteSpecialsUpToRole(AstNode.Roles.Comma, nextNode); formatter.WriteToken(","); lastWritten = LastWritten.Other; Space(!noSpaceAfterComma); // TODO: Comma policy has changed. } void WriteCommaSeparatedList(IEnumerable<AstNode> list) { bool isFirst = true; foreach (AstNode node in list) { if (isFirst) { isFirst = false; } else { Comma(node); } node.AcceptVisitor(this, null); } } void WriteCommaSeparatedListInParenthesis(IEnumerable<AstNode> list, bool spaceWithin) { LPar(); if (list.Any()) { Space(spaceWithin); WriteCommaSeparatedList(list); Space(spaceWithin); } RPar(); } #if DOTNET35 void WriteCommaSeparatedList(IEnumerable<VariableInitializer> list) { WriteCommaSeparatedList(list); } void WriteCommaSeparatedList(IEnumerable<AstType> list) { WriteCommaSeparatedList(list); } void WriteCommaSeparatedListInParenthesis(IEnumerable<Expression> list, bool spaceWithin) { WriteCommaSeparatedListInParenthesis(list.SafeCast<Expression, AstNode>(), spaceWithin); } void WriteCommaSeparatedListInParenthesis(IEnumerable<ParameterDeclaration> list, bool spaceWithin) { WriteCommaSeparatedListInParenthesis(list.SafeCast<ParameterDeclaration, AstNode>(), spaceWithin); } #endif void WriteCommaSeparatedListInBrackets(IEnumerable<ParameterDeclaration> list, bool spaceWithin) { WriteToken("[", AstNode.Roles.LBracket); if (list.Any()) { Space(spaceWithin); WriteCommaSeparatedList(list); Space(spaceWithin); } WriteToken("]", AstNode.Roles.RBracket); } #endregion #region Write tokens /// <summary> /// Writes a keyword, and all specials up to /// </summary> void WriteKeyword(string keyword, Role<VBTokenNode> tokenRole = null) { WriteSpecialsUpToRole(tokenRole ?? AstNode.Roles.Keyword); if (lastWritten == LastWritten.KeywordOrIdentifier) formatter.Space(); formatter.WriteKeyword(keyword); lastWritten = LastWritten.KeywordOrIdentifier; } void WriteIdentifier(string identifier, Role<Identifier> identifierRole = null) { WriteSpecialsUpToRole(identifierRole ?? AstNode.Roles.Identifier); if (lastWritten == LastWritten.KeywordOrIdentifier) Space(); // this space is not strictly required, so we call Space() if (IsKeyword(identifier, containerStack.Peek())) formatter.WriteToken("["); formatter.WriteIdentifier(identifier); if (IsKeyword(identifier, containerStack.Peek())) formatter.WriteToken("]"); lastWritten = LastWritten.KeywordOrIdentifier; } void WriteToken(string token, Role<VBTokenNode> tokenRole) { WriteSpecialsUpToRole(tokenRole); // Avoid that two +, - or ? tokens are combined into a ++, -- or ?? token. // Note that we don't need to handle tokens like = because there's no valid // C# program that contains the single token twice in a row. // (for +, - and &, this can happen with unary operators; // for ?, this can happen in "a is int? ? b : c" or "a as int? ?? 0"; // and for /, this can happen with "1/ *ptr" or "1/ //comment".) // if (lastWritten == LastWritten.Plus && token[0] == '+' // || lastWritten == LastWritten.Minus && token[0] == '-' // || lastWritten == LastWritten.Ampersand && token[0] == '&' // || lastWritten == LastWritten.QuestionMark && token[0] == '?' // || lastWritten == LastWritten.Division && token[0] == '*') // { // formatter.Space(); // } formatter.WriteToken(token); // if (token == "+") // lastWritten = LastWritten.Plus; // else if (token == "-") // lastWritten = LastWritten.Minus; // else if (token == "&") // lastWritten = LastWritten.Ampersand; // else if (token == "?") // lastWritten = LastWritten.QuestionMark; // else if (token == "/") // lastWritten = LastWritten.Division; // else lastWritten = LastWritten.Other; } void WriteTypeCharacter(TypeCode typeCharacter) { switch (typeCharacter) { case TypeCode.Empty: case TypeCode.Object: case TypeCode.DBNull: case TypeCode.Boolean: case TypeCode.Char: break; case TypeCode.SByte: break; case TypeCode.Byte: break; case TypeCode.Int16: break; case TypeCode.UInt16: break; case TypeCode.Int32: WriteToken("%", null); break; case TypeCode.UInt32: break; case TypeCode.Int64: WriteToken("&", null); break; case TypeCode.UInt64: break; case TypeCode.Single: WriteToken("!", null); break; case TypeCode.Double: WriteToken("#", null); break; case TypeCode.Decimal: WriteToken("@", null); break; case TypeCode.DateTime: break; case TypeCode.String: WriteToken("$", null); break; default: throw new Exception("Invalid value for TypeCode"); } } void LPar() { WriteToken("(", AstNode.Roles.LPar); } void RPar() { WriteToken(")", AstNode.Roles.LPar); } /// <summary> /// Writes a space depending on policy. /// </summary> void Space(bool addSpace = true) { if (addSpace) { formatter.Space(); lastWritten = LastWritten.Whitespace; } } void NewLine() { formatter.NewLine(); lastWritten = LastWritten.Whitespace; } void Indent() { formatter.Indent(); } void Unindent() { formatter.Unindent(); } void MarkFoldStart() { formatter.MarkFoldStart(); } void MarkFoldEnd() { formatter.MarkFoldEnd(); } #endregion #region IsKeyword Test static readonly HashSet<string> unconditionalKeywords = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "AddHandler", "AddressOf", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "EndIf", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "GetXmlNamespace", "Global", "GoSub", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "Namespace", "Narrowing", "Next", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "Variant", "Wend", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor" }; static readonly HashSet<string> queryKeywords = new HashSet<string> { }; /// <summary> /// Determines whether the specified identifier is a keyword in the given context. /// </summary> public static bool IsKeyword(string identifier, AstNode context) { if (identifier == "New") { if (context.PrevSibling is InstanceExpression) return false; return true; } if (unconditionalKeywords.Contains(identifier)) return true; // if (context.Ancestors.Any(a => a is QueryExpression)) { // if (queryKeywords.Contains(identifier)) // return true; // } return false; } #endregion #region Write constructs void WriteTypeArguments(IEnumerable<AstType> typeArguments) { if (typeArguments.Any()) { LPar(); WriteKeyword("Of"); WriteCommaSeparatedList(typeArguments); RPar(); } } void WriteTypeParameters(IEnumerable<TypeParameterDeclaration> typeParameters) { if (typeParameters.Any()) { LPar(); WriteKeyword("Of"); WriteCommaSeparatedList(typeParameters); RPar(); } } void WriteModifiers(IEnumerable<VBModifierToken> modifierTokens) { foreach (VBModifierToken modifier in modifierTokens) { modifier.AcceptVisitor(this, null); } } void WriteArraySpecifiers(IEnumerable<ArraySpecifier> arraySpecifiers) { foreach (ArraySpecifier specifier in arraySpecifiers) { specifier.AcceptVisitor(this, null); } } void WriteQualifiedIdentifier(IEnumerable<Identifier> identifiers) { bool first = true; foreach (Identifier ident in identifiers) { if (first) { first = false; if (lastWritten == LastWritten.KeywordOrIdentifier) formatter.Space(); } else { WriteSpecialsUpToRole(AstNode.Roles.Dot, ident); formatter.WriteToken("."); lastWritten = LastWritten.Other; } WriteSpecialsUpToNode(ident); formatter.WriteIdentifier(ident.Name); lastWritten = LastWritten.KeywordOrIdentifier; } } void WriteEmbeddedStatement(Statement embeddedStatement) { if (embeddedStatement.IsNull) return; BlockStatement block = embeddedStatement as BlockStatement; if (block != null) VisitBlockStatement(block, null); else embeddedStatement.AcceptVisitor(this, null); } void WriteBlock(BlockStatement body) { if (body.IsNull) { NewLine(); Indent(); NewLine(); Unindent(); } else VisitBlockStatement(body, null); } void WriteMembers(IEnumerable<AstNode> members) { Indent(); bool isFirst = true; foreach (var member in members) { if (isFirst) { isFirst = false; } else { NewLine(); } member.AcceptVisitor(this, null); } Unindent(); } void WriteAttributes(IEnumerable<AttributeBlock> attributes) { foreach (AttributeBlock attr in attributes) { attr.AcceptVisitor(this, null); } } void WritePrivateImplementationType(AstType privateImplementationType) { if (!privateImplementationType.IsNull) { privateImplementationType.AcceptVisitor(this, null); WriteToken(".", AstNode.Roles.Dot); } } void WriteImplementsClause(AstNodeCollection<InterfaceMemberSpecifier> implementsClause) { if (implementsClause.Any()) { Space(); WriteKeyword("Implements"); WriteCommaSeparatedList(implementsClause); } } void WriteImplementsClause(AstNodeCollection<AstType> implementsClause) { if (implementsClause.Any()) { WriteKeyword("Implements"); WriteCommaSeparatedList(implementsClause); } } void WriteHandlesClause(AstNodeCollection<EventMemberSpecifier> handlesClause) { if (handlesClause.Any()) { Space(); WriteKeyword("Handles"); WriteCommaSeparatedList(handlesClause); } } void WritePrimitiveValue(object val) { if (val == null) { WriteKeyword("Nothing"); return; } if (val is bool) { if ((bool)val) { WriteKeyword("True"); } else { WriteKeyword("False"); } return; } if (val is string) { formatter.WriteToken("\"" + ConvertString(val.ToString()) + "\""); lastWritten = LastWritten.Other; } else if (val is char) { formatter.WriteToken("\"" + ConvertCharLiteral((char)val) + "\"c"); lastWritten = LastWritten.Other; } else if (val is decimal) { formatter.WriteToken(((decimal)val).ToString(NumberFormatInfo.InvariantInfo) + "D"); lastWritten = LastWritten.Other; } else if (val is float) { float f = (float)val; if (float.IsInfinity(f) || float.IsNaN(f)) { // Strictly speaking, these aren't PrimitiveExpressions; // but we still support writing these to make life easier for code generators. WriteKeyword("Single"); WriteToken(".", AstNode.Roles.Dot); if (float.IsPositiveInfinity(f)) WriteIdentifier("PositiveInfinity"); else if (float.IsNegativeInfinity(f)) WriteIdentifier("NegativeInfinity"); else WriteIdentifier("NaN"); return; } formatter.WriteToken(f.ToString("R", NumberFormatInfo.InvariantInfo) + "F"); lastWritten = LastWritten.Other; } else if (val is double) { double f = (double)val; if (double.IsInfinity(f) || double.IsNaN(f)) { // Strictly speaking, these aren't PrimitiveExpressions; // but we still support writing these to make life easier for code generators. WriteKeyword("Double"); WriteToken(".", AstNode.Roles.Dot); if (double.IsPositiveInfinity(f)) WriteIdentifier("PositiveInfinity"); else if (double.IsNegativeInfinity(f)) WriteIdentifier("NegativeInfinity"); else WriteIdentifier("NaN"); return; } string number = f.ToString("R", NumberFormatInfo.InvariantInfo); if (number.IndexOf('.') < 0 && number.IndexOf('E') < 0) number += ".0"; formatter.WriteToken(number); // needs space if identifier follows number; this avoids mistaking the following identifier as type suffix lastWritten = LastWritten.KeywordOrIdentifier; } else if (val is IFormattable) { StringBuilder b = new StringBuilder(); b.Append(((IFormattable)val).ToString(null, NumberFormatInfo.InvariantInfo)); if (val is ushort || val is ulong) { b.Append("U"); } if (val is short || val is ushort) { b.Append("S"); } else if (val is uint) { b.Append("UI"); } else if (val is long || val is ulong) { b.Append("L"); } formatter.WriteToken(b.ToString()); // needs space if identifier follows number; this avoids mistaking the following identifier as type suffix lastWritten = LastWritten.KeywordOrIdentifier; } else { formatter.WriteToken(val.ToString()); lastWritten = LastWritten.Other; } } #endregion #region ConvertLiteral static string ConvertCharLiteral(char ch) { if (ch == '"') return "\"\""; return ch.ToString(); } static string ConvertString(string str) { StringBuilder sb = new StringBuilder(); foreach (char ch in str) { sb.Append(ConvertCharLiteral(ch)); } return sb.ToString(); } #endregion public object VisitVariableIdentifier(VariableIdentifier variableIdentifier, object data) { StartNode(variableIdentifier); WriteIdentifier(variableIdentifier.Name.Name); if (variableIdentifier.HasNullableSpecifier) WriteToken("?", VariableIdentifier.Roles.QuestionMark); if (variableIdentifier.ArraySizeSpecifiers.Count > 0) WriteCommaSeparatedListInParenthesis(variableIdentifier.ArraySizeSpecifiers, false); WriteArraySpecifiers(variableIdentifier.ArraySpecifiers); return EndNode(variableIdentifier); } public object VisitAccessor(Accessor accessor, object data) { StartNode(accessor); WriteAttributes(accessor.Attributes); WriteModifiers(accessor.ModifierTokens); if (accessor.Role == PropertyDeclaration.GetterRole) { WriteKeyword("Get"); } else if (accessor.Role == PropertyDeclaration.SetterRole) { WriteKeyword("Set"); } else if (accessor.Role == EventDeclaration.AddHandlerRole) { WriteKeyword("AddHandler"); } else if (accessor.Role == EventDeclaration.RemoveHandlerRole) { WriteKeyword("RemoveHandler"); } else if (accessor.Role == EventDeclaration.RaiseEventRole) { WriteKeyword("RaiseEvent"); } if (accessor.Parameters.Any()) WriteCommaSeparatedListInParenthesis(accessor.Parameters, false); WriteBlock(accessor.Body); WriteKeyword("End"); if (accessor.Role == PropertyDeclaration.GetterRole) { WriteKeyword("Get"); } else if (accessor.Role == PropertyDeclaration.SetterRole) { WriteKeyword("Set"); } else if (accessor.Role == EventDeclaration.AddHandlerRole) { WriteKeyword("AddHandler"); } else if (accessor.Role == EventDeclaration.RemoveHandlerRole) { WriteKeyword("RemoveHandler"); } else if (accessor.Role == EventDeclaration.RaiseEventRole) { WriteKeyword("RaiseEvent"); } NewLine(); return EndNode(accessor); } public object VisitLabelDeclarationStatement(LabelDeclarationStatement labelDeclarationStatement, object data) { StartNode(labelDeclarationStatement); labelDeclarationStatement.Label.AcceptVisitor(this, data); WriteToken(":", LabelDeclarationStatement.Roles.Colon); return EndNode(labelDeclarationStatement); } public object VisitLocalDeclarationStatement(LocalDeclarationStatement localDeclarationStatement, object data) { StartNode(localDeclarationStatement); if (localDeclarationStatement.ModifierToken != null && !localDeclarationStatement.ModifierToken.IsNull) WriteModifiers(new [] { localDeclarationStatement.ModifierToken }); WriteCommaSeparatedList(localDeclarationStatement.Variables); return EndNode(localDeclarationStatement); } public object VisitWithStatement(WithStatement withStatement, object data) { StartNode(withStatement); WriteKeyword("With"); withStatement.Expression.AcceptVisitor(this, data); withStatement.Body.AcceptVisitor(this, data); WriteKeyword("End"); WriteKeyword("With"); return EndNode(withStatement); } public object VisitSyncLockStatement(SyncLockStatement syncLockStatement, object data) { StartNode(syncLockStatement); WriteKeyword("SyncLock"); syncLockStatement.Expression.AcceptVisitor(this, data); syncLockStatement.Body.AcceptVisitor(this, data); WriteKeyword("End"); WriteKeyword("SyncLock"); return EndNode(syncLockStatement); } public object VisitTryStatement(TryStatement tryStatement, object data) { StartNode(tryStatement); WriteKeyword("Try"); tryStatement.Body.AcceptVisitor(this, data); foreach (var clause in tryStatement.CatchBlocks) { clause.AcceptVisitor(this, data); } if (!tryStatement.FinallyBlock.IsNull) { WriteKeyword("Finally"); tryStatement.FinallyBlock.AcceptVisitor(this, data); } WriteKeyword("End"); WriteKeyword("Try"); return EndNode(tryStatement); } public object VisitCatchBlock(CatchBlock catchBlock, object data) { StartNode(catchBlock); WriteKeyword("Catch"); catchBlock.ExceptionVariable.AcceptVisitor(this, data); if (!catchBlock.ExceptionType.IsNull) { WriteKeyword("As"); catchBlock.ExceptionType.AcceptVisitor(this, data); } NewLine(); Indent(); foreach (var stmt in catchBlock) { stmt.AcceptVisitor(this, data); NewLine(); } Unindent(); return EndNode(catchBlock); } public object VisitExpressionStatement(ExpressionStatement expressionStatement, object data) { StartNode(expressionStatement); expressionStatement.Expression.AcceptVisitor(this, data); return EndNode(expressionStatement); } public object VisitThrowStatement(ThrowStatement throwStatement, object data) { StartNode(throwStatement); WriteKeyword("Throw"); throwStatement.Expression.AcceptVisitor(this, data); return EndNode(throwStatement); } public object VisitIfElseStatement(IfElseStatement ifElseStatement, object data) { StartNode(ifElseStatement); WriteKeyword("If"); ifElseStatement.Condition.AcceptVisitor(this, data); Space(); WriteKeyword("Then"); bool needsEndIf = ifElseStatement.Body is BlockStatement; ifElseStatement.Body.AcceptVisitor(this, data); if (!ifElseStatement.ElseBlock.IsNull) { WriteKeyword("Else"); needsEndIf = ifElseStatement.ElseBlock is BlockStatement; ifElseStatement.ElseBlock.AcceptVisitor(this, data); } if (needsEndIf) { WriteKeyword("End"); WriteKeyword("If"); } return EndNode(ifElseStatement); } public object VisitReturnStatement(ReturnStatement returnStatement, object data) { StartNode(returnStatement); WriteKeyword("Return"); returnStatement.Expression.AcceptVisitor(this, data); return EndNode(returnStatement); } public object VisitBinaryOperatorExpression(BinaryOperatorExpression binaryOperatorExpression, object data) { StartNode(binaryOperatorExpression); binaryOperatorExpression.Left.AcceptVisitor(this, data); Space(); switch (binaryOperatorExpression.Operator) { case BinaryOperatorType.BitwiseAnd: WriteKeyword("And"); break; case BinaryOperatorType.BitwiseOr: WriteKeyword("Or"); break; case BinaryOperatorType.LogicalAnd: WriteKeyword("AndAlso"); break; case BinaryOperatorType.LogicalOr: WriteKeyword("OrElse"); break; case BinaryOperatorType.ExclusiveOr: WriteKeyword("Xor"); break; case BinaryOperatorType.GreaterThan: WriteToken(">", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.GreaterThanOrEqual: WriteToken(">=", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Equality: WriteToken("=", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.InEquality: WriteToken("<>", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.LessThan: WriteToken("<", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.LessThanOrEqual: WriteToken("<=", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Add: WriteToken("+", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Subtract: WriteToken("-", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Multiply: WriteToken("*", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Divide: WriteToken("/", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Modulus: WriteKeyword("Mod"); break; case BinaryOperatorType.DivideInteger: WriteToken("\\", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Power: WriteToken("*", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.Concat: WriteToken("&", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.ShiftLeft: WriteToken("<<", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.ShiftRight: WriteToken(">>", BinaryOperatorExpression.OperatorRole); break; case BinaryOperatorType.ReferenceEquality: WriteKeyword("Is"); break; case BinaryOperatorType.ReferenceInequality: WriteKeyword("IsNot"); break; case BinaryOperatorType.Like: WriteKeyword("Like"); break; case BinaryOperatorType.DictionaryAccess: WriteToken("!", BinaryOperatorExpression.OperatorRole); break; default: throw new Exception("Invalid value for BinaryOperatorType: " + binaryOperatorExpression.Operator); } Space(); binaryOperatorExpression.Right.AcceptVisitor(this, data); return EndNode(binaryOperatorExpression); } public object VisitIdentifierExpression(IdentifierExpression identifierExpression, object data) { StartNode(identifierExpression); identifierExpression.Identifier.AcceptVisitor(this, data); WriteTypeArguments(identifierExpression.TypeArguments); return EndNode(identifierExpression); } public object VisitAssignmentExpression(AssignmentExpression assignmentExpression, object data) { StartNode(assignmentExpression); assignmentExpression.Left.AcceptVisitor(this, data); Space(); switch (assignmentExpression.Operator) { case AssignmentOperatorType.Assign: WriteToken("=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.Add: WriteToken("+=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.Subtract: WriteToken("-=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.Multiply: WriteToken("*=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.Divide: WriteToken("/=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.Power: WriteToken("^=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.DivideInteger: WriteToken("\\=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.ConcatString: WriteToken("&=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.ShiftLeft: WriteToken("<<=", AssignmentExpression.OperatorRole); break; case AssignmentOperatorType.ShiftRight: WriteToken(">>=", AssignmentExpression.OperatorRole); break; default: throw new Exception("Invalid value for AssignmentOperatorType: " + assignmentExpression.Operator); } Space(); assignmentExpression.Right.AcceptVisitor(this, data); return EndNode(assignmentExpression); } public object VisitInvocationExpression(InvocationExpression invocationExpression, object data) { StartNode(invocationExpression); invocationExpression.Target.AcceptVisitor(this, data); WriteCommaSeparatedListInParenthesis(invocationExpression.Arguments, false); return EndNode(invocationExpression); } public object VisitArrayInitializerExpression(ArrayInitializerExpression arrayInitializerExpression, object data) { StartNode(arrayInitializerExpression); WriteToken("{", ArrayInitializerExpression.Roles.LBrace); Space(); WriteCommaSeparatedList(arrayInitializerExpression.Elements); Space(); WriteToken("}", ArrayInitializerExpression.Roles.RBrace); return EndNode(arrayInitializerExpression); } public object VisitArrayCreateExpression(ArrayCreateExpression arrayCreateExpression, object data) { StartNode(arrayCreateExpression); WriteKeyword("New"); Space(); arrayCreateExpression.Type.AcceptVisitor(this, data); if (arrayCreateExpression.Arguments.Any()) WriteCommaSeparatedListInParenthesis(arrayCreateExpression.Arguments, false); foreach (var specifier in arrayCreateExpression.AdditionalArraySpecifiers) { specifier.AcceptVisitor(this, data); } if (lastWritten != LastWritten.Whitespace) Space(); if (arrayCreateExpression.Initializer.IsNull) { WriteToken("{", ArrayInitializerExpression.Roles.LBrace); WriteToken("}", ArrayInitializerExpression.Roles.RBrace); } else { arrayCreateExpression.Initializer.AcceptVisitor(this, data); } return EndNode(arrayCreateExpression); } public object VisitObjectCreationExpression(ObjectCreationExpression objectCreationExpression, object data) { StartNode(objectCreationExpression); WriteKeyword("New"); objectCreationExpression.Type.AcceptVisitor(this, data); WriteCommaSeparatedListInParenthesis(objectCreationExpression.Arguments, false); if (!objectCreationExpression.Initializer.IsNull) { Space(); if (objectCreationExpression.Initializer.Elements.Any(x => x is FieldInitializerExpression)) WriteKeyword("With"); else WriteKeyword("From"); Space(); objectCreationExpression.Initializer.AcceptVisitor(this, data); } return EndNode(objectCreationExpression); } public object VisitCastExpression(CastExpression castExpression, object data) { StartNode(castExpression); switch (castExpression.CastType) { case CastType.DirectCast: WriteKeyword("DirectCast"); break; case CastType.TryCast: WriteKeyword("TryCast"); break; case CastType.CType: WriteKeyword("CType"); break; case CastType.CBool: WriteKeyword("CBool"); break; case CastType.CByte: WriteKeyword("CByte"); break; case CastType.CChar: WriteKeyword("CChar"); break; case CastType.CDate: WriteKeyword("CDate"); break; case CastType.CDec: WriteKeyword("CType"); break; case CastType.CDbl: WriteKeyword("CDec"); break; case CastType.CInt: WriteKeyword("CInt"); break; case CastType.CLng: WriteKeyword("CLng"); break; case CastType.CObj: WriteKeyword("CObj"); break; case CastType.CSByte: WriteKeyword("CSByte"); break; case CastType.CShort: WriteKeyword("CShort"); break; case CastType.CSng: WriteKeyword("CSng"); break; case CastType.CStr: WriteKeyword("CStr"); break; case CastType.CUInt: WriteKeyword("CUInt"); break; case CastType.CULng: WriteKeyword("CULng"); break; case CastType.CUShort: WriteKeyword("CUShort"); break; default: throw new Exception("Invalid value for CastType"); } WriteToken("(", CastExpression.Roles.LPar); castExpression.Expression.AcceptVisitor(this, data); if (castExpression.CastType == CastType.CType || castExpression.CastType == CastType.DirectCast || castExpression.CastType == CastType.TryCast) { WriteToken(",", CastExpression.Roles.Comma); Space(); castExpression.Type.AcceptVisitor(this, data); } WriteToken(")", CastExpression.Roles.RPar); return EndNode(castExpression); } public object VisitComment(Comment comment, object data) { formatter.WriteComment(comment.IsDocumentationComment, comment.Content); return null; } public object VisitEventDeclaration(EventDeclaration eventDeclaration, object data) { StartNode(eventDeclaration); WriteAttributes(eventDeclaration.Attributes); WriteModifiers(eventDeclaration.ModifierTokens); if (eventDeclaration.IsCustom) WriteKeyword("Custom"); WriteKeyword("Event"); WriteIdentifier(eventDeclaration.Name.Name); if (!eventDeclaration.IsCustom && eventDeclaration.ReturnType.IsNull) WriteCommaSeparatedListInParenthesis(eventDeclaration.Parameters, false); if (!eventDeclaration.ReturnType.IsNull) { Space(); WriteKeyword("As"); eventDeclaration.ReturnType.AcceptVisitor(this, data); } WriteImplementsClause(eventDeclaration.ImplementsClause); if (eventDeclaration.IsCustom) { MarkFoldStart(); NewLine(); Indent(); eventDeclaration.AddHandlerBlock.AcceptVisitor(this, data); eventDeclaration.RemoveHandlerBlock.AcceptVisitor(this, data); eventDeclaration.RaiseEventBlock.AcceptVisitor(this, data); Unindent(); WriteKeyword("End"); WriteKeyword("Event"); MarkFoldEnd(); } NewLine(); return EndNode(eventDeclaration); } public object VisitUnaryOperatorExpression(UnaryOperatorExpression unaryOperatorExpression, object data) { StartNode(unaryOperatorExpression); switch (unaryOperatorExpression.Operator) { case UnaryOperatorType.Not: WriteKeyword("Not"); break; case UnaryOperatorType.Minus: WriteToken("-", UnaryOperatorExpression.OperatorRole); break; case UnaryOperatorType.Plus: WriteToken("+", UnaryOperatorExpression.OperatorRole); break; case UnaryOperatorType.AddressOf: WriteKeyword("AddressOf"); break; case UnaryOperatorType.Await: WriteKeyword("Await"); break; default: throw new Exception("Invalid value for UnaryOperatorType"); } unaryOperatorExpression.Expression.AcceptVisitor(this, data); return EndNode(unaryOperatorExpression); } public object VisitFieldInitializerExpression(FieldInitializerExpression fieldInitializerExpression, object data) { StartNode(fieldInitializerExpression); if (fieldInitializerExpression.IsKey && fieldInitializerExpression.Parent is AnonymousObjectCreationExpression) { WriteKeyword("Key"); Space(); } WriteToken(".", FieldInitializerExpression.Roles.Dot); fieldInitializerExpression.Identifier.AcceptVisitor(this, data); Space(); WriteToken("=", FieldInitializerExpression.Roles.Assign); Space(); fieldInitializerExpression.Expression.AcceptVisitor(this, data); return EndNode(fieldInitializerExpression); } public object VisitNamedArgumentExpression(NamedArgumentExpression namedArgumentExpression, object data) { throw new NotImplementedException(); } public object VisitConditionalExpression(ConditionalExpression conditionalExpression, object data) { StartNode(conditionalExpression); WriteKeyword("If"); WriteToken("(", ConditionalExpression.Roles.LPar); conditionalExpression.ConditionExpression.AcceptVisitor(this, data); WriteToken(",", ConditionalExpression.Roles.Comma); Space(); if (!conditionalExpression.TrueExpression.IsNull) { conditionalExpression.TrueExpression.AcceptVisitor(this, data); WriteToken(",", ConditionalExpression.Roles.Comma); Space(); } conditionalExpression.FalseExpression.AcceptVisitor(this, data); WriteToken(")", ConditionalExpression.Roles.RPar); return EndNode(conditionalExpression); } public object VisitWhileStatement(WhileStatement whileStatement, object data) { StartNode(whileStatement); WriteKeyword("While"); Space(); whileStatement.Condition.AcceptVisitor(this, data); whileStatement.Body.AcceptVisitor(this, data); WriteKeyword("End"); WriteKeyword("While"); return EndNode(whileStatement); } public object VisitExitStatement(ExitStatement exitStatement, object data) { StartNode(exitStatement); WriteKeyword("Exit"); switch (exitStatement.ExitKind) { case ExitKind.Sub: WriteKeyword("Sub"); break; case ExitKind.Function: WriteKeyword("Function"); break; case ExitKind.Property: WriteKeyword("Property"); break; case ExitKind.Do: WriteKeyword("Do"); break; case ExitKind.For: WriteKeyword("For"); break; case ExitKind.While: WriteKeyword("While"); break; case ExitKind.Select: WriteKeyword("Select"); break; case ExitKind.Try: WriteKeyword("Try"); break; default: throw new Exception("Invalid value for ExitKind"); } return EndNode(exitStatement); } public object VisitForStatement(ForStatement forStatement, object data) { StartNode(forStatement); WriteKeyword("For"); forStatement.Variable.AcceptVisitor(this, data); WriteKeyword("To"); forStatement.ToExpression.AcceptVisitor(this, data); if (!forStatement.StepExpression.IsNull) { WriteKeyword("Step"); Space(); forStatement.StepExpression.AcceptVisitor(this, data); } forStatement.Body.AcceptVisitor(this, data); WriteKeyword("Next"); return EndNode(forStatement); } public object VisitForEachStatement(ForEachStatement forEachStatement, object data) { StartNode(forEachStatement); WriteKeyword("For"); WriteKeyword("Each"); forEachStatement.Variable.AcceptVisitor(this, data); Space(); WriteKeyword("In"); forEachStatement.InExpression.AcceptVisitor(this, data); forEachStatement.Body.AcceptVisitor(this, data); WriteKeyword("Next"); return EndNode(forEachStatement); } public object VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration, object data) { StartNode(operatorDeclaration); WriteAttributes(operatorDeclaration.Attributes); WriteModifiers(operatorDeclaration.ModifierTokens); WriteKeyword("Operator"); switch (operatorDeclaration.Operator) { case OverloadableOperatorType.Add: case OverloadableOperatorType.UnaryPlus: WriteToken("+", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Subtract: case OverloadableOperatorType.UnaryMinus: WriteToken("-", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Multiply: WriteToken("*", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Divide: WriteToken("/", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Modulus: WriteKeyword("Mod"); break; case OverloadableOperatorType.Concat: WriteToken("&", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Not: WriteKeyword("Not"); break; case OverloadableOperatorType.BitwiseAnd: WriteKeyword("And"); break; case OverloadableOperatorType.BitwiseOr: WriteKeyword("Or"); break; case OverloadableOperatorType.ExclusiveOr: WriteKeyword("Xor"); break; case OverloadableOperatorType.ShiftLeft: WriteToken("<<", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.ShiftRight: WriteToken(">>", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.GreaterThan: WriteToken(">", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.GreaterThanOrEqual: WriteToken(">=", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.Equality: WriteToken("=", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.InEquality: WriteToken("<>", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.LessThan: WriteToken("<", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.LessThanOrEqual: WriteToken("<=", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.IsTrue: WriteKeyword("IsTrue"); break; case OverloadableOperatorType.IsFalse: WriteKeyword("IsFalse"); break; case OverloadableOperatorType.Like: WriteKeyword("Like"); break; case OverloadableOperatorType.Power: WriteToken("^", OperatorDeclaration.Roles.Keyword); break; case OverloadableOperatorType.CType: WriteKeyword("CType"); break; case OverloadableOperatorType.DivideInteger: WriteToken("\\", OperatorDeclaration.Roles.Keyword); break; default: throw new Exception("Invalid value for OverloadableOperatorType"); } WriteCommaSeparatedListInParenthesis(operatorDeclaration.Parameters, false); if (!operatorDeclaration.ReturnType.IsNull) { Space(); WriteKeyword("As"); WriteAttributes(operatorDeclaration.ReturnTypeAttributes); operatorDeclaration.ReturnType.AcceptVisitor(this, data); } if (!operatorDeclaration.Body.IsNull) { MarkFoldStart(); WriteBlock(operatorDeclaration.Body); WriteKeyword("End"); WriteKeyword("Operator"); MarkFoldEnd(); } NewLine(); return EndNode(operatorDeclaration); } public object VisitSelectStatement(SelectStatement selectStatement, object data) { StartNode(selectStatement); WriteKeyword("Select"); WriteKeyword("Case"); selectStatement.Expression.AcceptVisitor(this, data); NewLine(); Indent(); foreach (CaseStatement stmt in selectStatement.Cases) { stmt.AcceptVisitor(this, data); } Unindent(); WriteKeyword("End"); WriteKeyword("Select"); return EndNode(selectStatement); } public object VisitCaseStatement(CaseStatement caseStatement, object data) { StartNode(caseStatement); WriteKeyword("Case"); if (caseStatement.Clauses.Count == 1 && caseStatement.Clauses.First().Expression.IsNull) WriteKeyword("Else"); else { Space(); WriteCommaSeparatedList(caseStatement.Clauses); } caseStatement.Body.AcceptVisitor(this, data); return EndNode(caseStatement); } public object VisitSimpleCaseClause(SimpleCaseClause simpleCaseClause, object data) { StartNode(simpleCaseClause); simpleCaseClause.Expression.AcceptVisitor(this, data); return EndNode(simpleCaseClause); } public object VisitRangeCaseClause(RangeCaseClause rangeCaseClause, object data) { StartNode(rangeCaseClause); rangeCaseClause.Expression.AcceptVisitor(this, data); WriteKeyword("To"); rangeCaseClause.ToExpression.AcceptVisitor(this, data); return EndNode(rangeCaseClause); } public object VisitComparisonCaseClause(ComparisonCaseClause comparisonCaseClause, object data) { StartNode(comparisonCaseClause); switch (comparisonCaseClause.Operator) { case ComparisonOperator.Equality: WriteToken("=", ComparisonCaseClause.OperatorRole); break; case ComparisonOperator.InEquality: WriteToken("<>", ComparisonCaseClause.OperatorRole); break; case ComparisonOperator.LessThan: WriteToken("<", ComparisonCaseClause.OperatorRole); break; case ComparisonOperator.GreaterThan: WriteToken(">", ComparisonCaseClause.OperatorRole); break; case ComparisonOperator.LessThanOrEqual: WriteToken("<=", ComparisonCaseClause.OperatorRole); break; case ComparisonOperator.GreaterThanOrEqual: WriteToken(">=", ComparisonCaseClause.OperatorRole); break; default: throw new Exception("Invalid value for ComparisonOperator"); } Space(); comparisonCaseClause.Expression.AcceptVisitor(this, data); return EndNode(comparisonCaseClause); } public object VisitYieldStatement(YieldStatement yieldStatement, object data) { StartNode(yieldStatement); WriteKeyword("Yield"); yieldStatement.Expression.AcceptVisitor(this, data); return EndNode(yieldStatement); } public object VisitVariableInitializer(VariableInitializer variableInitializer, object data) { StartNode(variableInitializer); variableInitializer.Identifier.AcceptVisitor(this, data); if (!variableInitializer.Type.IsNull) { if (lastWritten != LastWritten.Whitespace) Space(); WriteKeyword("As"); variableInitializer.Type.AcceptVisitor(this, data); } if (!variableInitializer.Expression.IsNull) { Space(); WriteToken("=", VariableInitializer.Roles.Assign); Space(); variableInitializer.Expression.AcceptVisitor(this, data); } return EndNode(variableInitializer); } public object VisitVariableDeclaratorWithTypeAndInitializer(VariableDeclaratorWithTypeAndInitializer variableDeclaratorWithTypeAndInitializer, object data) { StartNode(variableDeclaratorWithTypeAndInitializer); WriteCommaSeparatedList(variableDeclaratorWithTypeAndInitializer.Identifiers); if (lastWritten != LastWritten.Whitespace) Space(); WriteKeyword("As"); variableDeclaratorWithTypeAndInitializer.Type.AcceptVisitor(this, data); if (!variableDeclaratorWithTypeAndInitializer.Initializer.IsNull) { Space(); WriteToken("=", VariableDeclarator.Roles.Assign); Space(); variableDeclaratorWithTypeAndInitializer.Initializer.AcceptVisitor(this, data); } return EndNode(variableDeclaratorWithTypeAndInitializer); } public object VisitVariableDeclaratorWithObjectCreation(VariableDeclaratorWithObjectCreation variableDeclaratorWithObjectCreation, object data) { StartNode(variableDeclaratorWithObjectCreation); WriteCommaSeparatedList(variableDeclaratorWithObjectCreation.Identifiers); if (lastWritten != LastWritten.Whitespace) Space(); WriteKeyword("As"); variableDeclaratorWithObjectCreation.Initializer.AcceptVisitor(this, data); return EndNode(variableDeclaratorWithObjectCreation); } public object VisitDoLoopStatement(DoLoopStatement doLoopStatement, object data) { StartNode(doLoopStatement); WriteKeyword("Do"); if (doLoopStatement.ConditionType == ConditionType.DoUntil) { WriteKeyword("Until"); doLoopStatement.Expression.AcceptVisitor(this, data); } if (doLoopStatement.ConditionType == ConditionType.DoWhile) { WriteKeyword("While"); doLoopStatement.Expression.AcceptVisitor(this, data); } doLoopStatement.Body.AcceptVisitor(this, data); WriteKeyword("Loop"); if (doLoopStatement.ConditionType == ConditionType.LoopUntil) { WriteKeyword("Until"); doLoopStatement.Expression.AcceptVisitor(this, data); } if (doLoopStatement.ConditionType == ConditionType.LoopWhile) { WriteKeyword("While"); doLoopStatement.Expression.AcceptVisitor(this, data); } return EndNode(doLoopStatement); } public object VisitUsingStatement(UsingStatement usingStatement, object data) { StartNode(usingStatement); WriteKeyword("Using"); WriteCommaSeparatedList(usingStatement.Resources); usingStatement.Body.AcceptVisitor(this, data); WriteKeyword("End"); WriteKeyword("Using"); return EndNode(usingStatement); } public object VisitGoToStatement(GoToStatement goToStatement, object data) { StartNode(goToStatement); WriteKeyword("GoTo"); goToStatement.Label.AcceptVisitor(this, data); return EndNode(goToStatement); } public object VisitSingleLineSubLambdaExpression(SingleLineSubLambdaExpression singleLineSubLambdaExpression, object data) { StartNode(singleLineSubLambdaExpression); WriteModifiers(singleLineSubLambdaExpression.ModifierTokens); WriteKeyword("Sub"); WriteCommaSeparatedListInParenthesis(singleLineSubLambdaExpression.Parameters, false); Space(); singleLineSubLambdaExpression.EmbeddedStatement.AcceptVisitor(this, data); return EndNode(singleLineSubLambdaExpression); } public object VisitSingleLineFunctionLambdaExpression(SingleLineFunctionLambdaExpression singleLineFunctionLambdaExpression, object data) { StartNode(singleLineFunctionLambdaExpression); WriteModifiers(singleLineFunctionLambdaExpression.ModifierTokens); WriteKeyword("Function"); WriteCommaSeparatedListInParenthesis(singleLineFunctionLambdaExpression.Parameters, false); Space(); singleLineFunctionLambdaExpression.EmbeddedExpression.AcceptVisitor(this, data); return EndNode(singleLineFunctionLambdaExpression); } public object VisitMultiLineLambdaExpression(MultiLineLambdaExpression multiLineLambdaExpression, object data) { StartNode(multiLineLambdaExpression); WriteModifiers(multiLineLambdaExpression.ModifierTokens); if (multiLineLambdaExpression.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); WriteCommaSeparatedListInParenthesis(multiLineLambdaExpression.Parameters, false); multiLineLambdaExpression.Body.AcceptVisitor(this, data); WriteKeyword("End"); if (multiLineLambdaExpression.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); return EndNode(multiLineLambdaExpression); } public object VisitQueryExpression(QueryExpression queryExpression, object data) { StartNode(queryExpression); foreach (var op in queryExpression.QueryOperators) { op.AcceptVisitor(this, data); } return EndNode(queryExpression); } public object VisitContinueStatement(ContinueStatement continueStatement, object data) { StartNode(continueStatement); WriteKeyword("Continue"); switch (continueStatement.ContinueKind) { case ContinueKind.Do: WriteKeyword("Do"); break; case ContinueKind.For: WriteKeyword("For"); break; case ContinueKind.While: WriteKeyword("While"); break; default: throw new Exception("Invalid value for ContinueKind"); } return EndNode(continueStatement); } public object VisitExternalMethodDeclaration(ExternalMethodDeclaration externalMethodDeclaration, object data) { StartNode(externalMethodDeclaration); WriteAttributes(externalMethodDeclaration.Attributes); WriteModifiers(externalMethodDeclaration.ModifierTokens); WriteKeyword("Declare"); switch (externalMethodDeclaration.CharsetModifier) { case CharsetModifier.None: break; case CharsetModifier.Auto: WriteKeyword("Auto"); break; case CharsetModifier.Unicode: WriteKeyword("Unicode"); break; case CharsetModifier.Ansi: WriteKeyword("Ansi"); break; default: throw new Exception("Invalid value for CharsetModifier"); } if (externalMethodDeclaration.IsSub) WriteKeyword("Sub"); else WriteKeyword("Function"); externalMethodDeclaration.Name.AcceptVisitor(this, data); WriteKeyword("Lib"); Space(); WritePrimitiveValue(externalMethodDeclaration.Library); Space(); if (externalMethodDeclaration.Alias != null) { WriteKeyword("Alias"); Space(); WritePrimitiveValue(externalMethodDeclaration.Alias); Space(); } WriteCommaSeparatedListInParenthesis(externalMethodDeclaration.Parameters, false); if (!externalMethodDeclaration.IsSub && !externalMethodDeclaration.ReturnType.IsNull) { Space(); WriteKeyword("As"); WriteAttributes(externalMethodDeclaration.ReturnTypeAttributes); externalMethodDeclaration.ReturnType.AcceptVisitor(this, data); } NewLine(); return EndNode(externalMethodDeclaration); } public static string ToVBNetString(PrimitiveExpression primitiveExpression) { var writer = new StringWriter(); new OutputVisitor(writer, new VBFormattingOptions()).WritePrimitiveValue(primitiveExpression.Value); return writer.ToString(); } public object VisitEmptyExpression(EmptyExpression emptyExpression, object data) { StartNode(emptyExpression); return EndNode(emptyExpression); } public object VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpression anonymousObjectCreationExpression, object data) { StartNode(anonymousObjectCreationExpression); WriteKeyword("New"); WriteKeyword("With"); WriteToken("{", AnonymousObjectCreationExpression.Roles.LBrace); Space(); WriteCommaSeparatedList(anonymousObjectCreationExpression.Initializer); Space(); WriteToken("}", AnonymousObjectCreationExpression.Roles.RBrace); return EndNode(anonymousObjectCreationExpression); } public object VisitCollectionRangeVariableDeclaration(CollectionRangeVariableDeclaration collectionRangeVariableDeclaration, object data) { StartNode(collectionRangeVariableDeclaration); collectionRangeVariableDeclaration.Identifier.AcceptVisitor(this, data); if (!collectionRangeVariableDeclaration.Type.IsNull) { WriteKeyword("As"); collectionRangeVariableDeclaration.Type.AcceptVisitor(this, data); } WriteKeyword("In"); collectionRangeVariableDeclaration.Expression.AcceptVisitor(this, data); return EndNode(collectionRangeVariableDeclaration); } public object VisitFromQueryOperator(FromQueryOperator fromQueryOperator, object data) { StartNode(fromQueryOperator); WriteKeyword("From"); WriteCommaSeparatedList(fromQueryOperator.Variables); return EndNode(fromQueryOperator); } public object VisitAggregateQueryOperator(AggregateQueryOperator aggregateQueryOperator, object data) { StartNode(aggregateQueryOperator); WriteKeyword("Aggregate"); aggregateQueryOperator.Variable.AcceptVisitor(this, data); foreach (var operators in aggregateQueryOperator.SubQueryOperators) { operators.AcceptVisitor(this, data); } WriteKeyword("Into"); WriteCommaSeparatedList(aggregateQueryOperator.IntoExpressions); return EndNode(aggregateQueryOperator); } public object VisitSelectQueryOperator(SelectQueryOperator selectQueryOperator, object data) { StartNode(selectQueryOperator); WriteKeyword("Select"); WriteCommaSeparatedList(selectQueryOperator.Variables); return EndNode(selectQueryOperator); } public object VisitDistinctQueryOperator(DistinctQueryOperator distinctQueryOperator, object data) { StartNode(distinctQueryOperator); WriteKeyword("Distinct"); return EndNode(distinctQueryOperator); } public object VisitWhereQueryOperator(WhereQueryOperator whereQueryOperator, object data) { StartNode(whereQueryOperator); WriteKeyword("Where"); whereQueryOperator.Condition.AcceptVisitor(this, data); return EndNode(whereQueryOperator); } public object VisitPartitionQueryOperator(PartitionQueryOperator partitionQueryOperator, object data) { StartNode(partitionQueryOperator); switch (partitionQueryOperator.Kind) { case PartitionKind.Take: WriteKeyword("Take"); break; case PartitionKind.TakeWhile: WriteKeyword("Take"); WriteKeyword("While"); break; case PartitionKind.Skip: WriteKeyword("Skip"); break; case PartitionKind.SkipWhile: WriteKeyword("Skip"); WriteKeyword("While"); break; default: throw new Exception("Invalid value for PartitionKind"); } partitionQueryOperator.Expression.AcceptVisitor(this, data); return EndNode(partitionQueryOperator); } public object VisitOrderExpression(OrderExpression orderExpression, object data) { StartNode(orderExpression); orderExpression.Expression.AcceptVisitor(this, data); switch (orderExpression.Direction) { case QueryOrderingDirection.None: break; case QueryOrderingDirection.Ascending: WriteKeyword("Ascending"); break; case QueryOrderingDirection.Descending: WriteKeyword("Descending"); break; default: throw new Exception("Invalid value for QueryExpressionOrderingDirection"); } return EndNode(orderExpression); } public object VisitOrderByQueryOperator(OrderByQueryOperator orderByQueryOperator, object data) { StartNode(orderByQueryOperator); WriteKeyword("Order"); WriteKeyword("By"); WriteCommaSeparatedList(orderByQueryOperator.Expressions); return EndNode(orderByQueryOperator); } public object VisitLetQueryOperator(LetQueryOperator letQueryOperator, object data) { StartNode(letQueryOperator); WriteKeyword("Let"); WriteCommaSeparatedList(letQueryOperator.Variables); return EndNode(letQueryOperator); } public object VisitGroupByQueryOperator(GroupByQueryOperator groupByQueryOperator, object data) { StartNode(groupByQueryOperator); WriteKeyword("Group"); WriteCommaSeparatedList(groupByQueryOperator.GroupExpressions); WriteKeyword("By"); WriteCommaSeparatedList(groupByQueryOperator.ByExpressions); WriteKeyword("Into"); WriteCommaSeparatedList(groupByQueryOperator.IntoExpressions); return EndNode(groupByQueryOperator); } public object VisitJoinQueryOperator(JoinQueryOperator joinQueryOperator, object data) { StartNode(joinQueryOperator); WriteKeyword("Join"); joinQueryOperator.JoinVariable.AcceptVisitor(this, data); if (!joinQueryOperator.SubJoinQuery.IsNull) { joinQueryOperator.SubJoinQuery.AcceptVisitor(this, data); } WriteKeyword("On"); bool first = true; foreach (var cond in joinQueryOperator.JoinConditions) { if (first) first = false; else WriteKeyword("And"); cond.AcceptVisitor(this, data); } return EndNode(joinQueryOperator); } public object VisitJoinCondition(JoinCondition joinCondition, object data) { StartNode(joinCondition); joinCondition.Left.AcceptVisitor(this, data); WriteKeyword("Equals"); joinCondition.Right.AcceptVisitor(this, data); return EndNode(joinCondition); } public object VisitGroupJoinQueryOperator(GroupJoinQueryOperator groupJoinQueryOperator, object data) { StartNode(groupJoinQueryOperator); WriteKeyword("Group"); WriteKeyword("Join"); groupJoinQueryOperator.JoinVariable.AcceptVisitor(this, data); if (!groupJoinQueryOperator.SubJoinQuery.IsNull) { groupJoinQueryOperator.SubJoinQuery.AcceptVisitor(this, data); } WriteKeyword("On"); bool first = true; foreach (var cond in groupJoinQueryOperator.JoinConditions) { if (first) first = false; else WriteKeyword("And"); cond.AcceptVisitor(this, data); } WriteKeyword("Into"); WriteCommaSeparatedList(groupJoinQueryOperator.IntoExpressions); return EndNode(groupJoinQueryOperator); } public object VisitAddRemoveHandlerStatement(AddRemoveHandlerStatement addRemoveHandlerStatement, object data) { StartNode(addRemoveHandlerStatement); if (addRemoveHandlerStatement.IsAddHandler) WriteKeyword("AddHandler"); else WriteKeyword("RemoveHandler"); addRemoveHandlerStatement.EventExpression.AcceptVisitor(this, data); Comma(addRemoveHandlerStatement.DelegateExpression); addRemoveHandlerStatement.DelegateExpression.AcceptVisitor(this, data); return EndNode(addRemoveHandlerStatement); } } }
30.014378
157
0.721271
[ "MIT" ]
0xb1dd1e/ILSpy
NRefactory.VB/ICSharpCode.NRefactory.VB/OutputVisitor/OutputVisitor.cs
79,330
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Celia.io.Core.MicroServices.Utilities.Webs.Clients { /// <summary> /// Http请求 /// </summary> public abstract class HttpRequestBase<TRequest> where TRequest : IRequest<TRequest> { #region 字段 /// <summary> /// 地址 /// </summary> private string _url; /// <summary> /// Http动词 /// </summary> private readonly HttpMethod _httpMethod; /// <summary> /// 参数集合 /// </summary> private IDictionary<string, object> _params; /// <summary> /// 放入URL参数集合 /// </summary> private IDictionary<string, object> _urlParams; /// <summary> /// 参数 /// </summary> private string _data; /// <summary> /// 字符编码 /// </summary> private Encoding _encoding; /// <summary> /// 内容类型 /// </summary> private string _contentType; /// <summary> /// Cookie容器 /// </summary> private readonly CookieContainer _cookieContainer; /// <summary> /// 超时时间 /// </summary> private TimeSpan _timeout; /// <summary> /// 请求头集合 /// </summary> private readonly Dictionary<string, string> _headers; /// <summary> /// 执行失败的回调函数 /// </summary> private Action<string> _failAction; /// <summary> /// 执行失败的回调函数 /// </summary> private Action<string, HttpStatusCode> _failStatusCodeAction; /// <summary> /// ssl证书验证委托 /// </summary> private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback; /// <summary> /// 令牌 /// </summary> private string _token; #endregion #region 构造方法 /// <summary> /// 初始化Http请求 /// </summary> /// <param name="httpMethod">Http动词</param> /// <param name="url">地址</param> protected HttpRequestBase( HttpMethod httpMethod, string url ) { if( string.IsNullOrWhiteSpace( url ) ) throw new ArgumentNullException( nameof( url ) ); //System.Text.Encoding.RegisterProvider( CodePagesEncodingProvider.Instance ); _url = url; _httpMethod = httpMethod; _params = new Dictionary<string, object>(); _urlParams = new Dictionary<string, object>(); _contentType = HttpContentType.FormUrlEncoded.Description(); _cookieContainer = new CookieContainer(); _timeout = new TimeSpan( 0, 0, 30 ); _headers = new Dictionary<string, string>(); _encoding = System.Text.Encoding.UTF8; } #endregion #region 配置 /// <summary> /// 设置字符编码 /// </summary> /// <param name="encoding">字符编码</param> public TRequest Encoding( Encoding encoding ) { _encoding = encoding; return This(); } /// <summary> /// 设置字符编码 /// </summary> /// <param name="encoding">字符编码</param> public TRequest Encoding( string encoding ) { return Encoding( System.Text.Encoding.GetEncoding( encoding ) ); } /// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType( HttpContentType contentType ) { return ContentType( contentType.Description() ); } /// <summary> /// 设置内容类型 /// </summary> /// <param name="contentType">内容类型</param> public TRequest ContentType( string contentType ) { _contentType = contentType; return This(); } /// <summary> /// 返回自身 /// </summary> private TRequest This() { return (TRequest)(object)this; } /// <summary> /// 设置Cookie /// </summary> /// <param name="name">名称</param> /// <param name="value">值</param> /// <param name="expiresDate">有效时间,单位:天</param> public TRequest Cookie( string name, string value, double expiresDate ) { return Cookie( name, value, null, null, DateTime.Now.AddDays( expiresDate ) ); } /// <summary> /// 设置Cookie /// </summary> /// <param name="name">名称</param> /// <param name="value">值</param> /// <param name="expiresDate">到期时间</param> public TRequest Cookie( string name, string value, DateTime expiresDate ) { return Cookie( name, value, null, null, expiresDate ); } /// <summary> /// 设置Cookie /// </summary> /// <param name="name">名称</param> /// <param name="value">值</param> /// <param name="path">源服务器URL子集</param> /// <param name="domain">所属域</param> /// <param name="expiresDate">到期时间</param> public TRequest Cookie( string name, string value, string path = "/", string domain = null, DateTime? expiresDate = null ) { return Cookie( new Cookie( name, value, path, domain ) { Expires = expiresDate ?? DateTime.Now.AddYears( 1 ) } ); } /// <summary> /// 设置Cookie /// </summary> /// <param name="cookie">cookie</param> public TRequest Cookie( Cookie cookie ) { _cookieContainer.Add( new Uri( _url ), cookie ); return This(); } /// <summary> /// 超时时间 /// </summary> /// <param name="timeout">超时时间</param> public TRequest Timeout( int timeout ) { _timeout = new TimeSpan( 0, 0, timeout ); return This(); } /// <summary> /// 请求头 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public TRequest Header<T>( string key, T value ) { _headers.Add( key, value.SafeString() ); return This(); } /// <summary> /// 添加参数字典 /// </summary> /// <param name="parameters">参数字典</param> public TRequest Data( IDictionary<string, object> parameters ) { _params = parameters ?? throw new ArgumentNullException( nameof( parameters ) ); return This(); } /// <summary> /// 添加参数 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public TRequest Data( string key, object value ) { if( string.IsNullOrWhiteSpace( key ) ) throw new ArgumentNullException( nameof( key ) ); if( string.IsNullOrWhiteSpace( value.SafeString() ) ) return This(); _params.Add( key, value ); return This(); } /// <summary> /// 添加URL参数 /// </summary> /// <param name="key">键</param> /// <param name="value">值</param> public TRequest UrlData(string key, object value) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException(nameof(key)); if (string.IsNullOrWhiteSpace(value.SafeString())) return This(); _urlParams.Add(key, value); return This(); } /// <summary> /// 添加Json参数 /// </summary> /// <param name="value">值</param> public TRequest JsonData<T>( T value ) { ContentType( HttpContentType.Json ); _data = Json.ToJson( value ); return This(); } /// <summary> /// 添加Xml参数 /// </summary> /// <param name="value">值</param> public TRequest XmlData( string value ) { ContentType( HttpContentType.Xml ); _data = value; return This(); } /// <summary> /// 请求失败回调函数 /// </summary> /// <param name="action">执行失败的回调函数,参数为响应结果</param> public TRequest OnFail( Action<string> action ) { _failAction = action; return This(); } /// <summary> /// 请求失败回调函数 /// </summary> /// <param name="action">执行失败的回调函数,第一个参数为响应结果,第二个参数为状态码</param> public TRequest OnFail( Action<string, HttpStatusCode> action ) { _failStatusCodeAction = action; return This(); } /// <summary> /// 忽略Ssl /// </summary> public TRequest IgnoreSsl() { _serverCertificateCustomValidationCallback = ( a, b, c, d ) => true; return This(); } /// <summary> /// 设置Bearer令牌 /// </summary> /// <param name="token">令牌</param> public TRequest BearerToken( string token ) { _token = token; return This(); } #endregion #region ResultAsync(获取结果) /// <summary> /// 获取结果 /// </summary> public async Task<string> ResultAsync() { SendBefore(); var response = await SendAsync(); var result = await response.Content.ReadAsStringAsync(); SendAfter( result, response ); HttpTrace(); return result; } /// <summary> /// 请求跟踪 /// </summary> private void HttpTrace() { //调试信息 System.Diagnostics.Debug.WriteLine($"{_httpMethod.Method}|{_url}"); System.Diagnostics.Debug.WriteLine($"{Parameter()}"); } /// <summary> /// 参数Json格式 /// </summary> /// <returns></returns> public String Parameter() { if(this._httpMethod == HttpMethod.Get){ return Json.ToJson(_urlParams); } else { if(_contentType == HttpContentType.FormUrlEncoded.Description()){ return Json.ToJson(_params); } else{ return _data; } } } /// <summary> /// 请求地址 /// </summary> /// <returns></returns> public String Url() { return _url; } #endregion #region SendBefore(发送前操作) /// <summary> /// 发送前操作 /// </summary> protected virtual void SendBefore() { } #endregion #region SendAsync(发送请求) /// <summary> /// 发送请求 /// </summary> protected async Task<HttpResponseMessage> SendAsync() { var client = CreateHttpClient(); InitHttpClient( client ); var requestMessage = CreateRequestMessage(); var responseMessage = await client.SendAsync(requestMessage); return responseMessage; } /// <summary> /// 创建Http客户端 /// </summary> protected virtual HttpClient CreateHttpClient() { return new HttpClient( new HttpClientHandler { CookieContainer = _cookieContainer, ServerCertificateCustomValidationCallback = _serverCertificateCustomValidationCallback } ) { Timeout = _timeout }; } /// <summary> /// 初始化Http客户端 /// </summary> /// <param name="client">Http客户端</param> protected virtual void InitHttpClient( HttpClient client ) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token}"); //client.SetBearerToken( _token ); } /// <summary> /// 创建请求消息 /// </summary> protected virtual HttpRequestMessage CreateRequestMessage() { var message = new HttpRequestMessage { Method = _httpMethod, RequestUri = CreateRequestUri(_httpMethod,_url ), Content = CreateHttpContent(_httpMethod) }; foreach( var header in _headers ) message.Headers.Add( header.Key, header.Value ); return message; } /// <summary> /// 创建请求URI /// </summary> /// <param name="httpMethod">请求方式</param> /// <param name="url">地址</param> /// <returns></returns> private Uri CreateRequestUri(HttpMethod httpMethod, String url) { var urlParams = String.Empty; foreach (var keyValue in _urlParams) { urlParams += $"&{keyValue.Key}={keyValue.Value}"; } if (!String.IsNullOrEmpty(urlParams)) { _url = $"{url}?{urlParams.Substring(1)}"; } return new Uri(_url); } /// <summary> /// 创建请求内容 /// </summary> private HttpContent CreateHttpContent(HttpMethod httpMethod) { if(httpMethod == HttpMethod.Get) { return null; } var contentType = _contentType.SafeString().ToLower(); switch( contentType ) { case "application/x-www-form-urlencoded": return new FormUrlEncodedContent( _params.ToDictionary( t => t.Key, t => t.Value.SafeString() ) ); case "application/json": return CreateJsonContent(); case "text/xml": return CreateXmlContent(); } throw new NotImplementedException( "ContentType not implemented" ); } /// <summary> /// 创建json内容 /// </summary> private HttpContent CreateJsonContent() { if( string.IsNullOrWhiteSpace( _data ) ) _data = Json.ToJson( _params ); return new StringContent( _data, _encoding, "application/json" ); } /// <summary> /// 创建xml内容 /// </summary> private HttpContent CreateXmlContent() { return new StringContent( _data, _encoding, "text/xml" ); } #endregion #region SendAfter(发送后操作) /// <summary> /// 发送后操作 /// </summary> protected virtual void SendAfter( string result, HttpResponseMessage response ) { var contentType = GetContentType( response ); if( response.IsSuccessStatusCode ) { SuccessHandler( result, response.StatusCode, contentType ); return; } FailHandler( result, response.StatusCode, contentType ); } /// <summary> /// 获取内容类型 /// </summary> private string GetContentType( HttpResponseMessage response ) { return response?.Content?.Headers?.ContentType == null ? string.Empty : response.Content.Headers.ContentType.MediaType; } /// <summary> /// 成功处理操作 /// </summary> protected virtual void SuccessHandler( string result, HttpStatusCode statusCode, string contentType ) { } /// <summary> /// 失败处理操作 /// </summary> protected virtual void FailHandler( string result, HttpStatusCode statusCode, string contentType ) { _failAction?.Invoke( result ); _failStatusCodeAction?.Invoke( result, statusCode ); } #endregion } }
30.641326
136
0.513646
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
keith-leung/celia.utilities
Celia.io.Core.MicroServices.Utilities/Webs/Clients/HttpRequestBase.cs
16,511
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Storage.V20160501.Inputs { /// <summary> /// The custom domain assigned to this storage account. This can be set via Update. /// </summary> public sealed class CustomDomainArgs : Pulumi.ResourceArgs { /// <summary> /// Gets or sets the custom domain name assigned to the storage account. Name is the CNAME source. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates. /// </summary> [Input("useSubDomainName")] public Input<bool>? UseSubDomainName { get; set; } public CustomDomainArgs() { } } }
32.314286
127
0.648099
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Storage/V20160501/Inputs/CustomDomainArgs.cs
1,131
C#
namespace Machete.X12Schema.V5010 { using X12; public interface W10 : X12Segment { Value<string> UnitLoadOptionCode { get; } Value<int> QuantityOfPalletsShipped { get; } Value<string> PalletExchangeCode { get; } Value<string> SealNumber1 { get; } Value<string> SealNumber2 { get; } Value<string> Temperature1 { get; } Value<string> UnitOrBasisOfMeasurementCode1 { get; } Value<string> Temperature2 { get; } Value<string> UnitOrBasisOfMeasurementCode2 { get; } } }
23.444444
60
0.557662
[ "Apache-2.0" ]
ahives/Machete
src/Machete.X12Schema/V5010/Segments/W10.cs
633
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("Problem 2.Sort ArrayUsing Selection Sort")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem 2.Sort ArrayUsing Selection Sort")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6f65ccb8-ac04-4022-863a-66ae182c22b0")] // 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")]
39.27027
84
0.748107
[ "MIT" ]
Supbads/Softuni-Education
01. AdvancedCSharp 09.15/Homework 1 Arrays,Lists,Stacks,Queues/Problem 2.Sort ArrayUsing Selection Sort/Properties/AssemblyInfo.cs
1,456
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20190201.Outputs { [OutputType] public sealed class ExpressRouteCircuitSkuResponse { /// <summary> /// The family of the SKU. Possible values are: 'UnlimitedData' and 'MeteredData'. /// </summary> public readonly string? Family; /// <summary> /// The name of the SKU. /// </summary> public readonly string? Name; /// <summary> /// The tier of the SKU. Possible values are 'Standard', 'Premium' or 'Local'. /// </summary> public readonly string? Tier; [OutputConstructor] private ExpressRouteCircuitSkuResponse( string? family, string? name, string? tier) { Family = family; Name = name; Tier = tier; } } }
27.046512
90
0.594153
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20190201/Outputs/ExpressRouteCircuitSkuResponse.cs
1,163
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("14.IntegerCalculations")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("14.IntegerCalculations")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("40651843-41d4-4546-b908-0d851cf0b79c")] // 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.297297
84
0.747354
[ "MIT" ]
adachenski/CSharpPart2-Homeworks
Homework-Methods/14.IntegerCalculations/Properties/AssemblyInfo.cs
1,420
C#
using DotNetNuke.Entities.Modules; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Telerik.Web.UI; namespace BankProject.Views.TellerApplication { public partial class CashWithdrawalPreviewList : PortalModuleBase { protected void Page_Load(object sender, EventArgs e) { } private void LoadData() { radGridReview.DataSource = BankProject.DataProvider.Database.BCASHWITHRAWAL_GetbyStatus("UNA", this.UserId.ToString()); } protected void radGridReview_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e) { this.LoadData(); } } }
27.571429
132
0.67228
[ "Apache-2.0", "BSD-3-Clause" ]
nguyenppt/biscorebanksys
DesktopModules/TrainingCoreBanking/BankProject/Views/TellerApplication/CashWithdrawalPreviewList.ascx.cs
774
C#
/* MIT License Copyright (c) 2017 Lewis Johnson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using UnityEngine; namespace Assets.ScreenSpace.Offset.Scripts { [AddComponentMenu("Scripts/Offset/OffsetUI")] public class OffestUI : MonoBehaviour { [Range(5, 50)] public int BlackbarPercentage = 20; public bool ControllerOffset; public bool InvertOffset = true; [Range(0, 100)] public int Sensitivity = 50; public float XClampMax = 50; public float YClampMax = 50; public void FixedUpdate() { RefreshUI(); if (Input.GetJoystickNames().Length >= 1 && ControllerOffset) { float horz = Input.GetAxis("Horizontal"); float vert = Input.GetAxis("Vertical"); Vector3 controllerDir = new Vector3(horz, vert, 0); if (InvertOffset) { controllerDir = -controllerDir; } controllerDir.x *= Sensitivity; controllerDir.y *= Sensitivity; GetComponent<RectTransform>().localPosition = controllerDir; } else { Vector3 mouseDir = Camera.main.ScreenPointToRay(Input.mousePosition).direction; if (InvertOffset) { mouseDir = -mouseDir; } mouseDir.x *= Sensitivity; mouseDir.y *= Sensitivity; mouseDir.x = Mathf.Clamp(mouseDir.x, -XClampMax, XClampMax); mouseDir.y = Mathf.Clamp(mouseDir.y, -YClampMax, YClampMax); GetComponent<RectTransform>().localPosition = mouseDir; } } public void Start() { RefreshUI(); } private void RefreshUI() { int screenW = Screen.width; int screenH = Screen.height; double blackbarHeight = (double)BlackbarPercentage / 100 * screenH; int blackbarWidth = Mathf.RoundToInt(GetComponent<RectTransform>().sizeDelta.x) + Sensitivity * 2; GetComponent<RectTransform>().sizeDelta = new Vector2(screenW, screenH); // Can be replaced by transform.find("TopPanel") if you want to move the children. RectTransform topPanelRectTransform = transform.GetChild(0).GetComponent<RectTransform>(); // Can be replaced by transform.find("BottomPanel") if you want to move the children. RectTransform bottomPanelRectTransform = transform.GetChild(1).GetComponent<RectTransform>(); topPanelRectTransform.sizeDelta = new Vector2(blackbarWidth, (int)blackbarHeight); topPanelRectTransform.anchoredPosition = new Vector3(0, (int)-(blackbarHeight / 2), 0); bottomPanelRectTransform.sizeDelta = new Vector2(blackbarWidth, (int)blackbarHeight); bottomPanelRectTransform.anchoredPosition = new Vector3(0, (int)(blackbarHeight / 2), 0); } } }
39.959596
110
0.653943
[ "MIT" ]
Chapmania/unity-ui-examples
Assets/ScreenSpace/Offset/Scripts/OffestUI.cs
3,958
C#
/* * Copyright (c) 2003-2006, University of Maryland * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the University of Maryland nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Piccolo was written at the Human-Computer Interaction Laboratory www.cs.umd.edu/hcil by Jesse Grosjean * and ported to C# by Aaron Clamage under the supervision of Ben Bederson. The Piccolo website is * www.cs.umd.edu/hcil/piccolo. */ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using UMD.HCIL.Piccolo; using UMD.HCIL.Piccolo.Nodes; using UMD.HCIL.PiccoloX.Activities; namespace UMD.HCIL.PiccoloFeatures { public class PositionPathActivityExample : UMD.HCIL.PiccoloX.PForm { private System.ComponentModel.IContainer components = null; public PositionPathActivityExample() { // This call is required by the Windows Form Designer. InitializeComponent(); } public override void Initialize() { PLayer layer = Canvas.Layer; PNode animatedNode = PPath.CreateRectangle(0, 0, 100, 80); layer.AddChild(animatedNode); // create node to display animation path PPath ppath = new PPath(); // create animation path ppath.AddLine(0, 0, 300, 300); ppath.AddLine(300, 300, 300, 0); ppath.AddArc(0, 0, 300, 300, -90, 90); ppath.CloseFigure(); // add the path to the scene graph layer.AddChild(ppath); PPositionPathActivity positionPathActivity = new PPositionPathActivity(5000, 0, new PositionPathTarget(animatedNode)); positionPathActivity.PositionPath = (GraphicsPath)ppath.PathReference.Clone(); positionPathActivity.LoopCount = int.MaxValue; // add the activity animatedNode.AddActivity(positionPathActivity); } class PositionPathTarget : PPositionPathActivity.Target { PNode node; public PositionPathTarget(PNode node) { this.node = node; } public void SetPosition(float x, float y) { node.SetOffset(x, y); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // PositionPathActivityExample // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(392, 373); this.Location = new System.Drawing.Point(0, 0); this.Name = "PositionPathActivityExample"; this.Text = "PositionPathActivityExample"; } #endregion } }
36.905983
122
0.718157
[ "Unlicense" ]
mro/piccolo2d.net
Samples/Piccolo Features/Source/PositionPathActivityExample.cs
4,318
C#
using System; namespace Database.GraphQl { public record FileMetaInformationInput( string[] Path, Guid DataFormatId ); }
16.555556
43
0.651007
[ "MIT" ]
building-envelope-data/database
backend/src/GraphQl/FileMetaInformationInput.cs
149
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Serialization; using FubuCore.Logging; using FubuCore.Util; using FubuTransportation.Runtime; using FubuTransportation.Runtime.Delayed; using LightningQueues; using LightningQueues.Model; namespace FubuTransportation.LightningQueues { public class PersistentQueues : IPersistentQueues { private readonly ILogger _logger; private readonly IDelayedMessageCache<MessageId> _delayedMessages; private readonly QueueManagerConfiguration _queueManagerConfiguration; public const string EsentPath = "fubutransportation.esent"; private readonly Cache<int, QueueManager> _queueManagers; public PersistentQueues(ILogger logger, IDelayedMessageCache<MessageId> delayedMessages, LightningQueueSettings settings) { _logger = logger; _delayedMessages = delayedMessages; _queueManagerConfiguration = settings.ToConfiguration(); _queueManagers = new Cache<int, QueueManager>(port => new QueueManager(new IPEndPoint(IPAddress.Any, port), EsentPath + "." + port, _queueManagerConfiguration)); } public void Dispose() { _queueManagers.Each(x => x.Dispose()); } public IEnumerable<IQueueManager> AllQueueManagers { get { return _queueManagers.GetAll(); } } public void ClearAll() { _queueManagers.Each(x => x.ClearAllMessages()); } public IQueueManager ManagerFor(int port, bool incoming) { if (incoming) { return _queueManagers[port]; } return _queueManagers.First(); } public IQueueManager ManagerForReply() { return _queueManagers.First(); } public void Start(IEnumerable<LightningUri> uriList) { uriList.GroupBy(x => x.Port).Each(group => { try { string[] queueNames = group.Select(x => x.QueueName).ToArray(); var queueManager = _queueManagers[@group.Key]; queueManager.CreateQueues(queueNames); queueManager.CreateQueues(LightningQueuesTransport.DelayedQueueName); queueManager.CreateQueues(LightningQueuesTransport.ErrorQueueName); queueManager.Start(); RecoverDelayedMessages(queueManager); } catch (Exception e) { throw new LightningQueueTransportException(new IPEndPoint(IPAddress.Any, group.Key), e); } }); } private void RecoverDelayedMessages(QueueManager queueManager) { queueManager.GetQueue(LightningQueuesTransport.DelayedQueueName) .GetAllMessages(null) .Each(x => _delayedMessages.Add(x.Id, x.ExecutionTime())); } public void CreateQueue(LightningUri uri) { _queueManagers[uri.Port].CreateQueues(uri.QueueName); } public IEnumerable<EnvelopeToken> ReplayDelayed(DateTime currentTime) { return _queueManagers.SelectMany(x => ReplayDelayed(x, currentTime)); } public IEnumerable<EnvelopeToken> ReplayDelayed(QueueManager queueManager, DateTime currentTime) { var list = new List<EnvelopeToken>(); var transactionalScope = queueManager.BeginTransactionalScope(); try { var readyToSend = _delayedMessages.AllMessagesBefore(currentTime); readyToSend.Each(x => { var message = transactionalScope.ReceiveById(LightningQueuesTransport.DelayedQueueName, x); var uri = message.Headers[Envelope.ReceivedAtKey].ToLightningUri(); transactionalScope.EnqueueDirectlyTo(uri.QueueName, message.ToPayload()); list.Add(message.ToToken()); }); transactionalScope.Commit(); } catch (Exception e) { transactionalScope.Rollback(); _logger.Error("Error trying to move delayed messages back to the original queue", e); } return list; } } [Serializable] public class LightningQueueTransportException : Exception { public LightningQueueTransportException(IPEndPoint endpoint, Exception innerException) : base("Error trying to initialize LightningQueues queue manager at " + endpoint, innerException) { } protected LightningQueueTransportException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
36.722628
193
0.599284
[ "Apache-2.0" ]
DarthFubuMVC/FubuTransportation
src/FubuTransportation.LightningQueues/PersistentQueues.cs
5,031
C#
namespace Lavalink4NET.Tests { using System; using Lavalink4NET.MemoryCache; using Xunit; /// <summary> /// Contains tests for the <see cref="LavalinkCache"/> class. /// </summary> public class MemoryCacheTests { /// <summary> /// Tests the memory cache. /// </summary> [Fact] public void TestMemoryCache() { using (var cache = new LavalinkCache()) { // no item in cache Assert.False(cache.TryGetItem<string>("key", out _)); // add item to cache cache.AddItem("key", string.Empty, DateTimeOffset.UtcNow + TimeSpan.FromSeconds(10)); // item in cache Assert.True(cache.TryGetItem<string>("key", out _)); } } } }
27.258065
101
0.512426
[ "MIT" ]
Erwin-J/Lavalink4NET
src/Lavalink4NET.Tests/MemoryCacheTests.cs
847
C#
/* JustMock Lite Copyright © 2010-2015 Progress Software Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; #region JustMock Test Attributes #if NUNIT using NUnit.Framework; using TestCategory = NUnit.Framework.CategoryAttribute; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using AssertionException = NUnit.Framework.AssertionException; #elif XUNIT using Xunit; using Telerik.JustMock.XUnit.Test.Attributes; using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute; using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute; using TestMethod = Xunit.FactAttribute; using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute; using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute; using AssertionException = Telerik.JustMock.XUnit.AssertFailedException; #elif VSTEST_PORTABLE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException; #else using Microsoft.VisualStudio.TestTools.UnitTesting; using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException; #endif #endregion namespace Telerik.JustMock.Tests.Coverage { [TestClass] public class DoInsteadFixture { [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithFiveArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5) => { expected = arg1 + arg2 + arg3 + arg4 + arg5; }); foo.Submit(1, 1, 1, 1, 1); Assert.Equal(5, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithSixArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6; }); foo.Submit(1, 1, 1, 1, 1, 1); Assert.Equal(6, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithSevenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7; }); foo.Submit(1, 1, 1, 1, 1, 1, 1); Assert.Equal(7, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithEightArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(8, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithNineArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(9, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithTenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(10, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithElevenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(11, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithTwelveArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(12, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithThirteenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(13, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithFourteenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(14, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithFifteenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(15, expected); } [TestMethod, TestCategory("Lite"), TestCategory("Mock")] public void ShouldAssertDoInsteadWithSixteenArgsForExpected() { int expected = 0; var foo = Mock.Create<IFoo>(); Mock.Arrange(() => foo.Submit(Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt, Arg.AnyInt)) .DoInstead((int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16) => { expected = arg1 + arg2 + arg3 + arg4 + arg5 + arg6 + arg7 + arg8 + arg9 + arg10 + arg11 + arg12 + arg13 + arg14 + arg15 + arg16; }); foo.Submit(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); Assert.Equal(16, expected); } public interface IFoo { void Submit(int arg1, int arg2, int arg3, int arg4, int arg5); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15); void Submit(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7, int arg8, int arg9, int arg10, int arg11, int arg12, int arg13, int arg14, int arg15, int arg16); } } }
44.350195
320
0.685822
[ "Apache-2.0" ]
telerik/JustMockLite
Telerik.JustMock.Tests/Coverage/DoInsteadFixture.cs
11,401
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> //------------------------------------------------------------------------------ // Source Executable: c:\windows\system32\appvshnotify.exe // Interface ID: 7f89f606-468e-4ee4-b1f3-73b68767b0e1 // Interface Version: 1.0 namespace rpc_7f89f606_468e_4ee4_b1f3_73b68767b0e1_1_0 { #region Marshal Helpers internal class _Marshal_Helper : NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer { } internal class _Unmarshal_Helper : NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer { public _Unmarshal_Helper(NtApiDotNet.Win32.Rpc.RpcClientResponse r) : base(r.NdrBuffer, r.Handles, r.DataRepresentation) { } public _Unmarshal_Helper(byte[] ba) : base(ba) { } } #endregion #region Client Implementation public sealed class Client : NtApiDotNet.Win32.Rpc.RpcClientBase { public Client() : base("7f89f606-468e-4ee4-b1f3-73b68767b0e1", 1, 0) { } private _Unmarshal_Helper SendReceive(int p, _Marshal_Helper m) { return new _Unmarshal_Helper(SendReceive(p, m.DataRepresentation, m.ToArray(), m.Handles)); } public void s_IShellExtensionNotify_ShellNotify(out long p0) { _Marshal_Helper m = new _Marshal_Helper(); _Unmarshal_Helper u = SendReceive(0, m); p0 = u.ReadInt64(); } } #endregion }
31.927273
103
0.578018
[ "Unlicense" ]
ExpLife0011/WindowsRpcClients
Win10_20H1/appvshnotify.exe/7f89f606-468e-4ee4-b1f3-73b68767b0e1_1.0.cs
1,756
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace OctoAwesome.Threading { public class CountedScopeSemaphore : IDisposable { private readonly ManualResetEventSlim superLock; private readonly ManualResetEventSlim mainLock; private readonly object lockObject; private readonly object countLockObject; private int counter; public CountedScopeSemaphore() { mainLock = new ManualResetEventSlim(true); superLock = new ManualResetEventSlim(true); lockObject = new object(); countLockObject = new object(); } public SuperScope Wait() { lock (lockObject) { mainLock.Wait(); superLock.Reset(); } return new SuperScope(this); } public CountScope EnterScope() { lock (lockObject) { superLock.Wait(); lock (countLockObject) { counter++; if (counter > 0) mainLock.Reset(); } } return new CountScope(this); } public void Dispose() { superLock.Dispose(); mainLock.Dispose(); } private void LeaveMainScope() { lock (countLockObject) { counter--; if (counter == 0) mainLock.Set(); } } private void LeaveSuperScope() { superLock.Set(); } public readonly struct CountScope : IDisposable, IEquatable<CountScope> { public static CountScope Empty => new CountScope(null); private readonly CountedScopeSemaphore internalSemaphore; public CountScope(CountedScopeSemaphore countingSemaphore) { internalSemaphore = countingSemaphore; } public void Dispose() { internalSemaphore?.LeaveMainScope(); } public override bool Equals(object obj) => obj is CountScope scope && Equals(scope); public bool Equals(CountScope other) => EqualityComparer<CountedScopeSemaphore>.Default.Equals(internalSemaphore, other.internalSemaphore); public override int GetHashCode() => 37286538 + EqualityComparer<CountedScopeSemaphore>.Default.GetHashCode(internalSemaphore); public static bool operator ==(CountScope left, CountScope right) => left.Equals(right); public static bool operator !=(CountScope left, CountScope right) => !(left == right); } public readonly struct SuperScope : IDisposable, IEquatable<SuperScope> { public static SuperScope Empty => new SuperScope(null); private readonly CountedScopeSemaphore internalSemaphore; public SuperScope(CountedScopeSemaphore semaphore) { internalSemaphore = semaphore; } public void Dispose() { internalSemaphore?.LeaveSuperScope(); } public override bool Equals(object obj) => obj is SuperScope scope && Equals(scope); public bool Equals(SuperScope other) => EqualityComparer<CountedScopeSemaphore>.Default.Equals(internalSemaphore, other.internalSemaphore); public override int GetHashCode() => 37296538 + EqualityComparer<CountedScopeSemaphore>.Default.GetHashCode(internalSemaphore); public static bool operator ==(SuperScope left, SuperScope right) => left.Equals(right); public static bool operator !=(SuperScope left, SuperScope right) => !(left == right); } } }
30.886364
118
0.559725
[ "MIT" ]
OctoAwesome/octoawesome
OctoAwesome/OctoAwesome/Threading/CountedScopeSemaphore.cs
4,079
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ResultType { public class AttemptedToUnwrapUncheckedResultException : Exception { } }
17.384615
70
0.774336
[ "MIT" ]
Winwardo/ResultType
ResultType/Exceptions/AttemptedToUnwrapUncheckedResultException.cs
228
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File Microsoft.Win32.SafeHandles.SafeNCryptHandle.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace Microsoft.Win32.SafeHandles { abstract public partial class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid { #region Methods and constructors protected override bool ReleaseHandle() { return default(bool); } protected abstract bool ReleaseNativeHandle(); protected SafeNCryptHandle() : base (default(bool)) { } #endregion } }
41.824561
463
0.768876
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/System.Core/Sources/Microsoft.Win32.SafeHandles.SafeNCryptHandle.cs
2,384
C#
// Copyright © 2018, Meta Company. All rights reserved. // // Redistribution and use of this software (the "Software") in binary form, without modification, is // permitted provided that the following conditions are met: // // 1. Redistributions of the unmodified Software 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. // 2. The name of Meta Company (“Meta”) may not be used to endorse or promote products derived // from this Software without specific prior written permission from Meta. // 3. LIMITATION TO META PLATFORM: Use of the Software is limited to use on or in connection // with Meta-branded devices or Meta-branded software development kits. For example, a bona // fide recipient of the Software may incorporate an unmodified binary version of the // Software into an application limited to use on or in connection with a Meta-branded // device, while he or she may not incorporate an unmodified binary version of the Software // into an application designed or offered for use on a non-Meta-branded device. // // For the sake of clarity, the Software may not be redistributed under any circumstances in source // code form, or in the form of modified binary code – and nothing in this License shall be construed // to permit such redistribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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 META COMPANY 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 UnityEngine; namespace Meta.Reconstruction { /// <summary> /// Auto selects the default environment profile. /// </summary> public class DefaultEnvironmentProfileSelector : IEnvironmentProfileSelector { private readonly IEnvironmentProfileRepository _environmentProfileRepository; private readonly ISlamChecker _slamChecker; private readonly EnvironmentSelectionResultTypeEvent _environmentSelected = new EnvironmentSelectionResultTypeEvent(); private IEnvironmentProfile _defaultEnvironmentProfile; /// <summary> /// Occurs when an environment profile is selected. /// </summary> public EnvironmentSelectionResultTypeEvent EnvironmentSelected { get { return _environmentSelected; } } /// <summary> /// Creates an instance of <see cref="DefaultEnvironmentProfileSelector"/> class. /// </summary> /// <param name="environmentProfileRepository">Repository to access to the environment profiles.</param> /// <param name="slamChecker">Object to check if an slam map can be localized.</param> public DefaultEnvironmentProfileSelector(IEnvironmentProfileRepository environmentProfileRepository, ISlamChecker slamChecker) { if (environmentProfileRepository == null) { throw new ArgumentNullException("environmentProfileRepository"); } if (slamChecker == null) { throw new ArgumentNullException("slamChecker"); } _environmentProfileRepository = environmentProfileRepository; _slamChecker = slamChecker; } /// <summary> /// Selects an environment profile. /// </summary> public void Select() { Read(); FinishReading(); } /// <summary> /// Resets the environment profile selection. /// </summary> public void Reset() { if (_slamChecker != null) { _slamChecker.Stop(); } _environmentSelected.Invoke(EnvironmentSelectionResultTypeEvent.EnvironmentSelectionResultType.NewEnvironment); } private void Read() { _environmentProfileRepository.Read(); _defaultEnvironmentProfile = _environmentProfileRepository.GetDefault(); } private void FinishReading() { //If there is no default environment profile, or if it is not valid, just skip automatically and return to start creating one. if (_defaultEnvironmentProfile == null || !_environmentProfileRepository.Verify(_defaultEnvironmentProfile.Id)) { if (_environmentSelected != null) { _environmentSelected.Invoke(EnvironmentSelectionResultTypeEvent.EnvironmentSelectionResultType.NewEnvironment); } } else { //Otherwise, lets select the first one. SelectEnvironment(_defaultEnvironmentProfile); } } private void SelectEnvironment(IEnvironmentProfile environmentProfile) { _slamChecker.TryLocalizeMap(environmentProfile.MapName, (ok) => { if (ok) { _environmentProfileRepository.Select(environmentProfile.Id); } _environmentSelected.Invoke(ok ? EnvironmentSelectionResultTypeEvent.EnvironmentSelectionResultType.SelectedEnvironment : EnvironmentSelectionResultTypeEvent.EnvironmentSelectionResultType.NewEnvironment); }); } } }
45.878788
221
0.665621
[ "MIT" ]
JDZ-3/MXRManipulation
Assets/MetaSDK/Meta/Reconstruction/Scripts/Selection/DefaultEnvironmentProfileSelector.cs
6,073
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ShellAction { public interface IShell { bool CanHandle(string[] args); bool ExecuteAction(string[] args); string ShowUsage(); } }
16.444444
42
0.679054
[ "MIT" ]
raffaeler/InteropExperiments
WindowsAPISolution/ShellAction/IShell.cs
298
C#
// Copyright 2017 the original author or authors. // // 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. using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Linq; namespace Steeltoe.Management.Endpoint.Hypermedia { public static class EndpointServiceCollectionExtensions { public static void AddHypermediaActuator(this IServiceCollection services, IConfiguration config) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (config == null) { throw new ArgumentNullException(nameof(config)); } services.TryAddEnumerable(ServiceDescriptor.Singleton<IManagementOptions>(new ActuatorManagementOptions(config))); services.TryAddSingleton<IActuatorHypermediaOptions>(provider => { var mgmtOptions = provider .GetServices<IManagementOptions>().Single(m => m.GetType() == typeof(ActuatorManagementOptions)); var opts = new HypermediaEndpointOptions(config); mgmtOptions.EndpointOptions.Add(opts); return opts; }); services.TryAddSingleton<ActuatorEndpoint>(); } } }
36.596154
126
0.676826
[ "Apache-2.0" ]
FrancisChung/steeltoe
src/Management/src/EndpointCore/Hypermedia/EndpointServiceCollectionExtensions.cs
1,905
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 codedeploy-2014-10-06.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CodeDeploy.Model { ///<summary> /// CodeDeploy exception /// </summary> public class InvalidAutoScalingGroupException : AmazonCodeDeployException { /// <summary> /// Constructs a new InvalidAutoScalingGroupException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidAutoScalingGroupException(string message) : base(message) {} public InvalidAutoScalingGroupException(string message, Exception innerException) : base(message, innerException) {} public InvalidAutoScalingGroupException(Exception innerException) : base(innerException) {} public InvalidAutoScalingGroupException(string message, Exception innerException, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, RequestId, statusCode) {} public InvalidAutoScalingGroupException(string message, ErrorType errorType, string errorCode, string RequestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, RequestId, statusCode) {} } }
39.339623
174
0.692566
[ "Apache-2.0" ]
samritchie/aws-sdk-net
AWSSDK_DotNet35/Amazon.CodeDeploy/Model/InvalidAutoScalingGroupException.cs
2,085
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #pragma warning disable 1998 using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace ICSharpCode.Decompiler.Tests.TestCases.Pretty { public class Async { private int memberField; public async void SimpleVoidMethod() { Console.WriteLine("Before"); await Task.Delay(TimeSpan.FromSeconds(1.0)); Console.WriteLine("After"); } public async void VoidMethodWithoutAwait() { Console.WriteLine("No Await"); } public async void EmptyVoidMethod() { } public async void AwaitYield() { await Task.Yield(); } public async void AwaitDefaultYieldAwaitable() { await default(YieldAwaitable); } public async void AwaitDefaultHopToThreadPool() { // unlike YieldAwaitable which implements ICriticalNotifyCompletion, // the HopToThreadPoolAwaitable struct only implements // INotifyCompletion, so this results in different codegen await default(HopToThreadPoolAwaitable); } public async Task SimpleVoidTaskMethod() { Console.WriteLine("Before"); await Task.Delay(TimeSpan.FromSeconds(1.0)); Console.WriteLine("After"); } public async Task TaskMethodWithoutAwait() { Console.WriteLine("No Await"); } public async Task CapturingThis() { await Task.Delay(memberField); } public async Task CapturingThisWithoutAwait() { Console.WriteLine(memberField); } public async Task<bool> SimpleBoolTaskMethod() { Console.WriteLine("Before"); await Task.Delay(TimeSpan.FromSeconds(1.0)); Console.WriteLine("After"); return true; } public async void TwoAwaitsWithDifferentAwaiterTypes() { Console.WriteLine("Before"); if (await SimpleBoolTaskMethod()) { await Task.Delay(TimeSpan.FromSeconds(1.0)); } Console.WriteLine("After"); } public async void AwaitInLoopCondition() { while (await SimpleBoolTaskMethod()) { Console.WriteLine("Body"); } } #if CS60 public async Task AwaitInCatch(bool b, Task<int> task1, Task<int> task2) { try { Console.WriteLine("Start try"); await task1; Console.WriteLine("End try"); } catch (Exception) { if (!b) { await task2; } else { Console.WriteLine("No await"); } } } public async Task AwaitInFinally(bool b, Task<int> task1, Task<int> task2) { try { Console.WriteLine("Start try"); await task1; Console.WriteLine("End try"); } finally { if (!b) { await task2; } else { Console.WriteLine("No await"); } } } #endif public static async Task<int> GetIntegerSumAsync(IEnumerable<int> items) { await Task.Delay(100); int num = 0; foreach (int item in items) { num += item; } return num; } public static Func<Task<int>> AsyncLambda() { return async () => await GetIntegerSumAsync(new int[3] { 1, 2, 3 }); } public static Func<Task<int>> AsyncDelegate() { return async delegate { await Task.Delay(10); return 2; }; } public static async Task AlwaysThrow() { throw null; } public static async Task InfiniteLoop() { while (true) { } } public static async Task InfiniteLoopWithAwait() { while (true) { await Task.Delay(10); } } public async Task AsyncWithLocalVar() { object a = new object(); #if CS70 (object, string) tuple = (new object(), "abc"); #endif await UseObj(a); await UseObj(a); #if CS70 await UseObj(tuple); #endif } public static async Task UseObj(object a) { } #if CS70 public static async Task<int> AsyncLocalFunctions() { return await Nested(1) + await Nested(2); #if CS80 static async Task<int> Nested(int i) #else async Task<int> Nested(int i) #endif { await Task.Delay(i); return i; } } #endif } public struct AsyncInStruct { private int i; public async Task<int> Test(AsyncInStruct xx) { xx.i++; i++; await Task.Yield(); return i + xx.i; } } public struct HopToThreadPoolAwaitable : INotifyCompletion { public bool IsCompleted { get; set; } public HopToThreadPoolAwaitable GetAwaiter() { return this; } public void OnCompleted(Action continuation) { Task.Run(continuation); } public void GetResult() { } } }
21.081395
93
0.681008
[ "MIT" ]
zer0Kerbal/ILSpy
ICSharpCode.Decompiler.Tests/TestCases/Pretty/Async.cs
5,441
C#
using System.Runtime.Serialization; namespace VkNet.Model { using Utils; /// <summary> /// Объект для перечисления пользователей, которые выбрали определенные варианты ответа в опросе. /// </summary> [DataContract] public class PollAnswerVoters { /// <summary> /// Идентификатор варианта ответа /// </summary> public long? AnswerId { get; set; } /// <summary> /// Коллекция пользователей, только если Fields != null /// </summary> public VkCollection<User> Users { get; set; } /// <summary> /// Коллекция идентификаторов пользователей, только если Fields = null /// </summary> public VkCollection<long> UsersIds { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response">Ответ сервера.</param> /// <returns></returns> public static PollAnswerVoters FromJson(VkResponse response) { bool isLongMode = false; if (response.ContainsKey("users") && response["users"].ContainsKey("items")) { var array = (VkResponseArray)response["users"]["items"]; if (array.Count > 0 && !array[0].ContainsKey("id")) { isLongMode = true; } } var answer = new PollAnswerVoters { AnswerId = response["answer_id"], }; if (isLongMode) answer.UsersIds = response["users"].ToVkCollectionOf<long>(x => x); else answer.Users = response["users"].ToVkCollectionOf<User>(x => x); return answer; } } }
30.482759
101
0.522059
[ "MIT" ]
uid17/VK
VkNet/Model/PollAnswerVoters.cs
1,980
C#
using System.Runtime.Serialization; namespace EncompassRest.Loans.Enums { /// <summary> /// HelocTADailyBalanceType /// </summary> public enum HelocTADailyBalanceType { /// <summary> /// daily balance (including current transactions) /// </summary> [EnumMember(Value = "daily balance (including current transactions)")] DailyBalanceIncludingCurrentTransactions = 0, /// <summary> /// daily balance (excluding current transactions) /// </summary> [EnumMember(Value = "daily balance (excluding current transactions)")] DailyBalanceExcludingCurrentTransactions = 1, /// <summary> /// average daily balance (including current transactions) /// </summary> [EnumMember(Value = "average daily balance (including current transactions)")] AverageDailyBalanceIncludingCurrentTransactions = 2, /// <summary> /// average daily balance (excluding current transactions) /// </summary> [EnumMember(Value = "average daily balance (excluding current transactions)")] AverageDailyBalanceExcludingCurrentTransactions = 3 } }
38.451613
86
0.650168
[ "MIT" ]
EncompassRest/EncompassREST
src/EncompassRest/Loans/Enums/HelocTADailyBalanceType.cs
1,192
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Project_TIIK_WPF.Pages { /// <summary> /// Interaction logic for AboutPage.xaml /// </summary> public partial class AboutPage : Page { public AboutPage() { InitializeComponent(); } } }
22.034483
44
0.71518
[ "MIT" ]
lsmierzchalski/Projekt-TIIK
Project-TIIK-WPF/Project-TIIK-WPF/Pages/AboutPage.xaml.cs
641
C#
using System; using System.Diagnostics; using System.Linq; using System.Reflection; using FarseerPhysics.Common; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Contacts; using FarseerPhysics.Dynamics.Joints; using FarseerPhysics.Factories; using log4net; using Microsoft.Xna.Framework; using SFML.Graphics; using SFML.Window; // ReSharper disable RedundantDefaultMemberInitializer namespace Genetic_Cars.Car { enum EntityType { Normal, Clone, Random, Champion } /// <summary> /// Holds the graphics and physics objects for a car. /// </summary> sealed class Entity : IDisposable { private static readonly ILog Log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); // collision category for all car components public static readonly Category CollisionCategory = Category.Cat2; // graphical properties for the car private static readonly Color OutlineColor = Color.Black; private const float OutlineThickness = -.05f; private const float WheelAxisLineThickness = .04f; // cars are accelerated over a period of time to try to avoid wheelies // delta time for acceleration in seconds private const float AccelerationTime = 5; // time between each acceleration step private const float AccelerationInterval = 0.1f; // total number of acceleration steps private static readonly int AccelerationSteps = (int)Math.Round(AccelerationTime / AccelerationInterval); private bool m_disposed = false; private readonly PhysicsManager m_physicsManager; private readonly Definition m_definition; private EntityType m_type; private int m_id; // graphics fields private ConvexShape m_bodyShape; private CircleShape[] m_wheelShapes; private RectangleShape[] m_wheelLines; // physics fields private Body m_bodyBody; private Body[] m_wheelBodies; private RevoluteJoint[] m_wheelJoints; // acceleration fields private float m_accelerationTime; private float[] m_torqueStep; /// <summary> /// Builds a car. /// </summary> /// <param name="def">The parameters used to generate the car.</param> /// <param name="physics">The program physics system.</param> public Entity(Definition def, PhysicsManager physics) { if (physics == null) { throw new ArgumentNullException("physics"); } if (def == null) { throw new ArgumentNullException("def"); } // will throw on failure def.Validate(); m_definition = def; m_physicsManager = physics; m_physicsManager.PostStep += PhysicsPostStep; CreateBody(); CreateWheels(); Type = EntityType.Normal; } ~Entity() { Dispose(false); } /// <summary> /// Just an identifier for this car. /// </summary> public int Id { get { return m_id; } set { m_id = value; m_bodyBody.UserData = m_id; foreach (var wheelBody in m_wheelBodies) { wheelBody.UserData = m_id; } } } /// <summary> /// The geometric center of the car's body. /// </summary> public Vector2 Position { get { return m_bodyBody.Position; } } /// <summary> /// Sets the type of the car entity, affecting how cars are displayed. /// Defaults to normal. /// Normal: Red body /// Clone: Blue body /// Champion: Transparent green body, transparent wheels. /// </summary> public EntityType Type { get { return m_type; } set { Debug.Assert(m_bodyShape != null); Debug.Assert(m_wheelShapes.All(s => s != null)); m_type = value; //Log.DebugFormat("Car {0} type set to {1}", Id, m_type); var density = m_definition.CalcBodyDensity() / Definition.MaxBodyDensity; // greater density = darker color byte color = (byte)(255 - (125 * density)); byte alpha = 255; switch (m_type) { case EntityType.Normal: m_bodyShape.FillColor = new Color(color, 0, 0); break; case EntityType.Clone: m_bodyShape.FillColor = new Color(0, 0, color); break; case EntityType.Random: m_bodyShape.FillColor = new Color(color, 0, color); break; case EntityType.Champion: alpha = 64; m_bodyShape.FillColor = new Color(0, color, 0, alpha); break; } m_bodyShape.OutlineColor = m_bodyShape.OutlineColor.SetAlpha(alpha); for (var i = 0; i < m_wheelShapes.Length; i++) { var shape = m_wheelShapes[i]; shape.FillColor = shape.FillColor.SetAlpha(alpha); shape.OutlineColor = shape.OutlineColor.SetAlpha(alpha); var line = m_wheelLines[i]; line.FillColor = line.FillColor.SetAlpha(alpha); } } } /// <summary> /// Draws the car onto the target. /// </summary> /// <param name="target"></param> public void Draw(RenderTarget target) { if (target == null) { return; } for (var i = 0; i < m_wheelShapes.Length; i++) { target.Draw(m_wheelShapes[i]); target.Draw(m_wheelLines[i]); } target.Draw(m_bodyShape); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposeManaged) { if (m_disposed) { return; } if (disposeManaged) { m_bodyShape.Dispose(); for (var i = 0; i < m_wheelShapes.Length; i++) { m_wheelShapes[i].Dispose(); m_wheelLines[i].Dispose(); } } m_physicsManager.PreStep -= ApplyAcceleration; m_physicsManager.PostStep -= PhysicsPostStep; for (var i = 0; i < m_wheelShapes.Length; i++) { m_wheelBodies[i].OnCollision -= WheelInitialCollision; m_physicsManager.World.RemoveJoint(m_wheelJoints[i]); m_physicsManager.World.RemoveBody(m_wheelBodies[i]); } m_physicsManager.World.RemoveBody(m_bodyBody); m_disposed = true; } /// <summary> /// Creates the graphics and physics objects for the body of the car. /// </summary> private void CreateBody() { m_bodyShape = new ConvexShape((uint)Definition.NumBodyPoints) { OutlineColor = OutlineColor, OutlineThickness = OutlineThickness, Position = Car.StartPosition.ToVector2f().InvertY() }; // build the vertex list for the polygon var vertices = new Vertices(Definition.NumBodyPoints); var angleStep = 360f / Definition.NumBodyPoints; var angle = 0f; for (int i = 0; i < Definition.NumBodyPoints; i++) { // the distance this point is from the center var distance = m_definition.CalcBodyPoint(i); // turn the distance into a point centered around (0,0) var point = new Vector2f { X = distance * (float)Math.Cos(MathExtensions.DegToRad(angle)), Y = distance * (float)Math.Sin(MathExtensions.DegToRad(angle)) }; m_bodyShape.SetPoint((uint)i, point.InvertY()); vertices.Add(point.ToVector2()); angle += angleStep; } // build the physics shape m_bodyBody = BodyFactory.CreatePolygon( m_physicsManager.World, vertices, m_definition.CalcBodyDensity(), Car.StartPosition ); m_bodyBody.BodyType = BodyType.Dynamic; m_bodyBody.Friction = 1; m_bodyBody.CollidesWith = ~CollisionCategory; m_bodyBody.CollisionCategories = CollisionCategory; } /// <summary> /// Creates the wheels for the car. Must be called after CreateBody. /// </summary> private void CreateWheels() { Debug.Assert(m_bodyShape != null); Debug.Assert(m_bodyBody != null); m_wheelShapes = new CircleShape[Definition.NumWheels]; m_wheelLines = new RectangleShape[Definition.NumWheels]; m_wheelBodies = new Body[Definition.NumWheels]; m_wheelJoints = new RevoluteJoint[Definition.NumWheels]; m_torqueStep = new float[Definition.NumWheels]; for (int i = 0; i < m_wheelShapes.Length; i++) { // the offset of the attachment point from the center of the main body var attachOffset = m_bodyShape.GetPoint((uint) m_definition.WheelAttachment[i]); // the world position of the attachment point var attachPos = attachOffset + m_bodyShape.Position; var radius = m_definition.CalcWheelRadius(i); var density = m_definition.CalcWheelDensity(i); var densityFraction = density / Definition.MaxWheelDensity; // greater density = darker color byte color = (byte)(255 - (210 * densityFraction)); var shape = new CircleShape { FillColor = new Color(color, color, color), OutlineColor = OutlineColor, OutlineThickness = OutlineThickness, Origin = new Vector2f(radius, radius), Position = attachPos, Radius = radius }; var line = new RectangleShape { FillColor = Color.Black, Origin = new Vector2f(0, WheelAxisLineThickness / 2f), Size = new Vector2f(WheelAxisLineThickness, radius - WheelAxisLineThickness), Position = shape.Position }; var body = BodyFactory.CreateCircle( m_physicsManager.World, radius, density, attachPos.ToVector2().InvertY() ); body.BodyType = BodyType.Dynamic; body.Friction = 1; body.CollidesWith = Track.CollisionCategory; body.CollisionCategories = CollisionCategory; // need to catch the first collision of this body body.OnCollision += WheelInitialCollision; var joint = new RevoluteJoint( m_bodyBody, attachOffset.ToVector2().InvertY(), body, new Vector2(0, 0)) { MotorEnabled = false, MaxMotorTorque = 0, // speed must be negative for clockwise rotation MotorSpeed = -(float)MathExtensions.DegToRad(m_definition.CalcWheelSpeed(i)) }; m_physicsManager.World.AddJoint(joint); m_wheelShapes[i] = shape; m_wheelLines[i] = line; m_wheelBodies[i] = body; m_wheelJoints[i] = joint; } } /// <summary> /// Called on the first collision for either wheel (should always be with /// the track) to enable the motors, and starts the wheel acceleration. /// </summary> /// <param name="fixtureA"></param> /// <param name="fixtureB"></param> /// <param name="contact"></param> /// <returns></returns> private bool WheelInitialCollision( Fixture fixtureA, Fixture fixtureB, Contact contact) { //Log.DebugFormat("Starting the motors of car {0}", Id); for (var i = 0; i < m_wheelBodies.Length; i++) { m_wheelJoints[i].MotorEnabled = true; m_torqueStep[i] = m_definition.CalcWheelTorque(i) / AccelerationSteps; m_wheelBodies[i].OnCollision -= WheelInitialCollision; } m_accelerationTime = 0; m_physicsManager.PreStep += ApplyAcceleration; return true; } /// <summary> /// Updates the state of the car following a physics step. /// </summary> /// <param name="deltaTime"></param> private void PhysicsPostStep(float deltaTime) { // sync the positions of the graphical shapes to the physics bodies var pos = m_bodyBody.Position.ToVector2f().InvertY(); m_bodyShape.Position = pos; m_bodyShape.Rotation = (float)-MathExtensions.RadToDeg(m_bodyBody.Rotation); for (int i = 0; i < m_wheelShapes.Length; i++) { var wheelPos = m_wheelBodies[i].Position.ToVector2f().InvertY(); var wheelRot = (float)-MathExtensions.RadToDeg(m_wheelBodies[i].Rotation); m_wheelShapes[i].Position = wheelPos; m_wheelLines[i].Position = wheelPos; m_wheelLines[i].Rotation = wheelRot; } } /// <summary> /// Increases the torque for each wheel until the defined max torque is /// reached. /// </summary> /// <param name="deltaTime"></param> private void ApplyAcceleration(float deltaTime) { var done = false; m_accelerationTime += deltaTime; while (m_accelerationTime >= AccelerationInterval) { m_accelerationTime -= AccelerationInterval; for (var i = 0; i < m_wheelJoints.Length; i++) { m_wheelJoints[i].MaxMotorTorque += m_torqueStep[i]; if (m_wheelJoints[i].MaxMotorTorque >= m_definition.CalcWheelTorque(i)) { done = true; } } if (done) { //Log.DebugFormat("Car {0} completed acceleration", Id); m_physicsManager.PreStep -= ApplyAcceleration; break; } } } } }
29.993182
87
0.614761
[ "MIT" ]
mbcrawfo/genetic-cars
Genetic Cars/Car/Entity.cs
13,199
C#
using CancerRegistry.Models.Accounts.Doctor; using CancerRegistry.Models.Accounts.Patient; using CancerRegistry.Models.Diagnoses; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CancerRegistry.Identity; using CancerRegistry.Identity.Data; using CancerRegistry.Models.Diagnoses.Treatments; using Microsoft.AspNetCore.Identity; namespace CancerRegistry.Services { public class PatientService { private readonly DiagnoseContext _diagnoseContext; private readonly UserManager<ApplicationUser> _userManager; public PatientService(DiagnoseContext diagnoseContext, UserManager<ApplicationUser> userManager) { _diagnoseContext = diagnoseContext; _userManager = userManager; } public async Task<Patient> GetByIdAsync(string id) { return await _diagnoseContext.Patients .Where(p => p.UserId == id) .SingleOrDefaultAsync(); } public async Task<List<Patient>> SelectForDoctorUIDAsync(string doctorUID) { return await _diagnoseContext.Doctors .Where(doctor => doctor.UserId == doctorUID) .Join(_diagnoseContext.Diagnoses, doctor => doctor.UserId, diagnose => diagnose.Doctor.UserId, (doctor, diagnose) => diagnose) .Join(_diagnoseContext.Patients, diagnose => diagnose.Id, patient => patient.ActiveDiagnoseId, (diagnose, patient) => patient) .ToListAsync(); } internal async Task UpdateAsync() { await _diagnoseContext.SaveChangesAsync(); } public async Task AddPatient(string id, string number) { await _diagnoseContext.Patients.AddAsync(new Patient() { UserId = id, PhoneNumber = Int64.Parse(number)}); await _diagnoseContext.SaveChangesAsync(); } public async Task<IEnumerable<ApplicationUser>> GetAllPatients() { var patients = await _userManager.GetUsersInRoleAsync("Patient"); return patients; } public async Task DeletePatient(string id) { var patient = await _diagnoseContext.Patients.SingleOrDefaultAsync(p => p.UserId == id); _diagnoseContext.Patients.Remove(patient); await _diagnoseContext.SaveChangesAsync(); } public async Task<CurrentDiagnoseOutputModel> GetActiveDiagnose(string patientId) { var p = await _diagnoseContext.Patients .Where(x => x.UserId == patientId) .SingleOrDefaultAsync(); var diagnose = await _diagnoseContext.Diagnoses .Where(d => d.Id == p.ActiveDiagnoseId) .Include(d=>d.Doctor) .Include(d=>d.Patient) .SingleOrDefaultAsync(); if (diagnose == null) return null; var doctor = await _userManager.FindByIdAsync(diagnose.Doctor.UserId); var patient = await _userManager.FindByIdAsync(diagnose.Patient.UserId); var tumorState = StateTranslator.TranslateTumorState(diagnose.PrimaryTumor); var distantMetastasisState = StateTranslator.TranslateMetastatsisState(diagnose.DistantMetastasis); var regionalLymphNodesState = StateTranslator.TranslateRegionalLymphNodesState(diagnose.RegionalLymphNodes); var outputModel = new CurrentDiagnoseOutputModel() { DoctorName = doctor.FirstName + " " + doctor.LastName, PatientName = patient.FirstName + " " + patient.LastName, Stage = diagnose.Stage.ToString(), PrimaryTumorState = tumorState, DistantMetastasisState = distantMetastasisState, RegionalLymphNodesState = regionalLymphNodesState }; return outputModel; } public async Task<CurrentTreatmentOutputModel> GetCurrentTreatment(string patientId) { var activeDiagnoseId = await _diagnoseContext.Patients .Where(p => p.UserId == patientId) .Select(x => x.ActiveDiagnoseId) .SingleOrDefaultAsync(); var treatment = await _diagnoseContext.Diagnoses .Where(d => d.Treatment.DiagnoseId == activeDiagnoseId) .Include(d=>d.Treatment) .Include(d => d.Doctor) .Include(d=>d.Patient) .SingleOrDefaultAsync(); if (treatment == null) return null; var doctor = await _userManager.FindByIdAsync(treatment.Doctor.UserId); var patient = await _userManager.FindByIdAsync(treatment.Patient.UserId); var model = new CurrentTreatmentOutputModel() { DoctorName = doctor.FirstName + " " + doctor.LastName, PatientName = patient.FirstName + " " + patient.LastName, AddedOn = treatment.Treatment.Beginning.ToShortDateString(), Treatment = StateTranslator.GetTreatmentDisplayName(treatment.Treatment.Surgery, treatment.Treatment.Radiation, treatment.Treatment.Chemeotherapy, treatment.Treatment.EndocrineTreatment), Description = StateTranslator.GetTreatmentDescription(treatment.Treatment.Surgery, treatment.Treatment.Radiation, treatment.Treatment.Chemeotherapy, treatment.Treatment.EndocrineTreatment) }; return model; } public async Task<PatientHistoryOutputModel> GetHistory(string patientId) { var patient = await _userManager.FindByIdAsync(patientId); var diagnoses = await _diagnoseContext.Diagnoses .Include(d=>d.Patient) .Include(d => d.HealthChecks) .Where(d => d.Patient.UserId == patientId) .Select(x=>new { Type = "Диагноза", AddedOn = x.HealthChecks.SingleOrDefault().Timestamp, PrimaryTumor = x.PrimaryTumor, DistantMetastasis = x.DistantMetastasis, RegionalLymphNodes = x.RegionalLymphNodes, Stage = x.Stage }) .ToListAsync(); var treatments = await _diagnoseContext.Treatments .Include(t => t.Diagnose) .ThenInclude(d => d.Patient) .Where(t => t.Diagnose.Patient.UserId == patientId) .Select(x=>new { Type = "Лечение", AddedOn = x.Beginning, EndsOn = x.End, Surgery = x.Surgery, Radiation = x.Radiation, Chemeotherapy = x.Chemeotherapy, EndocrineTreatment = x.EndocrineTreatment, }) .ToListAsync(); if (treatments == null && diagnoses == null) return null; var history = diagnoses .Select(diagnose => new PatientHistory { Type = diagnose.Type, AddedOn = diagnose.AddedOn, Description = diagnose.PrimaryTumor + ", " + diagnose.DistantMetastasis + ", " + diagnose.RegionalLymphNodes }).ToList(); history.AddRange(treatments .Select(treatment => new PatientHistory { Type = treatment.Type, AddedOn = treatment.AddedOn, Description = treatment.Chemeotherapy + ", " + treatment.Surgery + ", " + treatment.Radiation + ", " + treatment.Chemeotherapy, EndsOn = treatment.EndsOn })); var model = new PatientHistoryOutputModel() { History = history.OrderBy(x => x.AddedOn), PatientName = patient.FirstName + " " + patient.LastName }; return model; } } }
40.584906
204
0.559391
[ "Apache-2.0" ]
Kroxitrock/cancer-registry
CancerRegistry/CancerRegistry/Services/PatientService.cs
8,621
C#
using System; using System.Windows.Forms; namespace iWay.RemoteControlClient.Common { public partial class InputDialog : Form { public InputDialog() { InitializeComponent(); } public string Title { get { return this.Text; } set { this.Text = value; } } public bool AllowEmpty { get; set; } public string Result { get { return textBox1.Text; } set { textBox1.Text = value; } } public int SelectionStart { get { return textBox1.SelectionStart; } set { textBox1.SelectionStart = value; } } public int SelectionLength { get { return textBox1.SelectionLength; } set { textBox1.SelectionLength = value; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '\r') { e.Handled = true; button1_Click(null, null); } } private void button1_Click(object sender, EventArgs e) { if (!AllowEmpty && textBox1.Text == "") return; this.DialogResult = DialogResult.OK; this.Close(); } private void button2_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } } }
22.573529
74
0.490554
[ "Apache-2.0" ]
PHPPlay/RemoteControl
RemoteControlClient/Common/InputDialog.cs
1,537
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using ObjCRuntime; using Foundation; using System.Linq; namespace Firebase.Storage { public partial class Storage { static string currentVersion; public static string CurrentVersion { get { if (currentVersion == null) { IntPtr RTLD_MAIN_ONLY = Dlfcn.dlopen (null, 0); IntPtr ptr = Dlfcn.dlsym (RTLD_MAIN_ONLY, "FIRStorageVersionString"); currentVersion = Marshal.PtrToStringAnsi (ptr); Dlfcn.dlclose (RTLD_MAIN_ONLY); } return currentVersion; } } } public partial class StorageMetadata { public StorageMetadata (Dictionary<object, object> dictionary) : this (NSDictionary.FromObjectsAndKeys (dictionary.Values.ToArray (), dictionary.Keys.ToArray (), dictionary.Keys.Count)) { } } public partial class StorageTaskSnapshot { public StorageTask GetTask () { var task = Runtime.GetNSObject<StorageTask> (_Task); return task; } public T GetTask<T> () where T : StorageTask { var task = Runtime.GetNSObject<T> (_Task); return task; } } }
22.16
187
0.716606
[ "MIT" ]
DigitallyImported/GoogleApisForiOSComponents
source/Firebase/Storage/Extension.cs
1,110
C#
using MediatR; using Microsoft.AspNetCore.Mvc; using shockz.msa.ordering.application.Features.Orders.Commands.CheckoutOrder; using shockz.msa.ordering.application.Features.Orders.Commands.DeleteOrder; using shockz.msa.ordering.application.Features.Orders.Commands.UpdateOrder; using shockz.msa.ordering.application.Features.Orders.Queries.GetOrdersList; using System.Net; namespace shockz.msa.ordering.api.Controllers { [Route("api/v1/[controller]")] [ApiController] public class OrderController : ControllerBase { private readonly IMediator _mediator; public OrderController(IMediator mediator) { _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); } [HttpGet("{userName}", Name = "GetOrder")] [ProducesResponseType(typeof(IEnumerable<OrdersViewModel>), (int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<OrdersViewModel>>> GetOrderByUserName(string userName) { var query = new GetOrdersListQuery(userName); var orders = await _mediator.Send(query); return Ok(orders); } // for now, test purpose [HttpPost(Name = "CheckoutOrder")] [ProducesResponseType((int)HttpStatusCode.OK)] public async Task<ActionResult<int>> CheckoutOrder([FromBody] CheckoutOrderCommand command) { var result = await _mediator.Send(command); return Ok(result); } [HttpPut(Name = "UpdateOrder")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task<ActionResult<int>> UpdateOrder([FromBody] UpdateOrderCommand command) { await _mediator.Send(command); return NoContent(); } [HttpDelete("{id}", Name = "DeleteOrder")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public async Task<ActionResult> DeleteOrder(int id) { var command = new DeleteOrderCommand { Id = id }; await _mediator.Send(command); return NoContent(); } } }
32.369231
101
0.731464
[ "MIT" ]
shockzinfinity/shockz.msa
src/services/ordering/shockz.msa.ordering.api/Controllers/OrderController.cs
2,106
C#
#region License // // MIT License // // CoiniumServ - Crypto Currency Mining Pool Server Software // Copyright (C) 2013 - 2017, CoiniumServ Project // Hüseyin Uslu, shalafiraistlin at gmail dot com // https://github.com/bonesoul/CoiniumServ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System; namespace CoiniumServ.Utils.Commands { /// <summary> /// Marks a class as an command group. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class CommandGroupAttribute : Attribute { /// <summary> /// Command group's name. /// </summary> public string Name { get; private set; } /// <summary> /// Help text for command group. /// </summary> public string Help { get; private set; } public CommandGroupAttribute(string name, string help) { Name = name.ToLower(); Help = help; } } [AttributeUsage(AttributeTargets.Method)] public class CommandAttribute : Attribute { /// <summary> /// Command's name. /// </summary> public string Name { get; private set; } /// <summary> /// Help text for command. /// </summary> public string Help { get; private set; } public CommandAttribute(string command, string help) { Name = command.ToLower(); Help = help; } } [AttributeUsage(AttributeTargets.Method)] public class DefaultCommand : CommandAttribute { public DefaultCommand() : base("", "") { } } }
32.470588
85
0.627536
[ "MIT" ]
1Blackdiamondsc/CoiniumServ
src/CoiniumServ/Utils/Commands/CommandAttributes.cs
2,763
C#
using System; using System.Threading.Tasks; using Microsoft.AspNet.SignalR; using Microsoft.Owin; using Microsoft.Owin.Cors; using Owin; [assembly: OwinStartup(typeof(Danmaku.Startup))] namespace Danmaku { public class Startup { public void Configuration(IAppBuilder app) { // 有关如何配置应用程序的详细信息,请访问 https://go.microsoft.com/fwlink/?LinkID=316888 // Branch the pipeline here for requests that start with "/signalr" app.Map("/signalr", map => { // Setup the CORS middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { // You can enable JSONP by uncommenting line below. // JSONP requests are insecure but some older browsers (and some // versions of IE) require JSONP to work cross domain // EnableJSONP = true }; // Run the SignalR pipeline. We're not using MapSignalR // since this branch already runs under the "/signalr" // path. map.RunSignalR(hubConfiguration); }); } } }
36.575
84
0.570745
[ "MIT" ]
yiyungent/demos
Danmaku/Danmaku/Danmaku/Danmaku/Startup.cs
1,503
C#
using System; using System.Collections.Generic; using System.Linq; using Kinetix.Search.ComponentModel; using Kinetix.Search.Contract; using Kinetix.Search.Elastic.Faceting; using Kinetix.Search.MetaModel; using Kinetix.Search.Model; using log4net; using Nest; namespace Kinetix.Search.Elastic { /// <summary> /// Store ElasticSearch. /// </summary> /// <typeparam name="TDocument">Type du document.</typeparam> public class ElasticStore<TDocument> : ISearchStore<TDocument> where TDocument : class { /// <summary> /// Taille de cluster pour l'insertion en masse. /// </summary> private const int ClusterSize = 2000; private const string MissingGroupPrefix = "_Missing"; private const string GroupAggs = "groupAggs"; /// <summary> /// Nom de l'aggrégation des top hits pour le groupement. /// </summary> private const string _topHitName = "top"; private static ILog _log = LogManager.GetLogger("Search"); /// <summary> /// Builder de requête. /// </summary> private readonly ElasticQueryBuilder _builder = new ElasticQueryBuilder(); /// <summary> /// Usine à mapping ElasticSearch. /// </summary> private readonly ElasticMappingFactory _factory = new ElasticMappingFactory(); /// <summary> /// Handler des facettes standard. /// </summary> private readonly IFacetHandler<TDocument> _standardHandler; /// <summary> /// Handler des facettes portefeuille. /// </summary> private readonly IFacetHandler<TDocument> _portfolioHandler; /// <summary> /// Nom de la source de données. /// </summary> private readonly string _dataSourceName; /// <summary> /// Définition du document. /// </summary> private readonly DocumentDefinition _definition; /// <summary> /// Nom du type du document. /// </summary> private readonly string _documentTypeName; /// <summary> /// Nom de l'index. /// </summary> private readonly string _indexName; /// <summary> /// Créé une nouvelle instance de ElasticStore. /// </summary> /// <param name="dataSourceName">Nom de la datasource.</param> public ElasticStore(string dataSourceName) { try { _definition = DocumentDescriptor.GetDefinition(typeof(TDocument)); _documentTypeName = _definition.DocumentTypeName; _dataSourceName = dataSourceName ?? throw new ArgumentNullException("dataSourceName"); _indexName = ElasticManager.Instance.LoadSearchSettings(_dataSourceName).IndexName; _standardHandler = new StandardFacetHandler<TDocument>(_definition); _portfolioHandler = new PortfolioFacetHandler<TDocument>(_definition); } catch (Exception e) { if (_log.IsErrorEnabled) { _log.Error("Echec d'instanciation du store.", e); } throw new NotSupportedException("Search Broker<" + typeof(TDocument).FullName + "> " + e.Message, e); } } /// <inheritdoc cref="ISearchStore{TDocument}.CreateDocumentType" /> public void CreateDocumentType() { if (_log.IsInfoEnabled) { _log.Info("Create Document type : " + _documentTypeName); } var client = GetClient(); var res = client.Map<TDocument>(x => x .Type(_documentTypeName) .Properties(selector => { foreach (var field in _definition.Fields) { _factory.AddField(selector, field); } return selector; })); res.CheckStatus("Map"); } /// <inheritdoc cref="ISearchStore{TDocument}.Get" /> public TDocument Get(string id) { var res = this.GetClient().Get(CreateDocumentPath(id)); res.CheckStatus("Get"); return res.Source; } /// <inheritdoc cref="ISearchStore{TDocument}.Put" /> public void Put(TDocument document) { var id = _definition.PrimaryKey.GetValue(document).ToString(); var res = this.GetClient().Index(FormatSortFields(document), x => x .Index(_indexName) .Type(_documentTypeName) .Id(id)); res.CheckStatus("Index"); } /// <inheritdoc cref="ISearchStore{TDocument}.PutAll" /> public void PutAll(IEnumerable<TDocument> documentList) { if (documentList == null) { throw new ArgumentNullException("documentList"); } if (!documentList.Any()) { return; } /* Découpage en cluster. */ var total = documentList.Count(); int left = total % ClusterSize; var clusterNb = ((total - left) / ClusterSize) + (left > 0 ? 1 : 0); for (int i = 1; i <= clusterNb; i++) { /* Extraction du cluster. */ var cluster = documentList .Skip((i - 1) * ClusterSize) .Take(ClusterSize); /* Indexation en masse du cluster. */ var res = this.GetClient().Bulk(x => { foreach (var document in cluster) { var id = _definition.PrimaryKey.GetValue(document).ToString(); x.Index<TDocument>(y => y .Document(FormatSortFields(document)) .Index(_indexName) .Type(_documentTypeName) .Id(id)); } return x; }); res.CheckStatus("Bulk"); } } /// <inheritdoc cref="ISearchStore{TDocument}.Remove" /> public void Remove(string id) { var res = this.GetClient().Delete(CreateDocumentPath(id)); res.CheckStatus("Delete"); } /// <inheritdoc cref="ISearchStore{TDocument}.Flush" /> public void Flush() { /* SEY : Non testé. */ var res = this.GetClient().DeleteByQuery<TDocument>(x => x.Index(_indexName).Type(_documentTypeName)); res.CheckStatus("DeleteAll"); } /// <inheritdoc cref="ISearchStore{TDocument}.AdvancedQuery" /> public QueryOutput<TDocument> AdvancedQuery(AdvancedQueryInput input) { if (input == null) { throw new ArgumentNullException("input"); } var apiInput = input.ApiInput; /* Tri */ var sortDef = GetSortDefinition(input); /* Requêtes de filtrage. */ var filterQuery = GetFilterQuery(input); var hasFilter = !string.IsNullOrEmpty(filterQuery); var postFilterQuery = GetPostFilterSubQuery(input); var hasPostFilter = !string.IsNullOrEmpty(postFilterQuery); /* Facettage. */ var facetDefList = GetFacetDefinitionList(input); var hasFacet = facetDefList.Any(); var portfolio = input.Portfolio; /* Group */ var groupFieldName = GetGroupFieldName(input); var hasGroup = !string.IsNullOrEmpty(apiInput.Group); /* Pagination. */ var skip = apiInput.Skip ?? 0; var size = hasGroup ? 0 : apiInput.Top ?? 1000; // TODO Paramétrable ? var res = this.GetClient() .Search<TDocument>(s => { s /* Index / type document. */ .Index(_indexName) .Type(_documentTypeName) /* Pagination */ .From(skip) .Size(size); /* Tri */ if (sortDef.HasSort) { s.Sort(x => x .Field(sortDef.FieldName, sortDef.Order)); } /* Critère de filtrage. */ if (hasFilter) { s.Query(q => q.QueryString(qs => qs.Query(filterQuery))); } /* Critère de post-filtrage. */ if (hasPostFilter) { s.PostFilter(q => q.QueryString(qs => qs.Query(postFilterQuery))); } /* Aggrégations. */ if (hasFacet || hasGroup) { s.Aggregations(a => { if (hasFacet) { /* Facettage. */ foreach (var facetDef in facetDefList) { GetHandler(facetDef).DefineAggregation(a, facetDef, facetDefList, input.ApiInput.Facets, portfolio); } } if (hasGroup) { /* Groupement. */ a.Filter(GroupAggs, f => { /* Critère de post-filtrage répété sur les groupes, puisque ce sont des agrégations qui par définition ne sont pas affectées par le post-filtrage. */ if (hasPostFilter) { f.Filter(q => q.QueryString(qs => qs.Query(postFilterQuery))); } return f.Aggregations(aa => aa /* Groupement. */ .Terms(groupFieldName, st => st .Field(groupFieldName) .Aggregations(g => g.TopHits(_topHitName, x => x.Size(input.GroupSize)))) /* Groupement pour les valeurs nulles */ .Missing(groupFieldName + MissingGroupPrefix, st => st .Field(groupFieldName) .Aggregations(g => g.TopHits(_topHitName, x => x.Size(input.GroupSize))))); }); } return a; }); } return s; }); res.CheckStatus("AdvancedQuery"); /* Extraction des facettes. */ var facetListOutput = new List<FacetOutput>(); if (hasFacet) { var aggs = res.Aggs; foreach (var facetDef in facetDefList) { facetListOutput.Add(new FacetOutput { Code = facetDef.Code, Label = facetDef.Label, IsMultiSelectable = facetDef.IsMultiSelectable, Values = GetHandler(facetDef).ExtractFacetItemList(aggs, facetDef, res.Total) }); } } /* Ajout des valeurs de facettes manquantes (cas d'une valeur demandée par le client non trouvée par la recherche.) */ if (input.ApiInput.Facets != null) { foreach (var facet in input.ApiInput.Facets) { var facetItems = facetListOutput.Single(f => f.Code == facet.Key).Values; /* On ajoute un FacetItem par valeur non trouvée, avec un compte de 0. */ foreach (var value in facet.Value) { if (!facetItems.Any(f => f.Code == value)) { facetItems.Add(new FacetItem { Code = value, Label = facetDefList.FirstOrDefault(fct => fct.Code == facet.Key)?.ResolveLabel(value), Count = 0 }); } } } } /* Extraction des résultats. */ var resultList = new List<TDocument>(); var groupResultList = new List<GroupResult<TDocument>>(); if (hasGroup) { /* Groupement. */ var bucket = (BucketAggregate)res.Aggs.Filter(GroupAggs).Aggregations[groupFieldName]; foreach (KeyedBucket<object> group in bucket.Items) { var list = ((TopHitsAggregate)group.Aggregations[_topHitName]).Documents<TDocument>().ToList(); groupResultList.Add(new GroupResult<TDocument> { Code = group.Key.ToString(), Label = facetDefList.First(f => f.Code == apiInput.Group).ResolveLabel(group.Key), List = list, TotalCount = (int)group.DocCount }); } /* Groupe pour les valeurs null. */ var nullBucket = (SingleBucketAggregate)res.Aggs.Filter(GroupAggs).Aggregations[groupFieldName + MissingGroupPrefix]; var nullTopHitAgg = (TopHitsAggregate)nullBucket.Aggregations[_topHitName]; var nullDocs = nullTopHitAgg.Documents<TDocument>().ToList(); if (nullDocs.Any()) { groupResultList.Add(new GroupResult<TDocument> { Code = FacetConst.NullValue, Label = input.FacetQueryDefinition.FacetNullValueLabel ?? "focus.search.results.missing", List = nullDocs, TotalCount = (int)nullBucket.DocCount }); } resultList = null; } else { /* Liste unique. */ resultList = res.Documents.ToList(); groupResultList = null; } /* Construction de la sortie. */ var output = new QueryOutput<TDocument> { List = resultList, Facets = facetListOutput, Groups = groupResultList, Query = apiInput, TotalCount = res.Total }; return output; } /// <inheritdoc cref="ISearchStore{TDocument}.AdvancedCount" /> public long AdvancedCount(AdvancedQueryInput input) { if (input == null) { throw new ArgumentNullException("input"); } /* Requête de filtrage, qui inclus ici le filtre et le post-filtre puisqu'on ne fait pas d'aggrégations. */ var filterQuery = _builder.BuildAndQuery(GetFilterQuery(input), GetPostFilterSubQuery(input)); var hasFilter = !string.IsNullOrEmpty(filterQuery); var res = this.GetClient() .Count<TDocument>(s => { /* Index / type document. */ s .Index(_indexName) .Type(_documentTypeName); /* Critère de filtrage. */ if (hasFilter) { s.Query(q => q.QueryString(qs => qs.Query(filterQuery))); } return s; }); res.CheckStatus("AdvancedCount"); return res.Count; } /// <summary> /// Créé la requête de filtrage. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Requête de filtrage.</returns> private string GetFilterQuery(AdvancedQueryInput input) { var textSubQuery = GetTextSubQuery(input); var textSubQueryBoost = GetTextSubQueryBoost(input); var securitySubQuery = GetSecuritySubQuery(input); var filterSubQuery = GetFilterSubQuery(input); var monoValuedFacetsSubQuery = GetFacetSelectionSubQuery(input); string queryWithBoost; if (!string.IsNullOrEmpty(textSubQuery) && !string.IsNullOrEmpty(textSubQueryBoost)) { queryWithBoost = "(" + textSubQuery + " " + textSubQueryBoost + ")"; } else { queryWithBoost = textSubQuery; } return _builder.BuildAndQuery(queryWithBoost, securitySubQuery, filterSubQuery, monoValuedFacetsSubQuery); } /// <summary> /// Crée la sous requête pour les champs de filtre. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetFilterSubQuery(AdvancedQueryInput input) { if (input.FilterList == null || !input.FilterList.Any()) { return string.Empty; } var filterList = new List<string>(); foreach (KeyValuePair<string, string> entry in input.FilterList) { DocumentFieldDescriptor field = _definition.Fields[entry.Key]; switch (field.Category) { case SearchFieldCategory.Term: case SearchFieldCategory.ListTerm: filterList.Add(_builder.BuildFilter(field.FieldName, entry.Value)); break; case SearchFieldCategory.TextSearch: filterList.Add(_builder.BuildFullTextSearch(field.FieldName, entry.Value)); break; } } return _builder.BuildAndQuery(filterList.ToArray()); } /// <summary> /// Créé la sous-requête pour le champ textuel. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetTextSubQuery(AdvancedQueryInput input) { var criteria = input.ApiInput.Criteria; var value = criteria?.Query; /* Absence de texte ou joker : sous-requête vide. */ if (string.IsNullOrEmpty(value) || value == "*") { return string.Empty; } /* Vérifie la présence d'un champ textuel. */ var fieldDesc = _definition.TextField; if (fieldDesc == null) { throw new ElasticException("The Document \"" + _definition.DocumentTypeName + "\" needs a Search category field to allow Query."); } /* Constuit la sous requête. */ return "+" + _builder.BuildFullTextSearch(fieldDesc.FieldName, value); } /// <summary> /// Créé la sous-requête pour le champ textuel. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetTextSubQueryBoost(AdvancedQueryInput input) { var criteria = input.ApiInput.Criteria; var value = criteria?.Query; if ((input.ApiInput.Boosts == null || !input.ApiInput.Boosts.Any()) || (string.IsNullOrEmpty(value) || value == "*")) { return string.Empty; } else { IList<string> boosts = new List<string>(); foreach (Boost boost in input.ApiInput.Boosts) { DocumentFieldDescriptor field = _definition.Fields[boost.Field]; boosts.Add(_builder.BuildFullTextSearch(field.FieldName, value, boost.BoostValue)); } /* Concatène en OR : les boosts ne doivent pas filtrer les résultats de recherche. */ return string.Join(" ", boosts); } } /// <summary> /// Créé la sous-requête le filtrage de sécurité. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetSecuritySubQuery(AdvancedQueryInput input) { var value = input.Security; /* Absence de filtrage de sécurité : sous-requêt vide. */ if (string.IsNullOrEmpty(value)) { return string.Empty; } /* Vérifie la présence d'un champ de sécurité. */ var fieldDesc = _definition.SecurityField; if (fieldDesc == null) { throw new ElasticException("The Document \"" + _definition.DocumentTypeName + "\" needs a Security category field to allow Query with security filtering."); } /* Constuit la sous requête. */ return _builder.BuildInclusiveInclude(fieldDesc.FieldName, value); } /// <summary> /// Créé la sous-requête le filtrage par sélection de facette non multi-sélectionnables. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetFacetSelectionSubQuery(AdvancedQueryInput input) { var facetList = input.ApiInput.Facets; if (facetList == null || !facetList.Any()) { return string.Empty; } /* Créé une sous-requête par facette. */ var facetSubQueryList = facetList .Select(f => { /* Récupère la définition de la facette non multi-sélectionnable. */ var def = input.FacetQueryDefinition.Facets.SingleOrDefault(x => x.IsMultiSelectable == false && x.Code == f.Key); if (def == null) { return null; } /* La facette n'est pas multi-sélectionnable donc on prend direct la première valeur. */ var s = f.Value[0]; return GetHandler(def).CreateFacetSubQuery(s, def, input.Portfolio); }) .Where(f => f != null) .ToArray(); if (facetSubQueryList.Any()) { /* Concatène en "ET" toutes les sous-requêtes. */ return _builder.BuildAndQuery(facetSubQueryList); } else { return string.Empty; } } /// <summary> /// Créé la sous-requête de post-filtrage pour les facettes multi-sélectionnables. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Sous-requête.</returns> private string GetPostFilterSubQuery(AdvancedQueryInput input) { var facetList = input.ApiInput.Facets; if (facetList == null || !facetList.Any()) { return string.Empty; } /* Créé une sous-requête par facette */ var facetSubQueryList = facetList .Select(f => { /* Récupère la définition de la facette multi-sélectionnable. */ var def = input.FacetQueryDefinition.Facets.SingleOrDefault(x => x.IsMultiSelectable == true && x.Code == f.Key); if (def == null) { return null; } var handler = GetHandler(def); /* On fait un "OR" sur toutes les valeurs sélectionnées. */ return _builder.BuildOrQuery(f.Value.Select(s => handler.CreateFacetSubQuery(s, def, input.Portfolio)).ToArray()); }) .Where(f => f != null) .ToArray(); if (facetSubQueryList.Any()) { /* Concatène en "ET" toutes les sous-requêtes. */ return _builder.BuildAndQuery(facetSubQueryList); } else { return string.Empty; } } /// <summary> /// Obtient la liste des facettes. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Définitions de facettes.</returns> private ICollection<IFacetDefinition> GetFacetDefinitionList(AdvancedQueryInput input) { var groupFacetName = input.ApiInput.Group; var list = input.FacetQueryDefinition != null ? input.FacetQueryDefinition.Facets : new List<IFacetDefinition>(); /* Recherche de la facette de groupement. */ string groupFieldName = null; if (!string.IsNullOrEmpty(groupFacetName)) { var groupFacetDef = input.FacetQueryDefinition.Facets.SingleOrDefault(x => x.Code == groupFacetName); if (groupFacetDef == null) { throw new ElasticException("No facet \"" + groupFacetName + "\" to group on."); } groupFieldName = groupFacetDef.FieldName; } foreach (var facetDef in list) { /* Vérifie que le champ à facetter existe sur le document. */ GetHandler(facetDef).CheckFacet(facetDef); } return list; } /// <summary> /// Obtient la définition du tri. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Définition du tri.</returns> private SortDefinition GetSortDefinition(AdvancedQueryInput input) { var fieldName = input.ApiInput.SortFieldName; /* Cas de l'absence de tri. */ if (string.IsNullOrEmpty(fieldName)) { return new SortDefinition(); } /* Vérifie la présence du champ. */ if (!_definition.Fields.HasProperty(fieldName)) { throw new ElasticException("The Document \"" + _definition.DocumentTypeName + "\" is missing a \"" + fieldName + "\" property to sort on."); } return new SortDefinition { FieldName = _definition.Fields[fieldName].FieldName, Order = input.ApiInput.SortDesc ? SortOrder.Descending : SortOrder.Ascending }; } /// <summary> /// Obtient le nom du champ pour le groupement. /// </summary> /// <param name="input">Entrée.</param> /// <returns>Nom du champ.</returns> private string GetGroupFieldName(AdvancedQueryInput input) { var groupFacetName = input.ApiInput.Group; /* Pas de groupement. */ if (string.IsNullOrEmpty(groupFacetName)) { return null; } /* Recherche de la facette de groupement. */ var facetDef = input.FacetQueryDefinition.Facets.SingleOrDefault(x => x.Code == groupFacetName); if (facetDef == null) { throw new ElasticException("No facet " + groupFacetName + " to group on."); } var fieldName = facetDef.FieldName; /* Vérifie la présence du champ. */ if (!_definition.Fields.HasProperty(fieldName)) { throw new ElasticException("The Document \"" + _definition.DocumentTypeName + "\" is missing a \"" + fieldName + "\" property to group on."); } return _definition.Fields[fieldName].FieldName; } /// <summary> /// Obtient le client ElastcSearch. /// </summary> /// <returns>Client Elastic.</returns> private ElasticClient GetClient() { return ElasticManager.Instance.ObtainClient(_dataSourceName); } /// <summary> /// Créé un DocumentPath. /// </summary> /// <param name="id">ID du document.</param> /// <returns>Le DocumentPath.</returns> private DocumentPath<TDocument> CreateDocumentPath(string id) { return new DocumentPath<TDocument>(id).Index(_indexName).Type(_documentTypeName); } /// <summary> /// Format les champs de tri du document. /// Les champs de tri sont mis manuellement en minuscule avant indexation. /// Ceci est nécessaire car en ElasticSearch 5.x, il n'est plus possible de trier sur un champ indexé (à faible coût). /// </summary> /// <param name="document">Document.</param> /// <returns>Document formaté.</returns> private TDocument FormatSortFields(TDocument document) { foreach (var field in _definition.Fields.Where(x => x.Category == SearchFieldCategory.Sort && x.PropertyType == typeof(string))) { var raw = field.GetValue(document); if (raw != null) { field.SetValue(document, ((string)raw).ToLowerInvariant()); } } return document; } /// <summary> /// Renvoie le handler de facet pour une définition de facet. /// </summary> /// <param name="def">Définition de facet.</param> /// <returns>Handler.</returns> private IFacetHandler<TDocument> GetHandler(IFacetDefinition def) { if (def.GetType() == typeof(PortfolioFacet)) { return _portfolioHandler; } return _standardHandler; } /// <summary> /// Définition de tri. /// </summary> private class SortDefinition { /// <summary> /// Ordre de tri. /// </summary> public SortOrder Order { get; set; } /// <summary> /// Champ du tri (camelCase). /// </summary> public string FieldName { get; set; } /// <summary> /// Indique si le tri est défini. /// </summary> public bool HasSort { get { return !string.IsNullOrEmpty(this.FieldName); } } } } }
40.726428
186
0.502103
[ "Apache-2.0" ]
KleeGroup/kinetix
Kinetix/Kinetix.Search/Elastic/ElasticStore.cs
30,795
C#
#region "copyright" /* Copyright © 2016 - 2021 Stefan Berg <isbeorn86+NINA@googlemail.com> and the N.I.N.A. contributors This file is part of N.I.N.A. - Nighttime Imaging 'N' Astronomy. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #endregion "copyright" using FTD2XX_NET; using NINA.MGEN.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NINA.MGEN.Commands.AppMode { public class StartCalibrationCommand : AutoGuidingCommand<MGENResult> { public override byte SubCommandCode { get; } = 0x20; protected override MGENResult ExecuteSubCommand(IFTDI device) { Write(device, SubCommandCode); var data = Read(device, 1); if (data[0] == 0x00) { return new MGENResult(true); } else if (data[0] == 0xf2) { throw new CameraIsOffException(); } else if (data[0] == 0xf3) { throw new AutoGuidingActiveException(); } else if (data[0] == 0xf1) { throw new AnotherCommandInProgressException(); } else if (data[0] == 0xf0) { throw new UILockedException(); } else { throw new UnexpectedReturnCodeException(); } } } }
32.630435
101
0.616922
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
USA-RedDragon/nina
NINA.MGEN/Commands/AppMode/AutoGuidingCommands/StartCalibrationCommand.cs
1,502
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Its.Log.Instrumentation; namespace Sample.Domain.Projections { public class OrderTally { static OrderTally() { Formatter<OrderTally>.RegisterForAllMembers(); } public string Status { get; set; } public int Count { get; set; } public enum OrderStatus { Pending, Canceled, Delivered, Misdelivered, Fulfilled } } }
21.586207
101
0.578275
[ "MIT" ]
gitter-badger/Its.Cqrs
Sample.Domain/Projections/OrderTally.cs
626
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GovUk.Frontend.AspNetCore.TagHelpers; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Razor.TagHelpers; using Xunit; namespace GovUk.Frontend.AspNetCore.Tests.TagHelpers { public class AccordionTagHelperTests { [Fact] public async Task ProcessAsync_GeneratesExpectedOutput() { // Arrange var context = new TagHelperContext( tagName: "govuk-accordion", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var accordionContext = (AccordionContext)context.Items[typeof(AccordionContext)]; accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = false, HeadingContent = new HtmlString("First heading"), SummaryContent = new HtmlString("First summary") }); accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = true, HeadingContent = new HtmlString("Second heading") }); var tagHelperContent = new DefaultTagHelperContent(); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionTagHelper(new DefaultGovUkHtmlGenerator()) { Id = "testaccordion", HeadingLevel = 1, }; // Act await tagHelper.ProcessAsync(context, output); // Assert Assert.Equal( "<div class=\"govuk-accordion\" data-module=\"govuk-accordion\" id=\"testaccordion\">" + "<div class=\"govuk-accordion__section\">" + "<div class=\"govuk-accordion__section-header\">" + "<h1 class=\"govuk-accordion__section-heading\">" + "<span class=\"govuk-accordion__section-button\" id=\"testaccordion-heading-0\">First heading</span>" + "</h1>" + "<div class=\"govuk-body govuk-accordion__section-summary\" id=\"testaccordion-summary-0\">" + "</div>" + "</div>" + "<div aria-labelledby=\"testaccordion-heading-0\" class=\"govuk-accordion__section-content\" id=\"testaccordion-content-0\">" + "First content" + "</div>" + "</div>" + "<div class=\"govuk-accordion__section--expanded govuk-accordion__section\">" + "<div class=\"govuk-accordion__section-header\">" + "<h1 class=\"govuk-accordion__section-heading\">" + "<span class=\"govuk-accordion__section-button\" id=\"testaccordion-heading-1\">Second heading</span>" + "</h1>" + "</div>" + "<div aria-labelledby=\"testaccordion-heading-1\" class=\"govuk-accordion__section-content\" id=\"testaccordion-content-1\">" + "First content" + "</div>" + "</div>" + "</div>", output.AsString()); } [Fact] public async Task ProcessAsync_NoIdThrowsInvalidOperationException() { // Arrange var context = new TagHelperContext( tagName: "govuk-accordion", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var accordionContext = (AccordionContext)context.Items[typeof(AccordionContext)]; accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = false, HeadingContent = new HtmlString("First heading"), SummaryContent = new HtmlString("First summary") }); accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = true, HeadingContent = new HtmlString("Second heading") }); var tagHelperContent = new DefaultTagHelperContent(); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionTagHelper(new DefaultGovUkHtmlGenerator()); // Act & Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output)); Assert.Equal("The 'id' attribute must be specified.", ex.Message); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(7)] public async Task ProcessAsync_InvalidLevelThrowsInvalidOperationException(int level) { // Arrange var context = new TagHelperContext( tagName: "govuk-accordion", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var accordionContext = (AccordionContext)context.Items[typeof(AccordionContext)]; accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = false, HeadingContent = new HtmlString("First heading"), SummaryContent = new HtmlString("First summary") }); accordionContext.AddItem(new AccordionItem() { Content = new HtmlString("First content"), Expanded = true, HeadingContent = new HtmlString("Second heading") }); var tagHelperContent = new DefaultTagHelperContent(); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionTagHelper(new DefaultGovUkHtmlGenerator()) { Id = "testaccordion", HeadingLevel = level }; // Act & Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output)); Assert.Equal("The 'heading-level' attribute must be between 1 and 6.", ex.Message); } } public class AccordionItemTagHelperTests { [Fact] public async Task ProcessAsync_AddsItemToContext() { // Arrange var accordionContext = new AccordionContext(); var context = new TagHelperContext( tagName: "govuk-accordion-item", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var itemContext = (AccordionItemContext)context.Items[typeof(AccordionItemContext)]; itemContext.TrySetHeading(attributes: null, new HtmlString("Heading")); itemContext.TrySetSummary(attributes: null, new HtmlString("Summary")); var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemTagHelper(); // Act await tagHelper.ProcessAsync(context, output); // Assert Assert.Equal(1, accordionContext.Items.Count); var firstItem = accordionContext.Items.First(); Assert.Equal("Heading", firstItem.HeadingContent.AsString()); Assert.Equal("Summary", firstItem.SummaryContent.AsString()); Assert.Equal("Content", firstItem.Content.AsString()); } [Fact] public async Task ProcessAsync_NoHeadingThrowsInvalidOperationException() { // Arrange var accordionContext = new AccordionContext(); var context = new TagHelperContext( tagName: "govuk-accordion-item", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var itemContext = (AccordionItemContext)context.Items[typeof(AccordionItemContext)]; itemContext.TrySetSummary(attributes: null, new HtmlString("Summary")); var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemTagHelper(); // Act & Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output)); Assert.Equal("Missing <govuk-accordion-item-heading> element.", ex.Message); } } public class AccordionItemHeadingTagHelperTests { [Fact] public async Task ProcessAsync_AddsHeadingToContext() { // Arrange var accordionContext = new AccordionContext(); var itemContext = new AccordionItemContext(); var context = new TagHelperContext( tagName: "govuk-accordion-item-heading", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext }, { typeof(AccordionItemContext), itemContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item-heading", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Summary content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemHeadingTagHelper(); // Act await tagHelper.ProcessAsync(context, output); // Assert Assert.NotNull(itemContext.Heading); Assert.Equal("Summary content", itemContext.Heading.Value.content.AsString()); } [Fact] public async Task ProcessAsync_ItemAlreadyHasHeaderThrowsInvalidOperationException() { // Arrange var accordionContext = new AccordionContext(); var itemContext = new AccordionItemContext(); itemContext.TrySetHeading(attributes: null, content: new HtmlString("Existing heading")); var context = new TagHelperContext( tagName: "govuk-accordion-item-heading", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext }, { typeof(AccordionItemContext), itemContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item-heading", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Summary content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemHeadingTagHelper(); // Act & Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output)); Assert.Equal("Cannot render <govuk-accordion-item-heading> here.", ex.Message); } } public class AccordionItemSummaryTagHelperTests { [Fact] public async Task ProcessAsync_AddsSummaryToContext() { // Arrange var accordionContext = new AccordionContext(); var itemContext = new AccordionItemContext(); var context = new TagHelperContext( tagName: "govuk-accordion-item-summary", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext }, { typeof(AccordionItemContext), itemContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item-summary", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Summary content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemSummaryTagHelper(); // Act await tagHelper.ProcessAsync(context, output); // Assert Assert.NotNull(itemContext.Summary); Assert.Equal("Summary content", itemContext.Summary?.content.AsString()); } [Fact] public async Task ProcessAsync_ItemAlreadyHasSummaryThrowsInvalidOperationException() { // Arrange var accordionContext = new AccordionContext(); var itemContext = new AccordionItemContext(); itemContext.TrySetSummary(attributes: null, new HtmlString("Existing summary")); var context = new TagHelperContext( tagName: "govuk-accordion-item-summary", allAttributes: new TagHelperAttributeList(), items: new Dictionary<object, object>() { { typeof(AccordionContext), accordionContext }, { typeof(AccordionItemContext), itemContext } }, uniqueId: "test"); var output = new TagHelperOutput( "govuk-accordion-item-summary", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Summary content"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var tagHelper = new AccordionItemSummaryTagHelper(); // Act & Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => tagHelper.ProcessAsync(context, output)); Assert.Equal("Cannot render <govuk-accordion-item-summary> here.", ex.Message); } } }
41.716707
143
0.54861
[ "MIT" ]
gunndabad/govuk-frontend-aspnetcore
test/GovUk.Frontend.AspNetCore.Tests/TagHelpers/AccordionTagHelperTests.cs
17,231
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes an elastic inference accelerator. /// </summary> public partial class ElasticInferenceAccelerator { private string _type; /// <summary> /// Gets and sets the property Type. /// <para> /// The type of elastic inference accelerator. The possible values are <code>eia1.small</code>, /// <code>eia1.medium</code>, and <code>eia1.large</code>. /// </para> /// </summary> [AWSProperty(Required=true)] public string Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
29.189655
104
0.641465
[ "Apache-2.0" ]
TallyUpTeam/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/ElasticInferenceAccelerator.cs
1,693
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using MyBudget.DAL; namespace MyBudget.WebUI.Pages.LoanType { public class IndexModel : PageModel { private readonly MyBudget.DAL.MyBudgetContext _context; public IndexModel(MyBudget.DAL.MyBudgetContext context) { _context = context; } public IList<LoanTypes> LoanTypes { get;set; } public async Task OnGetAsync() { LoanTypes = await _context.LoanTypes.ToListAsync(); } } }
23.724138
63
0.6875
[ "MIT" ]
aesalmela/personal-budget
MyBudget.WebUI/Pages/LoanType/Index.cshtml.cs
690
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace CleanArchitecture.Blazor.Domain.Entities; public class DocumentType : AuditableEntity { public int Id { get; set; } public string? Name { get; set; } public string? Description { get; set; } }
29.5
71
0.725989
[ "Apache-2.0" ]
JustCallMeAD/CleanArchitectureWithBlazorServer
src/Domain/Entities/DocumentType.cs
354
C#
using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; using Pave.Compiler.Build; namespace Pave.Compiler.Tests; public class PaveTest { [Theory, MemberData(nameof(GetFiles), "Files/Successful")] public void TestParser(string directory) { var manager = new BuildManager(); manager.RegisterDefaults(); manager.SetPrintLevel(LogLevel.Warn); Assert.Equal(0, manager.Build(new BuildOptions(directory))); } public static IEnumerable<object[]> GetFiles(string directory) { return Directory.GetDirectories(directory).Select(s => new object[] { s }); } }
25.84
83
0.695046
[ "MIT" ]
Pave-lang/Pave
Test/src/PaveTest.cs
646
C#
namespace TestApp.Client.Integration.Tests.Infrastructure { using Microsoft.Extensions.DependencyInjection; using System; [NotTest] public class ClientHostBuilder { /// <summary> /// Gets the service collection. /// </summary> public IServiceCollection Services { get; } public ClientHostBuilder() { Services = new ServiceCollection(); } public static ClientHostBuilder CreateDefault(string[] args = default) { args ??= Array.Empty<string>(); var builder = new ClientHostBuilder(); return builder; } public ClientHost Build() => new ClientHost(Services.BuildServiceProvider()); } }
25.076923
81
0.68865
[ "Unlicense" ]
GillCleeren/blazor-state
Tests/Client.Integration.Tests/Infrastructure/ClientHostBuilder.cs
652
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace Globomantics.Core.Authorization { public class CustomPolicyProvider : IAuthorizationPolicyProvider { private DefaultAuthorizationPolicyProvider BackupPolicyProvider { get; } public CustomPolicyProvider(IOptions<AuthorizationOptions> options) { BackupPolicyProvider = new DefaultAuthorizationPolicyProvider(options); } public Task<AuthorizationPolicy> GetPolicyAsync(string policyName) { if (policyName.StartsWith(RequiredRightAttribute.PolicyPrefix, StringComparison.OrdinalIgnoreCase)) { var policy = new AuthorizationPolicyBuilder() .AddRequirements(new RightRequirement(policyName.Substring(RequiredRightAttribute.PolicyPrefix.Length))) .Build(); return Task.FromResult(policy); } if (policyName == RequiresMfaChallengeAttribute.PolicyName) { var policy = new AuthorizationPolicyBuilder() .AddRequirements(new MfaChallengeRequirement()) .Build(); return Task.FromResult(policy); } return BackupPolicyProvider.GetPolicyAsync(policyName); } public Task<AuthorizationPolicy> GetDefaultPolicyAsync() { return Task.FromResult(new AuthorizationPolicyBuilder(CookieAuthenticationDefaults.AuthenticationScheme, "oidc") .RequireAuthenticatedUser() .Build()); } public Task<AuthorizationPolicy> GetFallbackPolicyAsync() { return Task.FromResult<AuthorizationPolicy>(null); } } }
34.315789
124
0.645194
[ "MIT" ]
vicluar/docker-k8s-fundamentals
Globomantics.Core/Authorization/CustomPolicyProvider.cs
1,958
C#
using Xunit; using ProtoBuf.Meta; namespace ProtoBuf.unittest.Meta { public class Interfaces { public class SomeClass { public ISomeInterface SomeProperty { get; set; } } public interface ISomeInterface { int Foo { get; set; } } public class SomeClass2 : ISomeInterface { private int foo; int ISomeInterface.Foo { get { return foo; } set { foo = value; } } } [Fact] public void ExposeInterfaceWithDefaultImplementation() { var model = RuntimeTypeModel.Create(); // note the following sets for the ConstructType for the ISomeInferface, not specifically for Foo model.Add(typeof(ISomeInterface), false).Add("Foo").ConstructType = typeof(SomeClass2); model.Add(typeof(SomeClass), false).Add("SomeProperty"); var orig = new SomeClass { SomeProperty = new SomeClass2() }; orig.SomeProperty.Foo = 123; var clone = (SomeClass)model.DeepClone(orig); Assert.Equal(123, clone.SomeProperty.Foo); } } }
26.914894
109
0.535178
[ "Apache-2.0" ]
ASuurkuusk/protobuf-net
src/protobuf-net.Test/Meta/Interfaces.cs
1,267
C#
using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osuTK; using osuTK.Graphics; using osuTK.Input; namespace TCC.Installer.Game.Components.UI.Containers { public partial class TCCScrollContainer { protected class TCCScrollbar : ScrollbarContainer { private const float dimSize = 10; private const float margin = 3; private Color4 hoverColour; private Color4 defaultColour; private Color4 highlightColour; private readonly Box box; public TCCScrollbar(Direction scrollDir) : base(scrollDir) { Blending = BlendingParameters.Additive; CornerRadius = 5; Masking = true; Margin = new MarginPadding { Horizontal = scrollDir == Direction.Vertical ? margin : 0, Vertical = scrollDir == Direction.Horizontal ? margin : 0, }; Child = box = new Box { RelativeSizeAxes = Axes.Both }; ResizeTo(1); } [BackgroundDependencyLoader] private void load() { Colour = defaultColour = TCCColours.FromHex("888"); hoverColour = TCCColours.FromHex("fff"); highlightColour = TCCColours.FromHex("88b300"); } public override void ResizeTo(float val, int duration = 0, Easing easing = Easing.None) { Vector2 size = new Vector2(dimSize) { [(int)ScrollDirection] = val }; this.ResizeTo(size, duration, easing); } protected override bool OnHover(HoverEvent e) { this.FadeColour(hoverColour, 100); return true; } protected override void OnHoverLost(HoverLostEvent e) { this.FadeColour(defaultColour, 100); } protected override bool OnMouseDown(MouseDownEvent e) { if (!base.OnMouseDown(e)) return false; box.FadeColour(highlightColour, 100); return true; } protected override void OnMouseUp(MouseUpEvent e) { if (e.Button != MouseButton.Left) { } else { box.FadeColour(Color4.White, 100); base.OnMouseUp(e); } } } } }
30.111111
99
0.505904
[ "MIT" ]
Coppertine/TCC.Installer
TCC.Installer.Game/Components/UI/Containers/TCCScrollbar.cs
2,712
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Encryption { using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; internal static class EncryptionProcessor { internal static readonly CosmosJsonDotNetSerializer baseSerializer = new CosmosJsonDotNetSerializer(); /// <remarks> /// If there isn't any PathsToEncrypt, input stream will be returned without any modification. /// Else input stream will be disposed, and a new stream is returned. /// In case of an exception, input stream won't be disposed, but position will be end of stream. /// </remarks> public static async Task<Stream> EncryptAsync( Stream input, Encryptor encryptor, EncryptionOptions encryptionOptions, CosmosDiagnosticsContext diagnosticsContext, CancellationToken cancellationToken) { Debug.Assert(diagnosticsContext != null); if (input == null) { throw new ArgumentNullException(nameof(input)); } if (encryptor == null) { throw new ArgumentNullException(nameof(encryptor)); } if (encryptionOptions == null) { throw new ArgumentNullException(nameof(encryptionOptions)); } if (string.IsNullOrWhiteSpace(encryptionOptions.DataEncryptionKeyId)) { throw new ArgumentNullException(nameof(encryptionOptions.DataEncryptionKeyId)); } if (string.IsNullOrWhiteSpace(encryptionOptions.EncryptionAlgorithm)) { throw new ArgumentNullException(nameof(encryptionOptions.EncryptionAlgorithm)); } if (encryptionOptions.PathsToEncrypt == null) { throw new ArgumentNullException(nameof(encryptionOptions.PathsToEncrypt)); } if (!encryptionOptions.PathsToEncrypt.Any()) { return input; } foreach (string path in encryptionOptions.PathsToEncrypt) { if (string.IsNullOrWhiteSpace(path) || path[0] != '/' || path.LastIndexOf('/') != 0) { throw new ArgumentException($"Invalid path {path ?? string.Empty}", nameof(encryptionOptions.PathsToEncrypt)); } } JObject itemJObj = EncryptionProcessor.baseSerializer.FromStream<JObject>(input); JObject toEncryptJObj = new JObject(); foreach (string pathToEncrypt in encryptionOptions.PathsToEncrypt) { string propertyName = pathToEncrypt.Substring(1); if (!itemJObj.TryGetValue(propertyName, out JToken propertyValue)) { throw new ArgumentException($"{nameof(encryptionOptions.PathsToEncrypt)} includes a path: '{pathToEncrypt}' which was not found."); } toEncryptJObj.Add(propertyName, propertyValue.Value<JToken>()); itemJObj.Remove(propertyName); } MemoryStream memoryStream = EncryptionProcessor.baseSerializer.ToStream<JObject>(toEncryptJObj); Debug.Assert(memoryStream != null); Debug.Assert(memoryStream.TryGetBuffer(out _)); byte[] plainText = memoryStream.ToArray(); byte[] cipherText = await encryptor.EncryptAsync( plainText, encryptionOptions.DataEncryptionKeyId, encryptionOptions.EncryptionAlgorithm, cancellationToken); if (cipherText == null) { throw new InvalidOperationException($"{nameof(Encryptor)} returned null cipherText from {nameof(EncryptAsync)}."); } EncryptionProperties encryptionProperties = new EncryptionProperties( encryptionFormatVersion: 2, encryptionOptions.EncryptionAlgorithm, encryptionOptions.DataEncryptionKeyId, encryptedData: cipherText); itemJObj.Add(Constants.EncryptedInfo, JObject.FromObject(encryptionProperties)); input.Dispose(); return EncryptionProcessor.baseSerializer.ToStream(itemJObj); } /// <remarks> /// If there isn't any data that needs to be decrypted, input stream will be returned without any modification. /// Else input stream will be disposed, and a new stream is returned. /// In case of an exception, input stream won't be disposed, but position will be end of stream. /// </remarks> public static async Task<Stream> DecryptAsync( Stream input, Encryptor encryptor, CosmosDiagnosticsContext diagnosticsContext, CancellationToken cancellationToken) { Debug.Assert(input != null); Debug.Assert(input.CanSeek); Debug.Assert(encryptor != null); Debug.Assert(diagnosticsContext != null); JObject itemJObj; using (StreamReader sr = new StreamReader(input, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { using (JsonTextReader jsonTextReader = new JsonTextReader(sr)) { itemJObj = JsonSerializer.Create().Deserialize<JObject>(jsonTextReader); } } JProperty encryptionPropertiesJProp = itemJObj.Property(Constants.EncryptedInfo); JObject encryptionPropertiesJObj = null; if (encryptionPropertiesJProp != null && encryptionPropertiesJProp.Value != null && encryptionPropertiesJProp.Value.Type == JTokenType.Object) { encryptionPropertiesJObj = (JObject)encryptionPropertiesJProp.Value; } if (encryptionPropertiesJObj == null) { input.Position = 0; return input; } EncryptionProperties encryptionProperties = encryptionPropertiesJObj.ToObject<EncryptionProperties>(); JObject plainTextJObj = await EncryptionProcessor.DecryptContentAsync( encryptionProperties, encryptor, diagnosticsContext, cancellationToken); foreach (JProperty property in plainTextJObj.Properties()) { itemJObj.Add(property.Name, property.Value); } itemJObj.Remove(Constants.EncryptedInfo); input.Dispose(); return EncryptionProcessor.baseSerializer.ToStream(itemJObj); } public static async Task<JObject> DecryptAsync( JObject document, Encryptor encryptor, CosmosDiagnosticsContext diagnosticsContext, CancellationToken cancellationToken) { Debug.Assert(document != null); Debug.Assert(encryptor != null); Debug.Assert(diagnosticsContext != null); if (!document.TryGetValue(Constants.EncryptedInfo, out JToken encryptedInfo)) { return document; } EncryptionProperties encryptionProperties = JsonConvert.DeserializeObject<EncryptionProperties>(encryptedInfo.ToString()); JObject plainTextJObj = await EncryptionProcessor.DecryptContentAsync( encryptionProperties, encryptor, diagnosticsContext, cancellationToken); document.Remove(Constants.EncryptedInfo); foreach (JProperty property in plainTextJObj.Properties()) { document.Add(property.Name, property.Value); } return document; } private static async Task<JObject> DecryptContentAsync( EncryptionProperties encryptionProperties, Encryptor encryptor, CosmosDiagnosticsContext diagnosticsContext, CancellationToken cancellationToken) { if (encryptionProperties.EncryptionFormatVersion != 2) { throw new NotSupportedException($"Unknown encryption format version: {encryptionProperties.EncryptionFormatVersion}. Please upgrade your SDK to the latest version."); } byte[] plainText = await encryptor.DecryptAsync( encryptionProperties.EncryptedData, encryptionProperties.DataEncryptionKeyId, encryptionProperties.EncryptionAlgorithm, cancellationToken); if (plainText == null) { throw new InvalidOperationException($"{nameof(Encryptor)} returned null plainText from {nameof(DecryptAsync)}."); } JObject plainTextJObj; using (MemoryStream memoryStream = new MemoryStream(plainText)) using (StreamReader streamReader = new StreamReader(memoryStream)) using (JsonTextReader jsonTextReader = new JsonTextReader(streamReader)) { plainTextJObj = JObject.Load(jsonTextReader); } return plainTextJObj; } } }
39.901235
182
0.598185
[ "MIT" ]
Camios/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos.Encryption/src/EncryptionProcessor.cs
9,698
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // This file was automatically generated and should not be edited directly. using System.Runtime.InteropServices; namespace SharpVk.Interop.NVidia { /// <summary> /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe struct DedicatedAllocationMemoryAllocateInfo { /// <summary> /// The type of this structure. /// </summary> public StructureType SType; /// <summary> /// Null or an extension-specific structure. /// </summary> public void* Next; /// <summary> /// image is null or a handle of an image which this memory will be /// bound to. /// </summary> public Image Image; /// <summary> /// buffer is null or a handle of a buffer which this memory will be /// bound to. /// </summary> public Buffer Buffer; } }
36.77193
81
0.67271
[ "MIT" ]
xuri02/SharpVk
src/SharpVk/Interop/NVidia/DedicatedAllocationMemoryAllocateInfo.gen.cs
2,096
C#
using System; using System.Runtime.CompilerServices; using Svelto.Common; namespace Svelto.ECS.DataStructures { public struct NativeDynamicArrayCast<T>:IDisposable where T : struct { public NativeDynamicArrayCast(uint size, Allocator allocator) { _array = NativeDynamicArray.Alloc<T>(allocator, size); } public NativeDynamicArrayCast(NativeDynamicArray array) : this() { _array = array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Count() => _array.Count<T>(); public int count { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array.Count<T>(); } public int capacity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => _array.Capacity<T>(); } public ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref _array.Get<T>((uint) index); } public ref T this[uint index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref _array.Get<T>(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(in T id) { _array.Add(id); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void UnorderedRemoveAt(uint index) { _array.UnorderedRemoveAt<T>(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RemoveAt(uint index) { _array.RemoveAt<T>(index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { _array.FastClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { _array.Dispose(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T AddAt(uint lastIndex) { return ref _array.AddAt<T>(lastIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Resize(uint newSize) { _array.Resize<T>(newSize); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public NativeDynamicArray ToNativeArray() { return _array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(uint index, in T value) { _array.Set(index, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(int index, in T value) { _array.Set((uint)index, value); } public bool isValid => _array.isValid; NativeDynamicArray _array; } }
32.756098
92
0.625838
[ "MIT" ]
cathei/Svelto.ECS
com.sebaslab.svelto.ecs/DataStructures/Unmanaged/NativeDynamicArrayCast.cs
2,688
C#
using System; namespace Elders.Skynet.Core { public static class MessageFactory { public static object ToPublishedMessage(this IMessage message, IMessageContext sender) { var genericType = typeof(Message<>); var messageType = message.GetType(); var type = genericType.MakeGenericType(messageType); return Activator.CreateInstance(type, new object[] { sender, message }); } } public class Message<T> { public Message(IMessageContext sender, T payload) { Context = sender; Payload = payload; } public IMessageContext Context { get; private set; } public T Payload { get; private set; } } }
27.814815
94
0.603196
[ "Apache-2.0" ]
Elders/Skynet
src/Elders.Skynet.Core/Message.cs
753
C#
using Microsoft.AspNetCore.Mvc; using Storm.Api.Swaggers.Attributes; namespace Storm.Api.Sample.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] {"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"}; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] [Category("SampleCategory")] public IEnumerable<WeatherForecast> Get() { Random? rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast {Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)]}) .ToArray(); } [HttpGet("all")] public IEnumerable<WeatherForecast> GetAll() { Random? rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast {Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)]}) .ToArray(); } [HttpPost("file")] [Category("FileUpload")] public IEnumerable<WeatherForecast> UploadFile(IFormFile file) { Random? rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast {Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)]}) .ToArray(); } [HttpGet("file")] [Category("FileUpload")] public IEnumerable<WeatherForecast> GetFile() { Random? rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast {Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)]}) .ToArray(); } [HttpGet("file2")] [Category("FileUpload")] public IEnumerable<WeatherForecast> GetFile2() { Random? rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast {Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)]}) .ToArray(); } }
35.177419
188
0.717561
[ "MIT" ]
Julien-Mialon/Storm.Api
sample/Storm.Api.Sample/Controllers/WeatherForecastController.cs
2,183
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace SpaceTrader.Net.Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // In production, the React files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } }); } } }
32.661765
143
0.590725
[ "MIT" ]
tympaniplayer/SpaceTrader.Net
src/SpaceTrader.Net.Web/Startup.cs
2,221
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("AnnoyingEmailsDES.Client.Installer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AnnoyingEmailsDES.Client.Installer")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
37.413793
84
0.748387
[ "MIT" ]
zbigniewmarszolik/AnnoyingEmailsDES
AnnoyingEmailsDES/AnnoyingEmailsDES.Client.Installer/Properties/AssemblyInfo.cs
1,088
C#
using System; using System.Threading.Tasks; using AowCore.Application; using AowCore.AppWeb.Helpers; using AowCore.AppWeb.ViewModels; using AowCore.Domain; using Microsoft.AspNetCore.Mvc; namespace AowCore.AppWeb.Areas.MyBooks.Controllers { [Area("MyBooks")] public class DashBoardController : Controller { private readonly ICookieHelper _cookieHelper; private readonly IApplicationDbContext _context; public DashBoardController(IApplicationDbContext context, ICookieHelper cookieHelper) { _context = context; _cookieHelper = cookieHelper; } public IActionResult Index() { return View(); } public IActionResult Blogs() { return View(); } [ValidateAntiForgeryToken] [HttpPost] public IActionResult Index(Guid companyId, Guid financialYearId, string themeId) { _cookieHelper.Set("cmpCookee", companyId.ToString(), 60); _cookieHelper.Set("fYrCookee", financialYearId.ToString(), 60); return Json(new { success = true, newLocation = "/MyBooks/DashBoard/DashBoard/" }); } public async Task<IActionResult> DashBoard() { var cmpid = _cookieHelper.Get("cmpCookee"); var fid = _cookieHelper.Get("fYrCookee"); if (string.IsNullOrEmpty(cmpid) && string.IsNullOrEmpty(fid)) { return Redirect("/"); } Guid fyrId = Guid.Parse(fid); Guid cmpidG = Guid.Parse(cmpid); Company company = await _context.Companies.FindAsync(cmpidG); FinancialYear fyr = await _context.FinancialYears.FindAsync(fyrId); DashboardViewModel dashboardViewModel = new DashboardViewModel { CompanyName = company.CompanyName, FyrName = string.Format("{0} - {1}", fyr.Start.Value.ToString("yyyy-MM-dd"), fyr.End.Value.ToString("yyyy-MM-dd")).Trim() }; return View(dashboardViewModel); } public IActionResult CookieCheck(string returnUrl) { var cmpid = _cookieHelper.Get("cmpCookee"); var fid = _cookieHelper.Get("fYrCookee"); if (string.IsNullOrEmpty(cmpid) && string.IsNullOrEmpty(fid)) { return Redirect("/"); } return RedirectToPage(returnUrl); } } }
33.567568
137
0.599839
[ "Apache-2.0" ]
dpk2789/aowmvc
AowCore.AppWeb/Areas/MyBooks/Controllers/DashBoardController.cs
2,486
C#
namespace Crikkit__Minecraft_Server_CP_ { partial class NewServer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.button_Create = new System.Windows.Forms.Button(); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.panel1 = new System.Windows.Forms.Panel(); this.panel2 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.textBoxWithWatermark1 = new Crikkit__Minecraft_Server_CP_.TextBoxWithWatermark(this.components); this.comboBox_ServerJarType = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // button_Create // this.button_Create.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(101)))), ((int)(((byte)(104))))); this.button_Create.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button_Create.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button_Create.ForeColor = System.Drawing.Color.White; this.button_Create.Location = new System.Drawing.Point(3, 3); this.button_Create.Name = "button_Create"; this.button_Create.Size = new System.Drawing.Size(154, 28); this.button_Create.TabIndex = 0; this.button_Create.Text = "Create Server"; this.button_Create.UseVisualStyleBackColor = false; this.button_Create.Click += new System.EventHandler(this.button_Create_Click); // // numericUpDown1 // this.numericUpDown1.Location = new System.Drawing.Point(117, 193); this.numericUpDown1.Maximum = new decimal(new int[] { 10000, 0, 0, 0}); this.numericUpDown1.Minimum = new decimal(new int[] { 128, 0, 0, 0}); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(79, 20); this.numericUpDown1.TabIndex = 2; this.numericUpDown1.Value = new decimal(new int[] { 1024, 0, 0, 0}); // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(43)))), ((int)(((byte)(43)))), ((int)(((byte)(43))))); this.panel1.Controls.Add(this.button_Create); this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 229); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(201, 33); this.panel1.TabIndex = 3; // // panel2 // this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(43)))), ((int)(((byte)(43)))), ((int)(((byte)(43))))); this.panel2.Controls.Add(this.comboBox_ServerJarType); this.panel2.Controls.Add(this.label2); this.panel2.Controls.Add(this.label1); this.panel2.Controls.Add(this.textBoxWithWatermark1); this.panel2.Controls.Add(this.numericUpDown1); this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(200, 226); this.panel2.TabIndex = 4; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Top; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(168, 18); this.label2.TabIndex = 4; this.label2.Text = "Server Specifications"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(12, 193); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(92, 17); this.label1.TabIndex = 3; this.label1.Text = "Memory (MB)"; // // textBoxWithWatermark1 // this.textBoxWithWatermark1.BackColor = System.Drawing.Color.White; this.textBoxWithWatermark1.ForeColor = System.Drawing.Color.Gray; this.textBoxWithWatermark1.Location = new System.Drawing.Point(3, 31); this.textBoxWithWatermark1.Name = "textBoxWithWatermark1"; this.textBoxWithWatermark1.Size = new System.Drawing.Size(193, 20); this.textBoxWithWatermark1.TabIndex = 1; this.textBoxWithWatermark1.Text = "Server name"; this.textBoxWithWatermark1.Watermark = "Server name"; // // comboBox_ServerJarType // this.comboBox_ServerJarType.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.comboBox_ServerJarType.FormattingEnabled = true; this.comboBox_ServerJarType.Location = new System.Drawing.Point(3, 57); this.comboBox_ServerJarType.Name = "comboBox_ServerJarType"; this.comboBox_ServerJarType.Size = new System.Drawing.Size(193, 21); this.comboBox_ServerJarType.TabIndex = 5; this.comboBox_ServerJarType.Text = "Server Jar Type"; // // NewServer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(63)))), ((int)(((byte)(65))))); this.ClientSize = new System.Drawing.Size(201, 262); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "NewServer"; this.Text = "NewServer"; ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); this.panel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private TextBoxWithWatermark textBoxWithWatermark1; private System.Windows.Forms.Button button_Create; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBox_ServerJarType; } }
48.623596
232
0.594801
[ "Apache-2.0" ]
WiseHollow/Crikkit-Minecraft-Server-CP-
Crikkit (Minecraft Server CP)/NewServer.Designer.cs
8,657
C#
using System; using System.Windows.Forms; using SkypeAssistant.App.Properties; using SkypeAssistant.Client.Interfaces; using TinyIoC; namespace SkypeAssistant.App { class Program { static void Main(string[] args) { var container = TinyIoCContainer.Current; IoC.ConfigureContainer(container); var skypeClient = container.Resolve<ISkypeClient>(); container.BuildUp(skypeClient); skypeClient.StartClient(); using (var icon = new ProcessIcon(skypeClient)) { icon.Display(); Application.Run(); } } public class ProcessIcon : IDisposable { private readonly ISkypeClient _skypeClient; private readonly NotifyIcon notifyIcon; public ProcessIcon(ISkypeClient skypeClient) { this._skypeClient = skypeClient; this.notifyIcon = new NotifyIcon(); } public void Display() { notifyIcon.Icon = Resources.TrayIcon_Running; notifyIcon.Text = Resources.TrayIcon_Running_Text; notifyIcon.Visible = true; notifyIcon.ContextMenuStrip = new ContextMenuStrip(); var start = new ToolStripMenuItem("Start") { Enabled = false }; var stop = new ToolStripMenuItem("Stop") { Enabled = true }; var exit = new ToolStripMenuItem("Exit"); start.Click += (sender, args) => { if (_skypeClient.IsRunning == false) { _skypeClient.StartClient(); notifyIcon.Icon = Resources.TrayIcon_Running; notifyIcon.Text = Resources.TrayIcon_Running_Text; start.Enabled = false; stop.Enabled = true; } }; stop.Click += (sender, args) => { if (_skypeClient.IsRunning) { _skypeClient.StopClient(); notifyIcon.Icon = Resources.TrayIcon_Stopped; notifyIcon.Text = Resources.TrayIcon_Stopped_Text; start.Enabled = true; stop.Enabled = false; } }; exit.Click += (sender, args) => { if (_skypeClient.IsRunning) { _skypeClient.StopClient(); } Application.Exit(); }; notifyIcon.ContextMenuStrip.Items.Add(start); notifyIcon.ContextMenuStrip.Items.Add(stop); notifyIcon.ContextMenuStrip.Items.Add(exit); } public void Dispose() { notifyIcon.Dispose(); } } } }
31.443299
79
0.482295
[ "MIT" ]
josh-leeming/SkypeAssistant
SkypeAssistant.App/Program.cs
3,052
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Versioning; using System.Threading.Tasks; using Microsoft.Extensions.FileSystemGlobbing; using Microsoft.VisualStudio.TestPlatform.Client; using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; using Microsoft.VisualStudio.TestPlatform.CommandLine.Publisher; using Microsoft.VisualStudio.TestPlatform.CommandLine.TestPlatformHelpers; using Microsoft.VisualStudio.TestPlatform.CommandLineUtilities; using Microsoft.VisualStudio.TestPlatform.Common.Utilities; using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Engine; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces; using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using vstest.console.Internal; using vstest.console.UnitTests.Processors; #nullable disable namespace Microsoft.VisualStudio.TestPlatform.CommandLine.UnitTests.Processors; // <summary> // Tests for ListTestsArgumentProcessor // </summary> [TestClass] public class ListTestsArgumentProcessorTests { private readonly Mock<IFileHelper> _mockFileHelper; private readonly Mock<IAssemblyMetadataProvider> _mockAssemblyMetadataProvider; private readonly InferHelper _inferHelper; private readonly string _dummyTestFilePath = "DummyTest.dll"; private readonly Mock<ITestPlatformEventSource> _mockTestPlatformEventSource; private readonly Task<IMetricsPublisher> _mockMetricsPublisherTask; private readonly Mock<IMetricsPublisher> _mockMetricsPublisher; private readonly Mock<IProcessHelper> _mockProcessHelper; private readonly Mock<ITestRunAttachmentsProcessingManager> _mockAttachmentsProcessingManager; private static ListTestsArgumentExecutor GetExecutor(ITestRequestManager testRequestManager, IOutput output) { var runSettingsProvider = new TestableRunSettingsProvider(); runSettingsProvider.AddDefaultRunSettings(); var listTestsArgumentExecutor = new ListTestsArgumentExecutor( CommandLineOptions.Instance, runSettingsProvider, testRequestManager, output ?? ConsoleOutput.Instance); return listTestsArgumentExecutor; } [TestCleanup] public void Cleanup() { CommandLineOptions.Instance.Reset(); } public ListTestsArgumentProcessorTests() { _mockFileHelper = new Mock<IFileHelper>(); _mockFileHelper.Setup(fh => fh.Exists(_dummyTestFilePath)).Returns(true); _mockFileHelper.Setup(x => x.GetCurrentDirectory()).Returns(""); _mockMetricsPublisher = new Mock<IMetricsPublisher>(); _mockMetricsPublisherTask = Task.FromResult(_mockMetricsPublisher.Object); _mockTestPlatformEventSource = new Mock<ITestPlatformEventSource>(); _mockAssemblyMetadataProvider = new Mock<IAssemblyMetadataProvider>(); _mockAssemblyMetadataProvider.Setup(x => x.GetArchitecture(It.IsAny<string>())).Returns(Architecture.X64); _mockAssemblyMetadataProvider.Setup(x => x.GetFrameWork(It.IsAny<string>())).Returns(new FrameworkName(Constants.DotNetFramework40)); _inferHelper = new InferHelper(_mockAssemblyMetadataProvider.Object); _mockProcessHelper = new Mock<IProcessHelper>(); _mockAttachmentsProcessingManager = new Mock<ITestRunAttachmentsProcessingManager>(); } /// <summary> /// The help argument processor get metadata should return help argument processor capabilities. /// </summary> [TestMethod] public void GetMetadataShouldReturnListTestsArgumentProcessorCapabilities() { var processor = new ListTestsArgumentProcessor(); Assert.IsTrue(processor.Metadata.Value is ListTestsArgumentProcessorCapabilities); } /// <summary> /// The help argument processor get executer should return help argument processor capabilities. /// </summary> [TestMethod] public void GetExecuterShouldReturnListTestsArgumentProcessorCapabilities() { var processor = new ListTestsArgumentProcessor(); Assert.IsTrue(processor.Executor.Value is ListTestsArgumentExecutor); } #region ListTestsArgumentProcessorCapabilitiesTests [TestMethod] public void CapabilitiesShouldReturnAppropriateProperties() { var capabilities = new ListTestsArgumentProcessorCapabilities(); Assert.AreEqual("/ListTests", capabilities.CommandName); Assert.AreEqual("/lt", capabilities.ShortCommandName); var expected = "-lt|--ListTests|/lt|/ListTests:<File Name>\r\n Lists all discovered tests from the given test container."; Assert.AreEqual(expected.NormalizeLineEndings().ShowWhiteSpace(), capabilities.HelpContentResourceName.NormalizeLineEndings().ShowWhiteSpace()); Assert.AreEqual(HelpContentPriority.ListTestsArgumentProcessorHelpPriority, capabilities.HelpPriority); Assert.IsTrue(capabilities.IsAction); Assert.AreEqual(ArgumentProcessorPriority.Normal, capabilities.Priority); Assert.IsFalse(capabilities.AllowMultiple); Assert.IsFalse(capabilities.AlwaysExecute); Assert.IsFalse(capabilities.IsSpecialCommand); } #endregion #region ListTestsArgumentExecutorTests [TestMethod] public void ExecutorInitializeWithValidSourceShouldAddItToTestSources() { CommandLineOptions.Instance.FileHelper = _mockFileHelper.Object; CommandLineOptions.Instance.FilePatternParser = new FilePatternParser(new Mock<Matcher>().Object, _mockFileHelper.Object); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, TestPlatformFactory.GetTestPlatform(), TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var executor = GetExecutor(testRequestManager, null); executor.Initialize(_dummyTestFilePath); Assert.IsTrue(Enumerable.Contains(CommandLineOptions.Instance.Sources, _dummyTestFilePath)); } [TestMethod] public void ExecutorExecuteForNoSourcesShouldReturnFail() { CommandLineOptions.Instance.Reset(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, TestPlatformFactory.GetTestPlatform(), TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var executor = GetExecutor(testRequestManager, null); Assert.ThrowsException<CommandLineException>(() => executor.Execute()); } [TestMethod] public void ExecutorExecuteShouldThrowTestPlatformException() { var mockTestPlatform = new Mock<ITestPlatform>(); var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Throws(new TestPlatformException("DummyTestPlatformException")); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny<IRequestData>(), It.IsAny<DiscoveryCriteria>(), It.IsAny<TestPlatformOptions>())).Returns(mockDiscoveryRequest.Object); ResetAndAddSourceToCommandLineOptions(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, mockTestPlatform.Object, TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var executor = GetExecutor(testRequestManager, null); Assert.ThrowsException<TestPlatformException>(() => executor.Execute()); } [TestMethod] public void ExecutorExecuteShouldThrowSettingsException() { var mockTestPlatform = new Mock<ITestPlatform>(); var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Throws(new SettingsException("DummySettingsException")); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny<IRequestData>(), It.IsAny<DiscoveryCriteria>(), It.IsAny<TestPlatformOptions>())).Returns(mockDiscoveryRequest.Object); ResetAndAddSourceToCommandLineOptions(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, mockTestPlatform.Object, TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var listTestsArgumentExecutor = GetExecutor(testRequestManager, null); Assert.ThrowsException<SettingsException>(() => listTestsArgumentExecutor.Execute()); } [TestMethod] public void ExecutorExecuteShouldThrowInvalidOperationException() { var mockTestPlatform = new Mock<ITestPlatform>(); var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Throws(new InvalidOperationException("DummyInvalidOperationException")); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny<IRequestData>(), It.IsAny<DiscoveryCriteria>(), It.IsAny<TestPlatformOptions>())).Returns(mockDiscoveryRequest.Object); ResetAndAddSourceToCommandLineOptions(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, mockTestPlatform.Object, TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var listTestsArgumentExecutor = GetExecutor(testRequestManager, null); Assert.ThrowsException<InvalidOperationException>(() => listTestsArgumentExecutor.Execute()); } [TestMethod] public void ExecutorExecuteShouldThrowOtherExceptions() { var mockTestPlatform = new Mock<ITestPlatform>(); var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Throws(new Exception("DummyException")); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny<IRequestData>(), It.IsAny<DiscoveryCriteria>(), It.IsAny<TestPlatformOptions>())).Returns(mockDiscoveryRequest.Object); ResetAndAddSourceToCommandLineOptions(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, mockTestPlatform.Object, TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); var executor = GetExecutor(testRequestManager, null); Assert.ThrowsException<Exception>(() => executor.Execute()); } [TestMethod] public void ExecutorExecuteShouldOutputDiscoveredTestsAndReturnSuccess() { var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); var mockConsoleOutput = new Mock<IOutput>(); RunListTestArgumentProcessorExecuteWithMockSetup(mockDiscoveryRequest, mockConsoleOutput); // Assert mockDiscoveryRequest.Verify(dr => dr.DiscoverAsync(), Times.Once); mockConsoleOutput.Verify((IOutput co) => co.WriteLine(" Test1", OutputLevel.Information)); mockConsoleOutput.Verify((IOutput co) => co.WriteLine(" Test2", OutputLevel.Information)); } [TestMethod] public void ListTestArgumentProcessorExecuteShouldInstrumentDiscoveryRequestStart() { var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); var mockConsoleOutput = new Mock<IOutput>(); RunListTestArgumentProcessorExecuteWithMockSetup(mockDiscoveryRequest, mockConsoleOutput); _mockTestPlatformEventSource.Verify(x => x.DiscoveryRequestStart(), Times.Once); } [TestMethod] public void ListTestArgumentProcessorExecuteShouldInstrumentDiscoveryRequestStop() { var mockDiscoveryRequest = new Mock<IDiscoveryRequest>(); var mockConsoleOutput = new Mock<IOutput>(); RunListTestArgumentProcessorExecuteWithMockSetup(mockDiscoveryRequest, mockConsoleOutput); _mockTestPlatformEventSource.Verify(x => x.DiscoveryRequestStop(), Times.Once); } #endregion private void RunListTestArgumentProcessorExecuteWithMockSetup(Mock<IDiscoveryRequest> mockDiscoveryRequest, Mock<IOutput> mockConsoleOutput) { var mockTestPlatform = new Mock<ITestPlatform>(); var list = new List<TestCase> { new TestCase("Test1", new Uri("http://FooTestUri1"), "Source1"), new TestCase("Test2", new Uri("http://FooTestUri2"), "Source2") }; mockDiscoveryRequest.Setup(dr => dr.DiscoverAsync()).Raises(dr => dr.OnDiscoveredTests += null, new DiscoveredTestsEventArgs(list)); mockTestPlatform.Setup(tp => tp.CreateDiscoveryRequest(It.IsAny<IRequestData>(), It.IsAny<DiscoveryCriteria>(), It.IsAny<TestPlatformOptions>())).Returns(mockDiscoveryRequest.Object); ResetAndAddSourceToCommandLineOptions(); var testRequestManager = new TestRequestManager(CommandLineOptions.Instance, mockTestPlatform.Object, TestRunResultAggregator.Instance, _mockTestPlatformEventSource.Object, _inferHelper, _mockMetricsPublisherTask, _mockProcessHelper.Object, _mockAttachmentsProcessingManager.Object); GetExecutor(testRequestManager, mockConsoleOutput.Object).Execute(); } private void ResetAndAddSourceToCommandLineOptions() { CommandLineOptions.Instance.Reset(); CommandLineOptions.Instance.FileHelper = _mockFileHelper.Object; CommandLineOptions.Instance.FilePatternParser = new FilePatternParser(new Mock<Matcher>().Object, _mockFileHelper.Object); CommandLineOptions.Instance.AddSource(_dummyTestFilePath); } }
50.111111
305
0.770025
[ "MIT" ]
Wivra/vstest
test/vstest.console.UnitTests/Processors/ListTestsArgumentProcessorTests.cs
14,432
C#
// <copyright file="IInvalidDummyFieldObject.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> namespace Datadog.Trace.DuckTyping.Tests.Errors.Fields.TypeChaining.ProxiesDefinitions { public interface IInvalidDummyFieldObject { [DuckField] int EvilNumber { get; set; } } }
36.714286
113
0.745136
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/test/Datadog.Trace.DuckTyping.Tests/Errors/Fields/TypeChaining/ProxiesDefinitions/IInvalidDummyFieldObject.cs
516
C#
// ReSharper disable All using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using MixERP.Net.Schemas.Core.Data; using MixERP.Net.EntityParser; using PetaPoco; using CustomField = PetaPoco.CustomField; namespace MixERP.Net.Api.Core.Fakes { public class ShipperScrudViewRepository : IShipperScrudViewRepository { public long Count() { return 1; } public IEnumerable<MixERP.Net.Entities.Core.ShipperScrudView> Get() { return Enumerable.Repeat(new MixERP.Net.Entities.Core.ShipperScrudView(), 1); } public IEnumerable<MixERP.Net.Entities.Core.ShipperScrudView> GetPaginatedResult() { return Enumerable.Repeat(new MixERP.Net.Entities.Core.ShipperScrudView(), 1); } public IEnumerable<MixERP.Net.Entities.Core.ShipperScrudView> GetPaginatedResult(long pageNumber) { return Enumerable.Repeat(new MixERP.Net.Entities.Core.ShipperScrudView(), 1); } public IEnumerable<DisplayField> GetDisplayFields() { return Enumerable.Repeat(new DisplayField(), 1); } public long CountWhere(List<EntityParser.Filter> filters) { return 1; } public IEnumerable<MixERP.Net.Entities.Core.ShipperScrudView> GetWhere(long pageNumber, List<EntityParser.Filter> filters) { return Enumerable.Repeat(new MixERP.Net.Entities.Core.ShipperScrudView(), 1); } public List<EntityParser.Filter> GetFilters(string catalog, string filterName) { return Enumerable.Repeat(new EntityParser.Filter(), 1).ToList(); } public long CountFiltered(string filterName) { return 1; } public IEnumerable<MixERP.Net.Entities.Core.ShipperScrudView> GetFiltered(long pageNumber, string filterName) { return Enumerable.Repeat(new MixERP.Net.Entities.Core.ShipperScrudView(), 1); } } }
30.537313
130
0.656403
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/Web API/Core/Fakes/ShipperScrudViewRepository.cs
2,046
C#
using System; using System.Collections.Generic; using System.Text; namespace TodoViewModel { public class TodoItemForUpdateViewModel { public string Name { get; set; } public bool IsComplete { get; set; } } }
18.384615
44
0.677824
[ "Apache-2.0" ]
bozhiqian/ASP.NET-Core-Auth
TodoWithIdentityServer/TodoViewModel/TodoItemForUpdateViewModel.cs
241
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.ComponentModel; using System.Globalization; using System.Threading; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.Progress; using OpenLiveWriter.Api; using OpenLiveWriter.Localization; namespace OpenLiveWriter.PostEditor.ContentSources { internal class UrlContentRetreivalWithProgress { public static bool ExecuteSimpleContentRetreival( IWin32Window dialogOwner, ContentSourceInfo contentSourceInfo, string url, ref string title, ref string newContent) { try { // if there is progress requested then just do it on the main UI thread if (contentSourceInfo.UrlContentSourceRequiresProgress) { // create the progress dialog and the async operation UrlContentRetreivalWithProgressDialog progressDialog = new UrlContentRetreivalWithProgressDialog(contentSourceInfo); progressDialog.CreateControl(); SimpleUrlContentRetreivalAsyncOperation asyncOperation = new SimpleUrlContentRetreivalAsyncOperation(progressDialog, contentSourceInfo.Instance as ContentSource, url, title); // execute and retreive results if (ExecuteWithProgress(dialogOwner, progressDialog, asyncOperation, contentSourceInfo)) { title = asyncOperation.Title; newContent = asyncOperation.NewContent; return true; } else { return false; } } else { try { (contentSourceInfo.Instance as ContentSource).CreateContentFromUrl(url, ref title, ref newContent); return true; } catch (Exception ex) { ContentSourceManager.DisplayContentRetreivalError(dialogOwner, ex, contentSourceInfo); return false; } } } catch (Exception ex) { Trace.Fail("Unexpected exception executing network operation for content source: " + ex.ToString()); return false; } } public static bool ExecuteSmartContentRetreival( IWin32Window dialogOwner, ContentSourceInfo contentSourceInfo, string url, ref string title, ISmartContent newContent) { try { if (contentSourceInfo.UrlContentSourceRequiresProgress) { // create the progress dialog and the async operation UrlContentRetreivalWithProgressDialog progressDialog = new UrlContentRetreivalWithProgressDialog(contentSourceInfo); progressDialog.CreateControl(); SmartUrlContentRetreivalAsyncOperation asyncOperation = new SmartUrlContentRetreivalAsyncOperation(progressDialog, contentSourceInfo.Instance as SmartContentSource, url, title, newContent); // execute and retreive results if (ExecuteWithProgress(dialogOwner, progressDialog, asyncOperation, contentSourceInfo)) { title = asyncOperation.Title; return true; } else { return false; } } else { try { (contentSourceInfo.Instance as SmartContentSource).CreateContentFromUrl(url, ref title, newContent); return true; } catch (Exception ex) { ContentSourceManager.DisplayContentRetreivalError(dialogOwner, ex, contentSourceInfo); return false; } } } catch (Exception ex) { Trace.Fail("Unexpected exception executing network operation for content source: " + ex.ToString()); return false; } } private static bool ExecuteWithProgress( IWin32Window dialogOwner, UrlContentRetreivalWithProgressDialog progressDialog, UrlContentRetreivalAsyncOperation asyncOperation, ContentSourceInfo contentSourceInfo) { try { // show the progress dialog using (progressDialog) { asyncOperation.Start(); progressDialog.ShowProgress(dialogOwner, asyncOperation); } // handle the result if (asyncOperation.Error != null) { ContentSourceManager.DisplayContentRetreivalError(dialogOwner, asyncOperation.Error, contentSourceInfo); return false; } else if (asyncOperation.WasCancelled) { return false; } else { return true; } } catch (Exception ex) { Trace.Fail("Unexpected exception executing network operation for content source: " + ex.ToString()); return false; } } } internal abstract class UrlContentRetreivalAsyncOperation : OpenLiveWriter.CoreServices.AsyncOperation { public UrlContentRetreivalAsyncOperation( ISynchronizeInvoke invokeTarget, WriterPlugin contentSource, string url, string title) : base(invokeTarget) { _url = url; _title = title; _contentSource = contentSource; } public bool WasCancelled { get { return CancelRequested; } } public Exception Error { get { return _contentRetrievalException; } } public string Title { get { return _title; } } protected string Url { get { return _url; } } protected WriterPlugin ContentSource { get { return _contentSource; } } protected abstract void RetreiveContent(ref string title); protected override void DoWork() { try { RetreiveContent(ref _title); } catch (OperationCancelledException) { // WasCancelled = true } catch (Exception ex) { _contentRetrievalException = ex; } } private string _url; private string _title; private WriterPlugin _contentSource; private Exception _contentRetrievalException; } internal class SimpleUrlContentRetreivalAsyncOperation : UrlContentRetreivalAsyncOperation { public SimpleUrlContentRetreivalAsyncOperation( ISynchronizeInvoke invokeTarget, ContentSource contentSource, string url, string title) : base(invokeTarget, contentSource, url, title) { } public string NewContent { get { return _newContent; } } protected override void RetreiveContent(ref string title) { (ContentSource as ContentSource).CreateContentFromUrl(Url, ref title, ref _newContent); } private string _newContent; } internal class SmartUrlContentRetreivalAsyncOperation : UrlContentRetreivalAsyncOperation { public SmartUrlContentRetreivalAsyncOperation( ISynchronizeInvoke invokeTarget, SmartContentSource contentSource, string url, string title, ISmartContent newContent) : base(invokeTarget, contentSource, url, title) { _newContent = newContent; } protected override void RetreiveContent(ref string title) { (ContentSource as SmartContentSource).CreateContentFromUrl(Url, ref title, _newContent); } private ISmartContent _newContent; } }
34.670635
209
0.556141
[ "MIT" ]
DNSNets/OpenLiveWriter
src/managed/OpenLiveWriter.PostEditor/ContentSources/UrlContentRetreivalWithProgress.cs
8,737
C#
using MockHttp.Matchers; namespace MockHttp; /// <summary> /// A builder to configure request matchers, accepting all matchers. /// </summary> internal sealed class AnyRequestMatching : RequestMatching { protected internal override void ValidateMatcher(IAsyncHttpRequestMatcher matcher) { // Ignore validation. } }
22.533333
86
0.736686
[ "Apache-2.0" ]
swoog/MockHttp
src/MockHttp/AnyRequestMatching.cs
340
C#
#region Using directives using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Xml.Serialization; using NBi.Xml; using NBi.Xml.Items; using NBi.Xml.Settings; using NBi.Xml.Systems; using NUnit.Framework; #endregion namespace NBi.Testing.Xml.Unit.Systems { [TestFixture] public class StructureXmlTest : BaseXmlTest { [Test] public void Deserialize_SampleFile_Hierarchy() { int testNr = 0; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); // Check the properties of the object. Assert.That(ts.Tests[testNr].Systems[0], Is.TypeOf<StructureXml>()); Assert.That(((StructureXml)ts.Tests[testNr].Systems[0]).Item, Is.TypeOf<HierarchyXml>()); HierarchyXml item = (HierarchyXml)((StructureXml)ts.Tests[testNr].Systems[0]).Item; Assert.That(item.Caption, Is.EqualTo("hierarchy")); Assert.That(item.Dimension, Is.EqualTo("dimension")); Assert.That(item.Perspective, Is.EqualTo("Perspective")); Assert.That(item.ConnectionString, Is.EqualTo("ConnectionString")); } [Test] public void GetAutoCategories_Hierarchy_ValidList() { int testNr = 0; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); // Check the properties of the object. var autoCategories = ts.Tests[testNr].Systems[0].GetAutoCategories(); Assert.That(autoCategories, Has.Member("Dimension 'dimension'")); Assert.That(autoCategories, Has.Member("Perspective 'Perspective'")); Assert.That(autoCategories, Has.Member("Hierarchy 'hierarchy'")); Assert.That(autoCategories, Has.Member("Hierarchies")); Assert.That(autoCategories, Has.Member("Structure")); } [Test] public void GetAutoCategories_MeasureGroup_ValidList() { int testNr = 1; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); // Check the properties of the object. var autoCategories = ts.Tests[testNr].Systems[0].GetAutoCategories(); Assert.That(autoCategories, Has.Member("Measure group 'MeasureGroupName'")); Assert.That(autoCategories, Has.Member("Perspective 'Perspective'")); Assert.That(autoCategories, Has.Member("Measure groups")); Assert.That(autoCategories, Has.Member("Structure")); } [Test] public void Deserialize_SampleFile_MeasureGroup() { int testNr = 1; // Create an instance of the XmlSerializer specifying type and namespace. TestSuiteXml ts = DeserializeSample(); // Check the properties of the object. Assert.That(ts.Tests[testNr].Systems[0], Is.TypeOf<StructureXml>()); Assert.That(((StructureXml)ts.Tests[testNr].Systems[0]).Item, Is.TypeOf<MeasureGroupXml>()); MeasureGroupXml item = (MeasureGroupXml)((StructureXml)ts.Tests[testNr].Systems[0]).Item; Assert.That(item.Perspective, Is.EqualTo("Perspective")); Assert.That(item.ConnectionString, Is.EqualTo("ConnectionString")); } [Test] public void Serialize_StructureXml_NoDefaultAndSettings() { var perspectiveXml = new PerspectiveXml(); perspectiveXml.Caption = "My Caption"; perspectiveXml.Default = new DefaultXml() { ApplyTo = SettingsXml.DefaultScope.Assert, ConnectionString = new ConnectionStringXml() { Inline = "connStr" } }; perspectiveXml.Settings = new SettingsXml() { References = new List<ReferenceXml>() { new ReferenceXml() { Name = "Bob", ConnectionString = new ConnectionStringXml() { Inline = "connStr" } } } }; var structureXml = new StructureXml() { Item = perspectiveXml }; var serializer = new XmlSerializer(typeof(StructureXml)); var stream = new MemoryStream(); var writer = new StreamWriter(stream, Encoding.UTF8); serializer.Serialize(writer, structureXml); var content = Encoding.UTF8.GetString(stream.ToArray()); writer.Close(); stream.Close(); Debug.WriteLine(content); Assert.That(content, Does.Contain("My Caption")); Assert.That(content, Does.Not.Contain("efault")); Assert.That(content, Does.Not.Contain("eference")); } } }
38.880952
169
0.618902
[ "Apache-2.0" ]
TheAutomatingMrLynch/NBi
NBi.Testing.Xml/Systems/StructureXmlTest.cs
4,901
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; using Stride.Core; using Stride.Core.Mathematics; using Stride.Shaders; namespace Stride.Rendering.Lights { public static partial class LightSimpleAmbientKeys { static LightSimpleAmbientKeys() { AmbientLight = ParameterKeys.NewValue(new Color3(1.0f, 1.0f, 1.0f)); } } }
30.333333
163
0.720565
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Rendering/Rendering/Lights/LightSimpleAmbientKeys.cs
637
C#
using System; using Microsoft.JSInterop; namespace BlazorRedux { public class ReduxOptions<TState> { public ReduxOptions() { // Defaults StateSerializer = state => Json.Serialize(state); StateDeserializer = Json.Deserialize<TState>; } public Reducer<TState, NewLocationAction> LocationReducer { get; set; } public Func<TState, string> GetLocation { get; set; } public Func<TState, string> StateSerializer { get; set; } public Func<string, TState> StateDeserializer { get; set; } } }
30.4
80
0.606908
[ "Apache-2.0" ]
torhovland/blazor-redux
src/BlazorRedux/ReduxOptions.cs
610
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 BaconianCipher.Properties { using System; [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Ressources { private static System.Resources.ResourceManager resourceMan; private static System.Globalization.CultureInfo resourceCulture; [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Ressources() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] internal static System.Resources.ResourceManager ResourceManager { get { if (object.Equals(null, resourceMan)) { System.Resources.ResourceManager temp = new System.Resources.ResourceManager("BaconianCipher.Properties.Ressources", typeof(Ressources).Assembly); resourceMan = temp; } return resourceMan; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] internal static System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.571429
166
0.595668
[ "Apache-2.0" ]
CrypToolProject/CrypTool-2
CrypPlugins/BaconCipher/Properties/Ressources.Designer.cs
1,941
C#
using AdvancedSharpAdbClient; using AdvancedSharpAdbClient.DeviceCommands; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows; namespace WSATools { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { [DllImport("kernel32.dll", EntryPoint = "WinExec")] public static extern int RunWinExec(string exeName, int operType); public static AdvancedAdbClient Client = null; public static DeviceData Device = null; public static PackageManager PackageManager = null; public static string PackageRoot = string.Empty; public static string WsaClientPath = string.Empty; public static string IconAndImageDirPath = string.Empty; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); using (var appx = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Appx")) { App.PackageRoot = appx.GetValue("PackageRoot") as string; } WsaClientPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) , "Microsoft" , "WindowsApps" , "MicrosoftCorporationII.WindowsSubsystemForAndroid_8wekyb3d8bbwe" , "WsaClient.exe"); IconAndImageDirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) , "Packages" , "MicrosoftCorporationII.WindowsSubsystemForAndroid_8wekyb3d8bbwe" , "LocalState"); Debug.WriteLine($"WsaClientPath: {WsaClientPath}"); Debug.WriteLine($"IconAndImageDirPath: {IconAndImageDirPath}"); Client = new AdvancedAdbClient(); Client.Connect(new System.Net.DnsEndPoint("127.0.0.1", 58526)); ResourceDictionary langRd = null; try { langRd = Application.LoadComponent(new Uri(@"Language\zh_CN.xaml", UriKind.RelativeOrAbsolute)) as ResourceDictionary; } catch (Exception ex) { Debug.WriteLine($"{DateTime.Now}:{ex}"); } if (langRd != null) { Application.Current.Resources.MergedDictionaries.Add(langRd); } Environment.SetEnvironmentVariable("PATH", Path.Combine(Environment.CurrentDirectory, "adb"), EnvironmentVariableTarget.Process); App.RunWinExec(WsaClientPath, 1); MainWindow mw = new MainWindow(); this.MainWindow = mw; this.MainWindow.Show(); } } }
39.697368
142
0.620152
[ "MIT" ]
haozekang/WSATools
WSATools/App.xaml.cs
3,019
C#
using DataCore.Test.Models; using NUnit.Framework; namespace DataCore.Test { [TestFixture] public class QueryTestPagination { [Test] public void CanGeneratePagination() { var query = new Query<TestClass>(new Translator()); query.Paginate(10, 5).Build(); Assert.AreEqual("SELECT * FROM TestClass WITH(NOLOCK) LIMIT 10, 40", query.SqlCommand.ToString()); } } }
22.35
110
0.610738
[ "MIT" ]
stefanmielke/DataCore
DataCore.Test/QueryTestPagination.cs
449
C#
using System.IO; using System.Collections.Generic; using MyWarez.Base; namespace MyWarez.Payloads { public sealed class PrintConfigTargetPath : ShellcodeCCxxSource, ITargetPathW, IShellcodeCCxxSourceIParameterlessCFunction { private static readonly string ResourceDirectory = Path.Join(Core.Constants.PayloadsResourceDirectory, "Windows", "PrivilegeEscalation", nameof(PrintConfigTargetPath)); public PrintConfigTargetPath() : base(SourceDirectoryToSourceFiles(ResourceDirectory)) { } public IEnumerable<string> ParameterTypes => null; } }
44.384615
176
0.786828
[ "MIT" ]
CreatePhotonW/MyWarez
MyWarez/Payloads/Windows/PrivilegeEscalation/PrintConfigTargetPath.cs
579
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Schlechtums.Core.Common.Extensions { public static class ListExtensions { public static T TryGetIndex<T>(this Collection<T> source, int index, T defaultValue = default(T)) { if (source.AnySafe() && source.Count > index) return source[index]; else return defaultValue; } public static T TryGetIndex<T>(this IList<T> source, int index, T defaultValue = default(T)) { if (source.AnySafe() && source.Count > index) return source[index]; else return defaultValue; } /// <summary> /// Returns if the collection contains the given item. If the collection is null it returns false instead of throwing an exception. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source">The source collection.</param> /// <param name="item">The item to find.</param> /// <returns>True/False.</returns> public static Boolean ContainsSafe<T>(this ICollection<T> source, T item) { if (source == null) return false; return source.Contains(item); } /// <summary> /// Returns if the collection contains an item which matches the selector function. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="selector"></param> /// <returns></returns> public static Boolean ContainsSafe<T>(this ICollection<T> source, Func<T, Boolean?> selector) { return source.AnySafe(i => selector(i)); } } }
35.865385
141
0.553887
[ "Unlicense" ]
schlechtums/Schlechtums.Core
src/Schlechtums.Core/Schlechtums.Core/Common/Extensions/ListExtensions.cs
1,867
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/sapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public enum SPINTERFERENCE { SPINTERFERENCE_NONE = 0, SPINTERFERENCE_NOISE = (SPINTERFERENCE_NONE + 1), SPINTERFERENCE_NOSIGNAL = (SPINTERFERENCE_NOISE + 1), SPINTERFERENCE_TOOLOUD = (SPINTERFERENCE_NOSIGNAL + 1), SPINTERFERENCE_TOOQUIET = (SPINTERFERENCE_TOOLOUD + 1), SPINTERFERENCE_TOOFAST = (SPINTERFERENCE_TOOQUIET + 1), SPINTERFERENCE_TOOSLOW = (SPINTERFERENCE_TOOFAST + 1), SPINTERFERENCE_LATENCY_WARNING = (SPINTERFERENCE_TOOSLOW + 1), SPINTERFERENCE_LATENCY_TRUNCATE_BEGIN = (SPINTERFERENCE_LATENCY_WARNING + 1), SPINTERFERENCE_LATENCY_TRUNCATE_END = (SPINTERFERENCE_LATENCY_TRUNCATE_BEGIN + 1), } }
46
145
0.736166
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/um/sapi/SPINTERFERENCE.cs
1,014
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; namespace System.Collections.Tests { internal sealed class DelegateEqualityComparer<T> : IEqualityComparer<T>, IEqualityComparer { private readonly Func<T, T, bool> _equals; private readonly Func<T, int> _getHashCode; private readonly Func<object, object, bool> _objectEquals; private readonly Func<object, int> _objectGetHashCode; public DelegateEqualityComparer( Func<T, T, bool> equals = null, Func<T, int> getHashCode = null, Func<object, object, bool> objectEquals = null, Func<object, int> objectGetHashCode = null ) { _equals = equals ?? ( (x, y) => { throw new NotImplementedException(); } ); _getHashCode = getHashCode ?? ( obj => { throw new NotImplementedException(); } ); _objectEquals = objectEquals ?? ( (x, y) => { throw new NotImplementedException(); } ); _objectGetHashCode = objectGetHashCode ?? ( obj => { throw new NotImplementedException(); } ); } public bool Equals(T x, T y) => _equals(x, y); public int GetHashCode(T obj) => _getHashCode(obj); bool IEqualityComparer.Equals(object x, object y) => _objectEquals(x, y); int IEqualityComparer.GetHashCode(object obj) => _objectGetHashCode(obj); } }
31.230769
95
0.474384
[ "MIT" ]
belav/runtime
src/libraries/Common/tests/System/Collections/DelegateEqualityComparer.cs
2,030
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace MessageBoard.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
19.543478
53
0.580645
[ "MIT" ]
TJEverett/Message_Board_API
MessageBoard/Controllers/ValuesController.cs
901
C#
using System; using System.Collections.Generic; namespace APIServer.Domain.Core.Models.WebHooks { public class WebHook { public WebHook() { this.Headers = new HashSet<WebHookHeader>(); this.HookEvents = new HookEventType[0]; this.Records = new List<WebHookRecord>(); } /// <summary> /// Hook DB Id /// </summary> public long ID { get; set; } /// <summary> /// <summary> /// Webhook endpoint /// </summary> public string WebHookUrl { get; set; } /// <summary> /// Webhook secret /// </summary> #nullable enable public string? Secret { get; set; } #nullable disable /// <summary> /// Content Type /// </summary> public string ContentType { get; set; } /// <summary> /// Is active / NotActiv /// </summary> public bool IsActive { get; set; } /// <summary> /// Hook Events context /// </summary> public HookEventType[] HookEvents { get; set; } /// <summary> /// Additional HTTP headers. Will be sent with hook. /// </summary> virtual public HashSet<WebHookHeader> Headers { get; set; } /// <summary> /// Hook call records history /// </summary> virtual public ICollection<WebHookRecord> Records { get; set; } /// <summary> /// Timestamp of last hook trigger /// </summary> /// <value></value> public DateTime? LastTrigger { get; set; } } }
23.897059
71
0.512615
[ "MIT" ]
MaxymGorn/trouble-training
Src/APIServer/Domain/Enity/Hooks/DB_WebHooks/WebHook.cs
1,625
C#
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Text.RegularExpressions; using System.Threading.Tasks; using Moq; using Moq.Protected; using Xunit; namespace Moq.Tests { public class VerifyFixture { [Fact] public void ThrowsIfVerifiableExpectationNotCalled() { var mock = new Mock<IFoo>(); mock.Setup(x => x.Submit()).Verifiable(); var mex = Assert.Throws<MockException>(() => mock.Verify()); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifiableExpectationNotCalledWithMessage() { var mock = new Mock<IFoo>(); mock.Setup(x => x.Submit()).Verifiable("Kaboom!"); var mex = Assert.Throws<MockException>(() => mock.Verify()); Assert.True(mex.IsVerificationError); Assert.Contains("Kaboom!", mex.Message); } [Fact] public void ThrowsWithEvaluatedExpressionsIfVerifiableExpectationNotCalled() { var expectedArg = "lorem,ipsum"; var mock = new Mock<IFoo>(); mock.Setup(x => x.Execute(expectedArg.Substring(0, 5))) .Returns("ack") .Verifiable(); var mex = Assert.Throws<MockException>(() => mock.Verify()); Assert.True(mex.IsVerificationError); Assert.True(mex.Message.Contains(@".Execute(""lorem"")"), "Contains evaluated expected argument."); } [Fact] public void ThrowsWithExpressionIfVerifiableExpectationWithLambdaMatcherNotCalled() { var mock = new Mock<IFoo>(); mock.Setup(x => x.Execute(It.Is<string>(s => string.IsNullOrEmpty(s)))) .Returns("ack") .Verifiable(); var mex = Assert.Throws<MockException>(() => mock.Verify()); Assert.True(mex.IsVerificationError); Assert.Contains(@".Execute(It.Is<string>(s => string.IsNullOrEmpty(s)))", mex.Message); } [Fact] public void VerifiesNoOpIfNoVerifiableExpectations() { var mock = new Mock<IFoo>(); mock.Verify(); } [Fact] public void ThrowsIfVerifyAllNotMet() { var mock = new Mock<IFoo>(); mock.Setup(x => x.Submit()); var mex = Assert.Throws<MockException>(() => mock.VerifyAll()); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyVoidMethodWithExpressionFails() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Submit())); Assert.True(mex.IsVerificationError); } [Fact] public void VerifiesVoidMethodWithExpression() { var mock = new Mock<IFoo>(); mock.Object.Submit(); mock.Verify(f => f.Submit()); } [Fact] public void ThrowsIfVerifyReturningMethodWithExpressionFails() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Execute("ping"))); Assert.True(mex.IsVerificationError); } [Fact] public void VerifiesReturningMethodWithExpression() { var mock = new Mock<IFoo>(); mock.Object.Execute("ping"); mock.Verify(f => f.Execute("ping")); } [Fact] public void VerifiesPropertyGetWithExpression() { var mock = new Mock<IFoo>(); var v = mock.Object.Value; mock.VerifyGet(f => f.Value); } [Fact] public void VerifiesReturningMethodWithExpressionAndMessage() { var mock = new Mock<IFoo>(); var me = Assert.Throws<MockException>( () => mock.Verify(f => f.Execute("ping"), "Execute should have been invoked with 'ping'")); Assert.Contains("Execute should have been invoked with 'ping'", me.Message); Assert.Contains("f.Execute(\"ping\")", me.Message); } [Fact] public void VerifiesVoidMethodWithExpressionAndMessage() { var mock = new Mock<IFoo>(); var me = Assert.Throws<MockException>( () => mock.Verify(f => f.Submit(), "Submit should be invoked")); Assert.Contains("Submit should be invoked", me.Message); Assert.Contains("f.Submit()", me.Message); } [Fact] public void VerifiesPropertyGetWithExpressionAndMessage() { var mock = new Mock<IFoo>(); var me = Assert.Throws<MockException>(() => mock.VerifyGet(f => f.Value, "Nobody called .Value")); Assert.Contains("Nobody called .Value", me.Message); Assert.Contains("f.Value", me.Message); } [Fact] public void VerifiesPropertySetWithExpressionAndMessage() { var mock = new Mock<IFoo>(); var me = Assert.Throws<MockException>(() => mock.VerifySet(f => f.Value = It.IsAny<int?>(), "Nobody called .Value")); Assert.Contains("Nobody called .Value", me.Message); Assert.Contains("f.Value", me.Message); } [Fact] public void VerifiesPropertySetValueWithExpressionAndMessage() { var mock = new Mock<IFoo>(); var e = Assert.Throws<MockException>(() => mock.VerifySet(f => f.Value = 5, "Nobody called .Value")); Assert.Contains("Nobody called .Value", e.Message); Assert.Contains("f.Value", e.Message); } [Fact] public void AsInterfaceVerifiesReturningMethodWithExpressionAndMessage() { var disposable = new Mock<IDisposable>(); var mock = disposable.As<IFoo>(); var e = Assert.Throws<MockException>( () => mock.Verify(f => f.Execute("ping"), "Execute should have been invoked with 'ping'")); Assert.Contains("Execute should have been invoked with 'ping'", e.Message); Assert.Contains("f.Execute(\"ping\")", e.Message); } [Fact] public void AsInferfaceVerifiesVoidMethodWithExpressionAndMessage() { var disposable = new Mock<IDisposable>(); var mock = disposable.As<IFoo>(); var e = Assert.Throws<MockException>(() => mock.Verify(f => f.Submit(), "Submit should be invoked")); Assert.Contains("Submit should be invoked", e.Message); Assert.Contains("f.Submit()", e.Message); } [Fact] public void AsInterfaceVerifiesPropertyGetWithExpressionAndMessage() { var disposable = new Mock<IDisposable>(); var mock = disposable.As<IFoo>(); var e = Assert.Throws<MockException>(() => mock.VerifyGet(f => f.Value, "Nobody called .Value")); Assert.Contains("Nobody called .Value", e.Message); Assert.Contains("f.Value", e.Message); } [Fact] public void AsInterfaceVerifiesPropertySetWithExpressionAndMessage() { var disposable = new Mock<IDisposable>(); var mock = disposable.As<IBar>(); var e = Assert.Throws<MockException>( () => mock.VerifySet(f => f.Value = It.IsAny<int?>(), "Nobody called .Value")); Assert.Contains("Nobody called .Value", e.Message); Assert.Contains("f.Value", e.Message); } [Fact] public void AsInterfaceVerifiesPropertySetValueWithExpressionAndMessage() { var disposable = new Mock<IDisposable>(); var mock = disposable.As<IBar>(); var e = Assert.Throws<MockException>(() => mock.VerifySet(f => f.Value = 5, "Nobody called .Value")); Assert.Contains("Nobody called .Value", e.Message); Assert.Contains("f.Value", e.Message); } [Fact] public void ThrowsIfVerifyPropertyGetWithExpressionFails() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.VerifyGet(f => f.Value)); Assert.True(mex.IsVerificationError); } [Fact] public void VerifiesPropertySetWithExpression() { var mock = new Mock<IFoo>(); mock.Object.Value = 5; mock.VerifySet(f => f.Value = It.IsAny<int?>()); } [Fact] public void ThrowsIfVerifyPropertySetWithExpressionFails() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.VerifySet(f => f.Value = It.IsAny<int?>())); Assert.True(mex.IsVerificationError); } [Fact] public void VerifiesSetterWithAction() { var mock = new Mock<IFoo>(); Assert.Throws<MockException>(() => mock.VerifySet(m => m.Value = 2)); mock.Object.Value = 2; mock.VerifySet(m => m.Value = 2); } [Fact] public void VerifiesSetterWithActionAndMessage() { var mock = new Mock<IFoo>(); var me = Assert.Throws<MockException>(() => mock.VerifySet(m => m.Value = 2, "foo")); Assert.Contains("foo", me.Message); mock.Object.Value = 2; mock.VerifySet(m => m.Value = 2, "foo"); } [Fact] public void VerifiesSetterWithActionAndMatcher() { var mock = new Mock<IFoo>(); Assert.Throws<MockException>(() => mock.VerifySet(m => m.Value = It.IsAny<int>())); mock.Object.Value = 2; mock.VerifySet(m => m.Value = It.IsAny<int>()); mock.VerifySet(m => m.Value = It.IsInRange(1, 2, Range.Inclusive)); mock.VerifySet(m => m.Value = It.Is<int>(i => i % 2 == 0)); } [Fact] public void VerifiesRefWithExpression() { var mock = new Mock<IFoo>(); var expected = "ping"; Assert.Throws<MockException>(() => mock.Verify(m => m.EchoRef(ref expected))); mock.Object.EchoRef(ref expected); mock.Verify(m => m.EchoRef(ref expected)); } [Fact] public void VerifiesOutWithExpression() { var mock = new Mock<IFoo>(); var expected = "ping"; Assert.Throws<MockException>(() => mock.Verify(m => m.EchoOut(out expected))); mock.Object.EchoOut(out expected); mock.Verify(m => m.EchoOut(out expected)); } [Fact] public void ThrowsIfVerifyVoidAtMostOnceAndMoreThanOneCall() { var mock = new Mock<IFoo>(); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.AtMostOnce()); mock.Object.Submit(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.AtMostOnce())); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock at most once, but was 2 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidAtMostAndMoreThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Submit(); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.AtMost(2)); mock.Object.Submit(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.AtMost(2))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock at most 2 times, but was 3 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidNeverAndOneCall() { var mock = new Mock<IFoo>(); mock.Verify(foo => foo.Submit(), Times.Never()); mock.Object.Submit(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.Never())); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock should never have been performed, but was 1 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidAtLeastOnceAndNotCalls() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.AtLeastOnce())); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock at least once, but was never performed: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.AtLeastOnce()); } [Fact] public void ThrowsIfVerifyVoidAtLeastAndLessThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Submit(); mock.Object.Submit(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.AtLeast(3))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock at least 3 times, but was 2 times: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.AtLeast(3)); } [Fact] public void ThrowsIfVerifyVoidExactlyAndLessOrMoreThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Submit(); mock.Object.Submit(); mock.Object.Submit(); mock.Object.Submit(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.Exactly(5))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock exactly 5 times, but was 4 times: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Exactly(5)); mock.Object.Submit(); mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.Exactly(5))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock exactly 5 times, but was 6 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidOnceAndLessOrMoreThanACall() { var mock = new Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.Once())); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock once, but was 0 times: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Once()); mock.Object.Submit(); mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Submit(), Times.Once())); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock once, but was 2 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidBetweenExclusiveAndLessOrEqualsFromOrMoreOrEqualToCalls() { var mock = new Mock<IFoo>(); mock.Object.Submit(); var mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock between 1 and 4 times (Exclusive), but was 1 times: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive)); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive)); mock.Object.Submit(); mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock between 1 and 4 times (Exclusive), but was 4 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyVoidBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock<IFoo>(); mock.Object.Submit(); var mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock between 2 and 4 times (Inclusive), but was 1 times: foo => foo.Submit()", mex.Message); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive)); mock.Object.Submit(); mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive)); mock.Object.Submit(); mock.Object.Submit(); mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Submit(), Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); Assert.Contains("Expected invocation on the mock between 2 and 4 times (Inclusive), but was 5 times: foo => foo.Submit()", mex.Message); } [Fact] public void ThrowsIfVerifyReturningAtMostOnceAndMoreThanOneCall() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.AtMostOnce()); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.AtMostOnce())); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyReturningAtMostAndMoreThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.AtMost(2)); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.AtMost(2))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyReturningNeverAndOneCall() { var mock = new Mock<IFoo>(); mock.Verify(foo => foo.Execute(""), Times.Never()); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.Never())); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyReturningAtLeastOnceAndNotCalls() { var mock = new Mock<IFoo>(); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.AtLeastOnce())); Assert.True(mex.IsVerificationError); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.AtLeastOnce()); } [Fact] public void ThrowsIfVerifyReturningAtLeastAndLessThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.AtLeast(3))); Assert.True(mex.IsVerificationError); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.AtLeast(3)); } [Fact] public void ThrowsIfVerifyReturningExactlyAndLessOrMoreThanNCalls() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); mock.Object.Execute(""); mock.Object.Execute(""); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.Exactly(5))); Assert.True(mex.IsVerificationError); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Exactly(5)); mock.Object.Execute(""); mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Execute(""), Times.Exactly(5))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyReturningBetweenExclusiveAndLessOrEqualsFromOrMoreOrEqualToCalls() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(1, 4, Range.Exclusive)); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(1, 4, Range.Exclusive)); mock.Object.Execute(""); mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Execute(""), Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyReturningBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock<IFoo>(); mock.Object.Execute(""); MockException mex = Assert.Throws<MockException>(() => mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive)); mock.Object.Execute(""); mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive)); mock.Object.Execute(""); mock.Object.Execute(""); mex = Assert.Throws<MockException>( () => mock.Verify(foo => foo.Execute(""), Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetAtMostOnceAndMoreThanOneCall() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.AtMostOnce()); value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.AtMostOnce())); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetAtMostAndMoreThanNCalls() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.AtMost(2)); value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.AtMost(2))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetNeverAndOneCall() { var mock = new Mock<IFoo>(); mock.VerifyGet(foo => foo.Value, Times.Never()); var value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.Never())); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetAtLeastOnceAndNotCalls() { var mock = new Mock<IFoo>(); MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.AtLeastOnce())); Assert.True(mex.IsVerificationError); var value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.AtLeastOnce()); } [Fact] public void ThrowsIfVerifyGetGetAtLeastAndLessThanNCalls() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.AtLeast(3))); Assert.True(mex.IsVerificationError); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.AtLeast(3)); } [Fact] public void ThrowsIfVerifyGetGetExactlyAndLessOrMoreThanNCalls() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; value = mock.Object.Value; value = mock.Object.Value; value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.Exactly(5))); Assert.True(mex.IsVerificationError); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Exactly(5)); value = mock.Object.Value; mex = Assert.Throws<MockException>(() => mock.VerifyGet(foo => foo.Value, Times.Exactly(5))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetBetweenExclusiveAndLessOrEqualsFromOrMoreOrEqualToCalls() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(1, 4, Range.Exclusive)); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(1, 4, Range.Exclusive)); value = mock.Object.Value; mex = Assert.Throws<MockException>(() => mock.VerifyGet(foo => foo.Value, Times.Between(1, 4, Range.Exclusive))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifyGetGetBetweenInclusiveAndLessFromOrMoreToCalls() { var mock = new Mock<IFoo>(); var value = mock.Object.Value; MockException mex = Assert.Throws<MockException>( () => mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive)); value = mock.Object.Value; mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive)); value = mock.Object.Value; value = mock.Object.Value; mex = Assert.Throws<MockException>(() => mock.VerifyGet(foo => foo.Value, Times.Between(2, 4, Range.Inclusive))); Assert.True(mex.IsVerificationError); } [Fact] public void ThrowsIfVerifySetAtMostOnceAndMoreThanOneCall() { var mock = new Mock<IFoo>(); mock.Object.Value = 3; mock.VerifySet(f => f.Value = 3, Times.AtMostOnce()); mock.Object.Value = 3; MockException mex = Assert.Throws<MockException>( () => mock.VerifySet(f => f.Value = 3, Times.AtMostOnce())); Assert.True(mex.IsVerificationError); } [Fact] public void IncludesActualCallsInFailureMessage() { var mock = new Moq.Mock<IFoo>(); mock.Object.Execute("ping"); mock.Object.Echo(42); mock.Object.Submit(); mock.Object.Save(new object[] {1, 2, "hello"}); var mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Execute("pong"))); Assert.True(mex.Message.ContainsConsecutiveLines( " VerifyFixture.IFoo.Execute(\"ping\")", " VerifyFixture.IFoo.Echo(42)", " VerifyFixture.IFoo.Submit()", " VerifyFixture.IFoo.Save([1, 2, \"hello\"])")); } [Fact] public void IncludesActualValuesFromVerifyNotVariableNames() { var expectedArg = "lorem,ipsum"; var mock = new Moq.Mock<IFoo>(); var mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Execute(expectedArg.Substring(0, 5)))); Assert.Contains("f.Execute(\"lorem\")", mex.Message); } [Fact] public void IncludesMessageAboutNoActualCallsInFailureMessage() { var mock = new Moq.Mock<IFoo>(); MockException mex = Assert.Throws<MockException>(() => mock.Verify(f => f.Execute("pong"))); Assert.Contains(" No invocations performed.", mex.Message); } [Fact] public void MatchesDerivedTypesForGenericTypes() { var mock = new Mock<IBaz>(); mock.Object.Call(new BazParam()); mock.Object.Call(new BazParam2()); mock.Verify(foo => foo.Call(It.IsAny<IBazParam>()), Times.Exactly(2)); } [Fact] public void Should_verify_derived_as_generic_parameters() { //Arrange var mock = new Mock<IBaz>(); //Act mock.Object.Subscribe<BazParam2>(); mock.Object.Subscribe<BazParam>(); mock.Object.Subscribe<IBazParam>(); //Assert mock.Verify(foo => foo.Subscribe<IBazParam>(), Times.Exactly(3)); mock.Verify(foo => foo.Subscribe<BazParam>(), Times.Exactly(2)); mock.Verify(foo => foo.Subscribe<BazParam2>(), Times.Once); } [Fact] public void Should_not_verify_nongeneric_when_generic_invoked() { //Arrange var mock = new Mock<IBaz>(); //Act mock.Object.Subscribe<IBazParam>(); //Assert mock.Verify(foo => foo.Subscribe<IBazParam>(), Times.Once); mock.Verify(foo => foo.Subscribe(), Times.Never); } [Fact] public void Should_not_verify_generic_when_nongeneric_invoked() { //Arrange var mock = new Mock<IBaz>(); //Act mock.Object.Subscribe(); //Assert mock.Verify(foo => foo.Subscribe<IBazParam>(), Times.Never); mock.Verify(foo => foo.Subscribe(), Times.Once); } [Fact] public void NullArrayValuesForActualInvocationArePrintedAsNullInMockExeptionMessage() { var strings = new string[] { "1", null, "3" }; var mock = new Mock<IArrays>(); mock.Object.Method(strings); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(null))); Assert.True(mex.Message.ContainsConsecutiveLines( @" VerifyFixture.IArrays.Method([""1"", null, ""3""])")); } [Fact] public void LargeEnumerablesInActualInvocationAreNotCutOffFor10Elements() { var strings = new string[] { "1", null, "3", "4", "5", "6", "7", "8", "9", "10" }; var mock = new Mock<IArrays>(); mock.Object.Method(strings); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(null))); Assert.True(mex.Message.ContainsConsecutiveLines( @" VerifyFixture.IArrays.Method([""1"", null, ""3"", ""4"", ""5"", ""6"", ""7"", ""8"", ""9"", ""10""])")); } [Fact] public void LargeEnumerablesInActualInvocationAreCutOffAfter10Elements() { var strings = new string[] { "1", null, "3", "4", "5", "6", "7", "8", "9", "10", "11" }; var mock = new Mock<IArrays>(); mock.Object.Method(strings); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(null))); Assert.True(mex.Message.ContainsConsecutiveLines( @" VerifyFixture.IArrays.Method([""1"", null, ""3"", ""4"", ""5"", ""6"", ""7"", ""8"", ""9"", ""10"", ...])")); } [Fact] public void NullArrayValuesForExpectedInvocationArePrintedAsNullInMockExeptionMessage() { var strings = new string[] { "1", null, "3" }; var mock = new Mock<IArrays>(); mock.Object.Method(null); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(strings))); Assert.Contains(@"Expected invocation on the mock at least once, but was never performed: _ => _.Method([""1"", null, ""3""])", mex.Message); } [Fact] public void LargeEnumerablesInExpectedInvocationAreNotCutOffFor10Elements() { var strings = new string[] { "1", null, "3", "4", "5", "6", "7", "8", "9", "10" }; var mock = new Mock<IArrays>(); mock.Object.Method(null); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(strings))); Assert.Contains(@"Expected invocation on the mock at least once, but was never performed: _ => _.Method([""1"", null, ""3"", ""4"", ""5"", ""6"", ""7"", ""8"", ""9"", ""10""])", mex.Message); } [Fact] public void LargeEnumerablesInExpectedInvocationAreCutOffAfter10Elements() { var strings = new string[] { "1", null, "3", "4", "5", "6", "7", "8", "9", "10", "11" }; var mock = new Mock<IArrays>(); mock.Object.Method(null); var mex = Assert.Throws<MockException>(() => mock.Verify(_ => _.Method(strings))); Assert.Contains(@"Expected invocation on the mock at least once, but was never performed: _ => _.Method([""1"", null, ""3"", ""4"", ""5"", ""6"", ""7"", ""8"", ""9"", ""10"", ...])", mex.Message); } /// <summary> /// Warning, this is a flaky test and doesn't fail when run as standalone. Running all tests at once will increase the chances of that test to fail. /// </summary> [Fact] public void DoesNotThrowCollectionModifiedWhenMoreInvocationsInterceptedDuringVerfication() { var mock = new Mock<IFoo>(); Parallel.For(0, 100, (i) => { mock.Object.Submit(); mock.Verify(foo => foo.Submit()); }); } [Fact] public void Enabling_diagnostic_file_info_leads_to_that_information_in_verification_error_messages() { var repository = new MockRepository(MockBehavior.Default); repository.Switches |= Switches.CollectDiagnosticFileInfoForSetups; var mock = repository.Create<IFoo>(); mock.Setup(m => m.Submit()); var ex = Assert.Throws<MockException>(() => repository.VerifyAll()); Assert.Contains("in ", ex.Message); Assert.Contains("VerifyFixture.cs: line ", ex.Message); } [Fact] public void Disabling_diagnostic_file_info_leads_to_that_information_missing_in_verification_error_messages() { var repository = new MockRepository(MockBehavior.Default); repository.Switches &= ~Switches.CollectDiagnosticFileInfoForSetups; var mock = repository.Create<IFoo>(); mock.Setup(m => m.Submit()); var ex = Assert.Throws<MockException>(() => repository.VerifyAll()); Assert.DoesNotContain("in ", ex.Message); Assert.DoesNotContain("VerifyFixture.cs: line ", ex.Message); } [Fact] public void CanVerifyMethodThatIsNamedLikeEventAddAccessor() { var mock = new Mock<IHaveMethodsNamedLikeEventAccessors>(); mock.Object.add_Something(); mock.Verify(m => m.add_Something(), Times.Once); } [Fact] public void CanVerifyMethodThatIsNamedLikeEventRemoveAccessor() { var mock = new Mock<IHaveMethodsNamedLikeEventAccessors>(); mock.Object.remove_Something(); mock.Verify(m => m.remove_Something(), Times.Once); } [Fact] public void Verify_ignores_conditional_setups() { var mock = new Mock<IFoo>(); mock.When(() => true).Setup(m => m.Submit()).Verifiable(); var exception = Record.Exception(() => { mock.Verify(); }); Assert.Null(exception); } [Fact] public void VerifyAll_ignores_conditional_setups() { var mock = new Mock<IFoo>(); mock.When(() => true).Setup(m => m.Submit()); var exception = Record.Exception(() => { mock.VerifyAll(); }); Assert.Null(exception); } [Fact, Obsolete("As long as SetupSet(Expression) still exists, this test is required.")] public void SetupGet_property_does_not_override_SetupSet_for_same_property_and_with_same_setup_expression() { var mock = new Mock<IFoo>(); mock.SetupSet(m => m.Value).Verifiable("setup for setter"); mock.SetupGet(m => m.Value).Verifiable("setup for getter"); var _ = mock.Object.Value; var exception = Record.Exception(() => { mock.VerifyAll(); }); Assert.IsAssignableFrom<MockException>(exception); Assert.Contains("setup for setter:", exception.Message); } [Fact, Obsolete("As long as SetupSet(Expression) still exists, this test is required.")] public void SetupSet_property_does_not_override_SetupGet_for_same_property_and_with_same_setup_expression() { var mock = new Mock<IFoo>(); mock.SetupGet(m => m.Value).Verifiable("setup for getter"); mock.SetupSet(m => m.Value).Verifiable("setup for setter"); mock.Object.Value = 42; var exception = Record.Exception(() => { mock.VerifyAll(); }); Assert.IsAssignableFrom<MockException>(exception); Assert.Contains("setup for getter:", exception.Message); } [Fact] public void Verify_if_successful_marks_matched_invocation_as_verified() { var mock = new Mock<IFoo>(); mock.Object.Submit(); var invocation = mock.MutableInvocations.ToArray()[0]; Assert.False(invocation.IsVerified); mock.Verify(m => m.Submit()); Assert.True(invocation.IsVerified); } [Fact] public void Verify_if_successful_marks_only_matched_invocations_as_verified() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); mock.Object.Echo(2); mock.Object.Echo(3); var invocations = mock.MutableInvocations.ToArray(); Assert.False(invocations[0].IsVerified); Assert.False(invocations[1].IsVerified); Assert.False(invocations[2].IsVerified); mock.Verify(m => m.Echo(It.Is<int>(i => i != 2))); Assert.True(invocations[0].IsVerified); Assert.False(invocations[1].IsVerified); Assert.True(invocations[2].IsVerified); } [Fact] public void Verify_if_unsuccessful_marks_no_matched_invocations_as_verified() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); mock.Object.Echo(2); mock.Object.Echo(3); var invocations = mock.MutableInvocations.ToArray(); Assert.False(invocations[0].IsVerified); Assert.False(invocations[1].IsVerified); Assert.False(invocations[2].IsVerified); Assert.Throws<MockException>(() => mock.Verify(m => m.Echo(It.Is<int>(i => i != 2)), Times.Exactly(1))); Assert.False(invocations[0].IsVerified); Assert.False(invocations[1].IsVerified); Assert.False(invocations[2].IsVerified); } [Fact] public void VerifyNoOtherCalls_succeeds_if_no_calls_were_made() { var mock = new Mock<IFoo>(); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_if_no_calls_were_made_on_mock_created_by_Mock_Of() { var mocked = Mock.Of<IFoo>(); var mock = Mock.Get(mocked); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_if_no_calls_were_made_on_mock_created_by_Mock_Of_with_single_dot_predicate() { var mocked = Mock.Of<IFoo>(m => m.Value == 1); var mock = Mock.Get(mocked); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_if_no_calls_were_made_on_mock_created_by_Mock_Of_with_multi_dot_predicate() { var mocked = Mock.Of<IFoo>(m => m.Bar.Value == 1); var mock = Mock.Get(mocked); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_fails_if_an_unverified_call_was_made() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); } [Fact] public void VerifyNoOtherCalls_includes_unverified_calls_in_exception_message() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); var ex = Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); Assert.Contains(".Echo(1)", ex.Message); } [Fact] public void VerifyNoOtherCalls_succeeds_if_a_verified_call_was_made() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); mock.Verify(m => m.Echo(1)); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_if_several_verified_call_were_made() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); mock.Object.Echo(2); mock.Object.Echo(3); mock.Object.Submit(); mock.Verify(m => m.Echo(It.IsAny<int>())); mock.Verify(m => m.Submit()); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_fails_if_several_verified_calls_and_several_unverified_call_were_made() { var mock = new Mock<IFoo>(); mock.Object.Echo(1); mock.Object.Echo(2); mock.Object.Echo(3); mock.Object.Submit(); mock.Verify(m => m.Echo(It.Is<int>(i => i > 1))); var ex = Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); Assert.Contains(".Echo(1)", ex.Message); Assert.Contains(".Submit()", ex.Message); } [Fact] public void VerifyNoOtherCalls_succeeds_with_DefaultValue_Mock_and_multi_dot_Verify_expression() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; mock.Object.Bar.Poke(); mock.Verify(m => m.Bar.Poke()); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_with_DefaultValue_Mock_and_multi_dot_VerifyGet_expression() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; var value = mock.Object.Bar.Value; mock.VerifyGet(m => m.Bar.Value); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_succeeds_with_DefaultValue_Mock_and_multi_dot_VerifySet_expression() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; mock.Object.Bar.Value = 42; mock.VerifySet(m => m.Bar.Value = 42); mock.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_performs_recursive_verification() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; mock.Object.Bar.Poke(); mock.VerifyGet(m => m.Bar); Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); // should fail due to the unverified call to `Poke` } [Fact] public void VerifyNoOtherCalls_requires_explicit_verification_of_automocked_properties_that_are_not_used_transitively() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; var _ = mock.Object.Bar; // Even though `Bar` is mockable and will be automatically mocked, it isn't used "transitively", // i.e. in a way to get at one of its members. Therefore, it ought to be verified explicitly. // Because we don't verify it, a verification exception should be thrown: Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); } [Fact(Skip = "Not yet implemented.")] public void VerifyNoOtherCalls_can_tell_apart_transitive_and_nontransitive_usages_of_automocked_properties() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; object _; _ = mock.Object.Bar; _ = mock.Object.Bar.Value; mock.Verify(m => m.Bar.Value); // `Bar` was used both in a "transitive" and non-transitive way. We would expect that the former // doesn't have to be explicitly verified (as it's implied by the verification of `Bar.Value`). // However, the non-transitive call ought to be explicitly verified. Because we don't, a verific- // ation exception is expected: (THIS DOES NOT WORK YET.) Assert.Throws<MockException>(() => mock.VerifyNoOtherCalls()); // HINT TO IMPLEMENTERS: One relatively easy way to implement this, given the way Moq is currently // build, would be to record all invocations with a globally unique, steadily increasing sequence // number. This would make it possible to say, for any two invocations (regardless of the mock on // which they occurred), which one happened earlier. Let's look at two calls of method X. The // earlier invocation happens at "time" t0, the later invocation happens at "time" t1 (t0 < t1). // If X returns a mock object, and that object has no invocations happening between t0 and t1, // then the first invocation of X was non-transitive. Likewise, the very last invocation of method // X is non-transitive if there are no invocations on the sub-object that occur later. } // (This test is somewhat duplicate, but sets the stage for the test following right after it.) [Fact] public void VerifyNoOtherCalls_works_together_with_parameterized_Verify() { var cat = new Mock<ICat>(); cat.Setup(x => x.Purr(15)).Returns("happy"); var mood = cat.Object.Purr(15); cat.Verify(x => x.Purr(15)); Assert.Equal("happy", mood); cat.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_works_together_with_parameterless_Verify() { var cat = new Mock<ICat>(); cat.Setup(x => x.Purr(15)).Returns("happy").Verifiable(); var mood = cat.Object.Purr(15); cat.Verify(); Assert.Equal("happy", mood); cat.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_works_together_with_parameterless_VerifyAll() { var cat = new Mock<ICat>(); cat.Setup(x => x.Purr(15)).Returns("happy"); var mood = cat.Object.Purr(15); cat.VerifyAll(); Assert.Equal("happy", mood); cat.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_still_complains_about_surplus_call_after_VerifyAll() { var cat = new Mock<ICat>(); cat.Setup(x => x.Purr(15)).Returns("happy"); var mood = cat.Object.Purr(15); cat.Object.Hiss(); cat.VerifyAll(); Assert.Throws<MockException>(() => cat.VerifyNoOtherCalls()); } [Fact] public void VerifyNoOtherCalls_works_with_a_combination_of_parameterised_Verify_and_VerifyAll() { var cat = new Mock<ICat>(); cat.Setup(x => x.Purr(15)).Returns("happy"); var mood = cat.Object.Purr(15); cat.Object.Hiss(); cat.VerifyAll(); cat.Verify(x => x.Hiss()); cat.VerifyNoOtherCalls(); } [Fact] public void VerifyNoOtherCalls_works_together_with_parameterless_VerifyAll_for_sequence_setups() { var mock = new Mock<ICat>(); mock.SetupSequence(x => x.Hiss()); mock.Object.Hiss(); mock.VerifyAll(); mock.VerifyNoOtherCalls(); } [Fact] public void Verification_error_message_contains_complete_call_expression_for_delegate_mock() { var mock = new Mock<Action>(); mock.Setup(m => m()); var ex = Record.Exception(() => mock.Verify(m => m(), Times.Once())); Assert.Contains("but was 0 times: m => m()", ex.Message); } [Fact] public void Verification_error_message_contains_complete_call_expression_for_delegate_mock_with_parameters() { var mock = new Mock<Action<int, int>>(); mock.Setup(m => m(1, It.IsAny<int>())); var ex = Record.Exception(() => mock.Verify(m => m(1, 2), Times.Once())); Assert.Contains("but was 0 times: m => m(1, 2)", ex.Message); } [Fact] public void VerifyAll_ignores_setups_from_SetupAllProperties() { var mock = new Mock<IFoo>(); mock.SetupAllProperties(); // This shouldn't fail. The intent behind the call to `SetupAllProperties` is to conveniently // auto-implement all properties such that they remember the values they're being set to. // But despite the `Setup` in the method name, they shouldn't create observable setups that // require verification. Otherwise, one would have to invoke each and every property accessor // to make `VerifyAll` happy. (This problem is exacerbated by the fact that `Mock.Of<T>` // performs a hidden call to `SetupAllProperties`, meaning that `VerifyAll` is quite useless // for mocks created that way if one has to call each and every property accessor.) mock.VerifyAll(); } [Fact] public void VerifyAll_ignores_setups_from_SetupAllProperties_but_not_other_property_setup() { var mock = new Mock<IFoo>(); mock.SetupAllProperties(); mock.Setup(m => m.Bar); Assert.Throws<MockException>(() => mock.VerifyAll()); } [Fact] public void VerifyAll_ignores_setups_from_SetupAllProperties_but_not_other_property_setup_unless_matched() { var mock = new Mock<IFoo>(); mock.SetupAllProperties(); mock.Setup(m => m.Bar); _ = mock.Object.Bar; mock.VerifyAll(); } [Fact] public void VerifyProtectedMethodOnChildClass() { var mock = new Mock<Child>(); mock.Protected().Setup("Populate", exactParameterMatch: true, ItExpr.Ref<ChildDto>.IsAny).CallBase().Verifiable(); ChildDto dto = new ChildDto(); _ = mock.Object.InvokePopulate(ref dto); mock.Protected().Verify("Populate", Times.Once(), exactParameterMatch: true, ItExpr.Ref<ChildDto>.IsAny); } [Fact] public void Verify_on_non_overridable_method_throws_NotSupportedException() { var mock = new Mock<Child>(); Assert.Throws<NotSupportedException>(() => mock.Verify(m => m.InvokePopulate(ref It.Ref<ChildDto>.IsAny), Times.Never)); } [Fact] public void Verification_marks_invocations_of_inner_mocks_as_verified() { var mock = new Mock<IFoo>() { DefaultValue = DefaultValue.Mock }; mock.Setup(m => m.Value).Returns(1); mock.Setup(m => m.Bar.Value).Returns(2); // Invoke everything that has been set up, and verify everything: _ = mock.Object.Value; _ = mock.Object.Bar.Value; mock.VerifyAll(); // The above call to `VerifyAll` should have marked all invocations as verified, // including those on the inner `Bar` mock: Mock.Get(mock.Object.Bar).VerifyNoOtherCalls(); } [Fact] public void Verify__marks_invocations_as_verified__even_if_the_setups_they_were_matched_by_were_conditional() { var mock = new Mock<IFoo>(); mock.When(() => true).Setup(m => m.Submit()).Verifiable(); mock.Object.Submit(); mock.Verify(); mock.VerifyNoOtherCalls(); } public class Exclusion_of_unreachable_inner_mocks { [Fact] public void Failing_setup_detached_at_root_is_excluded_from_verification() { var xMock = new Mock<IX>(); // Set up a call that would fail verification: xMock.Setup(x => x.Y.M()).Verifiable("M never called"); // Reset the root `.Y` of the above setup `.Y.M()` to something that'll pass verification: xMock.Setup(x => x.Y).Verifiable(); _ = xMock.Object.Y; // The first setup should be shadowed by the second, therefore verification should pass: xMock.Verify(); } [Fact] public void Failing_setup_detached_by_resetting_stubbed_property_is_excluded_from_verification() { var xMock = new Mock<IX> { DefaultValue = DefaultValue.Mock }; // Setup an inner mock (as the initial value of a stubbed property) that would fail verification: xMock.SetupAllProperties(); Mock.Get(xMock.Object.Y).Setup(y => y.M()).Verifiable("M never called"); // Reset the stubbed property to a different value: xMock.Object.Y = null; // Inner mock no longer reachable through `xMock`, verification should succeed: xMock.Verify(); } public interface IX { IY Y { get; set; } } public interface IY { void M(); } } public class Verify_forbidden_side_effects { [Fact] public void Does_not_create_setups_seen_by_VerifyAll() { var mock = new Mock<IX>(); mock.Verify(m => m.X.X, Times.Never); mock.VerifyAll(); } [Fact] public void Does_not_counteract_MockBehavior_Strict() { var mock = new Mock<IX>(MockBehavior.Strict); mock.Verify(m => m.X.X, Times.Never); Assert.Throws<MockException>(() => mock.Object.X); } [Fact] public void Does_not_create_inner_mocks() { var mock = new Mock<IX>(); mock.Verify(m => m.X.X, Times.Never); Assert.Throws<NullReferenceException>(() => _ = mock.Object.X.X); } [Fact] public void Does_not_override_existing_setups() { var mock = new Mock<IX>(); var nested = new Mock<IX>(); nested.Setup(m => m.Count).Returns(5); mock.Setup(m => m.X).Returns(nested.Object); mock.Verify(m => m.X.X, Times.Never); int c = mock.Object.X.Count; Assert.Equal(5, c); } public interface IX { IX X { get; } int Count { get; } } } public class Object_graph_loops { public interface IX { IX Self { get; } } [Fact] public void When_mock_returns_itself_via_setup_VerifyNoOtherCalls_wont_go_into_infinite_loop() { var mock = new Mock<IX>(); mock.Setup(m => m.Self).Returns(mock.Object); mock.VerifyNoOtherCalls(); } [Fact] public void When_mock_returns_itself_lazily_via_setup_VerifyNoOtherCalls_wont_go_into_infinite_loop() { var mock = new Mock<IX>(); mock.Setup(m => m.Self).Returns(() => mock.Object); mock.VerifyNoOtherCalls(); } [Fact] public void When_mock_returns_itself_via_setup_Verify_exception_message_wont_go_into_infinite_loop() { var mock = new Mock<IX>(); mock.Setup(m => m.Self).Returns(mock.Object); _ = mock.Object.Self; var ex = Assert.Throws<MockException>(() => mock.Verify(m => m.Self, Times.Never)); // ^^^^^^^^^^^ // We are intentionally provoking a verification exception so that Moq will have to // build an error message showing all invocations grouped by mock. Assert.Equal(2, SubstringCount(ex.Message, substring: mock.Name)); // That message should mention our mock only twice: once in the heading above // the mock's invocations; and once for the invocation that returned it. int SubstringCount(string str, string substring) { int count = 0; int index = -1; while ((index = str.IndexOf(substring, index + 1)) >= 0) ++count; return count; } } } [Fact] public void Property_getter_setup_created_by_SetupAllProperties_should_not_fail_verification_even_when_not_matched() { var mock = new Mock<IFoo>(); mock.SetupAllProperties(); // Due to `SetupAllProperties` working in a lazy fashion, // this should create two setups (one for the getter, one for the setter). // Only invoke the setter: mock.Object.Value = default; // The getter hasn't been matched, but verification should still pass: mock.VerifyAll(); } [Fact] public void Property_setter_setup_created_by_SetupAllProperties_should_not_fail_verification_even_when_not_matched() { var mock = new Mock<IFoo>(); mock.SetupAllProperties(); // Due to `SetupAllProperties` working in a lazy fashion, // this should create two setups (one for the getter, one for the setter). // Only invoke the getter: _ = mock.Object.Value; // The setter hasn't been matched, but verification should still pass: mock.VerifyAll(); } public interface IBar { int? Value { get; set; } void Poke(); } public interface IFoo { IBar Bar { get; } int WriteOnly { set; } int? Value { get; set; } void EchoRef<T>(ref T value); void EchoOut<T>(out T value); int Echo(int value); void Submit(); string Execute(string command); void Save(object o); } public interface IBazParam { } public interface IBaz { void Call<T>(T param) where T:IBazParam; void Subscribe<T>() where T : IBazParam; void Subscribe(); } public class BazParam:IBazParam { } public class BazParam2:BazParam { } public interface IArrays { void Method(string[] strings); } public interface IHaveMethodsNamedLikeEventAccessors { void add_Something(); void remove_Something(); } public interface ICat { string Purr(int amount); void Hiss(); } public class ParentDto { } public class ChildDto : ParentDto { } public class Parent { protected virtual bool Populate(ref ParentDto dto) { return true; } } public class Child : Parent { protected virtual bool Populate(ref ChildDto dto) { return true; } public bool InvokePopulate(ref ChildDto dto) { return Populate(ref dto); } } } } namespace SomeNamespace { public class VerifyExceptionsFixture { [Fact] public void RendersReadableMessageForVerifyFailures() { var mock = new Mock<Moq.Tests.VerifyFixture.IFoo>(); mock.Setup(x => x.Submit()); mock.Setup(x => x.Echo(1)); mock.Setup(x => x.Execute("ping")); var ex = Assert.Throws<MockException>(() => mock.VerifyAll()); Assert.True(ex.IsVerificationError); Assert.Contains("x => x.Submit()", ex.Message); Assert.Contains("x => x.Echo(1)", ex.Message); Assert.Contains("x => x.Execute(\"ping\")", ex.Message); } } }
29.165456
199
0.675815
[ "BSD-3-Clause" ]
FTWinston/moq4
tests/Moq.Tests/VerifyFixture.cs
52,177
C#
namespace More.Windows.Data { using System; using System.Windows; using System.Windows.Controls; /// <summary> /// Represents the metadata used to locate a resource-based data template. /// </summary> /// <remarks>The resource specified must be in the current <see cref="Application"/>.</remarks> [AttributeUsage( AttributeTargets.Property, AllowMultiple = false, Inherited = true )] public sealed class DataGridTemplateColumnAttribute : Attribute { /// <summary> /// Gets or sets the name of the resource dictionary that contains the data templates. /// </summary> /// <value>The name of the resource dictionary. This property can be null.</value> public string ResourceDictionary { get; set; } /// <summary> /// Gets or sets the name of the standard cell data template. /// </summary> /// <value>The name of the standard cell data template.</value> /// <remarks>If the <see cref="ResourceDictionary"/> property is null or an empty string, then this property /// is assumed to be the name of a resource that only contains a <see cref="DataTemplate"/>; otherwise, this /// property is the key for the <see cref="DataTemplate"/> in the corresponding <see cref="ResourceDictionary"/>.</remarks> public string CellTemplateName { get; set; } /// <summary> /// Gets or sets the name of the edit cell data template. /// </summary> /// <value>The name of the edit cell data template. This property can be null or an empty string if the column is read-only.</value> /// <remarks>If the <see cref="ResourceDictionary"/> property is null or an empty string, then this property /// is assumed to be the name of a resource that only contains a <see cref="DataTemplate"/>; otherwise, this /// property is the key for the <see cref="DataTemplate"/> in the corresponding <see cref="ResourceDictionary"/>.</remarks> public string CellEditingTemplateName { get; set; } /// <summary> /// Gets or sets the name of the dependency property in the content data template to apply the column binding to. /// </summary> /// <value>The name of the <see cref="DependencyProperty"/> to apply the <see cref="DataGridBoundColumn.Binding"/> property in the content returned /// in the <see cref="DataTemplate"/> provided by the <see cref="DataGridTemplateColumn.CellTemplate"/> property. This property can be null or an empty string. /// The default value is null.</value> /// <remarks>When a value is specified and a matching <see cref="DependencyProperty"/> is found on the content <see cref="FrameworkElement"/> /// generated for the cell, the <see cref="DependencyProperty"/> and <see cref="DataGridBoundColumn.Binding"/> properties are paired. This provides the ability to /// dynamically wire data binding so that a <see cref="DataTemplate"/> for a column can be reused.</remarks> public string ContentDependencyProperty { get; set; } /// <summary> /// Gets or sets the name of the dependency property in the editing content data template to apply the column binding to. /// </summary> /// <value>The name of the <see cref="DependencyProperty"/> to apply the <see cref="DataGridBoundColumn.Binding"/> property in the content returned /// in the <see cref="DataTemplate"/> provided by the <see cref="DataGridTemplateColumn.CellEditingTemplate"/> property. This property can be null or an empty string. /// The default value is null.</value> /// <remarks>When a value is specified and a matching <see cref="DependencyProperty"/> is found on the content <see cref="FrameworkElement"/> /// generated for the cell, the <see cref="DependencyProperty"/> and <see cref="DataGridBoundColumn.Binding"/> properties are paired. This provides the ability to /// dynamically wire data binding so that a <see cref="DataTemplate"/> for a column can be reused.</remarks> public string EditingContentDependencyProperty { get; set; } } }
69.616667
175
0.67752
[ "MIT" ]
JTOne123/More
src/More.UI.Presentation/Platforms/net45/More/Windows.Data/DataGridTemplateColumnAttribute.cs
4,179
C#
using Microsoft.Extensions.Logging; using PnP.Core.Model; using PnP.Core.Services.Core.CSOM; using PnP.Core.Services.Core.CSOM.Requests; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace PnP.Core.Services { /// <summary> /// Client that's reponsible for creating and processing batch requests /// </summary> internal sealed class BatchClient { #if DEBUG // Simple counter used to construct the batch key used for test mocking private int testUseCounter; #endif // Handles sending telemetry events private readonly TelemetryManager telemetryManager; // Collection of current batches, ensure thread safety via a concurrent dictionary private readonly ConcurrentDictionary<Guid, Batch> batches = new ConcurrentDictionary<Guid, Batch>(); #region Embedded classes #region Classes used for Graph batch (de)serialization internal class GraphBatchRequest { public string Id { get; set; } public string Method { get; set; } public string Url { get; set; } public string Body { get; set; } public Dictionary<string, string> Headers { get; set; } } internal class GraphBatchRequests { public IList<GraphBatchRequest> Requests { get; set; } = new List<GraphBatchRequest>(); } internal class GraphBatchResponse { public string Id { get; set; } public HttpStatusCode Status { get; set; } public Dictionary<string, string> Headers { get; set; } = new Dictionary<string, string>(); [JsonExtensionData] public Dictionary<string, JsonElement> Body { get; set; } = new Dictionary<string, JsonElement>(); } internal class GraphBatchResponses { public IList<GraphBatchResponse> Responses { get; set; } = new List<GraphBatchResponse>(); } #endregion #region Classes used to support REST batch handling internal class SPORestBatch { public SPORestBatch(Uri site) { Site = site; } public Batch Batch { get; set; } public Uri Site { get; set; } } #endregion #region Classes used to support CSOM batch handling internal class CsomBatch { public CsomBatch(Uri site) { Site = site; } public Batch Batch { get; set; } public Uri Site { get; set; } } #endregion internal class BatchResultMerge { internal object Model { get; set; } internal Type ModelType { get; set; } internal object KeyValue { get; set; } internal List<BatchRequest> Requests { get; set; } = new List<BatchRequest>(); } #endregion /// <summary> /// Constructor /// </summary> /// <param name="context">PnP Context</param> /// <param name="globalOptions">Global settings to use</param> /// <param name="telemetry">Telemetry manager</param> internal BatchClient(PnPContext context, PnPGlobalSettingsOptions globalOptions, TelemetryManager telemetry) { PnPContext = context; telemetryManager = telemetry; HttpMicrosoftGraphMaxRetries = globalOptions.HttpMicrosoftGraphMaxRetries; HttpMicrosoftGraphDelayInSeconds = globalOptions.HttpMicrosoftGraphDelayInSeconds; HttpMicrosoftGraphUseIncrementalDelay = globalOptions.HttpMicrosoftGraphUseIncrementalDelay; } /// <summary> /// PnP Context /// </summary> internal PnPContext PnPContext { get; private set; } /// <summary> /// Max requests in a single SharePointRest batch /// </summary> internal static int MaxRequestsInSharePointRestBatch => 100; /// <summary> /// Max requests in a single Csom batch /// </summary> internal static int MaxRequestsInCsomBatch => 50; /// <summary> /// Max requests in a single Microsoft Graph batch /// </summary> internal static int MaxRequestsInGraphBatch => 20; /// <summary> /// When not using retry-after, how many times can a retry be made. Defaults to 10 /// </summary> internal int HttpMicrosoftGraphMaxRetries { get; set; } /// <summary> /// How many seconds to wait for the next retry attempt. Defaults to 3 /// </summary> internal int HttpMicrosoftGraphDelayInSeconds { get; set; } /// <summary> /// Use an incremental strategy for the delay: each retry doubles the previous delay time. Defaults to true /// </summary> internal bool HttpMicrosoftGraphUseIncrementalDelay { get; set; } #if DEBUG /// <summary> /// Handler that can be used to rewrite mocking files before they're used /// </summary> internal Func<string, string> MockingFileRewriteHandler { get; set; } #endif /// <summary> /// Creates a new batch /// </summary> /// <returns>Newly created batch</returns> internal Batch EnsureBatch() { return EnsureBatch(Guid.NewGuid()); } /// <summary> /// Gets or creates a new batch /// </summary> /// <param name="id">Id for the batch to get or create</param> /// <returns>Ensured batch</returns> private Batch EnsureBatch(Guid id) { if (ContainsBatch(id)) { return batches[id]; } else { var batch = new Batch(id); if (batches.TryAdd(id, batch)) { return batch; } else { throw new ClientException(ErrorType.Unsupported, PnPCoreResources.Exception_Unsupported_CannotAddBatch); } } } /// <summary> /// Checks if a given batch is still listed for this batch client /// </summary> /// <param name="id">Id of the batch to check for</param> /// <returns>True if still listed, false otherwise</returns> internal bool ContainsBatch(Guid id) { return batches.ContainsKey(id); } /// <summary> /// Gets a batch via the given id /// </summary> /// <param name="id">Id of the batch to get</param> /// <returns>The found batch, null otherwise</returns> internal Batch GetBatchById(Guid id) { if (ContainsBatch(id)) { return batches[id]; } return null; } /// <summary> /// Executes a given batch /// </summary> /// <param name="batch">Batch to execute</param> /// <returns></returns> internal async Task<List<BatchResult>> ExecuteBatch(Batch batch) { bool anyPageToLoad; // Clear all collections foreach (var request in batch.Requests.Values) { if (request.ApiCall.SkipCollectionClearing || request.ApiCall.ExecuteRequestApiCall) { continue; } foreach (var fieldInfo in request.EntityInfo.Fields.Where(f => f.Load && request.Model.HasValue(f.Name))) { // Get the collection var property = fieldInfo.PropertyInfo.GetValue(request.Model); var requestableCollection = property as IRequestableCollection; requestableCollection?.Clear(); } } // Clear batch result collection batch.Results.Clear(); // Before we start running this new batch let's // clean previous batch execution data RemoveProcessedBatches(); var doneRequests = new List<BatchRequest>(); do { // Verify batch requests do not contain unresolved tokens CheckForUnresolvedTokens(batch); if (batch.HasInteractiveRequest) { if (batch.Requests.Count > 1) { throw new ClientException(ErrorType.Unsupported, PnPCoreResources.Exception_Unsupported_InteractiveRequestBatch); } if (batch.Requests.First().Value.ApiCall.Type == ApiType.SPORest) { await ExecuteSharePointRestInteractiveAsync(batch).ConfigureAwait(false); } } else { if (batch.HasMixedApiTypes) { if (batch.CanFallBackToSPORest) { // set the backup api call to be the actual api call for the api calls marked as graph batch.MakeSPORestOnlyBatch(); await ExecuteSharePointRestBatchAsync(batch).ConfigureAwait(false); } else { // implement logic to split batch in a rest batch and a graph batch (Batch spoRestBatch, Batch graphBatch, Batch graphBetaBatch, Batch csomBatch) = SplitIntoBatchesPerApiType(batch, PnPContext.GraphAlwaysUseBeta); // execute the 4 batches await ExecuteSharePointRestBatchAsync(spoRestBatch).ConfigureAwait(false); if (!PnPContext.GraphAlwaysUseBeta) { await ExecuteMicrosoftGraphBatchAsync(graphBatch).ConfigureAwait(false); } await ExecuteMicrosoftGraphBatchAsync(graphBetaBatch).ConfigureAwait(false); await ExecuteCsomBatchAsync(csomBatch).ConfigureAwait(false); // Aggregate batch results from the executed batches batch.Results.AddRange(spoRestBatch.Results); if (!PnPContext.GraphAlwaysUseBeta) { batch.Results.AddRange(graphBatch.Results); } batch.Results.AddRange(graphBetaBatch.Results); batch.Results.AddRange(csomBatch.Results); batch.Executed = true; } } else { if (batch.UseGraphBatch) { await ExecuteMicrosoftGraphBatchAsync(batch).ConfigureAwait(false); } else if (batch.UseCsomBatch) { await ExecuteCsomBatchAsync(batch).ConfigureAwait(false); } else { await ExecuteSharePointRestBatchAsync(batch).ConfigureAwait(false); } } // Executing a batch might have resulted in a mismatch between the model and the data in SharePoint: // Getting entities can result in duplicate entities (e.g. 2 lists when getting the same list twice in a single batch) // Adding entities can result in an entity in the model that does not have the proper key value set (as that value is only retrievable after the add in SharePoint) // Deleting entities can result in an entity in the model that also should have been deleted MergeBatchResultsWithModel(batch); } // Reset flag anyPageToLoad = false; // Make a copy of requests which need to load also other pages var requestWithLoadPages = batch.Requests.Values.Where(r => r.ApiCall.LoadPages).ToArray(); // Temporary keep requests into a final list doneRequests.AddRange(batch.Requests.Values); // Remove current requests in order to create another set batch.Requests.Clear(); foreach (var requestWithPages in requestWithLoadPages) { foreach (var fieldInfo in requestWithPages.EntityInfo.Fields.Where(f => f.Load && requestWithPages.Model.HasValue(f.Name))) { var property = fieldInfo.PropertyInfo.GetValue(requestWithPages.Model); // Check if collection supports pagination var typedCollection = property as ISupportPaging; if (typedCollection == null || !typedCollection.CanPage) continue; // Prepare api call IMetadataExtensible metadataExtensible = (IMetadataExtensible)typedCollection; (var nextLink, var nextLinkApiType) = QueryClient.BuildNextPageLink(metadataExtensible); // Clear the MetaData paging links to avoid loading the collection again via paging metadataExtensible.Metadata.Remove(PnPConstants.GraphNextLink); metadataExtensible.Metadata.Remove(PnPConstants.SharePointRestListItemNextLink); // Create a request for the next page batch.Add( requestWithPages.Model, requestWithPages.EntityInfo, HttpMethod.Get, new ApiCall { Type = nextLinkApiType, ReceivingProperty = fieldInfo.Name, Request = nextLink, LoadPages = true }, default, requestWithPages.FromJsonCasting, requestWithPages.PostMappingJson, "GetNextPage" ); anyPageToLoad = true; } } // Loop until there is no other pages to load } while (anyPageToLoad); // Restore all requests done batch.Requests.Clear(); // Rearrange order sequence doneRequests.ForEach(r => { r.Order = batch.Requests.Count; batch.Requests.Add(r.Order, r); }); // If there's an event handler attached then invoke it batch.BatchExecuted?.Invoke(); return batch.Results; } #region Graph batching private static List<Batch> MicrosoftGraphBatchSplitting(Batch batch) { List<Batch> batches = new List<Batch>(); // Only split if we have more than 20 requests in a single batch if (batch.Requests.Count <= MaxRequestsInGraphBatch) { batches.Add(batch); return batches; } int counter = 0; int order = 0; Batch currentBatch = new Batch() { ThrowOnError = batch.ThrowOnError }; foreach (var request in batch.Requests.OrderBy(p => p.Value.Order)) { currentBatch.Requests.Add(order, request.Value); order++; counter++; if (counter % MaxRequestsInGraphBatch == 0) { order = 0; batches.Add(currentBatch); currentBatch = new Batch() { ThrowOnError = batch.ThrowOnError }; } } // Add the last part if (currentBatch.Requests.Count > 0) { batches.Add(currentBatch); } return batches; } private async Task ExecuteMicrosoftGraphBatchAsync(Batch batch) { // Due to previous splitting we can see empty batches... if (!batch.Requests.Any(p => p.Value.ExecutionNeeded)) { return; } // Split the provided batch in multiple batches if needed. Possible split reasons are: // - too many requests var graphBatches = MicrosoftGraphBatchSplitting(batch); foreach (var graphBatch in graphBatches) { if (graphBatch.Requests.Count == 1) { await ExecuteMicrosoftGraphInteractiveAsync(graphBatch).ConfigureAwait(false); } else { if (!await ExecuteMicrosoftGraphBatchRequestAsync(graphBatch).ConfigureAwait(false)) { // If a request did not succeed and the returned error indicated a retry then try again int retryCount = 0; bool success = false; while (retryCount < HttpMicrosoftGraphMaxRetries) { // Call Delay method to get delay time Task delay = Delay(retryCount, HttpMicrosoftGraphDelayInSeconds, HttpMicrosoftGraphUseIncrementalDelay); await delay.ConfigureAwait(false); // Increase retryCount retryCount++; success = await ExecuteMicrosoftGraphBatchRequestAsync(graphBatch).ConfigureAwait(false); if (success) { break; } } if (!success) { // We passed the max retries...time to throw an error throw new ServiceException(ErrorType.TooManyBatchRetries, 0, string.Format(PnPCoreResources.Exception_ServiceException_BatchMaxRetries, retryCount)); } } } } // set the original batch to executed batch.Executed = true; } private static Task Delay(int retryCount, int delay, bool incrementalDelay) { double delayInSeconds; // Custom delay if (incrementalDelay) { // Incremental delay, the wait time between each delay exponentially gets bigger double power = Math.Pow(2, retryCount); delayInSeconds = power * delay; } else { // Linear delay delayInSeconds = delay; } // If the delay goes beyond our max wait time for a delay then cap it TimeSpan delayTimeSpan = TimeSpan.FromSeconds(Math.Min(delayInSeconds, RetryHandlerBase.MAXDELAY)); return Task.Delay(delayTimeSpan); } private async Task<bool> ExecuteMicrosoftGraphBatchRequestAsync(Batch batch) { string graphEndpoint = DetermineGraphEndpoint(batch); (string requestBody, string requestKey) = BuildMicrosoftGraphBatchRequestContent(batch); PnPContext.Logger.LogDebug($"{graphEndpoint} : {requestBody}"); // Make the batch call using StringContent content = new StringContent(requestBody); using (var request = new HttpRequestMessage(HttpMethod.Post, $"{graphEndpoint}/$batch")) { // Remove the default Content-Type content header if (content.Headers.Contains("Content-Type")) { content.Headers.Remove("Content-Type"); } // Add the batch Content-Type header content.Headers.Add($"Content-Type", "application/json"); // Connect content to request request.Content = content; #if DEBUG // Test recording if (PnPContext.Mode == TestMode.Record && PnPContext.GenerateTestMockingDebugFiles) { // Write request TestManager.RecordRequest(PnPContext, requestKey, content.ReadAsStringAsync().Result); } // If we are not mocking data, or if the mock data is not yet available if (PnPContext.Mode != TestMode.Mock) { #endif // Ensure the request contains authentication information var graphBaseUri = PnPConstants.MicrosoftGraphBaseUri; if (PnPContext.Environment.HasValue) { graphBaseUri = new Uri($"https://{CloudManager.GetMicrosoftGraphAuthority(PnPContext.Environment.Value)}/"); } await PnPContext.AuthenticationProvider.AuthenticateRequestAsync(graphBaseUri, request).ConfigureAwait(false); // Send the request HttpResponseMessage response = await PnPContext.GraphClient.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); try { // Process the request response if (response.IsSuccessStatusCode) { // Get the response string, using HttpCompletionOption.ResponseHeadersRead and ReadAsStreamAsync to lower the memory // pressure when processing larger responses + performance is better using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { using (StreamReader reader = new StreamReader(streamToReadFrom)) { string batchResponse = await reader.ReadToEndAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { batchResponse = MockingFileRewriteHandler(batchResponse); } // Write response TestManager.RecordResponse(PnPContext, requestKey, batchResponse, response.IsSuccessStatusCode, (int)response.StatusCode, MicrosoftGraphResposeHeadersToPropagate(response?.Headers)); } #endif var ready = await ProcessGraphRestBatchResponse(batch, batchResponse).ConfigureAwait(false); if (!ready) { return false; } } } } else { // Something went wrong... throw new MicrosoftGraphServiceException(ErrorType.GraphServiceError, (int)response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false)); } } finally { response.Dispose(); } #if DEBUG } else { var testResponse = TestManager.MockResponse(PnPContext, requestKey); string batchResponse = testResponse.Response; // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { batchResponse = MockingFileRewriteHandler(batchResponse); } var ready = await ProcessGraphRestBatchResponse(batch, batchResponse).ConfigureAwait(false); if (!ready) { return false; } } #endif } // Mark batch as executed batch.Executed = true; // All good so it seams return true; } private string DetermineGraphEndpoint(Batch graphBatch) { // If a request is in the batch it means we allowed to use Graph beta. To // maintain batch integretity we move a complete batch to beta if there's one // of the requests in the batch requiring Graph beta. if (PnPContext.GraphAlwaysUseBeta) { return PnPConstants.GraphBetaEndpoint; } else { if (graphBatch.Requests.Any(p => p.Value.ApiCall.Type == ApiType.GraphBeta)) { return PnPConstants.GraphBetaEndpoint; } else { return PnPConstants.GraphV1Endpoint; } } } private async Task<bool> ProcessGraphRestBatchResponse(Batch batch, string batchResponse) { // Deserialize the graph batch response json var graphBatchResponses = JsonSerializer.Deserialize<GraphBatchResponses>(batchResponse, PnPConstants.JsonSerializer_IgnoreNullValues_CamelCase); // Was there any request that's eligible for a retry? bool retryNeeded = false; foreach (var graphBatchResponse in graphBatchResponses.Responses) { if (int.TryParse(graphBatchResponse.Id, out int id)) { // Get the original request, requests use 0 based ordering var batchRequest = batch.GetRequest(id - 1); if (RetryHandlerBase.ShouldRetry(graphBatchResponse.Status)) { retryNeeded = true; batchRequest.FlagForRetry(graphBatchResponse.Status, graphBatchResponse.Headers); } else { if (graphBatchResponse.Body.TryGetValue("body", out JsonElement bodyContent)) { // If one of the requests in the batch failed then throw an exception if (!HttpRequestSucceeded(graphBatchResponse.Status)) { if (batch.ThrowOnError) { throw new MicrosoftGraphServiceException(ErrorType.GraphServiceError, (int)graphBatchResponse.Status, bodyContent); } else { batch.AddBatchResult(batchRequest, graphBatchResponse.Status, bodyContent.ToString(), new MicrosoftGraphError(ErrorType.GraphServiceError, (int)graphBatchResponse.Status, bodyContent)); } } else { string responseBody = bodyContent.ToString(); // Run request modules if they're connected if (batchRequest.RequestModules != null && batchRequest.RequestModules.Count > 0) { responseBody = ExecuteMicrosoftGraphRequestModulesOnResponse(graphBatchResponse.Status, graphBatchResponse.Headers, batchRequest, responseBody); } // All was good, connect response to the original request batchRequest.AddResponse(responseBody, graphBatchResponse.Status, graphBatchResponse.Headers); // Commit succesful updates in our model if (batchRequest.Method == new HttpMethod("PATCH") || batchRequest.ApiCall.Commit) { if (batchRequest.Model is TransientObject) { batchRequest.Model.Commit(); } } } } } } } if (retryNeeded) { return false; } using (var tracer = Tracer.Track(PnPContext.Logger, "ExecuteSharePointGraphBatchAsync-JSONToModel")) { // Map the retrieved JSON to our domain model foreach (var batchRequest in batch.Requests.Values) { // A raw request does not require loading of the response into the model if (!batchRequest.ApiCall.RawRequest) { await JsonMappingHelper.MapJsonToModel(batchRequest).ConfigureAwait(false); } // Invoke a delegate (if defined) to trigger processing of raw batch requests batchRequest.ApiCall.RawResultsHandler?.Invoke(batchRequest.ResponseJson, batchRequest.ApiCall); } } return true; } private Tuple<string, string> BuildMicrosoftGraphBatchRequestContent(Batch batch) { // See // - https://docs.microsoft.com/en-us/graph/json-batching?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 StringBuilder batchKey = new StringBuilder(); #if DEBUG if (PnPContext.Mode != TestMode.Default) { batchKey.Append($"{testUseCounter}@@"); testUseCounter++; } #endif GraphBatchRequests graphRequests = new GraphBatchRequests(); Dictionary<int, string> bodiesToReplace = new Dictionary<int, string>(); int counter = 1; foreach (var request in batch.Requests.Values) { if (request.ExecutionNeeded) { var graphRequest = new GraphBatchRequest() { Id = counter.ToString(CultureInfo.InvariantCulture), Method = request.Method.ToString(), Url = request.ApiCall.Request, }; if (!string.IsNullOrEmpty(request.ApiCall.JsonBody)) { bodiesToReplace.Add(counter, request.ApiCall.JsonBody); graphRequest.Body = $"@#|Body{counter}|#@"; graphRequest.Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }; }; if (graphRequest.Headers == null) { graphRequest.Headers = new Dictionary<string, string>(); } if (request.ApiCall.Headers != null && request.ApiCall.Headers.Count > 0) { foreach (var key in request.ApiCall.Headers.Keys) { string existingKey = graphRequest.Headers.Keys.FirstOrDefault(k => k.Equals(key, StringComparison.InvariantCultureIgnoreCase)); if (string.IsNullOrWhiteSpace(existingKey)) { graphRequest.Headers.Add(key, request.ApiCall.Headers[key]); } else { graphRequest.Headers[existingKey] = request.ApiCall.Headers[key]; } } } // Run request modules if they're connected if (request.RequestModules != null && request.RequestModules.Count > 0) { string requestUrl = graphRequest.Url; string requestBody = graphRequest.Body; ExecuteMicrosoftGraphRequestModules(request, graphRequest.Headers, ref requestUrl, ref requestBody); graphRequest.Url = requestUrl; graphRequest.Body = requestBody; } graphRequests.Requests.Add(graphRequest); #if DEBUG if (PnPContext.Mode != TestMode.Default) { batchKey.Append($"{request.Method}|{request.ApiCall.Request}@@"); } #endif } counter++; telemetryManager?.LogServiceRequest(request, PnPContext); } string stringContent = JsonSerializer.Serialize(graphRequests, PnPConstants.JsonSerializer_IgnoreNullValues_CamelCase); foreach (var bodyToReplace in bodiesToReplace) { stringContent = stringContent.Replace($"\"@#|Body{bodyToReplace.Key}|#@\"", bodyToReplace.Value); } return new Tuple<string, string>(stringContent, batchKey.ToString()); } private static Dictionary<string, string> MicrosoftGraphResposeHeadersToPropagate(HttpResponseHeaders headers) { Dictionary<string, string> responseHeaders = new Dictionary<string, string>(); if (headers != null && headers.Any()) { foreach (var header in headers) { responseHeaders[header.Key] = string.Join(",", header.Value); } } return responseHeaders; } private static void ExecuteMicrosoftGraphRequestModules(BatchRequest request, Dictionary<string, string> headers, ref string requestUrl, ref string requestBody) { foreach (var module in request.RequestModules.Where(p => p.ExecuteForMicrosoftGraph)) { if (module.RequestHeaderHandler != null) { module.RequestHeaderHandler.Invoke(headers); } if (module.RequestUrlHandler != null) { requestUrl = module.RequestUrlHandler.Invoke(requestUrl); } if (module.RequestBodyHandler != null) { requestBody = module.RequestBodyHandler.Invoke(requestBody); } } } private static string ExecuteMicrosoftGraphRequestModulesOnResponse(HttpStatusCode httpStatusCode, Dictionary<string, string> responseHeaders, BatchRequest currentBatchRequest, string responseStringContent) { foreach (var module in currentBatchRequest.RequestModules.Where(p => p.ExecuteForMicrosoftGraph)) { if (module.ResponseHandler != null) { responseStringContent = module.ResponseHandler.Invoke(httpStatusCode, responseHeaders, responseStringContent); } } return responseStringContent; } private async Task ExecuteMicrosoftGraphInteractiveAsync(Batch batch) { var graphRequest = batch.Requests.First().Value; StringContent content = null; ByteArrayContent binaryContent = null; try { string graphEndpoint = DetermineGraphEndpoint(batch); string requestUrl = graphRequest.ApiCall.Request; string requestBody = graphRequest.ApiCall.JsonBody; PnPContext.Logger.LogDebug($"{graphEndpoint} : {requestBody}"); Dictionary<string, string> headers = new Dictionary<string, string>(); // Run request modules if they're connected if (graphRequest.RequestModules != null && graphRequest.RequestModules.Count > 0) { ExecuteMicrosoftGraphRequestModules(graphRequest, headers, ref requestUrl, ref requestBody); } // Make the request using (var request = new HttpRequestMessage(graphRequest.Method, $"https://{CloudManager.GetMicrosoftGraphAuthority(PnPContext.Environment.Value)}/{graphEndpoint}/{requestUrl}")) { if (!string.IsNullOrEmpty(requestBody)) { content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Content = content; // Remove the default Content-Type content header if (content.Headers.Contains("Content-Type")) { content.Headers.Remove("Content-Type"); } content.Headers.Add($"Content-Type", $"application/json"); PnPContext.Logger.LogDebug(requestBody); } else if (graphRequest.ApiCall.BinaryBody != null) { binaryContent = new ByteArrayContent(graphRequest.ApiCall.BinaryBody); request.Content = binaryContent; } // Add extra headers foreach (var extraHeader in headers) { if (!request.Headers.Contains(extraHeader.Key)) { request.Headers.Add(extraHeader.Key, extraHeader.Value); } } telemetryManager?.LogServiceRequest(graphRequest, PnPContext); #if DEBUG string batchKey = null; if (PnPContext.Mode != TestMode.Default) { batchKey = $"{testUseCounter}@@{request.Method}|{graphRequest.ApiCall.Request}@@"; testUseCounter++; } // Test recording if (PnPContext.Mode == TestMode.Record && PnPContext.GenerateTestMockingDebugFiles) { // Write request TestManager.RecordRequest(PnPContext, batchKey, $"{graphRequest.Method}-{graphRequest.ApiCall.Request}-{(graphRequest.ApiCall.JsonBody ?? "")}"); } // If we are not mocking data, or if the mock data is not yet available if (PnPContext.Mode != TestMode.Mock) { #endif // Ensure the request contains authentication information var graphBaseUri = PnPConstants.MicrosoftGraphBaseUri; if (PnPContext.Environment.HasValue) { graphBaseUri = new Uri($"https://{CloudManager.GetMicrosoftGraphAuthority(PnPContext.Environment.Value)}/"); } await PnPContext.AuthenticationProvider.AuthenticateRequestAsync(graphBaseUri, request).ConfigureAwait(false); // Send the request HttpResponseMessage response = await PnPContext.GraphClient.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); // Process the request response if (response.IsSuccessStatusCode) { // Get the response string, using HttpCompletionOption.ResponseHeadersRead and ReadAsStreamAsync to lower the memory // pressure when processing larger responses + performance is better Stream requestResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record && !graphRequest.ApiCall.StreamResponse) { // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { string responseStringContent = null; if (response.StatusCode == HttpStatusCode.NoContent) { responseStringContent = ""; } else { using (var streamReader = new StreamReader(requestResponseStream)) { string requestResponse = await streamReader.ReadToEndAsync().ConfigureAwait(false); responseStringContent = requestResponse; } } var mockedRewrittenFileString = MockingFileRewriteHandler(responseStringContent); requestResponseStream = mockedRewrittenFileString.AsStream(); } // Write response TestManager.RecordResponse(PnPContext, batchKey, ref requestResponseStream, response.IsSuccessStatusCode, (int)response.StatusCode, MicrosoftGraphResposeHeadersToPropagate(response?.Headers)); } #endif await ProcessMicrosoftGraphInteractiveResponse(graphRequest, response.StatusCode, MicrosoftGraphResposeHeadersToPropagate(response?.Headers), requestResponseStream).ConfigureAwait(false); } else { string errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Write response TestManager.RecordResponse(PnPContext, batchKey, errorContent, response.IsSuccessStatusCode, (int)response.StatusCode, MicrosoftGraphResposeHeadersToPropagate(response?.Headers)); } #endif // Something went wrong... throw new MicrosoftGraphServiceException( ErrorType.GraphServiceError, (int)response.StatusCode, errorContent); } #if DEBUG } else { var testResponse = TestManager.MockResponse(PnPContext, batchKey); if (!testResponse.IsSuccessStatusCode) { throw new MicrosoftGraphServiceException(ErrorType.GraphServiceError, testResponse.StatusCode, testResponse.Response); } await ProcessMicrosoftGraphInteractiveResponse(graphRequest, (HttpStatusCode)testResponse.StatusCode, testResponse.Headers, testResponse.Response.AsStream()).ConfigureAwait(false); } #endif // Mark batch as executed batch.Executed = true; } } finally { if (content != null) { content.Dispose(); } if (binaryContent != null) { binaryContent.Dispose(); } } } private static async Task ProcessMicrosoftGraphInteractiveResponse(BatchRequest graphRequest, HttpStatusCode statusCode, Dictionary<string, string> responseHeaders, Stream responseContent) { // If a binary response content is expected if (graphRequest.ApiCall.ExpectBinaryResponse) { // Add it to the request and stop processing the response graphRequest.AddResponse(responseContent, statusCode); return; } string responseStringContent = null; if (statusCode == HttpStatusCode.NoContent) { responseStringContent = ""; } else { using (var streamReader = new StreamReader(responseContent)) { string requestResponse = await streamReader.ReadToEndAsync().ConfigureAwait(false); responseStringContent = requestResponse; } } // Run request modules if they're connected if (graphRequest.RequestModules != null && graphRequest.RequestModules.Count > 0) { responseStringContent = ExecuteMicrosoftGraphRequestModulesOnResponse(statusCode, responseHeaders, graphRequest, responseStringContent); } // Store the response for further processing graphRequest.AddResponse(responseStringContent, statusCode, responseHeaders); // Commit succesful updates in our model if (graphRequest.Method == new HttpMethod("PATCH") || graphRequest.ApiCall.Commit) { if (graphRequest.Model is TransientObject) { graphRequest.Model.Commit(); } } // Update our model by processing the "delete" if (graphRequest.Method == HttpMethod.Delete) { if (graphRequest.Model is TransientObject) { graphRequest.Model.RemoveFromParentCollection(); } } if (!string.IsNullOrEmpty(graphRequest.ResponseJson)) { // A raw request does not require loading of the response into the model if (!graphRequest.ApiCall.RawRequest) { await JsonMappingHelper.MapJsonToModel(graphRequest).ConfigureAwait(false); } } } #endregion #region SharePoint REST batching private static List<SPORestBatch> SharePointRestBatchSplitting(Batch batch) { List<SPORestBatch> batches = new List<SPORestBatch>(); foreach (var request in batch.Requests.OrderBy(p => p.Value.Order)) { // Group batched based up on the site url, a single batch must be scoped to a single web Uri site = new Uri(request.Value.ApiCall.Request.Substring(0, request.Value.ApiCall.Request.IndexOf("/_api/", 0))); var restBatch = batches.FirstOrDefault(b => b.Site == site); if (restBatch == null) { // Create a new batch restBatch = new SPORestBatch(site) { Batch = new Batch() { ThrowOnError = batch.ThrowOnError } }; batches.Add(restBatch); } // Add request to existing batch, we're adding the original request which ensures that once // we update the new batch with results these results are also part of the original batch restBatch.Batch.Requests.Add(request.Value.Order, request.Value); } return batches; } private static List<SPORestBatch> SharePointRestBatchSplittingBySize(SPORestBatch batch) { List<SPORestBatch> batches = new List<SPORestBatch>(); // No need to split if (batch.Batch.Requests.Count < MaxRequestsInSharePointRestBatch) { batches.Add(batch); return batches; } // Split in multiple batches int counter = 0; int order = 0; SPORestBatch currentBatch = new SPORestBatch(batch.Site) { Batch = new Batch() { ThrowOnError = batch.Batch.ThrowOnError } }; foreach (var request in batch.Batch.Requests.OrderBy(p => p.Value.Order)) { currentBatch.Batch.Requests.Add(order, request.Value); order++; counter++; if (counter % MaxRequestsInSharePointRestBatch == 0) { order = 0; batches.Add(currentBatch); currentBatch = new SPORestBatch(batch.Site) { Batch = new Batch() { ThrowOnError = batch.Batch.ThrowOnError } }; } } // Add the last part if (currentBatch.Batch.Requests.Count > 0) { batches.Add(currentBatch); } return batches; } private async Task ExecuteSharePointRestBatchAsync(Batch batch) { // Due to previous splitting we can see empty batches... if (!batch.Requests.Any(p => p.Value.ExecutionNeeded)) { return; } // A batch can only combine requests for the same web, if needed we need to split the incoming batch in batches per web var restBatches = SharePointRestBatchSplitting(batch); // Execute the batches foreach (var restBatch in restBatches) { // If there's only one request in the batch then we don't need to use batching to execute the request. // Non batched executions can use network payload compression, hence we skip batching for single requests. // If the code explicitely used a batch method than honor that as otherwise we would have breaking changes if (restBatch.Batch.Requests.Count == 1 && restBatch.Batch.Requests.First().Value.ApiCall.RawSingleResult == null && restBatch.Batch.Requests.First().Value.ApiCall.RawEnumerableResult == null) { await ExecuteSharePointRestInteractiveAsync(restBatch.Batch).ConfigureAwait(false); } else { // A batch can contain more than the maximum number of items in a SharePoint batch, so if needed breakup a batch in multiple batches var splitRestBatches = SharePointRestBatchSplittingBySize(restBatch); foreach (var splitRestBatch in splitRestBatches) { (string requestBody, string requestKey) = BuildSharePointRestBatchRequestContent(splitRestBatch.Batch); PnPContext.Logger.LogDebug(requestBody); // Make the batch call using StringContent content = new StringContent(requestBody); using (var request = new HttpRequestMessage(HttpMethod.Post, $"{splitRestBatch.Site.ToString().TrimEnd(new char[] { '/' })}/_api/$batch")) { // Remove the default Content-Type content header if (content.Headers.Contains("Content-Type")) { content.Headers.Remove("Content-Type"); } // Add the batch Content-Type header content.Headers.Add($"Content-Type", $"multipart/mixed; boundary=batch_{splitRestBatch.Batch.Id}"); // Connect content to request request.Content = content; #if DEBUG // Test recording if (PnPContext.Mode == TestMode.Record && PnPContext.GenerateTestMockingDebugFiles) { // Write request TestManager.RecordRequest(PnPContext, requestKey, content.ReadAsStringAsync().Result); } // If we are not mocking or if there is no mock data if (PnPContext.Mode != TestMode.Mock) { #endif // Process the authentication headers using the currently // configured instance of IAuthenticationProvider await ProcessSharePointRestAuthentication(splitRestBatch.Site, request).ConfigureAwait(false); // Send the request HttpResponseMessage response = await PnPContext.RestClient.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); try { // Process the request response if (response.IsSuccessStatusCode) { // Get the response string, using HttpCompletionOption.ResponseHeadersRead and ReadAsStreamAsync to lower the memory // pressure when processing larger responses + performance is better using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { using (StreamReader reader = new StreamReader(streamToReadFrom)) { string batchResponse = await reader.ReadToEndAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { batchResponse = MockingFileRewriteHandler(batchResponse); } // Write response TestManager.RecordResponse(PnPContext, requestKey, batchResponse, response.IsSuccessStatusCode, (int)response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers)); } #endif await ProcessSharePointRestBatchResponse(splitRestBatch, batchResponse, SpoRestResposeHeadersToPropagate(response?.Headers)).ConfigureAwait(false); } } } else { // Something went wrong... throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, (int)response.StatusCode, await response.Content.ReadAsStringAsync().ConfigureAwait(false), SpoRestResposeHeadersToPropagate(response.Headers)); } } finally { response.Dispose(); } #if DEBUG } else { var testResponse = TestManager.MockResponse(PnPContext, requestKey); await ProcessSharePointRestBatchResponse(splitRestBatch, testResponse.Response, testResponse.Headers).ConfigureAwait(false); } #endif // Mark batch as executed splitRestBatch.Batch.Executed = true; // Copy the results collection to the upper batch restBatch.Batch.Results.AddRange(splitRestBatch.Batch.Results); } } // Copy the results collection to the upper batch batch.Results.AddRange(restBatch.Batch.Results); } } // Mark the original (non split) batch as complete batch.Executed = true; } /// <summary> /// Constructs the content of the batch request to be sent /// </summary> /// <param name="batch">Batch to create the request content for</param> /// <returns>StringBuilder holding the created batch request content</returns> private Tuple<string, string> BuildSharePointRestBatchRequestContent(Batch batch) { StringBuilder sb = new StringBuilder(); StringBuilder batchKey = new StringBuilder(); #if DEBUG if (PnPContext.Mode != TestMode.Default) { batchKey.Append($"{testUseCounter}@@"); testUseCounter++; } #endif // See: // - https://www.odata.org/documentation/odata-version-3-0/batch-processing/ // - https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/make-batch-requests-with-the-rest-apis // - https://www.andrewconnell.com/blog/part-1-sharepoint-rest-api-batching-understanding-batching-requests // - http://connell59.rssing.com/chan-9164895/all_p12.html (scroll to Part 2 - SharePoint REST API Batching - Exploring Batch Requests, Responses and Changesets) foreach (var request in batch.Requests.Values) { Dictionary<string, string> headers = new Dictionary<string, string>(); if (request.Method == HttpMethod.Get) { headers.Add("Accept", "application/json;odata=nometadata"); } else if (request.Method == new HttpMethod("PATCH") || request.Method == HttpMethod.Post || request.Method == HttpMethod.Delete) { headers.Add("Accept", "application/json;odata=nometadata"); headers.Add("Content-Type", "application/json;odata=verbose"); } if (request.ApiCall.Headers != null && request.ApiCall.Headers.Count > 0) { foreach (var key in request.ApiCall.Headers.Keys) { string existingKey = headers.Keys.FirstOrDefault(k => k.Equals(key, StringComparison.InvariantCultureIgnoreCase)); if (string.IsNullOrWhiteSpace(existingKey)) { headers.Add(key, request.ApiCall.Headers[key]); } else { headers[existingKey] = request.ApiCall.Headers[key]; } } } string requestUrl = request.ApiCall.Request; string requestBody = request.ApiCall.JsonBody; // Run request modules if they're connected if (request.RequestModules != null && request.RequestModules.Count > 0) { ExecuteSpoRestRequestModules(request, headers, ref requestUrl, ref requestBody); } if (request.Method == HttpMethod.Get) { sb.AppendLine($"--batch_{batch.Id}"); sb.AppendLine("Content-Type: application/http"); sb.AppendLine("Content-Transfer-Encoding:binary"); sb.AppendLine(); sb.AppendLine($"{HttpMethod.Get.Method} {requestUrl} HTTP/1.1"); foreach (var header in headers) { sb.AppendLine($"{header.Key}: {header.Value}"); } sb.AppendLine(); } else if (request.Method == new HttpMethod("PATCH") || request.Method == HttpMethod.Post) { var changesetId = Guid.NewGuid().ToString("d", CultureInfo.InvariantCulture); sb.AppendLine($"--batch_{batch.Id}"); sb.AppendLine($"Content-Type: multipart/mixed; boundary=\"changeset_{changesetId}\""); sb.AppendLine(); sb.AppendLine($"--changeset_{changesetId}"); sb.AppendLine("Content-Type: application/http"); sb.AppendLine("Content-Transfer-Encoding:binary"); sb.AppendLine(); sb.AppendLine($"{request.Method.Method} {requestUrl} HTTP/1.1"); foreach (var header in headers) { sb.AppendLine($"{header.Key}: {header.Value}"); } if (!string.IsNullOrEmpty(requestBody)) { sb.AppendLine($"Content-Length: {requestBody.Length}"); } else { sb.AppendLine($"Content-Length: 0"); } sb.AppendLine($"If-Match: *"); // TODO: Here we need the E-Tag or something to specify to use * sb.AppendLine(); sb.AppendLine(requestBody); sb.AppendLine(); sb.AppendLine($"--changeset_{changesetId}--"); } else if (request.Method == HttpMethod.Delete) { var changesetId = Guid.NewGuid().ToString("d", CultureInfo.InvariantCulture); sb.AppendLine($"--batch_{batch.Id}"); sb.AppendLine($"Content-Type: multipart/mixed; boundary=\"changeset_{changesetId}\""); sb.AppendLine(); sb.AppendLine($"--changeset_{changesetId}"); sb.AppendLine("Content-Type: application/http"); sb.AppendLine("Content-Transfer-Encoding:binary"); sb.AppendLine(); sb.AppendLine($"{request.Method} {requestUrl} HTTP/1.1"); foreach (var header in headers) { sb.AppendLine($"{header.Key}: {header.Value}"); } sb.AppendLine($"IF-MATCH: *"); // TODO: Here we need the E-Tag or something to specify to use * sb.AppendLine(); sb.AppendLine($"--changeset_{changesetId}--"); } #if DEBUG if (PnPContext.Mode != TestMode.Default) { batchKey.Append($"{request.Method}|{request.ApiCall.Request}@@"); } #endif telemetryManager?.LogServiceRequest(request, PnPContext); } // Batch closing sb.AppendLine($"--batch_{batch.Id}--"); return new Tuple<string, string>(sb.ToString(), batchKey.ToString()); } /// <summary> /// Provides initial processing of a response for a SharePoint REST batch request /// </summary> /// <param name="restBatch">The batch request to process</param> /// <param name="batchResponse">The raw content of the response</param> /// <param name="headers">Batch request response headers</param> /// <returns></returns> private async Task ProcessSharePointRestBatchResponse(SPORestBatch restBatch, string batchResponse, Dictionary<string, string> headers) { using (var tracer = Tracer.Track(PnPContext.Logger, "ExecuteSharePointRestBatchAsync-JSONToModel")) { // Process the batch response, assign each response to it's request ProcessSharePointRestBatchResponseContent(restBatch.Batch, batchResponse, headers); // Map the retrieved JSON to our domain model foreach (var batchRequest in restBatch.Batch.Requests.Values) { if (!string.IsNullOrEmpty(batchRequest.ResponseJson)) { // A raw request does not require loading of the response into the model if (!batchRequest.ApiCall.RawRequest) { await JsonMappingHelper.MapJsonToModel(batchRequest).ConfigureAwait(false); } // Invoke a delegate (if defined) to trigger processing of raw batch requests batchRequest.ApiCall.RawResultsHandler?.Invoke(batchRequest.ResponseJson, batchRequest.ApiCall); } } } } /// <summary> /// Process the received batch response and connect the responses to the original requests in this batch /// </summary> /// <param name="batch">Batch that we're processing</param> /// <param name="batchResponse">Batch response received from the server</param> /// <param name="responseHeadersToPropagate">Batch request response headers</param> private static void ProcessSharePointRestBatchResponseContent(Batch batch, string batchResponse, Dictionary<string, string> responseHeadersToPropagate) { #if !NET5_0_OR_GREATER var responseLines = batchResponse.Split(new char[] { '\n' }); #endif int counter = -1; var httpStatusCode = HttpStatusCode.Continue; bool responseContentOpen = false; bool collectHeaders = false; Dictionary<string, string> responseHeaders = new Dictionary<string, string>(responseHeadersToPropagate); StringBuilder responseContent = new StringBuilder(); #if NET5_0_OR_GREATER foreach (ReadOnlySpan<char> line in batchResponse.SplitLines()) #else foreach (var line in responseLines) #endif { // Signals the start/end of a response // --batchresponse_6ed85e4b-869f-428e-90c9-19038f964718 if (line.StartsWith("--batchresponse_")) { // Reponse was closed, let's store the result if (responseContentOpen) { // responses are in the same order as the request, so use a counter based system BatchRequest currentBatchRequest = batch.GetRequest(counter); if (!HttpRequestSucceeded(httpStatusCode)) { if (batch.ThrowOnError) { throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, (int)httpStatusCode, responseContent.ToString(), responseHeaders); } else { // Store the batch error batch.AddBatchResult(currentBatchRequest, httpStatusCode, responseContent.ToString(), new SharePointRestError(ErrorType.SharePointRestServiceError, (int)httpStatusCode, responseContent.ToString(), responseHeaders)); } } else { string responseStringContent = null; if (httpStatusCode != HttpStatusCode.NoContent) { responseStringContent = responseContent.ToString(); } // Run request modules if they're connected if (currentBatchRequest.RequestModules != null && currentBatchRequest.RequestModules.Count > 0) { responseStringContent = ExecuteSpoRestRequestModulesOnResponse(httpStatusCode, responseHeaders, currentBatchRequest, responseStringContent); } if (httpStatusCode == HttpStatusCode.NoContent) { currentBatchRequest.AddResponse("", httpStatusCode, responseHeaders); } else { currentBatchRequest.AddResponse(responseStringContent, httpStatusCode, responseHeaders); } // Commit succesful updates in our model if (currentBatchRequest.Method == new HttpMethod("PATCH") || currentBatchRequest.ApiCall.Commit) { if (currentBatchRequest.Model is TransientObject) { currentBatchRequest.Model.Commit(); } } } httpStatusCode = 0; responseContentOpen = false; responseContent = new StringBuilder(); } collectHeaders = false; responseHeaders = new Dictionary<string, string>(responseHeadersToPropagate); counter++; } // Response status code else if (line.StartsWith("HTTP/1.1 ")) { // HTTP/1.1 200 OK #if NET5_0_OR_GREATER if (int.TryParse(line.Slice(9, 3), out int parsedHttpStatusCode)) #else if (int.TryParse(line.Substring(9, 3), out int parsedHttpStatusCode)) #endif { httpStatusCode = (HttpStatusCode)parsedHttpStatusCode; collectHeaders = true; } else { throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, 0, PnPCoreResources.Exception_SharePointRest_UnexpectedResult); } } // First real content returned, lines before are ignored else if ((line.StartsWith("{") || httpStatusCode == HttpStatusCode.NoContent) && !responseContentOpen) { // content can be seperated via \r\n and we split on \n. Since we're using AppendLine remove the carriage return to avoid duplication #if NET5_0_OR_GREATER responseContent.Append(line).AppendLine(); #else responseContent.AppendLine(line.TrimEnd('\r')); #endif responseContentOpen = true; } // More content is being returned, so let's append it else if (responseContentOpen) { // content can be seperated via \r\n and we split on \n. Since we're using AppendLine remove the carriage return to avoid duplication #if NET5_0_OR_GREATER responseContent.Append(line).AppendLine(); #else responseContent.AppendLine(line.TrimEnd('\r')); #endif } // Response headers e.g. CONTENT-TYPE: application/json;odata=verbose;charset=utf-8 else if (collectHeaders) { #if NET5_0_OR_GREATER HeaderSplit(line, responseHeaders); #else HeaderSplit(line.AsSpan(), responseHeaders); #endif } } } private static Dictionary<string, string> SpoRestResposeHeadersToPropagate(HttpResponseHeaders headers) { Dictionary<string, string> responseHeaders = new Dictionary<string, string>(); if (headers != null && headers.Any()) { if (headers.TryGetValues(PnPConstants.SPRequestGuidHeader, out IEnumerable<string> spRequestGuidHeader)) { responseHeaders.Add(PnPConstants.SPRequestGuidHeader, string.Join(",", spRequestGuidHeader)); } if (headers.TryGetValues(PnPConstants.SPClientServiceRequestDurationHeader, out IEnumerable<string> spClientServiceRequestDurationHeader)) { responseHeaders.Add(PnPConstants.SPClientServiceRequestDurationHeader, string.Join(",", spClientServiceRequestDurationHeader)); } if (headers.TryGetValues(PnPConstants.XSharePointHealthScoreHeader, out IEnumerable<string> xSharePointHealthScoreHeader)) { responseHeaders.Add(PnPConstants.XSharePointHealthScoreHeader, string.Join(",", xSharePointHealthScoreHeader)); } if (headers.TryGetValues(PnPConstants.XSPServerStateHeader, out IEnumerable<string> xSPServerStateHeader)) { responseHeaders.Add(PnPConstants.XSPServerStateHeader, string.Join(",", xSPServerStateHeader)); } } return responseHeaders; } private static void ExecuteSpoRestRequestModules(BatchRequest request, Dictionary<string, string> headers, ref string requestUrl, ref string requestBody) { foreach (var module in request.RequestModules.Where(p => p.ExecuteForSpoRest)) { if (module.RequestHeaderHandler != null) { module.RequestHeaderHandler.Invoke(headers); } if (module.RequestUrlHandler != null) { requestUrl = module.RequestUrlHandler.Invoke(requestUrl); } if (module.RequestBodyHandler != null) { requestBody = module.RequestBodyHandler.Invoke(requestBody); } } } private static string ExecuteSpoRestRequestModulesOnResponse(HttpStatusCode httpStatusCode, Dictionary<string, string> responseHeaders, BatchRequest currentBatchRequest, string responseStringContent) { foreach (var module in currentBatchRequest.RequestModules.Where(p => p.ExecuteForSpoRest)) { if (module.ResponseHandler != null) { responseStringContent = module.ResponseHandler.Invoke(httpStatusCode, responseHeaders, responseStringContent); } } return responseStringContent; } private static void HeaderSplit(ReadOnlySpan<char> input, Dictionary<string, string> headers) { if (!input.IsNullOrEmpty()) { var left = input.LeftPart(':'); var right = input.RightPart(':'); if (!left.IsNullOrEmpty() && !right.IsNullOrEmpty()) { if (!headers.ContainsKey(left.Trim().ToString())) { headers.Add(left.Trim().ToString(), right.Trim().ToString()); } } } } #endregion #region SharePoint REST interactive calls private async Task ExecuteSharePointRestInteractiveAsync(Batch batch) { var restRequest = batch.Requests.First().Value; StringContent content = null; ByteArrayContent binaryContent = null; try { string requestUrl = restRequest.ApiCall.Request; string requestBody = restRequest.ApiCall.JsonBody; Dictionary<string, string> headers = new Dictionary<string, string>(); if (restRequest.ApiCall.Headers != null && restRequest.ApiCall.Headers.Count > 0) { foreach (var key in restRequest.ApiCall.Headers.Keys) { string existingKey = headers.Keys.FirstOrDefault(k => k.Equals(key, StringComparison.InvariantCultureIgnoreCase)); if (string.IsNullOrWhiteSpace(existingKey)) { headers.Add(key, restRequest.ApiCall.Headers[key]); } else { headers[existingKey] = restRequest.ApiCall.Headers[key]; } } } // Run request modules if they're connected if (restRequest.RequestModules != null && restRequest.RequestModules.Count > 0) { ExecuteSpoRestRequestModules(restRequest, headers, ref requestUrl, ref requestBody); } using (var request = new HttpRequestMessage(restRequest.Method, requestUrl)) { PnPContext.Logger.LogDebug($"{restRequest.Method} {restRequest.ApiCall.Request}"); if (!string.IsNullOrEmpty(requestBody)) { content = new StringContent(requestBody, Encoding.UTF8, "application/json"); request.Content = content; // Remove the default Content-Type content header if (content.Headers.Contains("Content-Type")) { content.Headers.Remove("Content-Type"); } // Add the batch Content-Type header content.Headers.Add($"Content-Type", $"application/json;odata=verbose"); PnPContext.Logger.LogDebug(requestBody); } else if (restRequest.ApiCall.BinaryBody != null) { binaryContent = new ByteArrayContent(restRequest.ApiCall.BinaryBody); request.Content = binaryContent; } if (restRequest.ApiCall.ExpectBinaryResponse) { // Add the batch binarystringresponsebody header request.Headers.Add($"binarystringresponsebody", "true"); } if (request.Method == HttpMethod.Delete || request.Method == HttpMethod.Post || request.Method == new HttpMethod("PATCH")) { request.Headers.Add("If-Match", "*"); } // Add extra headers foreach (var extraHeader in headers) { if (extraHeader.Key == "Content-Type") { // Remove the default Content-Type content header if (request.Content.Headers.Contains("Content-Type")) { request.Content.Headers.Remove("Content-Type"); } request.Content.Headers.Add(extraHeader.Key, extraHeader.Value); } else { if (!request.Headers.Contains(extraHeader.Key)) { request.Headers.Add(extraHeader.Key, extraHeader.Value); } else { request.Headers.Remove(extraHeader.Key); request.Headers.Add(extraHeader.Key, extraHeader.Value); } } } telemetryManager?.LogServiceRequest(restRequest, PnPContext); #if DEBUG string batchKey = null; if (PnPContext.Mode != TestMode.Default) { batchKey = $"{testUseCounter}@@{request.Method}|{restRequest.ApiCall.Request}@@"; testUseCounter++; } // Test recording if (PnPContext.Mode == TestMode.Record && PnPContext.GenerateTestMockingDebugFiles) { // Write request TestManager.RecordRequest(PnPContext, batchKey, $"{restRequest.Method}-{restRequest.ApiCall.Request}-{(restRequest.ApiCall.JsonBody ?? "")}"); } // If we are not mocking or if there is no mock data if (PnPContext.Mode != TestMode.Mock) { #endif // Ensure the request contains authentication information Uri site; if (requestUrl.IndexOf("/_api/", 0) > -1) { site = new Uri(requestUrl.Substring(0, restRequest.ApiCall.Request.IndexOf("/_api/", 0))); } else { // We need this as we use _layouts/15/download.aspx to download files site = new Uri(requestUrl.Substring(0, restRequest.ApiCall.Request.IndexOf("/_layouts/", 0))); } // Do we need a streaming download? HttpCompletionOption httpCompletionOption = HttpCompletionOption.ResponseContentRead; if (restRequest.ApiCall.StreamResponse) { httpCompletionOption = HttpCompletionOption.ResponseHeadersRead; } // Process the authentication headers using the currently // configured instance of IAuthenticationProvider await ProcessSharePointRestAuthentication(site, request).ConfigureAwait(false); // Send the request HttpResponseMessage response = await PnPContext.RestClient.Client.SendAsync(request, httpCompletionOption).ConfigureAwait(false); // Process the request response if (response.IsSuccessStatusCode) { // Get the response string Stream requestResponseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record && !restRequest.ApiCall.StreamResponse) { // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { string responseStringContent = null; if (response.StatusCode == HttpStatusCode.NoContent) { responseStringContent = ""; } else { using (var streamReader = new StreamReader(requestResponseStream)) { string requestResponse = await streamReader.ReadToEndAsync().ConfigureAwait(false); responseStringContent = requestResponse; } } var mockedRewrittenFileString = MockingFileRewriteHandler(responseStringContent); requestResponseStream = mockedRewrittenFileString.AsStream(); } // Write response TestManager.RecordResponse(PnPContext, batchKey, ref requestResponseStream, response.IsSuccessStatusCode, (int)response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers)); } #endif await ProcessSharePointRestInteractiveResponse(restRequest, response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers), requestResponseStream).ConfigureAwait(false); } else { string errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Write response TestManager.RecordResponse(PnPContext, batchKey, errorContent, response.IsSuccessStatusCode, (int)response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers)); } #endif // Something went wrong... throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, (int)response.StatusCode, errorContent, SpoRestResposeHeadersToPropagate(response.Headers)); } #if DEBUG } else { var testResponse = TestManager.MockResponse(PnPContext, batchKey); if (!testResponse.IsSuccessStatusCode) { throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, testResponse.StatusCode, testResponse.Response, testResponse.Headers); } await ProcessSharePointRestInteractiveResponse(restRequest, (HttpStatusCode)testResponse.StatusCode, testResponse.Headers, testResponse.Response.AsStream()).ConfigureAwait(false); } #endif // Mark batch as executed batch.Executed = true; } } finally { if (content != null) { content.Dispose(); } if (binaryContent != null) { binaryContent.Dispose(); } } } private static async Task ProcessSharePointRestInteractiveResponse(BatchRequest restRequest, HttpStatusCode statusCode, Dictionary<string, string> responseHeaders, Stream responseContent) { // If a binary response content is expected if (restRequest.ApiCall.ExpectBinaryResponse) { // Add it to the request and stop processing the response restRequest.AddResponse(responseContent, statusCode); return; } string responseStringContent = null; if (statusCode == HttpStatusCode.NoContent) { responseStringContent = ""; } else { using (var streamReader = new StreamReader(responseContent)) { responseContent.Seek(0, SeekOrigin.Begin); string requestResponse = await streamReader.ReadToEndAsync().ConfigureAwait(false); responseStringContent = requestResponse; } } // Run request modules if they're connected if (restRequest.RequestModules != null && restRequest.RequestModules.Count > 0) { responseStringContent = ExecuteSpoRestRequestModulesOnResponse(statusCode, responseHeaders, restRequest, responseStringContent); } // Store the response for further processing restRequest.AddResponse(responseStringContent, statusCode, responseHeaders); // Commit succesful updates in our model if (restRequest.Method == new HttpMethod("PATCH") || restRequest.ApiCall.Commit) { if (restRequest.Model is TransientObject) { restRequest.Model.Commit(); } } // Update our model by processing the "delete" if (restRequest.Method == HttpMethod.Delete) { if (restRequest.Model is TransientObject) { restRequest.Model.RemoveFromParentCollection(); } } if (!string.IsNullOrEmpty(restRequest.ResponseJson)) { // A raw request does not require loading of the response into the model if (!restRequest.ApiCall.RawRequest) { await JsonMappingHelper.MapJsonToModel(restRequest).ConfigureAwait(false); } } } private async Task ProcessSharePointRestAuthentication(Uri site, HttpRequestMessage request) { // If the AuthenticationProvider is a legacy one var legacyAuthenticationProvider = PnPContext.AuthenticationProvider as ILegacyAuthenticationProvider; if (legacyAuthenticationProvider != null && legacyAuthenticationProvider.RequiresCookieAuthentication) { // Let's set the cookie header for legacy authentication request.Headers.Add("Cookie", legacyAuthenticationProvider.GetCookieHeader(site)); if (request.Method != HttpMethod.Get) { request.Headers.Add("X-RequestDigest", legacyAuthenticationProvider.GetRequestDigest()); } } else { // Ensure the request contains authentication information await PnPContext.AuthenticationProvider.AuthenticateRequestAsync(site, request).ConfigureAwait(false); } } #endregion #region CSOM batching /// <summary> /// Execute a batch with CSOM requests. /// See https://docs.microsoft.com/en-us/openspecs/sharepoint_protocols/ms-csom/fd645da2-fa28-4daa-b3cd-8f4e506df117 for the CSOM protocol specs /// </summary> /// <param name="batch">Batch to execute</param> /// <returns></returns> private async Task ExecuteCsomBatchAsync(Batch batch) { // Due to previous splitting we can see empty batches... if (!batch.Requests.Any(p => p.Value.ExecutionNeeded)) { return; } // A batch can only combine requests for the same web, if needed we need to split the incoming batch in batches per web var csomBatches = CsomBatchSplitting(batch); // Execute the batches foreach (var csomBatchBeforeSplit in csomBatches) { // A batch can contain more than the maximum number of items in a Csom batch, so if needed breakup a batch in multiple batches var splitCsomBatches = CsomBatchSplittingBySize(csomBatchBeforeSplit); foreach (var csomBatch in splitCsomBatches) { // Each csom batch only contains one request CSOMApiCallBuilder csomAPICallBuilder = new CSOMApiCallBuilder(); string requestBody = ""; foreach (var csomAPICall in csomBatch.Batch.Requests.Values) { foreach (IRequest<object> request in csomAPICall.ApiCall.CSOMRequests) { csomAPICallBuilder.AddRequest(request); } telemetryManager?.LogServiceRequest(csomAPICall, PnPContext); } requestBody = csomAPICallBuilder.SerializeCSOMRequests(); #if DEBUG string requestKey = ""; if (PnPContext.Mode != TestMode.Default) { requestKey = $"{testUseCounter}@@GET|dummy"; testUseCounter++; } #endif PnPContext.Logger.LogDebug(requestBody); // Make the batch call using (StringContent content = new StringContent(requestBody)) { using (var request = new HttpRequestMessage(HttpMethod.Post, $"{csomBatch.Site.ToString().TrimEnd(new char[] { '/' })}/_vti_bin/client.svc/ProcessQuery")) { // Remove the default Content-Type content header if (content.Headers.Contains("Content-Type")) { content.Headers.Remove("Content-Type"); } // Add the batch Content-Type header content.Headers.Add($"Content-Type", $"text/xml"); // Connect content to request request.Content = content; #if DEBUG // Test recording if (PnPContext.Mode == TestMode.Record && PnPContext.GenerateTestMockingDebugFiles) { // Write request TestManager.RecordRequest(PnPContext, requestKey, content.ReadAsStringAsync().Result); } // If we are not mocking or if there is no mock data if (PnPContext.Mode != TestMode.Mock) { #endif // Process the authentication headers using the currently // configured instance of IAuthenticationProvider await ProcessSharePointRestAuthentication(csomBatch.Site, request).ConfigureAwait(false); // Send the request HttpResponseMessage response = await PnPContext.RestClient.Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); try { // Process the request response if (response.IsSuccessStatusCode) { // Get the response string, using HttpCompletionOption.ResponseHeadersRead and ReadAsStreamAsync to lower the memory // pressure when processing larger responses + performance is better using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { using (StreamReader reader = new StreamReader(streamToReadFrom)) { string batchResponse = await reader.ReadToEndAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Call out to the rewrite handler if that one is connected if (MockingFileRewriteHandler != null) { batchResponse = MockingFileRewriteHandler(batchResponse); } // Write response TestManager.RecordResponse(PnPContext, requestKey, batchResponse, response.IsSuccessStatusCode, (int)response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers)); } #endif ProcessCsomBatchResponse(csomBatch, batchResponse, response.StatusCode); } } } else { string errorContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); #if DEBUG if (PnPContext.Mode == TestMode.Record) { // Write response TestManager.RecordResponse(PnPContext, requestKey, errorContent, response.IsSuccessStatusCode, (int)response.StatusCode, SpoRestResposeHeadersToPropagate(response?.Headers)); } #endif // Something went wrong... throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, (int)response.StatusCode, errorContent, SpoRestResposeHeadersToPropagate(response.Headers)); } } finally { response.Dispose(); } #if DEBUG } else { var testResponse = TestManager.MockResponse(PnPContext, requestKey); if (!testResponse.IsSuccessStatusCode) { throw new SharePointRestServiceException(ErrorType.SharePointRestServiceError, testResponse.StatusCode, testResponse.Response, testResponse.Headers); } ProcessCsomBatchResponse(csomBatch, testResponse.Response, (HttpStatusCode)testResponse.StatusCode); } #endif // Mark batch as executed csomBatch.Batch.Executed = true; // Copy the results collection to the upper batch csomBatchBeforeSplit.Batch.Results.AddRange(csomBatch.Batch.Results); } } } // Copy the results collection to the upper batch batch.Results.AddRange(csomBatchBeforeSplit.Batch.Results); } // Mark the original (non split) batch as complete batch.Executed = true; } /// <summary> /// Provides initial processing of a response for a Csom batch request /// </summary> /// <param name="csomBatch">The batch request to process</param> /// <param name="batchResponse">The raw content of the response</param> /// <param name="statusCode">The Http status code of the request</param> /// <returns></returns> private void ProcessCsomBatchResponse(CsomBatch csomBatch, string batchResponse, HttpStatusCode statusCode) { using (var tracer = Tracer.Track(PnPContext.Logger, "ExecuteCsomBatchAsync-JSONToModel")) { if (!string.IsNullOrEmpty(batchResponse)) { var responses = CsomHelper.ParseResponse(batchResponse); // The first response contains possible error status info var firstElement = responses[0]; if (!firstElement.Equals(default)) { var errorInfo = firstElement.GetProperty("ErrorInfo"); if (errorInfo.ValueKind != JsonValueKind.Null) { if (csomBatch.Batch.ThrowOnError) { // Oops, something went wrong throw new CsomServiceException(ErrorType.CsomServiceError, (int)statusCode, firstElement); } else { // Link the returned error to all the requests foreach (var request in csomBatch.Batch.Requests) { csomBatch.Batch.AddBatchResult(request.Value, statusCode, firstElement.ToString(), new CsomError(ErrorType.CsomServiceError, (int)statusCode, firstElement)); } } } } // No error, so let's return the results foreach (var request in csomBatch.Batch.Requests) { // Call the logic that processes the csom response request.Value.ApiCall.CSOMRequests[0].ProcessResponse(batchResponse); // Commit succesful updates in our model if (request.Value.ApiCall.Commit) { if (request.Value.Model is TransientObject) { request.Value.Model.Commit(); } } // Execute post mapping handler (even though, there is no actual mapping in this case) request.Value.PostMappingJson?.Invoke(batchResponse); } } } } private static List<CsomBatch> CsomBatchSplitting(Batch batch) { List<CsomBatch> batches = new List<CsomBatch>(); foreach (var request in batch.Requests.OrderBy(p => p.Value.Order)) { // Each request is a single batch Uri site = new Uri(request.Value.ApiCall.Request); var csomBatch = batches.FirstOrDefault(b => b.Site == site); if (csomBatch == null) { // Create a new batch csomBatch = new CsomBatch(site) { Batch = new Batch() { ThrowOnError = batch.ThrowOnError } }; batches.Add(csomBatch); } // Add request to existing batch, we're adding the original request which ensures that once // we update the new batch with results these results are also part of the original batch csomBatch.Batch.Requests.Add(request.Value.Order, request.Value); } return batches; } private static List<CsomBatch> CsomBatchSplittingBySize(CsomBatch batch) { List<CsomBatch> batches = new List<CsomBatch>(); // No need to split if (batch.Batch.Requests.Count < MaxRequestsInCsomBatch) { batches.Add(batch); return batches; } // Split in multiple batches int counter = 0; int order = 0; CsomBatch currentBatch = new CsomBatch(batch.Site) { Batch = new Batch() { ThrowOnError = batch.Batch.ThrowOnError } }; foreach (var request in batch.Batch.Requests.OrderBy(p => p.Value.Order)) { currentBatch.Batch.Requests.Add(order, request.Value); order++; counter++; if (counter % MaxRequestsInCsomBatch == 0) { order = 0; batches.Add(currentBatch); currentBatch = new CsomBatch(batch.Site) { Batch = new Batch() { ThrowOnError = batch.Batch.ThrowOnError } }; } } // Add the last part if (currentBatch.Batch.Requests.Count > 0) { batches.Add(currentBatch); } return batches; } #endregion /// <summary> /// Checks if a batch contains an API call that still has unresolved tokens...no point in sending the request at that point /// </summary> /// <param name="batch"></param> private static void CheckForUnresolvedTokens(Batch batch) { foreach (var request in batch.Requests) { var unresolvedTokens = TokenHandler.UnresolvedTokens(request.Value.ApiCall.Request); if (unresolvedTokens.Count > 0) { throw new ClientException(ErrorType.UnresolvedTokens, string.Format(PnPCoreResources.Exception_UnresolvedTokens, request.Value.ApiCall.Request)); } } } /// <summary> /// Splits a batch that contains rest, graph, graph beta or csom calls in four batches, each containing the respective calls /// </summary> /// <param name="input">Batch to split</param> /// <param name="graphAlwaysUsesBeta">Indicates if all Microsoft Graph use the Graph beta endpoint</param> /// <returns>A rest batch and graph batch</returns> private static Tuple<Batch, Batch, Batch, Batch> SplitIntoBatchesPerApiType(Batch input, bool graphAlwaysUsesBeta) { Batch restBatch = new Batch() { ThrowOnError = input.ThrowOnError }; Batch graphBatch = new Batch() { ThrowOnError = input.ThrowOnError }; Batch graphBetaBatch = new Batch() { ThrowOnError = input.ThrowOnError }; Batch csomBatch = new Batch() { ThrowOnError = input.ThrowOnError }; foreach (var request in input.Requests.Where(p => p.Value.ExecutionNeeded)) { var br = request.Value; if (br.ApiCall.Type == ApiType.SPORest) { restBatch.Add(br.Model, br.EntityInfo, br.Method, br.ApiCall, br.BackupApiCall, br.FromJsonCasting, br.PostMappingJson, br.OperationName, br.RequestModules); } else if (br.ApiCall.Type == ApiType.Graph) { if (graphAlwaysUsesBeta) { graphBetaBatch.Add(br.Model, br.EntityInfo, br.Method, br.ApiCall, br.BackupApiCall, br.FromJsonCasting, br.PostMappingJson, br.OperationName, br.RequestModules); } else { graphBatch.Add(br.Model, br.EntityInfo, br.Method, br.ApiCall, br.BackupApiCall, br.FromJsonCasting, br.PostMappingJson, br.OperationName, br.RequestModules); } } else if (br.ApiCall.Type == ApiType.GraphBeta) { graphBetaBatch.Add(br.Model, br.EntityInfo, br.Method, br.ApiCall, br.BackupApiCall, br.FromJsonCasting, br.PostMappingJson, br.OperationName, br.RequestModules); } else if (br.ApiCall.Type == ApiType.CSOM) { csomBatch.Add(br.Model, br.EntityInfo, br.Method, br.ApiCall, br.BackupApiCall, br.FromJsonCasting, br.PostMappingJson, br.OperationName, br.RequestModules); } } return new Tuple<Batch, Batch, Batch, Batch>(restBatch, graphBatch, graphBetaBatch, csomBatch); } /// <summary> /// Executing a batch might have resulted in a mismatch between the model and the data in SharePoint: /// Getting entities can result in duplicate entities (e.g. 2 lists when getting the same list twice in a single batch while using a different query) /// Adding entities can result in an entity in the model that does not have the proper key value set (as that value is only retrievable after the add in SharePoint) /// Deleting entities can result in an entity in the model that also should have been deleted /// </summary> /// <param name="batch">Batch to process</param> private static void MergeBatchResultsWithModel(Batch batch) { bool useGraphBatch = batch.UseGraphBatch; // Consolidate GET requests List<BatchResultMerge> getConsolidation = new List<BatchResultMerge>(); // Step 1: group the requests that have values with the same id (=keyfield) value foreach (var request in batch.Requests.Values.Where(p => p.Method == HttpMethod.Get)) { // ExecuteRequest requests are never impacting the domain model if (request.ApiCall.ExecuteRequestApiCall) { continue; } EntityFieldInfo keyField = useGraphBatch ? request.EntityInfo.GraphKeyField : request.EntityInfo.SharePointKeyField; // Consolidation can only happen when there's a keyfield set in the model if (keyField != null && request.Model.HasValue(keyField.Name)) { // Get the value of the model's keyfield property, since we always ask to load the keyfield property this should work var keyFieldValue = GetDynamicProperty(request.Model, keyField.Name); if (keyFieldValue != null) { var modelType = request.Model.GetType(); var consolidation = getConsolidation.FirstOrDefault(p => p.ModelType == modelType && p.KeyValue.Equals(keyFieldValue) && !p.Model.Equals(request.Model)); if (consolidation == null) { consolidation = new BatchResultMerge() { Model = request.Model, KeyValue = keyFieldValue, ModelType = modelType, }; getConsolidation.Add(consolidation); } consolidation.Requests.Add(request); } } } // Step 2: consolidate when we have multiple requests for the same key field foreach (var consolidation in getConsolidation.Where(p => p.Requests.Count(p => p.ApiCall.RawRequest == false) > 1)) { var firstRequest = consolidation.Requests.OrderBy(p => p.Order).First(); bool first = true; foreach (var request in consolidation.Requests.OrderBy(p => p.Order)) { if (!first) { // Merge properties/collections firstRequest.Model.Merge(request.Model); // Mark deleted objects as deleted and remove from their respective parent collection request.Model.RemoveFromParentCollection(); } else { first = false; } } } // Mark deleted objects as deleted and remove from their respective parent collection foreach (var request in batch.Requests.Values.Where(p => p.Method == HttpMethod.Delete || p.ApiCall.RemoveFromModel)) { // ExecuteRequest requests are never impacting the domain model if (request.ApiCall.ExecuteRequestApiCall) { continue; } request.Model.RemoveFromParentCollection(); } } private static bool HttpRequestSucceeded(HttpStatusCode httpStatusCode) { // See https://restfulapi.net/http-status-codes/ // For now let's fail all except the 200 range return (httpStatusCode >= HttpStatusCode.OK && httpStatusCode < HttpStatusCode.Ambiguous); } /// <summary> /// Remove processed batches to avoid unneeded memory consumption /// </summary> private void RemoveProcessedBatches() { // Retrieve the executed batches var keysToRemove = (from b in batches where b.Value.Executed select b.Key).ToList(); // And remove them from the current collection foreach (var key in keysToRemove) { batches.TryRemove(key, out Batch _); } } private static object GetDynamicProperty(object model, string propertyName) { var pnpObjectType = model.GetType(); var propertyToGet = pnpObjectType.GetProperty(propertyName); return propertyToGet.GetValue(model); } } }
46.01452
228
0.488067
[ "MIT" ]
joselu1sc/pnpcore
src/sdk/PnP.Core/Services/Core/BatchClient.cs
120,422
C#
using System; using System.Collections.Generic; using System.Text; namespace Mozilla.UniversalCharacterDetection.Prober.Sequence { public class Win1251Model : CyrillicModel { public Win1251Model() : base(win1251CharToOrderMap, Constants.CHARSET_WINDOWS_1251) { } private static short[] win1251CharToOrderMap = new short[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, //40 155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, //50 253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, //60 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, //70 191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, 207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, 223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238, 239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253, 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35, 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43, 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15, 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16, }; } }
47.857143
91
0.574925
[ "MIT" ]
XavierCai1996/L4D2ModManager
SourceCode/L4D2ModManager/Fork/UniversalCharacterDetection/Prober/Sequence/Win1251Model.cs
1,677
C#
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace silica { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// GetSystemApi operations. /// </summary> public partial interface IGetSystemApi { /// <summary> /// API Heartbeat Monitoring /// </summary> /// <remarks> /// Endpoint used for Heartbeat Monitoring. Monitoring will use this /// endpoint to check if the API is up and available. /// </remarks> /// <param name='aPIKey'> /// Client API Key /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> PingApiWithHttpMessagesAsync(string aPIKey, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
36.295455
202
0.611146
[ "MIT" ]
APEEYEDOTCOM/hapi-bells
public/sdks/csharp/IGetSystemApi.cs
1,597
C#