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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace Schema.NET { using System; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// A radio channel that uses FM. /// </summary> [DataContract] public partial class FMRadioChannel : RadioChannel { /// <summary> /// Gets the name of the type as specified by schema.org. /// </summary> [DataMember(Name = "@type", Order = 1)] public override string Type => "FMRadioChannel"; } }
24.4
65
0.594262
[ "MIT" ]
radetskyi/Schema.NET
Source/Schema.NET/core/FMRadioChannel.cs
488
C#
using System.Text.Json.Serialization; namespace Essensoft.Paylink.Alipay.Domain { /// <summary> /// ParamInfo Data Structure. /// </summary> public class ParamInfo : AlipayObject { /// <summary> /// 参数名 /// </summary> [JsonPropertyName("key")] public string Key { get; set; } /// <summary> /// 参数值 /// </summary> [JsonPropertyName("value")] public string Value { get; set; } } }
21.130435
41
0.524691
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Domain/ParamInfo.cs
500
C#
using GB28181.App; using System.Collections.Generic; namespace GB28181.Config { public interface ISipStorage { void Read(); void Save(SIPAccount account); List<SIPAccount> Accounts { get; } //Get Local Default SipDomain Info SIPAccount GetLocalSipAccout(); } }
16
42
0.640625
[ "MIT" ]
GB28181/GB28181.Platform2016
GB28181.SIPSorcery/Config/IStorageConfig.cs
322
C#
using AutoMapper; using starbase_nexus_api.Entities.InGame; using starbase_nexus_api.Models.InGame.MaterialCategory; namespace starbase_nexus_api.Profiles.InGame { public class MaterialCategoryProfile : Profile { public MaterialCategoryProfile() { CreateMap<MaterialCategory, ViewMaterialCategory>(); CreateMap<CreateMaterialCategory, MaterialCategory>(); CreateMap<PatchMaterialCategory, MaterialCategory>().ReverseMap(); } } }
30.529412
79
0.697495
[ "MIT" ]
WildChild85/starbase-nexus-api
starbase-nexus-api/Profiles/InGame/MaterialCategoryProfile.cs
521
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-04-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for CreateImage operation /// </summary> public class CreateImageResponseUnmarshaller : EC2ResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { CreateImageResponse response = new CreateImageResponse(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth = 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("imageId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ImageId = unmarshaller.Unmarshall(context); continue; } } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); return new AmazonEC2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static CreateImageResponseUnmarshaller _instance = new CreateImageResponseUnmarshaller(); internal static CreateImageResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateImageResponseUnmarshaller Instance { get { return _instance; } } } }
34.891089
158
0.633087
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/CreateImageResponseUnmarshaller.cs
3,524
C#
static internal class VoidType { public static readonly VARP.Scheme.Data.VoidType Void = new VARP.Scheme.Data.VoidType(); }
31.75
92
0.771654
[ "MIT" ]
hww/VARP
Assets/Varp/Scheme/Data/VoidType.cs
127
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PasswordItBackend.Systems { public static class DataScrambler { //Charcter collections for scrambling use //When processing char values as numbers, all values have to be >1 private const string AllowedChars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!?@#$%^&*()-_+=/,.:;<>~`"; private static Dictionary<char, int> CharTable; private const char FormattedDataSeperator = ':'; static DataScrambler() { //Build the dictionary CharTable = new(); for(int i = 0; i < AllowedChars.Length; i++) { CharTable.Add(AllowedChars[i], i + 2); } } // - - - Validating and Confirming - - - public static bool CharAllowed(char c) => AllowedChars.Contains(c); public static bool StringAllowed(string s) { foreach(char c in s) { if (!CharAllowed(c)) { return false; } } return true; } public static string CutUnallowedChars(string s) { string allStr = string.Empty; foreach (char c in s) { if (CharAllowed(c)) { allStr += c; } } return allStr; } // - - - Scrambling and unscrambling data - - - TODO: This probably should throw exceptions, not just return nulls public static string? ScrambleOnKey(string data, string key) { if(data == null || data.Length < 1 || key == null || key.Length < 1) { Console.WriteLine("Data provided to scrambler is empty."); return null; } else if(!StringAllowed(key) || !StringAllowed(data)) { Console.WriteLine("The provided data contains illegal characters"); return null; } //Convert key into an array of values based on the table int[] dataValues = new int[data.Length]; int[] keyValues = new int[key.Length]; for (int i = 0; i < key.Length; i++) { keyValues[i] = CharTable[key[i]]; } //Build data array by scrambling the key values with int keyIndex = 0; for (int i = 0; i < data.Length; i++) { if(keyIndex >= keyValues.Length) { keyIndex = 0; } dataValues[i] = CharTable[data[i]] * keyValues[keyIndex]; keyIndex++; } //Data should be scrambled, so use array to build a formatted string string output = ":"; foreach(var num in dataValues) { output += $"{num}{FormattedDataSeperator}"; } return output; } public static string? UnscrambleOnKey(string data, string key) { if (data == null || data.Length < 1 || key == null || key.Length < 1) { Console.WriteLine("Data provided to scrambler is empty."); return null; } //Convert key into an array of values based on the table int[] keyValues = new int[key.Length]; for (int i = 0; i < key.Length; i++) { keyValues[i] = CharTable[key[i]]; } //Seperate scrambled data into values string[] dataSplit = data.Split(FormattedDataSeperator, StringSplitOptions.RemoveEmptyEntries); //Parse split data into values int[] dataValues = new int[dataSplit.Length]; for(int i = 0; i < dataSplit.Length; i++) { dataValues[i] = int.Parse(dataSplit[i]); } //Decode each letter and add to output string string output = ""; int keyIndex = 0; for(int i = 0; i < dataValues.Length; i++) { if(keyIndex >= keyValues.Length) { keyIndex = 0; } //Make sure this index will be inside the bounds of the string int charIndex = (dataValues[i] / keyValues[keyIndex]) - 2; if (charIndex >= AllowedChars.Length || charIndex < 0) { output += " "; } else { output += AllowedChars[charIndex]; } keyIndex++; } //Return result return output; } public static string GenerateScrambledMasterKey(string userKey) { string? scrambledMasterKey = ScrambleOnKey(ScramblerMaster, userKey); if(scrambledMasterKey == null) { throw new ArgumentNullException("scrambledMasterKey", "The data scramble and unscramble methods are not set up right and should throw exceptions rather than returning nulls"); } return scrambledMasterKey; } public static bool ConfirmKeyAttempt(string keyAttm, string scrMasterKey) { string? scrambledMasterKeyAttm = ScrambleOnKey(ScramblerMaster, keyAttm); if (scrambledMasterKeyAttm == null) { throw new ArgumentNullException("scrambledMasterKey", "The data scramble and unscramble methods are not set up right and should throw exceptions rather than returning nulls"); } return scrMasterKey.Equals(scrambledMasterKeyAttm); } //Scramblers Key Allows us to validate user login by checking if their scrambled master key matches when scrambled with an attempted password //This should not be changed at any time during writing after: 1/3/22 private const string ScramblerMaster = "pEh&gw9=saDF2Y$BxTmc-J@?V!y6AgM41-lb8UAPjKB84n&Gi8&*d6nt!1Buhgt5XQlRgnJMSR49uTV^if?sbLS^zC&=rW0MOi$DCxZNNNoV6S12f7a&Q0-0xWw&kNs%9EAx&vn%KPvqkKmNbSLX0Xx&zPgQx3-S-=VGwt_%QKqrInRnl2J%Kg6e?2*ayMq$l@&1cY@lsYZ&So5hNKPdwd*$STN66Dx^opWf&-%%IQ9-m2ykd=1GxXsiCyFkD"; } }
44.255474
303
0.565727
[ "MIT" ]
ElephantInTheRom/PasswordIt
PasswordItBackend/Systems/DataScrambler.cs
6,065
C#
using BrockAllen.MembershipReboot.Hierarchical; using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Controllers { [Authorize] public class ChangeEmailController : Controller { UserAccountService<HierarchicalUserAccount> userAccountService; AuthenticationService<HierarchicalUserAccount> authSvc; public ChangeEmailController(AuthenticationService<HierarchicalUserAccount> authSvc) { this.userAccountService = authSvc.UserAccountService; this.authSvc = authSvc; } public ActionResult Index() { return View("Index"); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Index(ChangeEmailRequestInputModel model) { if (ModelState.IsValid) { try { this.userAccountService.ChangeEmailRequest(User.GetUserID(), model.NewEmail); if (userAccountService.Configuration.RequireAccountVerification) { return View("ChangeRequestSuccess", (object)model.NewEmail); } else { return View("Success"); } } catch (ValidationException ex) { ModelState.AddModelError("", ex.Message); } } return View("Index", model); } [AllowAnonymous] public ActionResult Confirm(string id) { var account = this.userAccountService.GetByVerificationKey(id); if (account.HasPassword()) { var vm = new ChangeEmailFromKeyInputModel(); vm.Key = id; return View("Confirm", vm); } else { try { userAccountService.VerifyEmailFromKey(id, out account); // since we've changed the email, we need to re-issue the cookie that // contains the claims. authSvc.SignIn(account); return RedirectToAction("Success"); } catch (ValidationException ex) { ModelState.AddModelError("", ex.Message); } return View("Confirm", null); } } [AllowAnonymous] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Confirm(ChangeEmailFromKeyInputModel model) { if (ModelState.IsValid) { try { HierarchicalUserAccount account; this.userAccountService.VerifyEmailFromKey(model.Key, model.Password, out account); // since we've changed the email, we need to re-issue the cookie that // contains the claims. authSvc.SignIn(account); return RedirectToAction("Success"); } catch (ValidationException ex) { ModelState.AddModelError("", ex.Message); } } return View("Confirm", model); } public ActionResult Success() { return View(); } } }
32.375
103
0.507722
[ "BSD-3-Clause" ]
SoftwareStudio/BrockAllen.MembershipReboot
samples/NoSql/SingleTenantWebApp/Areas/UserAccount/Controllers/ChangeEmailController.cs
3,628
C#
// --------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // // The MIT License (MIT) // // 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 AnnotatedAudio.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.Serialization.Json; using System.Threading.Tasks; using Windows.Storage.Streams; using Windows.UI; using Windows.UI.Core; using Windows.UI.Input.Inking; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; namespace AnnotatedAudio.ViewModel { public class SessionViewModel : BindableBase { public ObservableCollection<SessionPage> Pages { get; } = new ObservableCollection<SessionPage>(); public Func<string, Task<string>> StringInput { get; set; } public SessionPickerViewModel SessionPicker { get; set; } public InkCanvas Canvas { get; set; } public InkToolbar CanvasToolbar { get; set; } private InkStrokeContainer _container = new InkStrokeContainer(); private ObservableCollection<InkEvent> _events = new ObservableCollection<InkEvent>(); private Dictionary<int, InkStroke> _strokes = new Dictionary<int, InkStroke>(); public AudioPlaybackManager PlaybackManager { get => _playbackManager; set => SetProperty(ref _playbackManager, value); } private AudioPlaybackManager _playbackManager; public AudioRecordingManager RecordingManager { get => _recordingManager; set { if (SetProperty(ref _recordingManager, value)) { Record.RaiseCanExecuteChanged(); Stop.RaiseCanExecuteChanged(); } } } private AudioRecordingManager _recordingManager; public SolidColorBrush RecordingButtonForeground { get => RecordingManager != null && RecordingManager.IsRecording ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Black); } public object CurrentPage { get => _currentPage; set { if (SetProperty(ref _currentPage, value)) { DeletePage.RaiseCanExecuteChanged(); } } } private object _currentPage; public DelegateCommand PageSelected { get { return _pageSelected ?? (_pageSelected = new DelegateCommand( async () => { await RefreshInkAsync(); })); } } private DelegateCommand _pageSelected; public DelegateCommand AddPage { get { return _addPage ?? (_addPage = new DelegateCommand( async () => { var input = await this.StringInput("Please name your new session."); if (input != null && input != "") { SessionPage page = new SessionPage(); page.PageName = input; page.PageId = Pages.Count; Pages.Add(page); CurrentPage = page; await PageSelected.Execute(); } })); } } private DelegateCommand _addPage; public DelegateCommand DeletePage { get { return _deletePage ?? (_deletePage = new DelegateCommand( async () => { // If there's only one page, don't delete it. if (Pages.Count > 1) { var target = (SessionPage)CurrentPage; int targetIndex = Pages.IndexOf(target); Pages.Remove(target); // Calculate the new selected index. int newIndex = Math.Max(Math.Min(targetIndex, Pages.Count - 1), 0); // Attempt to set the SelectedSession. try { CurrentPage = Pages[newIndex]; await PageSelected.Execute(); } catch (ArgumentOutOfRangeException) { ; // Do nothing, because the list is empty. } } }, () => CurrentPage != null)); } } private DelegateCommand _deletePage; public DelegateCommand Record { get { return _record ?? (_record = new DelegateCommand( async () => { if (!RecordingManager.IsRecording) { await RecordingManager.Record(); Record.RaiseCanExecuteChanged(); Stop.RaiseCanExecuteChanged(); UpdateInkingMode(); OnPropertyChanged(nameof(RecordingButtonForeground)); } }, () => RecordingManager != null && !RecordingManager.IsRecording)); } } private DelegateCommand _record; public DelegateCommand Stop { get { return _stop ?? (_stop = new DelegateCommand( async () => { if (RecordingManager.IsRecording) { await RecordingManager.Stop(); await SessionPicker.SaveSessionList(); Record.RaiseCanExecuteChanged(); Stop.RaiseCanExecuteChanged(); UpdateInkingMode(); OnPropertyChanged(nameof(RecordingButtonForeground)); // Re-load the audio and cues for playback, because a new track was recorded. await PlaybackManager.LoadAudio(); PlaybackManager.LoadAudioCues(_events.Where(f => f.GetType() == (new InkEvent()).GetType()).Select(f => f as InkEvent).ToList()); // Compress session and upload to OneDrive. await SessionPicker.SelectedSession.CompressSession(false); await SessionPicker.OneDriveManager.UploadFile( await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync($"{SessionPicker.SelectedSession.Id.ToString()}.zip"), null); } }, () => RecordingManager != null && RecordingManager.IsRecording)); } } private DelegateCommand _stop; private void UpdateInkingMode() { if (!RecordingManager.IsRecording) { Canvas.InkPresenter.InputProcessingConfiguration.Mode = InkInputProcessingMode.None; CanvasToolbar.ActiveTool = null; CanvasToolbar.IsEnabled = false; } else { Canvas.InkPresenter.InputProcessingConfiguration.Mode = InkInputProcessingMode.Inking; CanvasToolbar.IsEnabled = true; CanvasToolbar.ActiveTool = CanvasToolbar.GetToolButton(InkToolbarTool.BallpointPen); } } public async Task Setup(SessionPickerViewModel SessionPicker, MediaPlayerElement media, InkCanvas ink, InkToolbar inkSettings) { this.SessionPicker = SessionPicker; Canvas = ink; CanvasToolbar = inkSettings; // Load pages and attach an event handler. await LoadPagesAsync(); Pages.CollectionChanged += async (s, e) => await SaveList<SessionPage>(Pages, "PageMeta.json"); // Create a new "Introduction" page if the list is empty. if (Pages.Count <= 0) { Pages.Add(new SessionPage() { PageId = 0, PageName = "Introduction" }); } CurrentPage = Pages.FirstOrDefault(); // Load ink strokes and attach an event handler. await LoadInkAsync(); _events.CollectionChanged += async (s, e) => await SaveList<InkEvent>(_events, "InkMeta.json"); // Load Audio manager. RecordingManager = await AudioRecordingManager.CreateAsync(); RecordingManager.CurrentSession = SessionPicker.SelectedSession; PlaybackManager = new AudioPlaybackManager(media); PlaybackManager.CurrentSession = SessionPicker.SelectedSession; // Load playback manager with existing audio. await PlaybackManager.LoadAudio(); PlaybackManager.PlaybackPositionChanged += async (s, ev) => { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => SetStrokeHighlighting(ev.Time, PlaybackManager.CurrentTrack)); }; // Load audio cues and the event handler. PlaybackManager.LoadAudioCues(_events.Where(f => f.GetType() == (new InkEvent()).GetType()).Select(f => f as InkEvent).ToList()); PlaybackManager.PlaybackCueTriggered += SetPlaybackToStrokeTime; // Attach event handler for when an ink stroke is tapped in review mode. Canvas.InkPresenter.UnprocessedInput.PointerPressed += SelectInkStroke; ; // Attach event handler for dynamically saving strokes added Canvas.InkPresenter.StrokesCollected += CollectInkStroke; // Write mode must be toggled after load to ensure that writing is not enabled before recording has been activated. UpdateInkingMode(); } private async void SetPlaybackToStrokeTime(object sender, PlaybackCueTriggeredEventArgs ev) { await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { // Get the last stroke that was made in the current track between playback poisition and 00:00:00. var lastStroke = _events.Where(e => e.SegmentId == ev.Segment && e.TimeHappened <= ev.Time) .OrderBy(e => e.TimeHappened) .LastOrDefault(); // Automatically switch pages, if the ink event above triggered in a different page. if (CurrentPage != null & ((SessionPage)CurrentPage).PageId != lastStroke.PageId) { CurrentPage = Pages.Where(p => p.PageId == lastStroke.PageId).FirstOrDefault(); await PageSelected.Execute(); } else SetStrokeHighlighting(ev.Time, ev.Segment); }); } private void SelectInkStroke(InkUnprocessedInput ink, PointerEventArgs e) { var start = e.CurrentPoint.Position; start.X -= 7; start.Y -= 7; var end = e.CurrentPoint.Position; end.X += 7; end.Y += 7; ink.InkPresenter.StrokeContainer.SelectWithLine(start, end); var stroke = ink.InkPresenter.StrokeContainer.GetStrokes().Where(str => str.Selected).FirstOrDefault(); // If a stroke wasn't found within 7 pixels of a click, try within 14 instead. if (stroke == null) { start.X += 14; end.X -= 14; ink.InkPresenter.StrokeContainer.SelectWithLine(start, end); stroke = ink.InkPresenter.StrokeContainer.GetStrokes().Where(str => str.Selected).FirstOrDefault(); } // If a stroke was found within 7 or 14 pixels, set the selected stroke and start playing audio from the point the stroke was made. if (stroke != null) { stroke.Selected = false; var evt = _events.Where(i => i.GetType() == typeof(InkEvent) && ((InkEvent)i).Id == stroke.CustomHashCode()).FirstOrDefault(); PlaybackManager.Play(evt.TimeHappened, (uint)evt.SegmentId); SetStrokeHighlighting(evt.TimeHappened, evt.SegmentId); } } private async void CollectInkStroke(object sender, InkStrokesCollectedEventArgs e) { InkEvent inkEvent = new InkEvent(); var stroke = e.Strokes.First().Clone(); _container.Clear(); _container.AddStroke(stroke); System.Diagnostics.Debug.WriteLine(Windows.Storage.ApplicationData.Current.LocalFolder.Path); // Save async -- save as timestamp.gif // Prevent updates to the file until updates are // finalized with call to CompleteUpdatesAsync. string fileName = $"stroke{_events.Count}.gif"; // Create sample file; replace if exists. Windows.Storage.StorageFile file = await(await SessionPicker.SelectedSession.GetFolder()).CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); Windows.Storage.CachedFileManager.DeferUpdates(file); // Open a file stream for writing. using (IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite)) { // Write the ink strokes to the output stream. using (IOutputStream outputStream = stream.GetOutputStreamAt(0)) { await _container.SaveAsync(outputStream); await outputStream.FlushAsync(); } } // Finalize write so other apps can update file. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { inkEvent.TimeHappened = RecordingManager.CurrentTrackRecordingTime; inkEvent.FileName = file.Name; inkEvent.Id = stroke.CustomHashCode(); inkEvent.SegmentId = RecordingManager.CurrentlyRecordingTrackNumber; inkEvent.PageId = ((SessionPage)CurrentPage).PageId; inkEvent.LogMessage("inking", "Successfully saved an inking file."); } else { inkEvent.LogMessage("inking", "Unsuccessfully saved an inking file."); } _events.Add(inkEvent); } private void SetStrokeHighlighting(TimeSpan pivotTime, int pivotTrack) { var strokesToUpdate = Canvas.InkPresenter.StrokeContainer.GetStrokes(); foreach (InkStroke update in strokesToUpdate) { foreach (var i in _events) { if (i.GetType() == (new InkEvent()).GetType()) { if (update.CustomHashCode() == (i as InkEvent).Id) { InkDrawingAttributes updateAttr = update.DrawingAttributes; int diff = TimeSpan.Compare(i.TimeHappened, pivotTime); if (pivotTrack > i.SegmentId) { updateAttr.Color = Windows.UI.Colors.CornflowerBlue; update.DrawingAttributes = updateAttr; } else if ((diff > 0) | (i.SegmentId > pivotTrack)) { updateAttr.Color = Windows.UI.Colors.Black; update.DrawingAttributes = updateAttr; } else { updateAttr.Color = Windows.UI.Colors.CornflowerBlue; update.DrawingAttributes = updateAttr; } } } } } } private async Task LoadPagesAsync() { try { var folder = await SessionPicker.SelectedSession.GetFolder(); Windows.Storage.StorageFile sampleFile = await folder.GetFileAsync($"PageMeta.json"); var buffer = (await Windows.Storage.FileIO.ReadBufferAsync(sampleFile)).ToArray(); using (var stream = new MemoryStream(buffer)) { SessionPage[] pages = new SessionPage[0]; pages = (SessionPage[])new DataContractJsonSerializer(pages.GetType()).ReadObject(stream); pages.ToList<SessionPage>().ForEach(p => Pages.Add(p)); } } catch (Exception) { } } private async Task RefreshInkAsync() { Canvas.InkPresenter.StrokeContainer.Clear(); _strokes.Clear(); foreach (var i in _events.Where(e => CurrentPage != null && e.PageId == ((SessionPage)CurrentPage).PageId)) { var folder = await SessionPicker.SelectedSession.GetFolder(); // If the event is an ink event, we need to load it. if (i.GetType() == (new InkEvent()).GetType()) { Windows.Storage.StorageFile file = await folder.GetFileAsync($"{(i as InkEvent).FileName}"); using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { using (var inputStream = stream.GetInputStreamAt(0)) { await _container.LoadAsync(inputStream); var stroke = _container.GetStrokes().First().Clone(); Canvas.InkPresenter.StrokeContainer.AddStroke(stroke); _strokes.Add(stroke.CustomHashCode(), stroke); } } } } SetStrokeHighlighting(PlaybackManager.PlaybackPosition, PlaybackManager.CurrentTrack); } private async Task LoadInkAsync() { try { var folder = await SessionPicker.SelectedSession.GetFolder(); Windows.Storage.StorageFile sampleFile = await folder.GetFileAsync($"InkMeta.json"); var buffer = (await Windows.Storage.FileIO.ReadBufferAsync(sampleFile)).ToArray(); using (var stream = new MemoryStream(buffer)) { InkEvent[] events = new InkEvent[0]; events = (InkEvent[])new DataContractJsonSerializer(events.GetType()).ReadObject(stream); _events = new ObservableCollection<InkEvent>(events); } await RefreshInkAsync(); } catch (Exception) { return; } } private async Task SaveList<T>(ObservableCollection<T> list, string fileName) { byte[] arr; using (var datastream = new MemoryStream()) { var settings = new DataContractJsonSerializerSettings(); settings.UseSimpleDictionaryFormat = true; new DataContractJsonSerializer(list.GetType(), settings).WriteObject(datastream, list); arr = datastream.ToArray(); } var folder = await SessionPicker.SelectedSession.GetFolder(); // Create sample file; replace if exists. var file = await folder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting); Windows.Storage.CachedFileManager.DeferUpdates(file); await Windows.Storage.FileIO.WriteBytesAsync(file, arr); // Finalize write so other apps can update file. var status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { arr.LogMessage("inking", "Successfully saved to the inking metadata"); } else { arr.LogMessage("inking", "Unsuccessfully saved to the inking metadata"); } } } }
40.783002
164
0.538554
[ "MIT" ]
Bhaskers-Blu-Org2/Windows-appsample-annotated-audio
AnnotatedAudio/ViewModel/SessionViewModel.cs
22,555
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KaziArac : Arac { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
14.947368
52
0.609155
[ "MIT" ]
BurakErenCatal/space-miners
project19/Assets/scripts/Arac/KaziArac.cs
286
C#
using System.Linq; using Jint.Native; using Jint.Native.Object; using Jint.Runtime.Descriptors; namespace Jint.Runtime.Environments { /// <summary> /// Represents an object environment record /// http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.1.2 /// </summary> public sealed class ObjectEnvironmentRecord : EnvironmentRecord { private readonly Engine _engine; private readonly ObjectInstance _bindingObject; private readonly bool _provideThis; public ObjectEnvironmentRecord(Engine engine, ObjectInstance bindingObject, bool provideThis) : base(engine) { _engine = engine; _bindingObject = bindingObject; _provideThis = provideThis; } public override bool HasBinding(string name) { return _bindingObject.HasProperty(name); } /// <summary> /// http://www.ecma-international.org/ecma-262/5.1/#sec-10.2.1.2.2 /// </summary> /// <param name="name"></param> /// <param name="configurable"></param> public override void CreateMutableBinding(string name, bool configurable = true) { _bindingObject.DefineOwnProperty(name, new PropertyDescriptor(Undefined.Instance, true, true, configurable), true); } public override void SetMutableBinding(string name, JsValue value, bool strict) { _bindingObject.Put(name, value, strict); } public override JsValue GetBindingValue(string name, bool strict) { // todo: can be optimized if (!_bindingObject.HasProperty(name)) { if(!strict) { return Undefined.Instance; } throw new JavaScriptException(_engine.ReferenceError); } return _bindingObject.Get(name); } public override bool DeleteBinding(string name) { return _bindingObject.Delete(name, false); } public override JsValue ImplicitThisValue() { if (_provideThis) { return new JsValue(_bindingObject); } return Undefined.Instance; } public override string[] GetAllBindingNames() { if (_bindingObject != null) { return _bindingObject.GetOwnProperties().Select( x=> x.Key).ToArray(); } return new string[0]; } } }
29.113636
127
0.576893
[ "Apache-2.0" ]
CSWCSS-InnoTech/Schobol
InnoTecheLearning/InnoTecheLearning/InnoTecheLearning.Droid/Jint/Runtime/Environments/ObjectEnvironmentRecord.cs
2,564
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 QuantConnect.Interfaces; using QuantConnect.Packets; namespace QuantConnect.Data { /// <summary> /// Represents the set of parameters for the <see cref="IHistoryProvider.Initialize"/> method /// </summary> public class HistoryProviderInitializeParameters { /// <summary> /// The job /// </summary> public AlgorithmNodePacket Job { get; } /// <summary> /// The provider used to get data when it is not present on disk /// </summary> public IDataProvider DataProvider { get; } /// <summary> /// The provider used to cache history data files /// </summary> public IDataCacheProvider DataCacheProvider { get; } /// <summary> /// The provider used to get a map file resolver to handle equity mapping /// </summary> public IMapFileProvider MapFileProvider { get; } /// <summary> /// The provider used to get factor files to handle equity price scaling /// </summary> public IFactorFileProvider FactorFileProvider { get; } /// <summary> /// A function used to send status updates /// </summary> public Action<int> StatusUpdateAction { get; } /// <summary> /// Initializes a new instance of the <see cref="HistoryProviderInitializeParameters"/> class from the specified parameters /// </summary> /// <param name="job">The job</param> /// <param name="dataProvider">Provider used to get data when it is not present on disk</param> /// <param name="dataCacheProvider">Provider used to cache history data files</param> /// <param name="mapFileProvider">Provider used to get a map file resolver to handle equity mapping</param> /// <param name="factorFileProvider">Provider used to get factor files to handle equity price scaling</param> /// <param name="statusUpdateAction">Function used to send status updates</param> public HistoryProviderInitializeParameters( AlgorithmNodePacket job, IDataProvider dataProvider, IDataCacheProvider dataCacheProvider, IMapFileProvider mapFileProvider, IFactorFileProvider factorFileProvider, Action<int> statusUpdateAction) { Job = job; DataProvider = dataProvider; DataCacheProvider = dataCacheProvider; MapFileProvider = mapFileProvider; FactorFileProvider = factorFileProvider; StatusUpdateAction = statusUpdateAction; } } }
40.277108
131
0.658989
[ "Apache-2.0" ]
szywi/Lean
Common/Data/HistoryProviderInitializeParameters.cs
3,345
C#
using System; using LibHac.Common; using LibHac.Diag; using static LibHac.Fs.StringTraits; namespace LibHac.Fs.Common { public ref struct DirectoryPathParser { private Span<byte> _buffer; private byte _replacedChar; private int _position; // Todo: Make private so we can use the GetCurrentPath method once lifetime tracking is better public Path CurrentPath; public void Dispose() { CurrentPath.Dispose(); } public Result Initialize(ref Path path) { Span<byte> pathBuffer = path.GetWriteBufferLength() != 0 ? path.GetWriteBuffer() : Span<byte>.Empty; int windowsSkipLength = WindowsPath.GetWindowsSkipLength(pathBuffer); _buffer = pathBuffer.Slice(windowsSkipLength); if (windowsSkipLength != 0) { Result rc = CurrentPath.InitializeWithNormalization(pathBuffer, windowsSkipLength + 1); if (rc.IsFailure()) return rc; _buffer = _buffer.Slice(1); } else { Span<byte> initialPath = ReadNextImpl(); if (!initialPath.IsEmpty) { Result rc = CurrentPath.InitializeWithNormalization(initialPath); if (rc.IsFailure()) return rc; } } return Result.Success; } // Todo: Return reference when escape semantics are better public readonly Path GetCurrentPath() { return CurrentPath; } public Result ReadNext(out bool isFinished) { isFinished = false; Span<byte> nextEntry = ReadNextImpl(); if (nextEntry.IsEmpty) { isFinished = true; return Result.Success; } return CurrentPath.AppendChild(nextEntry); } private Span<byte> ReadNextImpl() { // Check if we've already hit the end of the path. if (_position < 0 || _buffer.At(0) == 0) return Span<byte>.Empty; // Restore the character we previously replaced with a null terminator. if (_replacedChar != 0) { _buffer[_position] = _replacedChar; if (_replacedChar == DirectorySeparator) _position++; } // If the path is rooted, the first entry should be the root directory. if (_position == 0 && _buffer.At(0) == DirectorySeparator) { _replacedChar = _buffer[1]; _buffer[1] = 0; _position = 1; return _buffer; } // Find the end of the next entry, replacing the directory separator with a null terminator. Span<byte> entry = _buffer.Slice(_position); int i; for (i = _position; _buffer.At(i) != DirectorySeparator; i++) { if (_buffer.At(i) == 0) { if (i == _position) entry = Span<byte>.Empty; _position = -1; return entry; } } Assert.SdkAssert(_buffer.At(i + 1) != NullTerminator); _replacedChar = DirectorySeparator; _buffer[i] = 0; _position = i; return entry; } } }
30.316667
113
0.495327
[ "BSD-3-Clause" ]
Thealexbarney/LibHac
src/LibHac/Fs/Common/DirectoryPathParser.cs
3,640
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Markup; namespace ExpandTreeViewSilverlight { /// <summary> /// ViewModel for the Taxonomy data source and its derived classes. /// This ViewModel adds the notion of node selection and expansion. /// </summary> [ContentProperty("Subclasses")] public abstract class TaxonomyViewModel : INotifyPropertyChanged { /// <summary> /// Constructs a new TaxonomyViewModel from the given Taxonomy. /// </summary> /// <param name="taxonomy">The original Taxonomy object to wrap.</param> protected TaxonomyViewModel(Taxonomy taxonomy) { Taxonomy = taxonomy; subclasses = new TaxonomyViewModelCollection(taxonomy.Subclasses); } /// <summary> /// Original Taxonomy object being wrapped. /// </summary> public Taxonomy Taxonomy { get; private set; } /// <summary> /// Gets and sets the Classification of the original Taxonomy. /// </summary> public string Classification { get { return Taxonomy.Classification; } set { Taxonomy.Classification = value; OnPropertyChanged("Classification"); } } /// <summary> /// Gets the Rank of the original Taxonomy. /// </summary> public string Rank { get { return Taxonomy.Rank; } } /// <summary> /// The TaxonomyViewModelCollection ensures that any object added to it is also added /// to the original Taxonomy. /// </summary> private TaxonomyViewModelCollection subclasses; public Collection<TaxonomyViewModel> Subclasses { get { return subclasses; } } /// <summary> /// Determines whether the TreeViewItem associated with this data item /// is expanded. /// </summary> private bool isExpanded; public bool IsExpanded { get { return isExpanded; } set { isExpanded = value; OnPropertyChanged("IsExpanded"); } } /// <summary> /// Determines whether the TreeViewItem associated with this data item /// is selected. /// </summary> private bool isSelected; public bool IsSelected { get { return isSelected; } set { isSelected = value; OnPropertyChanged("IsSelected"); } } /// <summary> /// Event raised when a property changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Raises the PropertyChanged event. /// </summary> /// <param name="propertyName">The name of the property that has changed.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// This method traverses the entire view model hierarchy setting the IsExpanded /// property to true on each item. /// </summary> public void ExpandAll() { ApplyActionToAllItems(item => item.IsExpanded = true); } /// <summary> /// This method traverses the entire view model hierarchy setting the IsExpanded /// property to false on each item. /// </summary> public void CollapseAll() { // Here, I start collapsing items in the tree starting at the root. // It may seem that the tree needs to be collapsed starting at the leaf // nodes, but that's not the case because the entire tree will be updated // in one single layout pass. So in this case, the order in which items // are collapsed makes no difference. ApplyActionToAllItems(item => item.IsExpanded = false); } /// <summary> /// This helper method traverses the tree in a depth-first non-recursive way /// and executes the action passed as a parameter on each item. /// </summary> /// <param name="itemAction">Action to be executed for each item.</param> private void ApplyActionToAllItems(Action<TaxonomyViewModel> itemAction) { Stack<TaxonomyViewModel> dataItemStack = new Stack<TaxonomyViewModel>(); dataItemStack.Push(this); while (dataItemStack.Count != 0) { TaxonomyViewModel currentItem = dataItemStack.Pop(); itemAction(currentItem); foreach (TaxonomyViewModel childItem in currentItem.Subclasses) { dataItemStack.Push(childItem); } } } /// <summary> /// This method sets IsExpanded to true for each element in the ancestor chain of the item /// passed as a parameter. /// </summary> /// <param name="itemToLookFor">The element this method will look for.</param> /// <returns>True if it the itemToLookFor was found, false otherwise.</returns> public bool ExpandSuperclasses(TaxonomyViewModel itemToLookFor) { return ApplyActionToSuperclasses(itemToLookFor, superclass => superclass.IsExpanded = true); } /// <summary> /// This helper method uses recursion to look for the element passed as a parameter in the view model /// hierarchy and executes the action passed as a parameter to its entire ancestor chain (excluding /// the item itself). /// </summary> /// <param name="itemToLookFor">The element this method will look for.</param> /// <param name="itemAction">Action to be executed on each superclass in the ancestor chain.</param> /// <returns>True if it the itemToLookFor was found, false otherwise.</returns> private bool ApplyActionToSuperclasses(TaxonomyViewModel itemToLookFor, Action<TaxonomyViewModel> itemAction) { if (itemToLookFor == this) { return true; } else { foreach (TaxonomyViewModel subclass in this.Subclasses) { bool foundItem = subclass.ApplyActionToSuperclasses(itemToLookFor, itemAction); if (foundItem) { itemAction(this); return true; } } return false; } } /// <summary> /// A collection that keeps the original Taxonomy collection in sync with /// the view model collection. /// </summary> private class TaxonomyViewModelCollection : Collection<TaxonomyViewModel> { private Collection<Taxonomy> originalCollection; public TaxonomyViewModelCollection(Collection<Taxonomy> originalCollection) { this.originalCollection = originalCollection; } protected override void InsertItem(int index, TaxonomyViewModel item) { base.InsertItem(index, item); originalCollection.Insert(index, item.Taxonomy); } protected override void RemoveItem(int index) { base.RemoveItem(index); originalCollection.RemoveAt(index); } protected override void ClearItems() { base.ClearItems(); originalCollection.Clear(); } protected override void SetItem(int index, TaxonomyViewModel item) { base.SetItem(index, item); originalCollection[index] = item.Taxonomy; } } } /// <summary> /// Represents a Domain in a Linnaean taxonomy. /// </summary> public sealed class DomainViewModel : TaxonomyViewModel { public DomainViewModel() : base(new Domain()) { } } /// <summary> /// Represents a Kingdom in a Linnaean taxonomy. /// </summary> public sealed class KingdomViewModel : TaxonomyViewModel { public KingdomViewModel() : base(new Kingdom()) { } } /// <summary> /// Represents a Class in a Linnaean taxonomy. /// </summary> public sealed class ClassViewModel : TaxonomyViewModel { public ClassViewModel() : base(new Class()) { } } /// <summary> /// Represents a Family in a Linnaean taxonomy. /// </summary> public sealed class FamilyViewModel : TaxonomyViewModel { public FamilyViewModel() : base(new Family()) { } } /// <summary> /// Represents a Genus in a Linnaean taxonomy. /// </summary> public sealed class GenusViewModel : TaxonomyViewModel { public GenusViewModel() : base(new Genus()) { } } /// <summary> /// Represents an Order in a Linnaean taxonomy. /// </summary> public sealed class OrderViewModel : TaxonomyViewModel { public OrderViewModel() : base(new Order()) { } } /// <summary> /// Represents a Phylum in a Linnaean taxonomy. /// </summary> public sealed class PhylumViewModel : TaxonomyViewModel { public PhylumViewModel() : base(new Phylum()) { } } /// <summary> /// Represents a Species in a Linnaean taxonomy. /// </summary> public sealed class SpeciesViewModel : TaxonomyViewModel { public SpeciesViewModel() : base(new Species()) { } } }
32.242138
117
0.562274
[ "MIT" ]
bstollnitz/old-wpf-blog
48-ExpandTreeViewPart2/ExpandTreeViewSilverlight/ViewModel.cs
10,255
C#
using System.Diagnostics.Contracts; using System.Xml; using NUnit.Framework; using WordFind.Models.Trie; namespace WordFind.Tests.Models.Trie { [TestFixture] public class NodeTests { [Test] public void WhenAttachingANode_ReturnTheNode() { var root = new Node(); var newNode = root.Append('c'); Assert.That(newNode, Is.Not.Null); } [Test] public void WhenGettingAnExistingNode_ReturnTheNode() { var root = new Node(); var cNode = root.Append('c'); var actual = root.Get('c'); Assert.That(actual, Is.SameAs(cNode)); } [Test] public void WhenGettingANonexistingNode_ReturnNull() { var root = new Node(); var cNode = root.Get('c'); Assert.That(cNode, Is.Null); } } }
24.657895
62
0.52508
[ "MIT" ]
malevy/WordFind
WordFind.Tests/Models/Trie/NodeTests.cs
939
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.OutlookApi { #region Delegates #pragma warning disable #pragma warning restore #endregion /// <summary> /// CoClass ViewFont /// SupportByVersion Outlook, 12,14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff869120.aspx </remarks> [SupportByVersion("Outlook", 12,14,15,16)] [EntityType(EntityType.IsCoClass)] public class ViewFont : _ViewFont { #pragma warning disable #region Fields private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint; private string _activeSinkId; private static Type _type; #endregion #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } /// <summary> /// Type Cache /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ViewFont); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ViewFont(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ViewFont(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ViewFont(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ViewFont(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ViewFont(ICOMObject replacedObject) : base(replacedObject) { } /// <summary> /// Creates a new instance of ViewFont /// </summary> public ViewFont():base("Outlook.ViewFont") { } /// <summary> /// Creates a new instance of ViewFont /// </summary> ///<param name="progId">registered ProgID</param> public ViewFont(string progId):base(progId) { } #endregion #region Static CoClass Methods #endregion #region Events #endregion #pragma warning restore } }
28.138686
163
0.658885
[ "MIT" ]
DominikPalo/NetOffice
Source/Outlook/Classes/ViewFont.cs
3,857
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 Newtonsoft.Json; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Steeltoe.Management.Endpoint.Mappings { public class MappingDescription { private const string ALL_HTTP_METHODS = "GET || PUT || POST || DELETE || HEAD || OPTIONS"; public MappingDescription(string routeHandler, IRouteDetails routeDetails) { if (routeHandler == null) { throw new ArgumentNullException(nameof(routeHandler)); } if (routeDetails == null) { throw new ArgumentNullException(nameof(routeDetails)); } Predicate = CreatePredicateString(routeDetails); Handler = routeHandler; } public MappingDescription(MethodInfo routeHandler, IRouteDetails routeDetails) { if (routeHandler == null) { throw new ArgumentNullException(nameof(routeHandler)); } if (routeDetails == null) { throw new ArgumentNullException(nameof(routeDetails)); } Predicate = CreatePredicateString(routeDetails); Handler = CreateHandlerString(routeHandler); } [JsonProperty("handler")] public string Handler { get; } [JsonProperty("predicate")] public string Predicate { get; } [JsonProperty("details")] public object Details { get; } // Always null for .NET private string CreateHandlerString(MethodInfo actionHandlerMethod) { return actionHandlerMethod.ToString(); } private string CreatePredicateString(IRouteDetails routeDetails) { StringBuilder sb = new StringBuilder("{"); sb.Append("[" + routeDetails.RouteTemplate + "]"); sb.Append(",methods="); sb.Append("[" + CreateRouteMethods(routeDetails.HttpMethods) + "]"); if (!IsEmpty(routeDetails.Produces)) { sb.Append(",produces="); sb.Append("[" + string.Join(" || ", routeDetails.Produces) + "]"); } if (!IsEmpty(routeDetails.Consumes)) { sb.Append(",consumes="); sb.Append("[" + string.Join(" || ", routeDetails.Consumes) + "]"); } sb.Append("}"); return sb.ToString(); } private string CreateRouteMethods(IList<string> httpMethods) { if (IsEmpty(httpMethods)) { return ALL_HTTP_METHODS; } return string.Join(" || ", httpMethods); } private bool IsEmpty(IList<string> list) { if (list == null || list.Count == 0) { return true; } return false; } } }
29.831933
98
0.572676
[ "ECL-2.0", "Apache-2.0" ]
SteeltoeOSS/Management
src/Steeltoe.Management.EndpointBase/Mappings/MappingDescription.cs
3,552
C#
using System; using UnityEngine; public class AsteroidModel : BaseModel { public float speed; public GameObject explosion; public float tumble; public int baseScore = 10; protected int score; void Start() { Init(); InitializeMovement(); ChangeSize(); } void OnDestroy() { CalculateScore(); } void ChangeSize() { float scalar = UnityEngine.Random.Range(0.5f, 1.5f); transform.localScale += new Vector3(transform.localScale.x * scalar, transform.localScale.y * scalar, transform.localScale.z * scalar); rig.mass = rig.mass * scalar; speed = speed * (3.5f / scalar); } public void MakeSmallerThan(Rigidbody parentRigidbody) { transform.localScale = new Vector3( parentRigidbody.transform.localScale.x / 2.0f, parentRigidbody.transform.localScale.y / 2.0f, parentRigidbody.transform.localScale.z / 2.0f ); rig.mass = rig.mass / 2.0f; speed = speed * 2.0f; } void InitializeMovement() { rig.angularVelocity = UnityEngine.Random.insideUnitSphere * tumble; rig.velocity = (UnityEngine.Random.onUnitSphere * speed); // Clamp velocity to the Y Plane rig.velocity = new Vector3( rig.velocity.x, 0, rig.velocity.z ); } void FixedUpdate() { Rigidbody rigidBody = GetComponent<Rigidbody>(); Boundary.UpdateRigidbodyPosition(rigidBody); } public int CalculateScore() { return (int)(baseScore * rig.transform.localScale.magnitude * (rig.velocity.magnitude / 2.0f)); } public void SpawnReward() { // Spawn a reward on destroying this object } void OnTriggerEnter(Collider other) { if (other.name.Equals("AsteroidModel")) { // Asteroids can collide and not explode } else if (other.name.Equals("PlayerShipModel")) { PlayerDestruction(other); } else if (other.name.Equals("BoltModel")) { AsteroidDestruction(other); } } private void PlayerDestruction(Collider other) { Destroy(other.gameObject); Destroy(gameObject); Instantiate(explosion, transform.position, transform.rotation); other.GetComponent<PlayerShipModel>().Death(); } private void AsteroidDestruction(Collider other) { gameController.UpdateScore(CalculateScore()); Destroy(other.gameObject); Destroy(gameObject); Instantiate(explosion, transform.position, transform.rotation); // Last Asteroid destroyed if(GameObject.FindObjectsOfType<AsteroidModel>().Length == 1) { gameController.StartSpawnWave(); } } }
25.584071
143
0.598755
[ "Apache-2.0" ]
carneymo/wormhole
Assets/Scripts/Model/AsteroidModel.cs
2,893
C#
using System; using HmsPlugin.Button; using HmsPlugin.Extensions; using UnityEngine; namespace HmsPlugin.Window { public class ModalDialog : ModalWindow { private IDrawer _footer; private Action _onOk; private Action _onCancel; private const int MAX_BUTTON_SIZE = 80; public static ModalDialog CreateDialog(string title, Vector2 size, IDrawer contentDrawer, Action OnOk = null, Action onCancel = null) { var dialog = Create<ModalDialog>(title, size, contentDrawer); dialog.SetupTwoButtonFooter(size); if (OnOk != null) dialog.SetOkCallback(OnOk); if (onCancel != null) dialog.SetCancelCallback(onCancel); return dialog; } public static ModalDialog CreateOneButtonDialog(string title, Vector2 size, IDrawer contentDrawer, Action OnOk = null) { var dialog = Create<ModalDialog>(title, size, contentDrawer); dialog.SetupOneButtonFooter(); if (OnOk != null) dialog.SetOkCallback(OnOk); return dialog; } private void SetupOneButtonFooter() { _footer = new VerticalSequenceDrawer(new Space(10), new Button.Button("OK", Ok)); } private void SetupTwoButtonFooter(Vector2 size) { int buttonSize; int spaceSize; if (size.x < MAX_BUTTON_SIZE * 2) { buttonSize = (int)(size.x / 2); spaceSize = 0; } else { buttonSize = MAX_BUTTON_SIZE; spaceSize = (int)(size.x - MAX_BUTTON_SIZE * 2); } _footer = new HorizontalSequenceDrawer(new Button.Button("Cancel", Cancel).SetWidth(buttonSize), new Space(spaceSize), new Button.Button("OK", Ok).SetWidth(buttonSize)); } private ModalDialog() { } public void SetOkCallback(Action callback) { _onOk = callback; } public void SetCancelCallback(Action callback) { _onCancel = callback; } protected override void Draw(Rect region) { base.Draw(region); if (_footer != null) { _footer.Draw(); } } protected virtual void Cancel() { _onCancel.InvokeSafe(); Close(); } protected virtual void Ok() { _onOk.InvokeSafe(); Close(); } } }
27.157895
181
0.548062
[ "MIT" ]
DimitriUK/Junction-21-Huawei-Example
Assets/Huawei/Editor/General/UI/Window/ModalDialog.cs
2,582
C#
namespace MilitaryElite.Models.Soldiers.PrivateSoldier { using MilitaryElite.Models.Soldiers.Interfaces; public class Private : Soldier, IPrivate { public Private(int id, string firstName, string lastName, decimal salary) : base(id, firstName, lastName) { this.Salary = salary; } public decimal Salary { get; private set; } public override string ToString() { return $"Name: {this.FirstName} {this.LastName} Id: {this.Id} Salary: {this.Salary:F2}"; } } }
27.047619
100
0.607394
[ "MIT" ]
Statev7/SoftUni
C03_C#OOP-October-2021/06_Interfaces and Abstraction - Exercise/P07_MilitaryElite/Models/Soldiers/PrivateSoldiers/Private.cs
570
C#
namespace 河北干部网络学院挂机 { partial class Form1 { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.textBox_UserName = new System.Windows.Forms.TextBox(); this.textBox_Password = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.listBox_ClassList = new System.Windows.Forms.ListBox(); this.label3 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.rb_XueXiBan = new System.Windows.Forms.RadioButton(); this.rb_XuanXiu = new System.Windows.Forms.RadioButton(); this.rb_BiXiu = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label_StudySchedule = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.timer_StudyScheduleCheck = new System.Windows.Forms.Timer(this.components); this.timer_StydyHeartBeat = new System.Windows.Forms.Timer(this.components); this.label_Test = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // textBox_UserName // this.textBox_UserName.Location = new System.Drawing.Point(37, 17); this.textBox_UserName.Name = "textBox_UserName"; this.textBox_UserName.Size = new System.Drawing.Size(120, 21); this.textBox_UserName.TabIndex = 0; // // textBox_Password // this.textBox_Password.Location = new System.Drawing.Point(196, 17); this.textBox_Password.Name = "textBox_Password"; this.textBox_Password.Size = new System.Drawing.Size(49, 21); this.textBox_Password.TabIndex = 1; this.textBox_Password.Text = "888888"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(2, 23); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 12); this.label1.TabIndex = 2; this.label1.Text = "账号"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(161, 23); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(29, 12); this.label2.TabIndex = 2; this.label2.Text = "密码"; // // listBox_ClassList // this.listBox_ClassList.FormattingEnabled = true; this.listBox_ClassList.HorizontalScrollbar = true; this.listBox_ClassList.ItemHeight = 12; this.listBox_ClassList.Location = new System.Drawing.Point(19, 194); this.listBox_ClassList.Name = "listBox_ClassList"; this.listBox_ClassList.Size = new System.Drawing.Size(330, 244); this.listBox_ClassList.TabIndex = 4; this.listBox_ClassList.SelectedIndexChanged += new System.EventHandler(this.listBox_ClassList_SelectedIndexChanged); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(17, 179); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(53, 12); this.label3.TabIndex = 5; this.label3.Text = "课程列表"; // // button1 // this.button1.Location = new System.Drawing.Point(254, 16); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(72, 21); this.button1.TabIndex = 6; this.button1.Text = "登录"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.rb_XueXiBan); this.groupBox1.Controls.Add(this.rb_XuanXiu); this.groupBox1.Controls.Add(this.rb_BiXiu); this.groupBox1.Location = new System.Drawing.Point(19, 64); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(330, 45); this.groupBox1.TabIndex = 7; this.groupBox1.TabStop = false; this.groupBox1.Text = "课程类型"; // // rb_XueXiBan // this.rb_XueXiBan.AutoSize = true; this.rb_XueXiBan.Enabled = false; this.rb_XueXiBan.Location = new System.Drawing.Point(136, 18); this.rb_XueXiBan.Name = "rb_XueXiBan"; this.rb_XueXiBan.Size = new System.Drawing.Size(59, 16); this.rb_XueXiBan.TabIndex = 0; this.rb_XueXiBan.TabStop = true; this.rb_XueXiBan.Text = "学习班"; this.rb_XueXiBan.UseVisualStyleBackColor = true; // // rb_XuanXiu // this.rb_XuanXiu.AutoSize = true; this.rb_XuanXiu.Checked = true; this.rb_XuanXiu.Location = new System.Drawing.Point(71, 18); this.rb_XuanXiu.Name = "rb_XuanXiu"; this.rb_XuanXiu.Size = new System.Drawing.Size(59, 16); this.rb_XuanXiu.TabIndex = 0; this.rb_XuanXiu.TabStop = true; this.rb_XuanXiu.Text = "选修课"; this.rb_XuanXiu.UseVisualStyleBackColor = true; // // rb_BiXiu // this.rb_BiXiu.AutoSize = true; this.rb_BiXiu.Location = new System.Drawing.Point(6, 18); this.rb_BiXiu.Name = "rb_BiXiu"; this.rb_BiXiu.Size = new System.Drawing.Size(59, 16); this.rb_BiXiu.TabIndex = 0; this.rb_BiXiu.TabStop = true; this.rb_BiXiu.Text = "必修课"; this.rb_BiXiu.UseVisualStyleBackColor = true; // // groupBox2 // this.groupBox2.Controls.Add(this.label_StudySchedule); this.groupBox2.Location = new System.Drawing.Point(19, 117); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(330, 42); this.groupBox2.TabIndex = 8; this.groupBox2.TabStop = false; this.groupBox2.Text = "学习进度"; // // label_StudySchedule // this.label_StudySchedule.AutoSize = true; this.label_StudySchedule.Location = new System.Drawing.Point(6, 22); this.label_StudySchedule.Name = "label_StudySchedule"; this.label_StudySchedule.Size = new System.Drawing.Size(65, 12); this.label_StudySchedule.TabIndex = 0; this.label_StudySchedule.Text = "学习进度:"; // // groupBox3 // this.groupBox3.Controls.Add(this.textBox_UserName); this.groupBox3.Controls.Add(this.textBox_Password); this.groupBox3.Controls.Add(this.label1); this.groupBox3.Controls.Add(this.button1); this.groupBox3.Controls.Add(this.label2); this.groupBox3.Location = new System.Drawing.Point(19, 12); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(330, 45); this.groupBox3.TabIndex = 9; this.groupBox3.TabStop = false; this.groupBox3.Text = "账号"; // // timer_StudyScheduleCheck // this.timer_StudyScheduleCheck.Enabled = true; this.timer_StudyScheduleCheck.Interval = 60000; this.timer_StudyScheduleCheck.Tick += new System.EventHandler(this.timer_StudyScheduleCheck_Tick); // // timer_StydyHeartBeat // this.timer_StydyHeartBeat.Interval = 30000; this.timer_StydyHeartBeat.Tick += new System.EventHandler(this.timer_StydyHeartBeat_Tick); // // label_Test // this.label_Test.AutoSize = true; this.label_Test.Location = new System.Drawing.Point(182, 166); this.label_Test.Name = "label_Test"; this.label_Test.Size = new System.Drawing.Size(41, 12); this.label_Test.TabIndex = 10; this.label_Test.Text = "label4"; this.label_Test.Visible = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(370, 473); this.Controls.Add(this.label_Test); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.label3); this.Controls.Add(this.listBox_ClassList); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "Form1"; this.Text = "安比网络科技"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox_UserName; private System.Windows.Forms.TextBox textBox_Password; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.ListBox listBox_ClassList; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button button1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton rb_XueXiBan; private System.Windows.Forms.RadioButton rb_XuanXiu; private System.Windows.Forms.RadioButton rb_BiXiu; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label_StudySchedule; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Timer timer_StudyScheduleCheck; private System.Windows.Forms.Timer timer_StydyHeartBeat; private System.Windows.Forms.Label label_Test; } }
45.475655
138
0.571899
[ "MIT" ]
elceric/hebgb
Form1.Designer.cs
12,398
C#
using System; using System.Linq.Expressions; using System.Collections.Generic; namespace Restful.Linq { /// <summary> /// 定义用于创建和执行 IInsertable 对象所描述的插入的方法。 /// </summary> public interface IInsertProvider { /// <summary> /// 构造一个 IInsertable 对象,该对象可计算指定表达式树所表示的插入。 /// </summary> /// <returns>一个 IInsertable,它可计算指定表达式树所表示的插入。</returns> IInsertable CreateInsert( Type elementType ); /// <summary> /// 构造一个 IInsertable<T> 对象,该对象可计算指定表达式树所表示的插入。 /// </summary> /// <returns>一个 IInsertable<T>,它可计算指定表达式树所表示的插入。</returns> /// <typeparam name="T">需插入的元素类型</typeparam> IInsertable<T> CreateInsert<T>(); /// <summary> /// 执行删除操作。 /// </summary> /// <param name="elementType">元素类型</param> /// <param name="predicate">where 表达式树</param> int Execute( Type elementType, IDictionary<MemberExpression,object> properties ); /// <summary> /// 执行插入操作。 /// </summary> /// <param name="properties">插入时需设置的属性集合</param> int Execute<T>( IDictionary<MemberExpression,object> properties ); } }
29.4
89
0.594388
[ "Apache-2.0" ]
linli8/Restful
src/Restful/Restful.Linq/IInsertProvider.cs
1,486
C#
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org/?p=license&r=2.4 // **************************************************************** using System; namespace NUnit.Framework.Tests { public class MessageWriterTests : AssertionHelper { protected TextMessageWriter writer; [SetUp] public void SetUp() { writer = new TextMessageWriter(); } } [TestFixture] public class TestMessageWriterTests : MessageWriterTests { [Test] public void ConnectorIsWrittenWithSurroundingSpaces() { writer.WriteConnector("and"); Expect(writer.ToString(), EqualTo(" and ")); } [Test] public void PredicateIsWrittenWithTrailingSpace() { writer.WritePredicate("contains"); Expect(writer.ToString(), EqualTo("contains ")); } [TestFixture] public class ExpectedValueTests : ValueTests { protected override void WriteValue(object obj) { writer.WriteExpectedValue(obj); } } [TestFixture] public class ActualValueTests : ValueTests { protected override void WriteValue(object obj) { writer.WriteActualValue( obj ); } } public abstract class ValueTests : MessageWriterTests { protected abstract void WriteValue( object obj); [Test] public void IntegerIsWrittenAsIs() { WriteValue(42); Expect(writer.ToString(), EqualTo("42")); } [Test] public void StringIsWrittenWithQuotes() { WriteValue("Hello"); Expect(writer.ToString(), EqualTo("\"Hello\"")); } // This test currently fails because control character replacement is // done at a higher level... // TODO: See if we should do it at a lower level // [Test] // public void ControlCharactersInStringsAreEscaped() // { // WriteValue("Best Wishes,\r\n\tCharlie\r\n"); // Assert.That(writer.ToString(), Is.EqualTo("\"Best Wishes,\\r\\n\\tCharlie\\r\\n\"")); // } [Test] public void FloatIsWrittenWithTrailingF() { WriteValue(0.5f); Expect(writer.ToString(), EqualTo("0.5f")); } [Test] public void FloatIsWrittenToNineDigits() { WriteValue(0.33333333333333f); int digits = writer.ToString().Length - 3; // 0.dddddddddf Expect(digits, EqualTo(9)); Expect(writer.ToString().Length, EqualTo(12)); } [Test] public void DoubleIsWrittenWithTrailingD() { WriteValue(0.5d); Expect(writer.ToString(), EqualTo("0.5d")); } [Test] public void DoubleIsWrittenToSeventeenDigits() { WriteValue(0.33333333333333333333333333333333333333333333d); Expect(writer.ToString().Length, EqualTo(20)); // add 3 for leading 0, decimal and trailing d } [Test] public void DecimalIsWrittenWithTrailingM() { WriteValue(0.5m); Expect(writer.ToString(), EqualTo("0.5m")); } [Test] public void DecimalIsWrittenToTwentyNineDigits() { WriteValue(12345678901234567890123456789m); Expect(writer.ToString(), EqualTo("12345678901234567890123456789m")); } } } }
30.152672
109
0.512405
[ "Apache-2.0" ]
SvenPeldszus/conqat
org.conqat.engine.dotnet/test-data/org.conqat.engine.dotnet.scope/NUnit_Folder/NUnitFramework/tests/MessageWriterTests.cs
3,950
C#
/* * Copyright 2004 The Apache Software Foundation * * 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; namespace Monodoc.Lucene.Net.Store { /// <summary>Abstract base class for input from a file in a {@link Directory}. A /// random-access input stream. Used for all Lucene index input operations. /// </summary> /// <seealso cref="Directory"> /// </seealso> /// <seealso cref="OutputStream"> /// </seealso> public abstract class InputStream : System.ICloneable { internal static readonly int BUFFER_SIZE; private byte[] buffer; private char[] chars; private long bufferStart = 0; // position in file of buffer private int bufferLength = 0; // end of valid bytes private int bufferPosition = 0; // next byte to read protected internal long length; // set by subclasses /// <summary>Reads and returns a single byte.</summary> /// <seealso cref="OutputStream#WriteByte(byte)"> /// </seealso> public byte ReadByte() { if (bufferPosition >= bufferLength) Refill(); return buffer[bufferPosition++]; } /// <summary>Reads a specified number of bytes into an array at the specified offset.</summary> /// <param name="b">the array to read bytes into /// </param> /// <param name="offset">the offset in the array to start storing bytes /// </param> /// <param name="len">the number of bytes to read /// </param> /// <seealso cref="OutputStream#WriteBytes(byte[],int)"> /// </seealso> public void ReadBytes(byte[] b, int offset, int len) { if (len < BUFFER_SIZE) { for (int i = 0; i < len; i++) // read byte-by-byte b[i + offset] = (byte) ReadByte(); } else { // read all-at-once long start = GetFilePointer(); SeekInternal(start); ReadInternal(b, offset, len); bufferStart = start + len; // adjust stream variables bufferPosition = 0; bufferLength = 0; // trigger refill() on read } } /// <summary>Reads four bytes and returns an int.</summary> /// <seealso cref="OutputStream#WriteInt(int)"> /// </seealso> public int ReadInt() { return ((ReadByte() & 0xFF) << 24) | ((ReadByte() & 0xFF) << 16) | ((ReadByte() & 0xFF) << 8) | (ReadByte() & 0xFF); } /// <summary>Reads an int stored in variable-length format. Reads between one and /// five bytes. Smaller values take fewer bytes. Negative numbers are not /// supported. /// </summary> /// <seealso cref="OutputStream#WriteVInt(int)"> /// </seealso> public int ReadVInt() { byte b = ReadByte(); int i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = ReadByte(); i |= (b & 0x7F) << shift; } return i; } /// <summary>Reads eight bytes and returns a long.</summary> /// <seealso cref="OutputStream#WriteLong(long)"> /// </seealso> public long ReadLong() { return (((long) ReadInt()) << 32) | (ReadInt() & 0xFFFFFFFFL); } /// <summary>Reads a long stored in variable-length format. Reads between one and /// nine bytes. Smaller values take fewer bytes. Negative numbers are not /// supported. /// </summary> public long ReadVLong() { byte b = ReadByte(); long i = b & 0x7F; for (int shift = 7; (b & 0x80) != 0; shift += 7) { b = ReadByte(); i |= (b & 0x7FL) << shift; } return i; } /// <summary>Reads a string.</summary> /// <seealso cref="OutputStream#WriteString(String)"> /// </seealso> public System.String ReadString() { int length = ReadVInt(); if (chars == null || length > chars.Length) chars = new char[length]; ReadChars(chars, 0, length); return new System.String(chars, 0, length); } /// <summary>Reads UTF-8 encoded characters into an array.</summary> /// <param name="buffer">the array to read characters into /// </param> /// <param name="start">the offset in the array to start storing characters /// </param> /// <param name="length">the number of characters to read /// </param> /// <seealso cref="OutputStream#WriteChars(String,int,int)"> /// </seealso> public void ReadChars(char[] buffer, int start, int length) { int end = start + length; for (int i = start; i < end; i++) { byte b = ReadByte(); if ((b & 0x80) == 0) buffer[i] = (char) (b & 0x7F); else if ((b & 0xE0) != 0xE0) { buffer[i] = (char) (((b & 0x1F) << 6) | (ReadByte() & 0x3F)); } else buffer[i] = (char) (((b & 0x0F) << 12) | ((ReadByte() & 0x3F) << 6) | (ReadByte() & 0x3F)); } } private void Refill() { long start = bufferStart + bufferPosition; long end = start + BUFFER_SIZE; if (end > length) // don't read past EOF end = length; bufferLength = (int) (end - start); if (bufferLength == 0) throw new System.IO.IOException("read past EOF"); if (buffer == null) buffer = new byte[BUFFER_SIZE]; // allocate buffer lazily ReadInternal(buffer, 0, bufferLength); bufferStart = start; bufferPosition = 0; } /// <summary>Expert: implements buffer refill. Reads bytes from the current position /// in the input. /// </summary> /// <param name="b">the array to read bytes into /// </param> /// <param name="offset">the offset in the array to start storing bytes /// </param> /// <param name="length">the number of bytes to read /// </param> public abstract void ReadInternal(byte[] b, int offset, int length); /// <summary>Closes the stream to futher operations. </summary> public abstract void Close(); /// <summary>Returns the current position in this file, where the next read will /// occur. /// </summary> /// <seealso cref="#Seek(long)"> /// </seealso> public long GetFilePointer() { return bufferStart + bufferPosition; } /// <summary>Sets current position in this file, where the next read will occur.</summary> /// <seealso cref="#GetFilePointer()"> /// </seealso> public void Seek(long pos) { if (pos >= bufferStart && pos < (bufferStart + bufferLength)) bufferPosition = (int) (pos - bufferStart); // seek within buffer else { bufferStart = pos; bufferPosition = 0; bufferLength = 0; // trigger refill() on read() SeekInternal(pos); } } /// <summary>Expert: implements seek. Sets current position in this file, where the /// next {@link #ReadInternal(byte[],int,int)} will occur. /// </summary> /// <seealso cref="#ReadInternal(byte[],int,int)"> /// </seealso> public abstract void SeekInternal(long pos); /// <summary>The number of bytes in the file. </summary> public long Length() { return length; } /// <summary>Returns a clone of this stream. /// /// <p>Clones of a stream access the same data, and are positioned at the same /// point as the stream they were cloned from. /// /// <p>Expert: Subclasses must ensure that clones may be positioned at /// different points in the input from each other and from the stream they /// were cloned from. /// </summary> public virtual System.Object Clone() { InputStream clone = null; try { clone = (InputStream) this.MemberwiseClone(); } catch (System.Exception e) { throw new Exception("Can't clone InputStream.", e); } if (buffer != null) { clone.buffer = new byte[BUFFER_SIZE]; Array.Copy(buffer, 0, clone.buffer, 0, bufferLength); } clone.chars = null; return clone; } static InputStream() { BUFFER_SIZE = OutputStream.BUFFER_SIZE; } } }
28.910394
119
0.624101
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/tools/monodoc/Lucene.Net/Lucene.Net/Store/InputStream.cs
8,066
C#
using System.ComponentModel.DataAnnotations; namespace KdyWeb.Entity.SearchVideo { /// <summary> /// 影片类型 /// </summary> /// <remarks> /// 电影、电视剧、纪录片、综艺、动画 /// </remarks> public enum Subtype : byte { [Display(Name = "未知")] None = 0, /// <summary> /// 电影 /// </summary> [Display(Name = "电影")] Movie = 5, /// <summary> /// 电视剧 /// </summary> [Display(Name = "电视剧")] Tv, /// <summary> /// 记录片 /// </summary> [Display(Name = "记录片")] Documentary, /// <summary> /// 综艺 /// </summary> [Display(Name = "综艺")] TvShow, /// <summary> /// 动画 /// </summary> [Display(Name = "动画")] Animation } }
17.893617
45
0.401902
[ "Apache-2.0" ]
bohejing/KdyWeb.NetCore
src/KdyWeb.Entity/SearchVideo/Enum/Subtype.cs
935
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System.Diagnostics; using System.IO; namespace OpenLiveWriter.CoreServices { /// <summary> /// A TransientFile represents a file without a location; it is composed /// entirely of filename and data. /// </summary> public class TransientFile : TransientFileSystemItem { private string name; private Stream data; public TransientFile(string name, Stream data, bool allowUnicodeName) { if (allowUnicodeName) this.name = FileHelper.GetValidFileName(name); else this.name = FileHelper.GetValidAnsiFileName(name); this.data = data; } public TransientFile(string name, byte[] data, bool allowUnicodeName) : this(name, new MemoryStream(data, false), allowUnicodeName) { } public TransientFile(FileInfo file, bool allowUnicodeName) : this(file.Name, new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), allowUnicodeName) { } public TransientFile(string name, FileInfo file, bool allowUnicodeName) : this(name, new FileStream(file.FullName, FileMode.Open, FileAccess.Read), allowUnicodeName) { } public string Name { get { return name; } set { name = value; } } public int MaxElementsOfPathLongerThan(int inputLen) { if (name.Length + 1 > inputLen) return 1; else return -1; } public FileSystemInfo Create(DirectoryInfo destination) { string truncatedName; // TODO: use constant instead of literal 260 int charsLeft = 247 - destination.FullName.Length; if (charsLeft < name.Length + 1) { truncatedName = Path.GetExtension(name); if (truncatedName == null) truncatedName = string.Empty; int charsForName = charsLeft - truncatedName.Length/*extension*/ - 1/*path seperator*/; if (charsForName < 1) throw new PathTooLongException(); truncatedName = Path.GetFileNameWithoutExtension(name).Substring(0, charsForName) + truncatedName; } else { truncatedName = name; } // create the file Debug.WriteLine("TransientFile: Want to create " + Path.Combine(destination.FullName, truncatedName)); string newFile = TempFileManager.CreateNewFile(destination.FullName, truncatedName, false); lock (this) { using (data) { using (FileStream fs = File.Create(newFile)) { int b; while ((b = data.ReadByte()) != -1) fs.WriteByte((byte)b); } } } return new FileInfo(newFile); } } }
31.980583
186
0.541287
[ "MIT" ]
DNSNets/OpenLiveWriter
src/managed/OpenLiveWriter.CoreServices/TransientFile.cs
3,294
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); /// <summary> /// Returns all symbols associated with an edit. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol)> GetSymbolsForEdit( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract void ReportTypeDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, INamedTypeSymbol oldSymbol, INamedTypeSymbol newSymbol, SyntaxNode newDeclaration, CancellationToken cancellationToken); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// or null if <paramref name="node"/> is not an accessor. /// </summary> internal abstract SyntaxNode? TryGetAssociatedMemberDeclaration(SyntaxNode node); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, ActiveStatementsMap oldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); // Do not analyze trivia in presence of syntactic rude edits. // The implementation depends on edit map capturing all updates and inserts, // which might not be the case when rude edits are reported. if (diagnostics.Count == 0) { AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, diagnostics, cancellationToken); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} trivia rude edits, first: {1}@{2}", diagnostics.Count, newDocument.FilePath, diagnostics.First().Span.Start); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); } var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol) { // Consider replacing following syntax analysis with semantic analysis of the corresponding symbols, // or a combination of semantic and syntax analysis (e.g. primarily analyze symbols but fall back // to syntax analysis for comparisons of attribute values, optional parameter values, etc.). // Such approach would likely be simpler and allow us to handle more cases. var match = ComputeTopLevelDeclarationMatch(oldNode, newNode); var syntacticEdits = match.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); ReportMemberUpdateRudeEdits(diagnostics, newNode, GetDiagnosticSpan(newNode, EditKind.Update)); } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { Debug.Assert(diagnostics.Count == 0); var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { triviaEdits.Add((oldNode, newNode)); // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } ReportMemberUpdateRudeEdits(diagnostics, newNode, rudeEditSpan); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode)); ReportMemberUpdateRudeEdits(diagnostics, segment.newNode, span: null); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } protected static readonly SymbolEquivalenceComparer s_assemblyEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { return oldParameters.SequenceEqual(newParameters, s_assemblyEqualityComparer.ParameterEquivalenceComparer) && s_assemblyEqualityComparer.Equals(oldReturnType, newReturnType); } protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbols in GetSymbolsForEdit(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { SymbolKey? lazySymbolKey = null; Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol) = symbols; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); switch (edit.Kind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfFalse(newSymbol == null); Contract.ThrowIfFalse(newDeclaration == null); if (!processedSymbols.Add(oldSymbol)) { // Node doesn't represent a symbol or it represents multiple symbols and the semantic delete // will be issued for node that represents the specific symbol. continue; } var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. var symbolKey = SymbolKey.Create(oldSymbol, cancellationToken); lazySymbolKey = symbolKey; // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. newSymbol = symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, editScript, oldDeclaration, oldSymbol, RudeEditKind.DeleteActiveStatement); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } else if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits); } } // can't change visibility: if (newSymbol.DeclaredAccessibility != oldSymbol.DeclaredAccessibility) { ReportDeletedMemberRudeEdit(diagnostics, editScript, oldDeclaration, oldSymbol, RudeEditKind.ChangingVisibility); continue; } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { // Check if the symbol being deleted is a member of a type or associated with a property or event that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var oldContainingSymbol = (oldSymbol as IMethodSymbol)?.AssociatedSymbol ?? oldSymbol.ContainingType; if (oldContainingSymbol != null) { var containingSymbolKey = SymbolKey.Create(oldContainingSymbol, cancellationToken); var newContatiningSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContatiningSymbol == null) { continue; } } // deleting symbol is not allowed var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfFalse(oldSymbol == null); Contract.ThrowIfFalse(oldDeclaration == null); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; if (!processedSymbols.Add(newSymbol)) { // Node doesn't represent a symbol or it represents multiple symbols and the semantic insert // will be issued for node that represents the specific symbol. continue; } editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); lazySymbolKey = symbolKey; // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol = symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // Replace implicit declaration with an explicit one with a different visibility is a rude edit. if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ChangingVisibility, GetDiagnosticSpan(newDeclaration, edit.Kind), arguments: new[] { GetDisplayName(newDeclaration, edit.Kind) })); continue; } // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfFalse(oldDeclaration == null); oldDeclaration = GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences[0], cancellationToken); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newSymbol.ContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits); } } editKind = SemanticEditKind.Update; } } else if (newSymbol is IFieldSymbol { ContainingType: { TypeKind: TypeKind.Enum } }) { // Skip enum field declarations. Enums can't be partial their fields must be inserted at the same time as the enum itself. continue; } else if (newSymbol is INamedTypeSymbol { TypeKind: not (TypeKind.Delegate or TypeKind.Enum) } newTypeSymbol) { // The old symbol must be named type as well since we resolved it via symbol key above. var oldTypeSymbol = (INamedTypeSymbol)oldSymbol; // The types have multiple partial declaration parts, each can contribute attributes and base types. // All have to declare the same type parameters, but each can add different attributes to them. // Only one can contribute generic type parameter constraints. // We collect all these entities and require them to be unchanged. ReportTypeDeclarationInsertDeleteRudeEdits(diagnostics, oldTypeSymbol, newTypeSymbol, newDeclaration, cancellationToken); continue; } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); Contract.ThrowIfFalse(oldDeclaration == null); oldDeclaration = GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences[0], cancellationToken); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol); // If a node has been inserted but neither old nor new has a body, we can stop processing. // The exception to this is explicitly implemented properties that implement positional parameters of // records, as even not having an initializer is an "edit", since the compiler generated property would have // had one. var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); var newBody = TryGetDeclarationBody(newDeclaration); if (oldBody == null && newBody == null && !isRecordPrimaryConstructorParameter) { continue; } if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isNewConstructorWithMemberInitializers || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration) || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } } else if (newSymbol.ContainingType != null) { // The edit actually adds a new symbol into an existing or a new type. // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. var newAssociatedMemberDeclaration = TryGetAssociatedMemberDeclaration(newDeclaration); if (newAssociatedMemberDeclaration != null && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { continue; } var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newSymbol.ContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits); } } else { // adds a new top-level type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { if (oldSymbol == null) { // May happen when the old node represents partial method changed from a definition to an implementation (adding a body). // This is already reported as rude edit. continue; } Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); if (!processedSymbols.Add(newSymbol)) { // node doesn't represent a symbol or the symbol has already been processed continue; } editKind = SemanticEditKind.Update; syntaxMap = null; var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } // Need to check for attribute rude edits for fields and properties AnalyzeCustomAttributes(oldSymbol, newSymbol, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { AnalyzeCustomAttributes(oldSymbol, newSymbol, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); // The only update to the type itself that's supported is an addition or removal of the partial modifier, // which does not have impact on the emitted type metadata. if (newSymbol is INamedTypeSymbol) { continue; } // The field/property itself is being updated. Currently we do not allow any modifiers to be updated. Attribute // updates will have been handled already if (newSymbol is IFieldSymbol or IPropertySymbol) { continue; } // The only updates allowed for a parameter or type parameter is an attribute change, but we only need the edit // for the containing symbol which will be handled elsewhere. if (newSymbol is IParameterSymbol or ITypeParameterSymbol) { continue; } } lazySymbolKey ??= SymbolKey.Create(newSymbol, cancellationToken); // Edits in data member initializers and constructors are deferred, edits of other members (even on partial types) // do not need merging accross partial type declarations. semanticEdits.Add(new SemanticEditInfo(editKind, lazySymbolKey.Value, syntaxMap, syntaxMapTree: null, partialType: null)); } } foreach (var (oldEditNode, newEditNode) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol) in GetSymbolsForEdit(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // Edits in data member initializers and constructors are deferred, edits of other members (even on partial types) // do not need merging accross partial type declarations. var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, partialType: null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, processedSymbols, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, processedSymbols, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.ToImmutable(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private void AnalyzeCustomAttributes(ISymbol? oldSymbol, ISymbol newSymbol, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo>? semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var needsEdit = false; if (newSymbol is IMethodSymbol newMethod) { if (oldSymbol is not IMethodSymbol oldMethod) { return; } needsEdit |= HasCustomAttributeChanges(oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), newMethod, capabilities, diagnostics); } else if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null } newType) { var oldType = oldSymbol as INamedTypeSymbol; // If this is a delegate with attributes on its return type for example, they are found on the DelegateInvokeMethod AnalyzeCustomAttributes(oldType?.DelegateInvokeMethod, newType.DelegateInvokeMethod, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } foreach (var parameter in newSymbol.GetParameters()) { var oldParameter = oldSymbol?.GetParameters().FirstOrDefault(p => p.Name.Equals(parameter.Name)); needsEdit |= HasCustomAttributeChanges(oldParameter?.GetAttributes(), parameter.GetAttributes(), parameter, capabilities, diagnostics); } foreach (var typeParam in newSymbol.GetTypeParameters()) { var oldParameter = oldSymbol?.GetTypeParameters().FirstOrDefault(p => p.Name.Equals(typeParam.Name)); needsEdit |= HasCustomAttributeChanges(oldParameter?.GetAttributes(), typeParam.GetAttributes(), typeParam, capabilities, diagnostics); } // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. needsEdit |= HasCustomAttributeChanges(oldSymbol?.GetAttributes(), newSymbol.GetAttributes(), newSymbol, capabilities, diagnostics); // If we don't need to add an edit, then we're done if (!needsEdit || semanticEdits is null) { return; } // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is ITypeParameterSymbol or IMethodSymbol { MethodKind: MethodKind.DelegateInvoke }) { var symbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, partialType: null)); } } private bool HasCustomAttributeChanges(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol newSymbol, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { var newNode = FindSyntaxNode(newSymbol); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static SyntaxNode FindSyntaxNode(ISymbol symbol) { // In VB parameters of delegates don't have declaring syntax references so we have to go all the way up to the delegate // See: https://github.com/dotnet/roslyn/issues/53337 if (symbol.DeclaringSyntaxReferences.Length == 0) { return FindSyntaxNode(symbol.ContainingSymbol); } return symbol.DeclaringSyntaxReferences.First().GetSyntax(); } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> editScript, SyntaxNode oldNode, ISymbol oldSymbol, RudeEditKind rudeEditKind) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldNode), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldNode, EditKind.Delete), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, IReadOnlySet<ISymbol> processedSymbols, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; var isPartialEdit = oldType.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newType.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial var newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Compiler generated constructors of records are not implicitly declared, since they // points to the actual record declaration. We want to skip these checks because we can't // reason about initializers for them. if (!IsRecordDeclaration(newDeclaration)) { // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, and hence this // actually finds the old record declaration, but that is actually sufficient for our needs, as all // we're using it for is detecting an update, and any changes to the standard record constructors must // be an update by definition. if (topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfNull(oldCtor); } else if (newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !IsRecordDeclaration(newDeclaration) && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, diagnostics, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } var reverseCapturesMap = ArrayBuilder<int>.GetInstance(newCaptures.Length, 0); // { new capture index -> new closure scope or null for "this" } var newCapturesToClosureScopes = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, null); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } var oldCapturesToClosureScopes = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, null); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _1 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _2 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); foreach (var newLambda in newMemberBody.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(newLambda, out var newLambdaBody1, out var newLambdaBody2)) { if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } syntaxMapRequired = true; } } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. foreach (var oldLambda in oldMemberBody.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(oldLambda, out var oldLambdaBody1, out var oldLambdaBody2) && !map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } } reverseCapturesMap.Free(); newCapturesToClosureScopes.Free(); oldCapturesToClosureScopes.Free(); } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!s_assemblyEqualityComparer.Equals(oldTypeOpt, newTypeOpt)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } protected virtual void ReportLambdaSignatureRudeEdits( SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { hasErrors = false; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); AnalyzeCustomAttributes(oldLambdaSymbol, newLambdaSymbol, capabilities, diagnostics, semanticEdits: null, syntaxMap: null, cancellationToken); RudeEditKind rudeEdit; if (!oldLambdaSymbol.Parameters.SequenceEqual(newLambdaSymbol.Parameters, s_assemblyEqualityComparer.ParameterEquivalenceComparer)) { rudeEdit = RudeEditKind.ChangingLambdaParameters; } else if (!s_assemblyEqualityComparer.ReturnTypeEquals(oldLambdaSymbol, newLambdaSymbol)) { rudeEdit = RudeEditKind.ChangingLambdaReturnType; } else { hasErrors = false; return; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newLambda, EditKind.Update), newLambda, new[] { GetDisplayName(newLambda) })); hasErrors = true; } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } internal void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { _abstractEditAndContinueAnalyzer.AnalyzeTrivia(topMatch, editMap, triviaEdits, lineEdits, diagnostics, cancellationToken); } } #endregion } }
52.821195
297
0.56331
[ "MIT" ]
lambdaxymox/roslyn
src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.cs
250,216
C#
// Originally copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // See license.txt, section Ionic.Zlib license #if __MonoCS__ using System; using System.IO; using ClassicalSharp; namespace Ionic.Zlib { internal class DeflateStream : ReadOnlyStream { ZlibCodec z; bool _leaveOpen; byte[] workBuffer; Stream _stream; public DeflateStream(Stream stream, bool leaveOpen) { _stream = stream; _leaveOpen = leaveOpen; workBuffer = new byte[16384]; // TODO: 1024 bytes? z = new ZlibCodec(); } public override void Close() { z.EndInflate(); z = null; if (!_leaveOpen) _stream.Dispose(); _stream = null; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (count == 0) return 0; int rc = 0; // set up the output of the deflate/inflate codec: z.OutputBuffer = buffer; z.NextOut = offset; z.AvailableBytesOut = count; z.InputBuffer = workBuffer; bool endOfInput = false; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if (z.AvailableBytesIn == 0 && !endOfInput) { // No data available, so try to Read data from the captive stream. z.NextIn = 0; z.AvailableBytesIn = _stream.Read(workBuffer, 0, workBuffer.Length); if (z.AvailableBytesIn == 0) endOfInput = true; } rc = z.Inflate(); if (endOfInput && rc == RCode.BufferError) return 0; if (rc != RCode.Okay && rc != RCode.StreamEnd) throw new InvalidDataException("inflating: rc=" + rc); if ((endOfInput || rc == RCode.StreamEnd) && z.AvailableBytesOut == count) break; // nothing more to read } while (z.AvailableBytesOut > 0 && !endOfInput && rc == RCode.Okay); return count - z.AvailableBytesOut; } } } #endif
29.333333
96
0.635052
[ "BSD-3-Clause" ]
Andresian/ClassicalSharp
ClassicalSharp/Ionic.Zlib/DeflateStream.cs
2,211
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 quicksight-2018-04-01.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.QuickSight.Model { ///<summary> /// QuickSight exception /// </summary> #if !PCL && !CORECLR [Serializable] #endif public class UnsupportedUserEditionException : AmazonQuickSightException { /// <summary> /// Constructs a new UnsupportedUserEditionException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public UnsupportedUserEditionException(string message) : base(message) {} /// <summary> /// Construct instance of UnsupportedUserEditionException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public UnsupportedUserEditionException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of UnsupportedUserEditionException /// </summary> /// <param name="innerException"></param> public UnsupportedUserEditionException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of UnsupportedUserEditionException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public UnsupportedUserEditionException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of UnsupportedUserEditionException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public UnsupportedUserEditionException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !CORECLR /// <summary> /// Constructs a new instance of the UnsupportedUserEditionException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected UnsupportedUserEditionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.917526
178
0.656338
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/QuickSight/Generated/Model/UnsupportedUserEditionException.cs
4,260
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using NuGet.Packaging; using NuGet.Services.Entities; using NuGetGallery.Packaging; using NuGetGallery.ViewModels; namespace NuGetGallery { public class VerifyPackageRequest { public VerifyPackageRequest() { } public VerifyPackageRequest(PackageMetadata packageMetadata, IEnumerable<User> possibleOwners, PackageRegistration existingPackageRegistration) { Id = packageMetadata.Id; Version = packageMetadata.Version.ToFullStringSafe(); OriginalVersion = packageMetadata.Version.OriginalVersion; HasSemVer2Version = packageMetadata.Version.IsSemVer2; HasSemVer2Dependency = packageMetadata.GetDependencyGroups().Any(d => d.Packages.Any( p => (p.VersionRange.HasUpperBound && p.VersionRange.MaxVersion.IsSemVer2) || (p.VersionRange.HasLowerBound && p.VersionRange.MinVersion.IsSemVer2))); // Verifiable fields Language = packageMetadata.Language; MinClientVersionDisplay = packageMetadata.MinClientVersion.ToFullStringSafe(); FrameworkReferenceGroups = packageMetadata.GetFrameworkReferenceGroups(); Dependencies = new DependencySetsViewModel(packageMetadata.GetDependencyGroups().AsPackageDependencyEnumerable()); DevelopmentDependency = packageMetadata.DevelopmentDependency; Authors = packageMetadata.Authors.Flatten(); Copyright = packageMetadata.Copyright; Description = packageMetadata.Description; IconUrl = packageMetadata.IconUrl.ToEncodedUrlStringOrNull(); LicenseUrl = packageMetadata.LicenseUrl.ToEncodedUrlStringOrNull(); LicenseExpression = packageMetadata.LicenseMetadata?.Type == LicenseType.Expression ? packageMetadata.LicenseMetadata?.License : null; ProjectUrl = packageMetadata.ProjectUrl.ToEncodedUrlStringOrNull(); RepositoryUrl = packageMetadata.RepositoryUrl.ToEncodedUrlStringOrNull(); RepositoryType = packageMetadata.RepositoryType; ReleaseNotes = packageMetadata.ReleaseNotes; RequiresLicenseAcceptance = packageMetadata.RequireLicenseAcceptance; Summary = packageMetadata.Summary; Tags = PackageHelper.ParseTags(packageMetadata.Tags); Title = packageMetadata.Title; IsNewId = existingPackageRegistration == null; if (!IsNewId) { ExistingOwners = string.Join(", ", ParseUserList(existingPackageRegistration.Owners)); } // Editable server-state Listed = true; Edit = new EditPackageVersionReadMeRequest(); PossibleOwners = ParseUserList(possibleOwners); } public string Id { get; set; } /// <summary> /// The normalized, full version string (for display purposes). /// </summary> public string Version { get; set; } /// <summary> /// The non-normalized, unmodified, original version as defined in the nuspec. /// </summary> public string OriginalVersion { get; set; } /// <summary> /// This is a new ID. /// There are no existing packages with this ID. /// </summary> public bool IsNewId { get; set; } /// <summary> /// The username of the <see cref="User"/> to upload the package as. /// </summary> public string Owner { get; set; } /// <summary> /// The <see cref="User"/>s that own the existing package registration that this package will be added to in a string. /// E.g. "alice, bob, chad". /// </summary> public string ExistingOwners { get; set; } /// <summary> /// The usernames of the <see cref="User"/>s that the current user can upload the package as. /// </summary> public IReadOnlyCollection<string> PossibleOwners { get; set; } public bool IsSemVer2 => HasSemVer2Version || HasSemVer2Dependency; public bool HasSemVer2Version { get; set; } public bool HasSemVer2Dependency { get; set; } // Editable server-state public bool Listed { get; set; } public EditPackageVersionReadMeRequest Edit { get; set; } // Verifiable fields public string Authors { get; set; } public string Copyright { get; set; } public string Description { get; set; } public DependencySetsViewModel Dependencies { get; set; } public bool DevelopmentDependency { get; set; } public IReadOnlyCollection<FrameworkSpecificGroup> FrameworkReferenceGroups { get; set; } public string IconUrl { get; set; } public string Language { get; set; } public string LicenseUrl { get; set; } public string LicenseExpression { get; set; } public IReadOnlyCollection<CompositeLicenseExpressionSegmentViewModel> LicenseExpressionSegments { get; set; } public string LicenseFileContents { get; set; } public string MinClientVersionDisplay { get; set; } public string ProjectUrl { get; set; } public string RepositoryUrl { get; set; } public string RepositoryType { get; set; } public string ReleaseNotes { get; set; } public bool RequiresLicenseAcceptance { get; set; } public string Summary { get; set; } public string Tags { get; set; } public string Title { get; set; } public bool IsSymbolsPackage { get; set; } public bool HasExistingAvailableSymbols { get; set; } public List<JsonValidationMessage> Warnings { get; set; } = new List<JsonValidationMessage>(); private static IReadOnlyCollection<string> ParseUserList(IEnumerable<User> users) { return users.Select(u => u.Username).ToList(); } } }
45.77037
151
0.648487
[ "Apache-2.0" ]
304NotModified/NuGetGallery
src/NuGetGallery/RequestModels/VerifyPackageRequest.cs
6,181
C#
namespace In.ProjectEKA.HipServiceTest.OpenMrs { public static class Endpoints { public static class OpenMrs { public const string OnProgramEnrollmentPath = "ws/rest/v1/bahmniprogramenrollment"; public const string OnVisitPath = "ws/rest/v1/visit"; public const string OnPatientPath = "ws/rest/v1/patient"; } public static class Fhir { public const string OnPatientPath = "ws/fhir2/Patient"; } } }
30.705882
96
0.601533
[ "MIT" ]
thanakritTW/hip-service
test/In.ProjectEKA.HipServiceTest/OpenMrs/Endpoints.cs
522
C#
namespace LogSpect.Formatting.MethodEvents { using System; using System.Reflection; public interface IFormattingModeReader { /// <summary> /// Reads the attributes of the specified property and determines how it should be serialized when the containing object is logged. /// </summary> /// <param name="member"></param> /// <returns>The formatting mode.</returns> /// <exception cref="ArgumentNullException">If property is null.</exception> FormattingMode ReadMode(MemberInfo member); FormattingMode ReadMode(ParameterInfo parameter); } }
33.894737
140
0.652174
[ "MIT" ]
LorandBiro/LogSpect
Source/LogSpect.Core/Formatting/MethodEvents/IFormattingModeReader.cs
646
C#
using System.Diagnostics; using System.Text; using System.Windows.Forms; using ARKBreedingStats.species; using ARKBreedingStats.values; namespace ARKBreedingStats.uiControls { public partial class Hatching : UserControl { public Hatching() { InitializeComponent(); } /// <summary> /// Set a species to display the stats of the current top levels. This can help in determine if a new creature is good. /// </summary> /// <param name="species"></param> /// <param name="highLevels"></param> public void SetSpecies(Species species, int[] highLevels, int[] lowLevels) { if (species == null) { LbHeader.Text = "no species selected"; LbStatNames.Text = string.Empty; LbStatValues.Text = string.Empty; LbStatLevels.Text = string.Empty; LbLowestValues.Text = string.Empty; LbLowestLevels.Text = string.Empty; return; } if (highLevels == null) highLevels = new int[Values.STATS_COUNT]; if (lowLevels == null) lowLevels = new int[Values.STATS_COUNT]; LbHeader.Text = $"Best stat values for bred creatures without imprinting of the species {species.DescriptiveNameAndMod} in this library."; string sbNames = null; string sbValues = null; string sbLevels = null; string sbLowestValues = null; string sbLowestLevels = null; foreach (var si in Values.statsDisplayOrder) { if (!species.UsesStat(si)) continue; var precision = Utils.Precision(si); var statValue = StatValueCalculation.CalculateValue(species, si, highLevels[si], 0, true, 1, 0); var statRepresentation = precision == 3 ? $"{statValue * 100:0.0} %" : $"{statValue:0.0} "; sbNames += $"{Utils.StatName(si, customStatNames: species.statNames)}\n"; sbValues += statRepresentation + "\n"; sbLevels += highLevels[si] + "\n"; statValue = StatValueCalculation.CalculateValue(species, si, lowLevels[si], 0, true, 1, 0); statRepresentation = precision == 3 ? $"{statValue * 100:0.0} %" : $"{statValue:0.0} "; sbLowestValues += statRepresentation + "\n"; sbLowestLevels += lowLevels[si] + "\n"; } LbStatNames.Text = sbNames; LbStatValues.Text = sbValues; LbStatLevels.Text = sbLevels; LbLowestValues.Text = sbLowestValues; LbLowestLevels.Text = sbLowestLevels; } } }
38.746479
150
0.568521
[ "MIT" ]
CataclysmicAngel/ARKStatsExtractor
ARKBreedingStats/uiControls/Hatching.cs
2,753
C#
namespace EasyCon2.Graphic { public struct HSVColor { public double H { get; private set; } public double S { get; private set; } public double V { get; private set; } Color _c; public HSVColor(Color c) { _c = c; var r = _c.R / 255.0; var g = _c.G / 255.0; var b = _c.B / 255.0; var cmax = Math.Max(Math.Max(r, g), b); var cmin = Math.Min(Math.Min(r, g), b); var dt = cmax - cmin; if (dt == 0) H = 0; else if (cmax == r) H = 60 * (((g - b) / dt + 6) % 6); else if (cmax == g) H = 60 * ((b - r) / dt + 2); else H = 60 * ((r - g) / dt + 4); if (cmax == 0) S = 0; else S = dt / cmax * 100; V = cmax * 100; } public static implicit operator HSVColor(Color c) { return new HSVColor(c); } } }
25.829268
57
0.372993
[ "MIT" ]
ca1e/PokemonTycoon
EasyCon2/Graphic/HSVColor.cs
1,061
C#
namespace SqlMigrator.Core.ExecutionBuilder { public class SqlCommand { public string Comments { get; set; } public string Command { get; set; } } }
17.8
44
0.629213
[ "MIT" ]
avifatal/sql-blinker
SqlMigrator.Core/ExecutionBuilder/SqlCommand.cs
178
C#
using System; using System.Collections.Generic; using System.Linq; namespace DirectedGraphLesson.Clients { public class SymbolGraph { private List<string[]> _graphData; private DirectedGraph _graph; private Dictionary<string, int> _index; public SymbolGraph() { _graphData = new List<string[]>(); } public void Insert(string[] vertices) { if (vertices == null || vertices.Length == 0) throw new ArgumentNullException(); _graphData.Add(vertices); } public void Build() { if (_graphData.Count == 0) throw new InvalidOperationException(); BuildIndex(); BuildGraph(); } public bool Contains(string vertex) { if (string.IsNullOrWhiteSpace(vertex)) throw new ArgumentNullException(); return _index.ContainsKey(vertex); } public int Index(string vertex) { if (string.IsNullOrWhiteSpace(vertex)) throw new ArgumentNullException(); return _index[vertex]; } public string Name(int vertex) { var result = _index.FirstOrDefault(x => x.Value == vertex).Key; if (string.IsNullOrWhiteSpace(result)) throw new InvalidOperationException(); return result; } public DirectedGraph Graph() { return _graph; } private void BuildIndex() { _index = new Dictionary<string, int>(); foreach (var row in _graphData) { for (var i = 0; i < row.Length; i++) { if (!_index.ContainsKey(row[i])) _index.Add(row[i], _index.Count); } } } private void BuildGraph() { _graph = new DirectedGraph(_index.Count); foreach (var row in _graphData) { var source = _index[row[0]]; for (var i = 1; i < row.Length; i++) { var destination = _index[row[i]]; _graph.InsertEdge(source, destination); } } } } }
25.183673
76
0.467585
[ "MIT" ]
mainframebot/csharp-datastructures-graphs
DirectedGraphLesson/Clients/SymbolGraph.cs
2,470
C#
using SFA.DAS.ApplyService.Application.Apply.Roatp; using System; namespace SFA.DAS.ApplyService.Web.ViewModels.Roatp { public class ConfirmTrusteesViewModel : WhosInControlViewModel, IPageViewModel { public bool VerifiedCompaniesHouse { get; set; } public Guid ApplicationId { get; set; } public PeopleInControl Trustees { get; set; } public string Title { get { return "Confirm your organisation's trustees"; } set { } } public int SequenceId { get { return RoatpWorkflowSequenceIds.YourOrganisation; } set { } } public int SectionId { get { return RoatpWorkflowSectionIds.YourOrganisation.WhosInControl; } set { } } public string PageId { get; set; } public string GetHelpQuestion { get; set; } public bool GetHelpQuerySubmitted { get; set; } public string GetHelpErrorMessage { get; set; } public string GetHelpAction { get { return "ConfirmTrusteesNoDob"; } set { } } } }
44.545455
111
0.688776
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-apply-service
src/SFA.DAS.ApplyService.Web/ViewModels/Roatp/WhosInControl/ConfirmTrusteesViewModel.cs
982
C#
using System; using System.Text; using System.Xml.Linq; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.Extensions.DependencyInjection; using SS.Api.infrastructure.exceptions; namespace SS.Api.infrastructure.encryption { public class AesGcmXmlEncryptor : IXmlEncryptor { private readonly byte[] _key; public AesGcmXmlEncryptor(IServiceProvider services) { var options = services.GetRequiredService<AesGcmEncryptionOptions>(); _key = Encoding.UTF8.GetBytes(options.Key); if (_key.Length != 32) throw new ConfigurationException("Key length not 32 bytes (256 bits)"); } public EncryptedXmlInfo Encrypt(XElement plaintextElement) { if (plaintextElement == null) throw new ArgumentNullException(nameof(plaintextElement)); using var aesObj = new AesGcmService(_key); var element = new XElement("encryptedKey", new XComment(" This key is encrypted with AES-256-GCM. "), new XElement("value", aesObj.Encrypt(plaintextElement.ToString()))); return new EncryptedXmlInfo(element, typeof(AesGcmXmlDecryptor)); } } }
33.473684
87
0.652516
[ "Apache-2.0" ]
bcgov/sheriff-scheduling
api/infrastructure/encryption/AesGcmXmlEncryptor.cs
1,274
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 codeguru-reviewer-2019-09-19.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.CodeGuruReviewer.Model { /// <summary> /// Information about a third party source repository connected through CodeStar Connections. /// </summary> public partial class ThirdPartySourceRepository { private string _connectionArn; private string _name; private string _owner; /// <summary> /// Gets and sets the property ConnectionArn. /// <para> /// The Amazon Resource Name (ARN) identifying the repository connection. /// </para> /// </summary> [AWSProperty(Required=true, Min=0, Max=256)] public string ConnectionArn { get { return this._connectionArn; } set { this._connectionArn = value; } } // Check to see if ConnectionArn property is set internal bool IsSetConnectionArn() { return this._connectionArn != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the third party source repository. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Owner. /// <para> /// The username of the owner of the repository. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=100)] public string Owner { get { return this._owner; } set { this._owner = value; } } // Check to see if Owner property is set internal bool IsSetOwner() { return this._owner != null; } } }
29.443299
115
0.595238
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/CodeGuruReviewer/Generated/Model/ThirdPartySourceRepository.cs
2,856
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Dayu.V20180709.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DescribeInsurePacksResponse : AbstractModel { /// <summary> /// 保险包套餐列表 /// </summary> [JsonProperty("InsurePacks")] public KeyValueRecord[] InsurePacks{ get; set; } /// <summary> /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 /// </summary> [JsonProperty("RequestId")] public string RequestId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArrayObj(map, prefix + "InsurePacks.", this.InsurePacks); this.SetParamSimple(map, prefix + "RequestId", this.RequestId); } } }
30.980392
82
0.648734
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Dayu/V20180709/Models/DescribeInsurePacksResponse.cs
1,652
C#
/* ** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $ ** a generic input stream interface ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace KopiLua { using ZIO = Lua.Zio; public partial class Lua { public const int EOZ = -1; /* end of stream */ //public class ZIO : Zio { }; public static int char2int(char c) { return (int)c; } public static int zgetc(ZIO z) { if (z.n-- > 0) { int ch = char2int(z.p[0]); z.p.inc(); return ch; } else return luaZ_fill(z); } public class Mbuffer { public CharPtr buffer = new CharPtr(); public uint n; public uint buffsize; }; public static void luaZ_initbuffer(lua_State L, Mbuffer buff) { buff.buffer = null; } public static CharPtr luaZ_buffer(Mbuffer buff) {return buff.buffer;} public static uint luaZ_sizebuffer(Mbuffer buff) { return buff.buffsize; } public static uint luaZ_bufflen(Mbuffer buff) {return buff.n;} public static void luaZ_resetbuffer(Mbuffer buff) {buff.n = 0;} public static void luaZ_resizebuffer(lua_State L, Mbuffer buff, int size) { if (buff.buffer == null) buff.buffer = new CharPtr(); luaM_reallocvector(L, ref buff.buffer.chars, (int)buff.buffsize, size); buff.buffsize = (uint)buff.buffer.chars.Length; } public static void luaZ_freebuffer(lua_State L, Mbuffer buff) {luaZ_resizebuffer(L, buff, 0);} /* --------- Private Part ------------------ */ public class Zio { public uint n; /* bytes still unread */ public CharPtr p; /* current position in buffer */ public lua_Reader reader; public object data; /* additional data */ public lua_State L; /* Lua state (for reader) */ }; public static int luaZ_fill (ZIO z) { uint size; lua_State L = z.L; CharPtr buff; lua_unlock(L); buff = z.reader(L, z.data, out size); lua_lock(L); if (buff == null || size == 0) return EOZ; z.n = size - 1; z.p = new CharPtr(buff); int result = char2int(z.p[0]); z.p.inc(); return result; } public static int luaZ_lookahead (ZIO z) { if (z.n == 0) { if (luaZ_fill(z) == EOZ) return EOZ; else { z.n++; /* luaZ_fill removed first byte; put back it */ z.p.dec(); } } return char2int(z.p[0]); } public static void luaZ_init(lua_State L, ZIO z, lua_Reader reader, object data) { z.L = L; z.reader = reader; z.data = data; z.n = 0; z.p = null; } /* --------------------------------------------------------------- read --- */ public static uint luaZ_read (ZIO z, CharPtr b, uint n) { b = new CharPtr(b); while (n != 0) { uint m; if (luaZ_lookahead(z) == EOZ) return n; // return number of missing bytes m = (n <= z.n) ? n : z.n; // min. between n and z.n memcpy(b, z.p, m); z.n -= m; z.p += m; b = b + m; n -= m; } return 0; } /* ------------------------------------------------------------------------ */ public static CharPtr luaZ_openspace (lua_State L, Mbuffer buff, uint n) { if (n > buff.buffsize) { if (n < LUA_MINBUFFER) n = LUA_MINBUFFER; luaZ_resizebuffer(L, buff, (int)n); } return buff.buffer; } } }
23.895833
97
0.553909
[ "MIT" ]
DGoodayle/kopilua
src/lzio.cs
3,441
C#
#define DISABLE_LOGOS using System; using System.Collections.Generic; using System.Reflection; using System.Windows; using System.Windows.Threading; using ModernMessageBoxLib; namespace SaberColorfulStartmenu { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { public static readonly string CommonStartMenu = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu); public static readonly string StartMenu = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); public static Dictionary<string, string> charMap_Cn; private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) => new ErrorReport(e.Exception).ShowDialog(); static App() => AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => { var assName = new AssemblyName(e.Name); switch (assName.FullName.Replace(" ", string.Empty)) { case "ModernMessageBoxLib,Version=1.3.0.0,Culture=neutral,PublicKeyToken=null": return Assembly.Load(SaberColorfulStartmenu.Properties.Resources.ModernMessageBoxLib); default: return null; } }; protected override void OnStartup(StartupEventArgs e) { charMap_Cn = new Dictionary<string, string>(); var lens = SaberColorfulStartmenu.Properties.Resources.SysCharMap_CN.Replace("\r\n", "\n").Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in lens) { var word = item.Split(','); charMap_Cn.Add(word[0], word[1]); } QModernMessageBox.MainLang = new QMetroMessageLang() { Abort = "中止(A)", Cancel = "取消(C)", Ignore = "忽略(I)", No = "否(N)", Ok = "确定", Retry = "重试(R)", Yes = "是(Y)" }; base.OnStartup(e); } } }
34.206349
116
0.581439
[ "MIT" ]
hv0905/SaberColorfulStartmenu
SaberColorfulStartmenu/App.xaml.cs
2,191
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Speech.V1P1Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.Speech.V1P1Beta1; using System; public sealed partial class GeneratedAdaptationClientStandaloneSnippets { /// <summary>Snippet for ListCustomClasses</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void ListCustomClassesRequestObject() { // Create client AdaptationClient adaptationClient = AdaptationClient.Create(); // Initialize request argument(s) ListCustomClassesRequest request = new ListCustomClassesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListCustomClassesResponse, CustomClass> response = adaptationClient.ListCustomClasses(request); // Iterate over all response items, lazily performing RPCs as required foreach (CustomClass item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListCustomClassesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (CustomClass item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<CustomClass> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (CustomClass item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } }
41.038961
123
0.626266
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/speech/v1p1beta1/google-cloud-speech-v1p1beta1-csharp/Google.Cloud.Speech.V1P1Beta1.StandaloneSnippets/AdaptationClient.ListCustomClassesRequestObjectSnippet.g.cs
3,160
C#
using System; using Xamarin.Forms; namespace UrbanSketchers.Controls { /// <summary> /// Image that supports connected animations /// </summary> public class ConnectedImage : Image { private bool _started; /// <summary> /// Gets or sets the native control /// </summary> public object Control { get; set; } /// <summary> /// Gets or sets the name of the connected animation /// </summary> public string Name { get; set; } /// <summary> /// Event to animate the destination control /// </summary> public event EventHandler<TypedEventArgs<string>> Animate; /// <summary> /// Event to prepare the source control to animate /// </summary> public event EventHandler<TypedEventArgs<string>> PrepareToAnimate; /// <summary> /// Start the connected animation /// </summary> /// <param name="name">the name of the animation</param> public void StartConnectedAnimation(string name) { if (_started) { return; } Animate?.Invoke(Control, new TypedEventArgs<string>(name)); _started = true; } /// <summary> /// Prepare to animate /// </summary> /// <param name="name">the animation name</param> public void Prepare(string name) { PrepareToAnimate?.Invoke(Control, new TypedEventArgs<string>(name)); } } }
26.864407
80
0.538801
[ "MIT" ]
mscherotter/UrbanSketchers
UrbanSketchers/UrbanSketchers/Controls/ConnectedImage.cs
1,587
C#
using UnityEngine; using System.Collections; namespace EnhancedScrollerDemos.JumpToDemo { public class Data { public string cellText; } }
15.9
42
0.710692
[ "BSD-3-Clause" ]
bac0264/LuaTest
Assets/EnhancedScroller v2/Demos/04 Jump To Demo/Data.cs
161
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using NiceShop.Common; using NiceShop.Data.Models; using NiceShop.Data.Repositories.Contracts; namespace NiceShop.Web.Common.MiddleWares.Seeders { public class SeedCategory { private readonly RequestDelegate next; public SeedCategory(RequestDelegate next) { this.next = next; } public async Task InvokeAsync( HttpContext context, IRepository<Category> categoryRepository, IRepository<Shop> shopRepository, IRepository<ShopCategory> shopCategoryRepository) { if (!categoryRepository.ReadAll().Any()) { var shop = shopRepository .ReadAll() .FirstOrDefault(x => x.Name == WebConstants.OnlineShopName); var category = new Category { Name = WebConstants.OtherCategoryName, }; var shopId = shop.Id; var categoryId = await categoryRepository.CreateAsync(category); var shopCategory = new ShopCategory { CategoryId = categoryId, ShopId = shopId }; await shopCategoryRepository.CreateAsync(shopCategory); } await this.next(context); } } }
28.54902
80
0.559066
[ "MIT" ]
km3to/NiceShop
src/NiceShop.Web/Common/MiddleWares/Seeders/SeedCategory.cs
1,458
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the networkmanager-2019-07-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.NetworkManager.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.NetworkManager.Model.Internal.MarshallTransformations { /// <summary> /// CreateCoreNetwork Request Marshaller /// </summary> public class CreateCoreNetworkRequestMarshaller : IMarshaller<IRequest, CreateCoreNetworkRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((CreateCoreNetworkRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(CreateCoreNetworkRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.NetworkManager"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-07-05"; request.HttpMethod = "POST"; request.ResourcePath = "/core-networks"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetClientToken()) { context.Writer.WritePropertyName("ClientToken"); context.Writer.Write(publicRequest.ClientToken); } else if(!(publicRequest.IsSetClientToken())) { context.Writer.WritePropertyName("ClientToken"); context.Writer.Write(Guid.NewGuid().ToString()); } if(publicRequest.IsSetDescription()) { context.Writer.WritePropertyName("Description"); context.Writer.Write(publicRequest.Description); } if(publicRequest.IsSetGlobalNetworkId()) { context.Writer.WritePropertyName("GlobalNetworkId"); context.Writer.Write(publicRequest.GlobalNetworkId); } if(publicRequest.IsSetPolicyDocument()) { context.Writer.WritePropertyName("PolicyDocument"); context.Writer.Write(publicRequest.PolicyDocument); } if(publicRequest.IsSetTags()) { context.Writer.WritePropertyName("Tags"); context.Writer.WriteArrayStart(); foreach(var publicRequestTagsListValue in publicRequest.Tags) { context.Writer.WriteObjectStart(); var marshaller = TagMarshaller.Instance; marshaller.Marshall(publicRequestTagsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static CreateCoreNetworkRequestMarshaller _instance = new CreateCoreNetworkRequestMarshaller(); internal static CreateCoreNetworkRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static CreateCoreNetworkRequestMarshaller Instance { get { return _instance; } } } }
36.664286
149
0.595558
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/NetworkManager/Generated/Model/Internal/MarshallTransformations/CreateCoreNetworkRequestMarshaller.cs
5,133
C#
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ namespace IronRuby { public enum RubyCompatibility { Default = Ruby19, Ruby186 = 186, Ruby187 = 187, Ruby19 = 190, Ruby20 = 200, } }
35.72
98
0.554311
[ "MIT" ]
rifraf/IronRuby_Framework_4.7.2
Languages/Ruby/Ruby/RubyCompatibility.cs
895
C#
using System; using System.Linq; using Xamarin.Forms; using Plugin.Geolocator; namespace GeolocatorTests { public class App : Application { Label listenLabel; public App() { var label = new Label { Text = "Click Get Location" }; var addressLabel = new Label { Text = "Click Get Address" }; listenLabel = new Label { Text = "Click to listen" }; var button = new Button { Text = "Get Location" }; var addressBtn = new Button { Text = "Get Address" }; var listenToggle = new Button { Text = "Listen" }; var buttonIsAvailable = new Button { Text = "IsAvailable" }; var buttonIsEnabled = new Button { Text = "IsEnabled" }; buttonIsAvailable.Clicked += (sender, args) => { buttonIsAvailable.Text = CrossGeolocator.Current.IsGeolocationAvailable ? "Available" : "Not Available"; }; buttonIsEnabled.Clicked += (sender, args) => { buttonIsEnabled.Text = CrossGeolocator.Current.IsGeolocationEnabled ? "Enabled" : "Not Enabled"; }; button.Clicked += async (sender, e) => { try { button.IsEnabled = false; label.Text = "Getting..."; var cached = await CrossGeolocator.Current.GetLastKnownLocationAsync(); if (cached == null) label.Text += "No cached"; else label.Text += "\n" + "Cached: Lat: " + cached.Latitude.ToString() + " Long: " + cached.Longitude.ToString(); var test = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromMinutes(2)); label.Text += "\n" + "Full: Lat: " + test.Latitude.ToString() + " Long: " + test.Longitude.ToString(); label.Text += "\n" + $"Time: {test.Timestamp.ToString()}"; label.Text += "\n" + $"Heading: {test.Heading.ToString()}"; label.Text += "\n" + $"Speed: {test.Speed.ToString()}"; label.Text += "\n" + $"Accuracy: {test.Accuracy.ToString()}"; label.Text += "\n" + $"Altitude: {test.Altitude.ToString()}"; label.Text += "\n" + $"AltitudeAccuracy: {test.AltitudeAccuracy.ToString()}"; } catch (Exception ex) { label.Text = ex.Message; } finally { button.IsEnabled = true; } }; addressBtn.Clicked += async (sender, e) => { try { addressBtn.IsEnabled = false; label.Text = "Getting address..."; var position = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromMinutes(2)); var addresses = await CrossGeolocator.Current.GetAddressesForPositionAsync(position, "RJHqIE53Onrqons5CNOx~FrDr3XhjDTyEXEjng-CRoA~Aj69MhNManYUKxo6QcwZ0wmXBtyva0zwuHB04rFYAPf7qqGJ5cHb03RCDw1jIW8l"); var address = addresses.FirstOrDefault(); if (address == null) { addressLabel.Text = "No address found for position."; } else { addressLabel.Text = $"Address: {address.Thoroughfare} {address.Locality}"; } } catch (Exception ex) { label.Text = ex.Message; } finally { addressBtn.IsEnabled = true; } }; listenToggle.Clicked += async (sender, args) => { if(CrossGeolocator.Current.IsListening) { listenToggle.Text = "Stopped Listening"; await CrossGeolocator.Current.StopListeningAsync(); CrossGeolocator.Current.PositionChanged -= Current_PositionChanged; return; } listenToggle.Text = "Listening"; await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 1, true, new Plugin.Geolocator.Abstractions.ListenerSettings { ActivityType = Plugin.Geolocator.Abstractions.ActivityType.AutomotiveNavigation, AllowBackgroundUpdates = false, DeferLocationUpdates = false, DeferralDistanceMeters = 1, DeferralTime = TimeSpan.FromSeconds(1), ListenForSignificantChanges = false, PauseLocationUpdatesAutomatically = false }); CrossGeolocator.Current.PositionChanged += Current_PositionChanged; }; // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { buttonIsAvailable, buttonIsEnabled, label, button, addressBtn, addressLabel, listenToggle, listenLabel } } }; } private void Current_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e) { Device.BeginInvokeOnMainThread(() => { var test = e.Position; listenLabel.Text = "Full: Lat: " + test.Latitude.ToString() + " Long: " + test.Longitude.ToString(); listenLabel.Text += "\n" + $"Time: {test.Timestamp.ToString()}"; listenLabel.Text += "\n" + $"Heading: {test.Heading.ToString()}"; listenLabel.Text += "\n" + $"Speed: {test.Speed.ToString()}"; listenLabel.Text += "\n" + $"Accuracy: {test.Accuracy.ToString()}"; listenLabel.Text += "\n" + $"Altitude: {test.Altitude.ToString()}"; listenLabel.Text += "\n" + $"AltitudeAccuracy: {test.AltitudeAccuracy.ToString()}"; }); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
35.451777
217
0.480813
[ "MIT" ]
ghuntley/GeolocatorPlugin
tests/GeolocatorTests/GeolocatorTests.cs
6,986
C#
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using CodingCoach.Core.Services; using Xamarin.Forms; using CodingCoach.Models; using CodingCoach.Services; using CodingCoach.Views; namespace CodingCoach.ViewModels { public class ItemsViewModel : BaseViewModel { private readonly IDataStore<Item> _dataStore; private readonly IApiAccessService _apiAccessService; public ObservableCollection<Item> Items { get; set; } public ObservableCollection<Mentor> Mentors { get; set; } public Command LoadItemsCommand { get; set; } public ItemsViewModel() : this( DependencyService.Get<IDataStore<Item>>() ?? new MockDataStore(), DependencyService.Get<IApiAccessService>() ) { } public ItemsViewModel( IDataStore<Item> dataStore, IApiAccessService apiAccessService ) { _dataStore = dataStore; _apiAccessService = apiAccessService; Title = "Mentors"; Items = new ObservableCollection<Item>(); Mentors = new ObservableCollection<Mentor>(); LoadItemsCommand = new Command( async () => await ExecuteLoadItemsCommand() ); MessagingCenter.Subscribe<NewItemPage, Item>( this, "AddItem", async ( obj, item ) => { var newItem = item as Item; Items.Add( newItem ); await _dataStore.AddItemAsync( newItem ); } ); } async Task ExecuteLoadItemsCommand() { if ( IsBusy ) return; IsBusy = true; try { Mentors.Clear(); var mentors = _apiAccessService.GetMentors(); if ( mentors?.Any() ?? false ) { foreach ( var mentor in mentors ) { Mentors.Add( mentor ); } } Items.Clear(); var items = await _dataStore.GetItemsAsync( true ); foreach ( var item in items ) { Items.Add( item ); } } catch (Exception ex) { Debug.WriteLine( ex ); } finally { IsBusy = false; } } } }
32.551282
103
0.513194
[ "MIT" ]
bbenetskyy/mobile
CodingCoach/CodingCoach/ViewModels/ItemsViewModel.cs
2,541
C#
namespace catEncyption_GUI { partial class Form1 { /// <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.plainTextLabel = new System.Windows.Forms.Label(); this.meowTextLabel = new System.Windows.Forms.Label(); this.plainTextBox = new System.Windows.Forms.TextBox(); this.meowTextBox = new System.Windows.Forms.TextBox(); this.encodeButton = new System.Windows.Forms.Button(); this.decodeButton = new System.Windows.Forms.Button(); this.clearButton = new System.Windows.Forms.Button(); this.languageButton = new System.Windows.Forms.Button(); this.exceptionLabel = new System.Windows.Forms.Label(); this.SuspendLayout(); // // plainTextLabel // this.plainTextLabel.AutoSize = true; this.plainTextLabel.Location = new System.Drawing.Point(62, 38); this.plainTextLabel.Name = "plainTextLabel"; this.plainTextLabel.Size = new System.Drawing.Size(205, 24); this.plainTextLabel.TabIndex = 0; this.plainTextLabel.Text = "Plain Text (Uncoded)"; // // meowTextLabel // this.meowTextLabel.AutoSize = true; this.meowTextLabel.Location = new System.Drawing.Point(440, 38); this.meowTextLabel.Name = "meowTextLabel"; this.meowTextLabel.Size = new System.Drawing.Size(214, 24); this.meowTextLabel.TabIndex = 1; this.meowTextLabel.Text = "Meow Text (Encoded)"; // // plainTextBox // this.plainTextBox.Location = new System.Drawing.Point(66, 95); this.plainTextBox.Multiline = true; this.plainTextBox.Name = "plainTextBox"; this.plainTextBox.Size = new System.Drawing.Size(281, 291); this.plainTextBox.TabIndex = 2; this.plainTextBox.TextChanged += new System.EventHandler(this.plainTextBox_TextChanged); // // meowTextBox // this.meowTextBox.Location = new System.Drawing.Point(444, 95); this.meowTextBox.Multiline = true; this.meowTextBox.Name = "meowTextBox"; this.meowTextBox.Size = new System.Drawing.Size(281, 291); this.meowTextBox.TabIndex = 3; this.meowTextBox.TextChanged += new System.EventHandler(this.meowTextBox_TextChanged); // // encodeButton // this.encodeButton.Location = new System.Drawing.Point(104, 392); this.encodeButton.Name = "encodeButton"; this.encodeButton.Size = new System.Drawing.Size(195, 66); this.encodeButton.TabIndex = 4; this.encodeButton.Text = "Encode Plain Text"; this.encodeButton.UseVisualStyleBackColor = true; this.encodeButton.Click += new System.EventHandler(this.encodeButton_Click); // // decodeButton // this.decodeButton.Location = new System.Drawing.Point(477, 392); this.decodeButton.Name = "decodeButton"; this.decodeButton.Size = new System.Drawing.Size(216, 66); this.decodeButton.TabIndex = 4; this.decodeButton.Text = "Decode Meow Text"; this.decodeButton.UseVisualStyleBackColor = true; this.decodeButton.Click += new System.EventHandler(this.decodeButton_Click); // // clearButton // this.clearButton.Location = new System.Drawing.Point(354, 258); this.clearButton.Name = "clearButton"; this.clearButton.Size = new System.Drawing.Size(84, 73); this.clearButton.TabIndex = 5; this.clearButton.Text = "Clear"; this.clearButton.UseVisualStyleBackColor = true; this.clearButton.Click += new System.EventHandler(this.clearButton_Click); // // languageButton // this.languageButton.Location = new System.Drawing.Point(354, 148); this.languageButton.Name = "languageButton"; this.languageButton.Size = new System.Drawing.Size(84, 73); this.languageButton.TabIndex = 6; this.languageButton.Text = "喵"; this.languageButton.UseVisualStyleBackColor = true; this.languageButton.Click += new System.EventHandler(this.languageButton_Click); // // exceptionLabel // this.exceptionLabel.Location = new System.Drawing.Point(151, 461); this.exceptionLabel.Name = "exceptionLabel"; this.exceptionLabel.Size = new System.Drawing.Size(490, 109); this.exceptionLabel.TabIndex = 7; this.exceptionLabel.Text = "Fine"; this.exceptionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.exceptionLabel.Visible = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 651); this.Controls.Add(this.exceptionLabel); this.Controls.Add(this.languageButton); this.Controls.Add(this.clearButton); this.Controls.Add(this.decodeButton); this.Controls.Add(this.encodeButton); this.Controls.Add(this.meowTextBox); this.Controls.Add(this.plainTextBox); this.Controls.Add(this.meowTextLabel); this.Controls.Add(this.plainTextLabel); this.Name = "Form1"; this.Text = "cat encoder ver. 1.0"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label plainTextLabel; private System.Windows.Forms.Label meowTextLabel; private System.Windows.Forms.TextBox plainTextBox; private System.Windows.Forms.TextBox meowTextBox; private System.Windows.Forms.Button encodeButton; private System.Windows.Forms.Button decodeButton; private System.Windows.Forms.Button clearButton; private System.Windows.Forms.Button languageButton; private System.Windows.Forms.Label exceptionLabel; } }
44.723926
107
0.596708
[ "Apache-2.0" ]
t41372/catEncyption-GUI
catEncyption-GUI/Form1.Designer.cs
7,294
C#
using Microsoft.Extensions.Options; using Newtonsoft.Json; using System; using System.IO; using System.Threading.Tasks; using Omnia.CLI.Infrastructure; using System.ComponentModel; using Spectre.Cli; namespace Omnia.CLI.Commands.Subscriptions { [Description("Remove a given subscription configuration.")] public sealed class RemoveCommand : AsyncCommand<RemoveCommandSettings> { private readonly AppSettings _settings; public RemoveCommand(IOptions<AppSettings> options) { _settings = options.Value; } public override ValidationResult Validate(CommandContext context, RemoveCommandSettings settings) { if (string.IsNullOrWhiteSpace(settings.Name)) { return ValidationResult.Error($"{nameof(settings.Name)} is required"); } if (!_settings.Exists(settings.Name)) { return ValidationResult.Error($"Subscription \"{settings.Name}\" can't be found."); } return base.Validate(context, settings); } public override Task<int> ExecuteAsync(CommandContext context, RemoveCommandSettings settings) { var subscription = _settings.GetSubscription(settings.Name); _settings.Subscriptions.Remove(subscription); var directory = SettingsPathFactory.Path(); using (var file = File.CreateText(Path.Combine(directory, "appsettings.json"))) { var serializer = new JsonSerializer(); serializer.Serialize(file, _settings); } Console.WriteLine($"Subscription \"{settings.Name}\" configuration removed successfully."); return Task.FromResult((int)StatusCodes.Success); } } }
34.788462
105
0.644555
[ "MIT" ]
davidcaldas/omnia-cli
src/Console/Commands/Subscriptions/RemoveCommand.cs
1,811
C#
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace Npoi.Core.Util { using System; /// <summary> /// A List of short's; as full an implementation of the java.Util.List /// interface as possible, with an eye toward minimal creation of /// objects /// /// the mimicry of List is as follows: /// <ul> /// <li> if possible, operations designated 'optional' in the List /// interface are attempted</li> /// <li> wherever the List interface refers to an object, substitute /// short</li> /// <li> wherever the List interface refers to a Collection or List, /// substitute shortList</li> /// </ul> /// /// the mimicry is not perfect, however: /// <ul> /// <li> operations involving Iterators or ListIterators are not /// supported</li> /// <li> Remove(object) becomes RemoveValue to distinguish it from /// Remove(short index)</li> /// <li> subList is not supported</li> /// </ul> /// </summary> public class ShortList { private short[] _array; private int _limit; private static int _default_size = 128; /// <summary> /// create an shortList of default size /// </summary> public ShortList() : this(_default_size) { } /// <summary> /// create a copy of an existing shortList /// </summary> /// <param name="list">the existing shortList</param> public ShortList(ShortList list) : this(list._array.Length) { Array.Copy(list._array, 0, _array, 0, _array.Length); _limit = list._limit; } /// <summary> /// create an shortList with a predefined Initial size /// </summary> /// <param name="InitialCapacity">the size for the internal array</param> public ShortList(int InitialCapacity) { _array = new short[InitialCapacity]; _limit = 0; } /// <summary> /// add the specfied value at the specified index /// </summary> /// <param name="index">the index where the new value is to be Added</param> /// <param name="value">the new value</param> public void Add(int index, short value) { if (index > _limit) { throw new IndexOutOfRangeException(); } else if (index == _limit) { Add(value); } else { // index < limit -- insert into the middle if (_limit == _array.Length) { GrowArray(_limit * 2); } Array.Copy(_array, index, _array, index + 1, _limit - index); _array[index] = value; _limit++; } } /// <summary> /// Appends the specified element to the end of this list /// </summary> /// <param name="value">element to be Appended to this list.</param> /// <returns>return true (as per the general contract of the Collection.add method).</returns> public bool Add(short value) { if (_limit == _array.Length) { GrowArray(_limit * 2); } _array[_limit++] = value; return true; } /// <summary> /// Appends all of the elements in the specified collection to the /// end of this list, in the order that they are returned by the /// specified collection's iterator. The behavior of this /// operation is unspecified if the specified collection is /// modified while the operation is in progress. (Note that this /// will occur if the specified collection is this list, and it's /// nonempty.) /// </summary> /// <param name="c">collection whose elements are to be Added to this list.</param> /// <returns>return true if this list Changed as a result of the call.</returns> public bool AddAll(ShortList c) { if (c._limit != 0) { if ((_limit + c._limit) > _array.Length) { GrowArray(_limit + c._limit); } Array.Copy(c._array, 0, _array, _limit, c._limit); _limit += c._limit; } return true; } /// <summary> /// Inserts all of the elements in the specified collection into /// this list at the specified position. Shifts the element /// currently at that position (if any) and any subsequent elements /// to the right (increases their indices). The new elements will /// appear in this list in the order that they are returned by the /// specified collection's iterator. The behavior of this /// operation is unspecified if the specified collection is /// modified while the operation is in progress. (Note that this /// will occur if the specified collection is this list, and it's /// nonempty.) /// </summary> /// <param name="index">index at which to insert first element from the specified collection.</param> /// <param name="c">elements to be inserted into this list.</param> /// <returns>return true if this list Changed as a result of the call.</returns> /// <exception cref="IndexOutOfRangeException"> if the index is out of range (index &lt; 0 || index &gt; size())</exception> public bool AddAll(int index, ShortList c) { if (index > _limit) { throw new IndexOutOfRangeException(); } if (c._limit != 0) { if ((_limit + c._limit) > _array.Length) { GrowArray(_limit + c._limit); } // make a hole Array.Copy(_array, index, _array, index + c._limit, _limit - index); // fill it in Array.Copy(c._array, 0, _array, index, c._limit); _limit += c._limit; } return true; } /// <summary> /// Removes all of the elements from this list. This list will be /// empty After this call returns (unless it throws an exception). /// </summary> public void Clear() { _limit = 0; } /// <summary> /// Returns true if this list Contains the specified element. More /// formally, returns true if and only if this list Contains at /// least one element e such that o == e /// </summary> /// <param name="o">element whose presence in this list is to be Tested.</param> /// <returns>return true if this list Contains the specified element.</returns> public bool Contains(short o) { bool rval = false; for (int j = 0; !rval && (j < _limit); j++) { if (_array[j] == o) { rval = true; } } return rval; } /// <summary> /// Returns true if this list Contains all of the elements of the specified collection. /// </summary> /// <param name="c">collection to be Checked for Containment in this list.</param> /// <returns>return true if this list Contains all of the elements of the specified collection.</returns> public bool ContainsAll(ShortList c) { bool rval = true; if (this != c) { for (int j = 0; rval && (j < c._limit); j++) { if (!Contains(c._array[j])) { rval = false; } } } return rval; } /// <summary> /// Compares the specified object with this list for Equality. /// Returns true if and only if the specified object is also a /// list, both lists have the same size, and all corresponding /// pairs of elements in the two lists are Equal. (Two elements e1 /// and e2 are equal if e1 == e2.) In other words, two lists are /// defined to be equal if they contain the same elements in the /// same order. This defInition ensures that the Equals method /// works properly across different implementations of the List /// interface. /// </summary> /// <param name="o">the object to be Compared for Equality with this list.</param> /// <returns>return true if the specified object is equal to this list.</returns> public override bool Equals(object o) { bool rval = this == o; if (!rval && (o != null) && (o.GetType() == GetType())) { ShortList other = (ShortList)o; if (other._limit == _limit) { // assume match rval = true; for (int j = 0; rval && (j < _limit); j++) { rval = _array[j] == other._array[j]; } } } return rval; } /// <summary> /// Returns the element at the specified position in this list. /// </summary> /// <param name="index">index of element to return.</param> /// <returns>return the element at the specified position in this list.</returns> public short Get(int index) { if (index >= _limit) { throw new IndexOutOfRangeException(); } return _array[index]; } /// <summary> /// Returns the hash code value for this list. The hash code of a /// list is defined to be the result of the following calculation: /// /// <code> /// hashCode = 1; /// Iterator i = list.Iterator(); /// while (i.HasNext()) { /// object obj = i.Next(); /// hashCode = 31*hashCode + (obj==null ? 0 : obj.HashCode()); /// } /// </code> /// /// This ensures that list1.Equals(list2) implies that /// list1.HashCode()==list2.HashCode() for any two lists, list1 and /// list2, as required by the general contract of object.HashCode. /// </summary> /// <returns>return the hash code value for this list.</returns> public override int GetHashCode() { int hash = 0; for (int j = 0; j < _limit; j++) { hash = (31 * hash) + _array[j]; } return hash; } /// <summary> /// Returns the index in this list of the first occurrence of the /// specified element, or -1 if this list does not contain this /// element. More formally, returns the lowest index i such that /// (o == Get(i)), or -1 if there is no such index. /// </summary> /// <param name="o">element to search for.</param> /// <returns>the index in this list of the first occurrence of the /// specified element, or -1 if this list does not contain /// this element. /// </returns> public int IndexOf(short o) { int rval = 0; for (; rval < _limit; rval++) { if (o == _array[rval]) { break; } } if (rval == _limit) { rval = -1; // didn't find it } return rval; } /// <summary> /// Returns true if this list Contains no elements. /// </summary> /// <returns>return true if this list Contains no elements.</returns> public bool IsEmpty() { return _limit == 0; } /// <summary> /// Returns the index in this list of the last occurrence of the /// specified element, or -1 if this list does not contain this /// element. More formally, returns the highest index i such that /// (o == Get(i)), or -1 if there is no such index. /// </summary> /// <param name="o">element to search for.</param> /// <returns>return the index in this list of the last occurrence of the /// specified element, or -1 if this list does not contain this element.</returns> public int LastIndexOf(short o) { int rval = _limit - 1; for (; rval >= 0; rval--) { if (o == _array[rval]) { break; } } return rval; } /// <summary> /// Removes the element at the specified position in this list. /// Shifts any subsequent elements to the left (subtracts one from /// their indices). Returns the element that was Removed from the /// list. /// </summary> /// <param name="index">the index of the element to Removed.</param> /// <returns>return the element previously at the specified position.</returns> public short Remove(int index) { if (index >= _limit) { throw new IndexOutOfRangeException(); } short rval = _array[index]; Array.Copy(_array, index + 1, _array, index, _limit - index); _limit--; return rval; } /// <summary> /// Removes the first occurrence in this list of the specified /// element (optional operation). If this list does not contain /// the element, it is unChanged. More formally, Removes the /// element with the lowest index i such that (o.Equals(get(i))) /// (if such an element exists). /// </summary> /// <param name="o">element to be Removed from this list, if present.</param> /// <returns>return true if this list Contained the specified element.</returns> public bool RemoveValue(short o) { bool rval = false; for (int j = 0; !rval && (j < _limit); j++) { if (o == _array[j]) { Array.Copy(_array, j + 1, _array, j, _limit - j); _limit--; rval = true; } } return rval; } /// <summary> /// Removes from this list all the elements that are Contained in the specified collection /// </summary> /// <param name="c">collection that defines which elements will be removed from this list.</param> /// <returns>return true if this list Changed as a result of the call.</returns> public bool RemoveAll(ShortList c) { bool rval = false; for (int j = 0; j < c._limit; j++) { if (RemoveValue(c._array[j])) { rval = true; } } return rval; } /// <summary> /// Retains only the elements in this list that are Contained in /// the specified collection. In other words, Removes from this /// list all the elements that are not Contained in the specified /// collection. /// </summary> /// <param name="c">collection that defines which elements this Set will retain.</param> /// <returns>return true if this list Changed as a result of the call.</returns> public bool RetainAll(ShortList c) { bool rval = false; for (int j = 0; j < _limit;) { if (!c.Contains(_array[j])) { Remove(j); rval = true; } else { j++; } } return rval; } /// <summary> /// Replaces the element at the specified position in this list with the specified element /// </summary> /// <param name="index">index of element to Replace.</param> /// <param name="element">element to be stored at the specified position.</param> /// <returns>return the element previously at the specified position.</returns> public short Set(int index, short element) { if (index >= _limit) { throw new IndexOutOfRangeException(); } short rval = _array[index]; _array[index] = element; return rval; } /// <summary> /// Returns the number of elements in this list. If this list /// Contains more than int.MaxValue elements, returns /// int.MaxValue. /// </summary> /// <returns>return the number of elements in this shortList</returns> public int Size() { return _limit; } /// <summary> /// the number of elements in this shortList /// </summary> public int Count { get { return _limit; } } /// <summary> /// Returns an array Containing all of the elements in this list in /// proper sequence. Obeys the general contract of the /// Collection.ToArray method. /// </summary> /// <returns>an array Containing all of the elements in this list in /// proper sequence.</returns> public short[] ToArray() { short[] rval = new short[_limit]; Array.Copy(_array, 0, rval, 0, _limit); return rval; } /// <summary> /// Returns an array Containing all of the elements in this list in /// proper sequence. Obeys the general contract of the /// Collection.ToArray(object[]) method. /// </summary> /// <param name="a">the array into which the elements of this list are to /// be stored, if it is big enough; otherwise, a new array /// is allocated for this purpose.</param> /// <returns>return an array Containing the elements of this list.</returns> public short[] ToArray(short[] a) { short[] rval; if (a.Length == _limit) { Array.Copy(_array, 0, a, 0, _limit); rval = a; } else { rval = ToArray(); } return rval; } private void GrowArray(int new_size) { int size = (new_size == _array.Length) ? new_size + 1 : new_size; short[] new_array = new short[size]; Array.Copy(_array, 0, new_array, 0, _limit); _array = new_array; } } // end public class shortList }
36.203936
132
0.508647
[ "Apache-2.0" ]
Arch/Npoi.Core
src/Npoi.Core/Util/ShortList.cs
20,238
C#
using AbpApi.Localization; using Volo.Abp.AuditLogging; using Volo.Abp.BackgroundJobs; using Volo.Abp.FeatureManagement; using Volo.Abp.Identity; using Volo.Abp.IdentityServer; using Volo.Abp.Localization; using Volo.Abp.Localization.ExceptionHandling; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement; using Volo.Abp.SettingManagement; using Volo.Abp.TenantManagement; using Volo.Abp.Validation.Localization; using Volo.Abp.VirtualFileSystem; namespace AbpApi { [DependsOn( typeof(AbpAuditLoggingDomainSharedModule), typeof(AbpBackgroundJobsDomainSharedModule), typeof(AbpFeatureManagementDomainSharedModule), typeof(AbpIdentityDomainSharedModule), typeof(AbpIdentityServerDomainSharedModule), typeof(AbpPermissionManagementDomainSharedModule), typeof(AbpSettingManagementDomainSharedModule), typeof(AbpTenantManagementDomainSharedModule) )] public class AbpApiDomainSharedModule : AbpModule { public override void PreConfigureServices(ServiceConfigurationContext context) { AbpApiGlobalFeatureConfigurator.Configure(); AbpApiModuleExtensionConfigurator.Configure(); } public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpVirtualFileSystemOptions>(options => { options.FileSets.AddEmbedded<AbpApiDomainSharedModule>(); }); Configure<AbpLocalizationOptions>(options => { options.Resources .Add<AbpApiResource>("en") .AddBaseTypes(typeof(AbpValidationResource)) .AddVirtualJson("/Localization/AbpApi"); options.DefaultResourceType = typeof(AbpApiResource); }); Configure<AbpExceptionLocalizationOptions>(options => { options.MapCodeNamespace("AbpApi", typeof(AbpApiResource)); }); } } }
33.933333
86
0.683202
[ "MIT" ]
bartvanhoey/AbpApiConsumedByXamarin
XamarinForms/AbpApi/src/AbpApi.Domain.Shared/AbpApiDomainSharedModule.cs
2,038
C#
using UnityEngine; public class Weapon : ScriptableObject { public new string name = ""; public float baseDamage = 0f; public Sprite image; public AudioClip pickUpSound; public bool isGun = false; public int value = 0; }
17.769231
40
0.731602
[ "MIT" ]
edunne4/Zombs
Scripts/Weapon.cs
233
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Configuration; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Packaging.PackageExtraction; using NuGet.Packaging.Signing; using NuGet.ProjectManagement; using NuGet.ProjectManagement.Projects; using NuGet.Protocol.Core.Types; namespace NuGet.PackageManagement { public class PackageRestoreManager : IPackageRestoreManager { private ISourceRepositoryProvider SourceRepositoryProvider { get; } private ISolutionManager SolutionManager { get; } private ISettings Settings { get; } public event EventHandler<PackagesMissingStatusEventArgs> PackagesMissingStatusChanged; public event EventHandler<PackageRestoredEventArgs> PackageRestoredEvent; public event EventHandler<PackageRestoreFailedEventArgs> PackageRestoreFailedEvent; public PackageRestoreManager( ISourceRepositoryProvider sourceRepositoryProvider, ISettings settings, ISolutionManager solutionManager) { SourceRepositoryProvider = sourceRepositoryProvider ?? throw new ArgumentNullException(nameof(sourceRepositoryProvider)); Settings = settings ?? throw new ArgumentNullException(nameof(settings)); SolutionManager = solutionManager ?? throw new ArgumentNullException(nameof(solutionManager)); } public virtual async Task RaisePackagesMissingEventForSolutionAsync(string solutionDirectory, CancellationToken token) { // This method is called by different event handlers. // If the solutionDirectory is null, there's no need to do needless work. // Even though the solution closed even calls the synchronous ClearMissingEventForSolution // there's no guarantee that some weird ordering of events won't make the solutionDirectory null. var missing = false; if (!string.IsNullOrEmpty(solutionDirectory)) { var packages = await GetPackagesInSolutionAsync(solutionDirectory, token); missing = packages.Any(p => p.IsMissing); } PackagesMissingStatusChanged?.Invoke(this, new PackagesMissingStatusEventArgs(missing)); } // A synchronous method called during the solution closed event. This is done to avoid needless thread switching protected void ClearMissingEventForSolution() { PackagesMissingStatusChanged?.Invoke(this, new PackagesMissingStatusEventArgs(packagesMissing: false)); } /// <summary> /// Get the missing packages in the solution given the <paramref name="solutionDirectory"></paramref>. /// </summary> /// <returns> /// Returns a read-only dictionary of missing package references and the corresponding project names on which /// each missing package is installed. /// </returns> public async Task<IEnumerable<PackageRestoreData>> GetPackagesInSolutionAsync(string solutionDirectory, CancellationToken token) { var packageReferencesDictionary = await GetPackagesReferencesDictionaryAsync(token); return GetPackagesRestoreData(solutionDirectory, packageReferencesDictionary); } /// <summary> /// Get packages restore data for given package references. /// </summary> /// <param name="solutionDirectory">Current solution directory</param> /// <param name="packageReferencesDict">Dictionary of package reference with project names</param> /// <returns>List of packages restore data with missing package details.</returns> public IEnumerable<PackageRestoreData> GetPackagesRestoreData(string solutionDirectory, Dictionary<PackageReference, List<string>> packageReferencesDict) { var packages = new List<PackageRestoreData>(); if (packageReferencesDict?.Any() == true) { var nuGetPackageManager = GetNuGetPackageManager(solutionDirectory); foreach (var packageReference in packageReferencesDict.Keys) { var isMissing = false; if (!nuGetPackageManager.PackageExistsInPackagesFolder(packageReference.PackageIdentity)) { isMissing = true; } var projectNames = packageReferencesDict[packageReference]; Debug.Assert(projectNames != null); packages.Add(new PackageRestoreData(packageReference, projectNames, isMissing)); } } return packages; } private async Task<Dictionary<PackageReference, List<string>>> GetPackagesReferencesDictionaryAsync(CancellationToken token) { var packageReferencesDict = new Dictionary<PackageReference, List<string>>(new PackageReferenceComparer()); if (!await SolutionManager.IsSolutionAvailableAsync()) { return packageReferencesDict; } foreach (var nuGetProject in (await SolutionManager.GetNuGetProjectsAsync())) { // skip project k projects and build aware projects if (nuGetProject is INuGetIntegratedProject) { continue; } try { var nuGetProjectName = NuGetProject.GetUniqueNameOrName(nuGetProject); var installedPackageReferences = await nuGetProject.GetInstalledPackagesAsync(token); foreach (var installedPackageReference in installedPackageReferences) { List<string> projectNames = null; if (!packageReferencesDict.TryGetValue(installedPackageReference, out projectNames)) { projectNames = new List<string>(); packageReferencesDict.Add(installedPackageReference, projectNames); } projectNames.Add(nuGetProjectName); } } catch (Exception) { // ignore failed projects, and continue with other projects } } return packageReferencesDict; } /// <summary> /// Restores missing packages for the entire solution /// </summary> /// <returns></returns> public virtual async Task<PackageRestoreResult> RestoreMissingPackagesInSolutionAsync( string solutionDirectory, INuGetProjectContext nuGetProjectContext, CancellationToken token) { var packageReferencesDictionary = await GetPackagesReferencesDictionaryAsync(token); // When this method is called, the step to compute if a package is missing is implicit. Assume it is true var packages = packageReferencesDictionary.Select(p => { Debug.Assert(p.Value != null); return new PackageRestoreData(p.Key, p.Value, isMissing: true); }); using (var cacheContext = new SourceCacheContext()) { var logger = new LoggerAdapter(nuGetProjectContext); var downloadContext = new PackageDownloadContext(cacheContext) { ParentId = nuGetProjectContext.OperationId, ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, logger) }; return await RestoreMissingPackagesAsync( solutionDirectory, packages, nuGetProjectContext, downloadContext, NullLogger.Instance, token); } } /// <summary> /// Restores missing packages for the entire solution /// </summary> /// <returns></returns> public virtual async Task<PackageRestoreResult> RestoreMissingPackagesInSolutionAsync( string solutionDirectory, INuGetProjectContext nuGetProjectContext, ILogger logger, CancellationToken token) { var packageReferencesDictionary = await GetPackagesReferencesDictionaryAsync(token); // When this method is called, the step to compute if a package is missing is implicit. Assume it is true var packages = packageReferencesDictionary.Select(p => { Debug.Assert(p.Value != null); return new PackageRestoreData(p.Key, p.Value, isMissing: true); }); using (var cacheContext = new SourceCacheContext()) { var adapterLogger = new LoggerAdapter(nuGetProjectContext); var downloadContext = new PackageDownloadContext(cacheContext) { ParentId = nuGetProjectContext.OperationId, ClientPolicyContext = ClientPolicyContext.GetClientPolicy(Settings, adapterLogger) }; return await RestoreMissingPackagesAsync( solutionDirectory, packages, nuGetProjectContext, downloadContext, logger, token); } } public virtual Task<PackageRestoreResult> RestoreMissingPackagesAsync(string solutionDirectory, IEnumerable<PackageRestoreData> packages, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext, CancellationToken token) { if (packages == null) { throw new ArgumentNullException(nameof(packages)); } var nuGetPackageManager = GetNuGetPackageManager(solutionDirectory); var packageRestoreContext = new PackageRestoreContext( nuGetPackageManager, packages, token, PackageRestoredEvent, PackageRestoreFailedEvent, sourceRepositories: null, maxNumberOfParallelTasks: PackageManagementConstants.DefaultMaxDegreeOfParallelism, logger: NullLogger.Instance); if (nuGetProjectContext.PackageExtractionContext == null) { nuGetProjectContext.PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(Settings, packageRestoreContext.Logger), packageRestoreContext.Logger); } return RestoreMissingPackagesAsync(packageRestoreContext, nuGetProjectContext, downloadContext); } public virtual Task<PackageRestoreResult> RestoreMissingPackagesAsync(string solutionDirectory, IEnumerable<PackageRestoreData> packages, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext, ILogger logger, CancellationToken token) { if (packages == null) { throw new ArgumentNullException(nameof(packages)); } var nuGetPackageManager = GetNuGetPackageManager(solutionDirectory); var packageRestoreContext = new PackageRestoreContext( nuGetPackageManager, packages, token, PackageRestoredEvent, PackageRestoreFailedEvent, sourceRepositories: null, maxNumberOfParallelTasks: PackageManagementConstants.DefaultMaxDegreeOfParallelism, logger: logger); if (nuGetProjectContext.PackageExtractionContext == null) { nuGetProjectContext.PackageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv2, PackageExtractionBehavior.XmlDocFileSaveMode, ClientPolicyContext.GetClientPolicy(Settings, packageRestoreContext.Logger), packageRestoreContext.Logger); } return RestoreMissingPackagesAsync(packageRestoreContext, nuGetProjectContext, downloadContext); } private NuGetPackageManager GetNuGetPackageManager(string solutionDirectory) { var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(solutionDirectory, Settings); return new NuGetPackageManager( SourceRepositoryProvider, Settings, packagesFolderPath); } /// <summary> /// The static method which takes in all the possible parameters /// </summary> /// <returns>Returns true if at least one of the packages needed to be restored and got restored</returns> /// <remarks> /// Best use case is 'nuget.exe restore .sln' where there is no project loaded and there is no SolutionManager. /// The references are obtained by parsing of solution file and by using PackagesConfigReader. In this case, /// you don't construct an object of PackageRestoreManager, /// but just the NuGetPackageManager using constructor that does not need the SolutionManager, and, optionally /// register to events and/or specify the source repositories /// </remarks> public static async Task<PackageRestoreResult> RestoreMissingPackagesAsync( PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext) { if (packageRestoreContext == null) { throw new ArgumentNullException(nameof(packageRestoreContext)); } if (nuGetProjectContext == null) { throw new ArgumentNullException(nameof(nuGetProjectContext)); } ActivityCorrelationId.StartNew(); var missingPackages = packageRestoreContext.Packages.Where(p => p.IsMissing).ToList(); if (!missingPackages.Any()) { return new PackageRestoreResult(true, Enumerable.Empty<PackageIdentity>()); } // It is possible that the dictionary passed in may not have used the PackageReferenceComparer. // So, just to be sure, create a hashset with the keys from the dictionary using the PackageReferenceComparer // Now, we are guaranteed to not restore the same package more than once var hashSetOfMissingPackageReferences = new HashSet<PackageReference>(missingPackages.Select(p => p.PackageReference), new PackageReferenceComparer()); nuGetProjectContext.PackageExtractionContext.CopySatelliteFiles = false; packageRestoreContext.Token.ThrowIfCancellationRequested(); var attemptedPackages = await ThrottledPackageRestoreAsync( hashSetOfMissingPackageReferences, packageRestoreContext, nuGetProjectContext, downloadContext); packageRestoreContext.Token.ThrowIfCancellationRequested(); await ThrottledCopySatelliteFilesAsync( hashSetOfMissingPackageReferences, packageRestoreContext, nuGetProjectContext); return new PackageRestoreResult( attemptedPackages.All(p => p.Restored), attemptedPackages.Select(p => p.Package.PackageIdentity).ToList()); } /// <summary> /// ThrottledPackageRestoreAsync method throttles the number of tasks created to perform package restore in /// parallel /// The maximum number of parallel tasks that may be created can be specified via /// <paramref name="packageRestoreContext" /> /// The method creates a ConcurrentQueue of passed in <paramref name="packageReferences" />. And, creates a /// fixed number of tasks /// that dequeue from the ConcurrentQueue and perform package restore. So, this method should pre-populate the /// queue and must not enqueued to by other methods /// </summary> private static async Task<IEnumerable<AttemptedPackage>> ThrottledPackageRestoreAsync( HashSet<PackageReference> packageReferences, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext) { var packageReferencesQueue = new ConcurrentQueue<PackageReference>(packageReferences); var tasks = new List<Task<List<AttemptedPackage>>>(); for (var i = 0; i < Math.Min(packageRestoreContext.MaxNumberOfParallelTasks, packageReferences.Count); i++) { tasks.Add(Task.Run(() => PackageRestoreRunnerAsync( packageReferencesQueue, packageRestoreContext, nuGetProjectContext, downloadContext))); } return (await Task.WhenAll(tasks)).SelectMany(package => package); } /// <summary> /// This is the runner which dequeues package references from <paramref name="packageReferencesQueue" />, and /// performs package restore /// Note that this method should only Dequeue from the concurrent queue and not Enqueue /// </summary> private static async Task<List<AttemptedPackage>> PackageRestoreRunnerAsync( ConcurrentQueue<PackageReference> packageReferencesQueue, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext) { PackageReference currentPackageReference = null; var attemptedPackages = new List<AttemptedPackage>(); while (packageReferencesQueue.TryDequeue(out currentPackageReference)) { var attemptedPackage = await RestorePackageAsync( currentPackageReference, packageRestoreContext, nuGetProjectContext, downloadContext); attemptedPackages.Add(attemptedPackage); } return attemptedPackages; } /// <summary> /// ThrottledCopySatelliteFilesAsync method throttles the number of tasks created to perform copy satellite /// files in parallel /// The maximum number of parallel tasks that may be created can be specified via /// <paramref name="packageRestoreContext" /> /// The method creates a ConcurrentQueue of passed in <paramref name="packageReferences" />. And, creates a /// fixed number of tasks /// that dequeue from the ConcurrentQueue and perform copying of satellite files. So, this method should /// pre-populate the queue and must not enqueued to by other methods /// </summary> private static Task ThrottledCopySatelliteFilesAsync(HashSet<PackageReference> packageReferences, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext) { var packageReferencesQueue = new ConcurrentQueue<PackageReference>(packageReferences); var tasks = new List<Task>(); for (var i = 0; i < Math.Min(packageRestoreContext.MaxNumberOfParallelTasks, packageReferences.Count); i++) { tasks.Add(Task.Run(() => CopySatelliteFilesRunnerAsync(packageReferencesQueue, packageRestoreContext, nuGetProjectContext))); } return Task.WhenAll(tasks); } private static async Task<AttemptedPackage> RestorePackageAsync( PackageReference packageReference, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext, PackageDownloadContext downloadContext) { Exception exception = null; var restored = false; try { restored = await packageRestoreContext.PackageManager.RestorePackageAsync( packageReference.PackageIdentity, nuGetProjectContext, downloadContext, packageRestoreContext.SourceRepositories, packageRestoreContext.Token); } catch (Exception ex) { exception = ex; } packageRestoreContext.PackageRestoredEvent?.Invoke(null, new PackageRestoredEventArgs(packageReference.PackageIdentity, restored)); // PackageReferences cannot be null here if (exception != null) { if (!string.IsNullOrEmpty(exception.Message)) { nuGetProjectContext.Log(MessageLevel.Warning, exception.Message); } if (packageRestoreContext.PackageRestoreFailedEvent != null) { var packageReferenceComparer = new PackageReferenceComparer(); var packageRestoreData = packageRestoreContext.Packages .Where(p => packageReferenceComparer.Equals(p.PackageReference, packageReference)) .SingleOrDefault(); if (packageRestoreData != null) { Debug.Assert(packageRestoreData.ProjectNames != null); packageRestoreContext.PackageRestoreFailedEvent( null, new PackageRestoreFailedEventArgs(packageReference, exception, packageRestoreData.ProjectNames)); } } } return new AttemptedPackage { Restored = restored, Package = packageReference }; } /// <summary> /// This is the runner which dequeues package references from <paramref name="packageReferencesQueue" />, and /// performs copying of satellite files /// Note that this method should only Dequeue from the concurrent queue and not Enqueue /// </summary> private static async Task CopySatelliteFilesRunnerAsync(ConcurrentQueue<PackageReference> packageReferencesQueue, PackageRestoreContext packageRestoreContext, INuGetProjectContext nuGetProjectContext) { PackageReference currentPackageReference = null; while (packageReferencesQueue.TryDequeue(out currentPackageReference)) { var result = await packageRestoreContext.PackageManager.CopySatelliteFilesAsync( currentPackageReference.PackageIdentity, nuGetProjectContext, packageRestoreContext.Token); } } private class AttemptedPackage { public bool Restored { get; set; } public PackageReference Package { get; set; } } } }
44.552876
163
0.623844
[ "Apache-2.0" ]
BlackGad/NuGet.Client
src/NuGet.Core/NuGet.PackageManagement/IDE/PackageRestoreManager.cs
24,014
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace PdfiumViewer { /// <summary> /// The text and rect. /// </summary> public class PdfTextAndRect { /// <summary> /// The text /// </summary> public string Text { get; } /// <summary> /// The rectangle which surrounds text /// </summary> public RectangleF Rect { get; } /// <summary> /// Construct /// </summary> /// <param name="text">The text</param> /// <param name="rect">The rectangle which surrounds text</param> public PdfTextAndRect(string text, RectangleF rect) { Text = text; Rect = rect; } } }
23.285714
74
0.503067
[ "Apache-2.0" ]
HiraokaHyperTools/PdfiumViewer
PdfiumViewer/PdfTextAndRect.cs
817
C#
using NBitcoin; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Blockchain.TransactionOutputs; using WalletWasabi.Helpers; using WalletWasabi.Tests.Helpers; using WalletWasabi.WabiSabi; using WalletWasabi.WabiSabi.Backend; using WalletWasabi.WabiSabi.Backend.Rounds; using WalletWasabi.WabiSabi.Client; using WalletWasabi.WabiSabi.Models; using WalletWasabi.WabiSabi.Models.MultipartyTransaction; using Xunit; namespace WalletWasabi.Tests.UnitTests.WabiSabi.Backend.PhaseStepping; public class StepOutputRegistrationTests { [Fact] public async Task AllBobsRegisteredAsync() { WabiSabiConfig cfg = new() { MaxInputCountByRound = 2, MinInputCountByRoundMultiplier = 0.5 }; var (key1, coin1, key2, coin2) = WabiSabiFactory.CreateCoinKeyPairs(); var mockRpc = WabiSabiFactory.CreatePreconfiguredRpcClient(coin1.Coin, coin2.Coin); using Arena arena = await WabiSabiFactory.CreateAndStartArenaAsync(cfg, mockRpc); var (round, arenaClient, alices) = await CreateRoundWithTwoConfirmedConnectionsAsync(arena, key1, coin1, key2, coin2); var (amountCredentials1, vsizeCredentials1) = (alices[0].IssuedAmountCredentials, alices[0].IssuedVsizeCredentials); var (amountCredentials2, vsizeCredentials2) = (alices[1].IssuedAmountCredentials, alices[1].IssuedVsizeCredentials); // Register outputs. var bobClient = new BobClient(round.Id, arenaClient); using var destKey1 = new Key(); await bobClient.RegisterOutputAsync( destKey1.PubKey.WitHash.ScriptPubKey, amountCredentials1.Take(ProtocolConstants.CredentialNumber), vsizeCredentials1.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); using var destKey2 = new Key(); await bobClient.RegisterOutputAsync( destKey2.PubKey.WitHash.ScriptPubKey, amountCredentials2.Take(ProtocolConstants.CredentialNumber), vsizeCredentials2.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); foreach (var alice in alices) { await alice.ReadyToSignAsync(CancellationToken.None); } await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Equal(Phase.TransactionSigning, round.Phase); var tx = round.Assert<SigningState>().CreateTransaction(); Assert.Equal(2, tx.Inputs.Count); Assert.Equal(2, tx.Outputs.Count); await arena.StopAsync(CancellationToken.None); } [Fact] public async Task SomeBobsRegisteredTimeoutAsync() { WabiSabiConfig cfg = new() { MaxInputCountByRound = 2, MinInputCountByRoundMultiplier = 0.5, OutputRegistrationTimeout = TimeSpan.Zero }; var (key1, coin1, key2, coin2) = WabiSabiFactory.CreateCoinKeyPairs(); var mockRpc = WabiSabiFactory.CreatePreconfiguredRpcClient(coin1.Coin, coin2.Coin); using Arena arena = await WabiSabiFactory.CreateAndStartArenaAsync(cfg, mockRpc); var (round, arenaClient, alices) = await CreateRoundWithTwoConfirmedConnectionsAsync(arena, key1, coin1, key2, coin2); var (amountCredentials1, vsizeCredentials1) = (alices[0].IssuedAmountCredentials, alices[0].IssuedVsizeCredentials); var (amountCredentials2, vsizeCredentials2) = (alices[1].IssuedAmountCredentials, alices[1].IssuedVsizeCredentials); // Register outputs. var bobClient = new BobClient(round.Id, arenaClient); using var destKey = new Key(); await bobClient.RegisterOutputAsync( destKey.PubKey.WitHash.ScriptPubKey, amountCredentials1.Take(ProtocolConstants.CredentialNumber), vsizeCredentials1.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Equal(Phase.TransactionSigning, round.Phase); var tx = round.Assert<SigningState>().CreateTransaction(); Assert.Equal(2, tx.Inputs.Count); Assert.Equal(2, tx.Outputs.Count); Assert.Contains(cfg.BlameScript, tx.Outputs.Select(x => x.ScriptPubKey)); await arena.StopAsync(CancellationToken.None); } [Fact] public async Task DiffTooSmallToBlameAsync() { WabiSabiConfig cfg = new() { MaxInputCountByRound = 2, MinInputCountByRoundMultiplier = 0.5, OutputRegistrationTimeout = TimeSpan.Zero }; var (key1, coin1, key2, coin2) = WabiSabiFactory.CreateCoinKeyPairs(); var mockRpc = WabiSabiFactory.CreatePreconfiguredRpcClient(coin1.Coin, coin2.Coin); using Arena arena = await WabiSabiFactory.CreateAndStartArenaAsync(cfg, mockRpc); var (round, arenaClient, alices) = await CreateRoundWithTwoConfirmedConnectionsAsync(arena, key1, coin1, key2, coin2); var (amountCredentials1, vsizeCredentials1) = (alices[0].IssuedAmountCredentials, alices[0].IssuedVsizeCredentials); var (amountCredentials2, vsizeCredentials2) = (alices[1].IssuedAmountCredentials, alices[1].IssuedVsizeCredentials); // Register outputs. var bobClient = new BobClient(round.Id, arenaClient); using var destKey1 = new Key(); using var destKey2 = new Key(); await bobClient.RegisterOutputAsync( destKey1.PubKey.WitHash.ScriptPubKey, amountCredentials1.Take(ProtocolConstants.CredentialNumber), vsizeCredentials1.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); await bobClient.RegisterOutputAsync( destKey2.PubKey.WitHash.ScriptPubKey, amountCredentials2.Take(ProtocolConstants.CredentialNumber), vsizeCredentials2.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); // Add another input. The input must be able to pay for itself, but // the remaining amount after deducting the fees needs to be less // than the minimum. var txParams = round.Assert<ConstructionState>().Parameters; var extraAlice = WabiSabiFactory.CreateAlice(txParams.FeeRate.GetFee(Constants.P2wpkhInputVirtualSize) + txParams.AllowedOutputAmounts.Min - new Money(1L), round); round.Alices.Add(extraAlice); round.CoinjoinState = round.Assert<ConstructionState>().AddInput(extraAlice.Coin); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Equal(Phase.TransactionSigning, round.Phase); var tx = round.Assert<SigningState>().CreateTransaction(); Assert.Equal(3, tx.Inputs.Count); Assert.Equal(2, tx.Outputs.Count); Assert.DoesNotContain(cfg.BlameScript, tx.Outputs.Select(x => x.ScriptPubKey)); await arena.StopAsync(CancellationToken.None); } [Fact] public async Task DoesntSwitchImmaturelyAsync() { WabiSabiConfig cfg = new() { MaxInputCountByRound = 2, MinInputCountByRoundMultiplier = 0.5 }; var (key1, coin1, key2, coin2) = WabiSabiFactory.CreateCoinKeyPairs(); var mockRpc = WabiSabiFactory.CreatePreconfiguredRpcClient(coin1.Coin, coin2.Coin); using Arena arena = await WabiSabiFactory.CreateAndStartArenaAsync(cfg, mockRpc); var (round, arenaClient, alices) = await CreateRoundWithTwoConfirmedConnectionsAsync(arena, key1, coin1, key2, coin2); var (amountCredentials1, vsizeCredentials1) = (alices[0].IssuedAmountCredentials, alices[0].IssuedVsizeCredentials); var (amountCredentials2, vsizeCredentials2) = (alices[1].IssuedAmountCredentials, alices[1].IssuedVsizeCredentials); // Register outputs. var bobClient = new BobClient(round.Id, arenaClient); using var destKey = new Key(); await bobClient.RegisterOutputAsync( destKey.PubKey.WitHash.ScriptPubKey, amountCredentials1.Take(ProtocolConstants.CredentialNumber), vsizeCredentials1.Take(ProtocolConstants.CredentialNumber), CancellationToken.None); await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Equal(Phase.OutputRegistration, round.Phase); await arena.StopAsync(CancellationToken.None); } private async Task<(Round Round, ArenaClient ArenaClient, AliceClient[] alices)> CreateRoundWithTwoConfirmedConnectionsAsync(Arena arena, Key key1, SmartCoin coin1, Key key2, SmartCoin coin2) { // Create the round. await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); var arenaClient = WabiSabiFactory.CreateArenaClient(arena); var round = Assert.Single(arena.Rounds); round.MaxVsizeAllocationPerAlice = 11 + 31 + MultipartyTransactionParameters.SharedOverhead; using RoundStateUpdater roundStateUpdater = new(TimeSpan.FromSeconds(2), arena); await roundStateUpdater.StartAsync(CancellationToken.None); var identificationKey = new Key(); var task1 = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, coin1, key1.GetBitcoinSecret(round.Network), identificationKey, roundStateUpdater, CancellationToken.None); var task2 = AliceClient.CreateRegisterAndConfirmInputAsync(RoundState.FromRound(round), arenaClient, coin2, key2.GetBitcoinSecret(round.Network), identificationKey, roundStateUpdater, CancellationToken.None); while (Phase.ConnectionConfirmation != round.Phase) { await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); } await Task.WhenAll(task1, task2); var aliceClient1 = task1.Result; var aliceClient2 = task2.Result; await arena.TriggerAndWaitRoundAsync(TimeSpan.FromSeconds(21)); Assert.Equal(Phase.OutputRegistration, round.Phase); await roundStateUpdater.StopAsync(CancellationToken.None); return (round, arenaClient, new[] { aliceClient1, aliceClient2 }); } }
41.420814
210
0.786978
[ "MIT" ]
dorisoy/WalletWasabi
WalletWasabi.Tests/UnitTests/WabiSabi/Backend/PhaseStepping/StepOutputRegistrationTests.cs
9,154
C#
using FluentValidation; namespace CulinaCloud.CookBook.Application.Ingredients.Queries.GetIngredient { public class GetIngredientQueryValidator : AbstractValidator<GetIngredientQuery> { public GetIngredientQueryValidator() { RuleFor(x => x.Id) .NotEmpty(); } } }
25.230769
84
0.658537
[ "MIT" ]
zayscue/culina-cloud
src/Services/CookBook/CookBook.Application/Ingredients/Queries/GetIngredient/GetIngredientQueryValidator.cs
330
C#
using System; using System.Linq; using Lightweight.Model.Entities; using NHibernate; using NHibernate.Linq; using System.Collections.Generic; using System.Transactions; using Lightweight.Business.Exceptions; namespace Lightweight.Business.Repository.Entities { public class UserRepository : Repository<Guid, User> { public UserRepository(ISession session) : base(session) { } public UserRepository(Repository<Guid, User> repository) : base(repository.Session) { } public string GetUserNameByEmail(string email, Guid tenantId) { BeginTransaction(); var q = from user in All() where user.Email == email && user.Tenant.Id == tenantId select user.UserName; string username = q.SingleOrDefault(); CommitTransaction(); return username; } public User GetUserByName(string username, Guid tenantId) { BeginTransaction(); var q = from user in All() where user.UserName == username && user.Tenant.Id == tenantId select user; var result = q.SingleOrDefault(); CommitTransaction(); return result; } public User GetUserById(Guid userId, Guid tenantId) { BeginTransaction(); var q = from user in All() where user.Id == userId && user.Tenant.Id == tenantId select user; var result = q.SingleOrDefault(); CommitTransaction(); return result; } public User GetUserWithRolesById(Guid userId, Guid tenantId) { BeginTransaction(); var q = from user in All() where user.Id == userId && user.Tenant.Id == tenantId select user; q = q.Fetch(u => u.Roles); var result = q.SingleOrDefault(); CommitTransaction(); return result; } // checks if there is another user with the same name or email on the specified tenant public bool IsUserNameAndEmailUnique(string username, string email, Guid tenantId) { BeginTransaction(); var q = from user in All() where user.Tenant.Id == tenantId && (user.UserName == username || user.Email == email) select user.Id; int found = q.Count(); CommitTransaction(); return found == 0; } // returns a list of all users for the specified tenant public List<User> GetAllUsers(Guid tenantId, int? pageIndex = null, int? pageSize = null) { BeginTransaction(); var q = from user in All() where user.Tenant.Id == tenantId select user; if (pageIndex.HasValue && pageSize.HasValue) { if (pageIndex < 1) pageIndex = 1; if (pageSize.Value > 0 && pageSize < int.MaxValue) q = q.Skip((pageIndex.Value - 1) * pageSize.Value).Take(pageSize.Value); } q = q.Fetch(u => u.Profile); var users = q.ToList(); CommitTransaction(); return users; } public UserProfile GetProfileByUserName(string username, Guid tenantId, out Guid userId) { BeginTransaction(); var qu = from user in All() where user.UserName == username && user.Tenant.Id == tenantId select user.Id; var _userId = qu.SingleOrDefault(); var qp = from user in All() where user.Id == _userId select user.Profile; var profile = qp.SingleOrDefault(); CommitTransaction(); userId = _userId; return profile; } public void SaveUser(User user) { using (TransactionScope ts = new TransactionScope()) { var exists = user.Id == default(Guid) && GetUserByName(user.UserName, user.Tenant.Id) != null; if (exists) throw new BusinessException("Failed to save user. A user with the same username already exists."); Save(user); ts.Complete(); } } public void SaveProfile(UserProfile profile) { new Repository<Guid, UserProfile>(_session) .Save(profile); } public void UpdatePassword(string username, Guid tenantId, string p) { using (TransactionScope ts = new TransactionScope()) { BeginTransaction(); var usr = (from user in All() where user.UserName == username && user.Tenant.Id == tenantId select user).SingleOrDefault(); CommitTransaction(); usr.Hash = p; Update(usr); ts.Complete(); } } } }
26.835821
118
0.502039
[ "MIT" ]
noir2501/lightweight
src/Lightweight.Business/Repository/Entities/UserRepository.cs
5,396
C#
namespace Recipes.Data.Configurations { using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Recipes.Data.Models; public class RecipeLikeConfiguration : IEntityTypeConfiguration<RecipeLike> { public void Configure(EntityTypeBuilder<RecipeLike> recipeLike) { recipeLike .HasKey(rl => new { rl.RecipeId, rl.UserId }); } } }
27.8125
79
0.676404
[ "MIT" ]
ChristinaNikolova/Recipes---React
server/RecipesWebApi/Data/Recipes.Data/Configurations/RecipeLikeConfiguration.cs
447
C#
using NHibernate; using Pizza.Framework.Operations; using Pizza.Framework.Persistence.Transactions; using Pizza.Framework.TestTypes.Model.PersistenceModels; using Pizza.Framework.TestTypes.ViewModels.Customers; using Pizza.Framework.ValueInjection; namespace Pizza.Framework.IntegrationTests.SutServices { [Transactional] public class CustomersCrudService : CrudServiceBase<Customer, CustomerGridModel, CustomerDetailsModel, CustomerEditModel, CustomerCreateModel>, ICustomersCrudService { public CustomersCrudService(ISession session) : base(session) { } public void FailingUpdate(CustomerEditModel editModel) { var persistenceModel = this.session.Get<Customer>(editModel.Id); persistenceModel.InjectFromViewModel(editModel); this.session.Update(persistenceModel); } } }
34.230769
115
0.738202
[ "MIT" ]
dwdkls/pizzamvc
tests/Pizza.Framework.IntegrationTests/SutServices/CustomersCrudService.cs
892
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Core.Data; namespace Microsoft.ML.Runtime.Data { /// <summary> /// An estimator class for composite data reader. /// It can be used to build a 'trainable smart data reader', although this pattern is not very common. /// </summary> public sealed class CompositeReaderEstimator<TSource, TLastTransformer> : IDataReaderEstimator<TSource, CompositeDataReader<TSource, TLastTransformer>> where TLastTransformer : class, ITransformer { private readonly IDataReaderEstimator<TSource, IDataReader<TSource>> _start; private readonly EstimatorChain<TLastTransformer> _estimatorChain; public CompositeReaderEstimator(IDataReaderEstimator<TSource, IDataReader<TSource>> start, EstimatorChain<TLastTransformer> estimatorChain = null) { Contracts.CheckValue(start, nameof(start)); Contracts.CheckValueOrNull(estimatorChain); _start = start; _estimatorChain = estimatorChain ?? new EstimatorChain<TLastTransformer>(); // REVIEW: enforce that estimator chain can read the reader's schema. // Right now it throws. // GetOutputSchema(); } public CompositeDataReader<TSource, TLastTransformer> Fit(TSource input) { var start = _start.Fit(input); var idv = start.Read(input); var xfChain = _estimatorChain.Fit(idv); return new CompositeDataReader<TSource, TLastTransformer>(start, xfChain); } public SchemaShape GetOutputSchema() { var shape = _start.GetOutputSchema(); return _estimatorChain.GetOutputSchema(shape); } /// <summary> /// Append another estimator to the end. /// </summary> public CompositeReaderEstimator<TSource, TNewTrans> Append<TNewTrans>(IEstimator<TNewTrans> estimator) where TNewTrans : class, ITransformer { Contracts.CheckValue(estimator, nameof(estimator)); return new CompositeReaderEstimator<TSource, TNewTrans>(_start, _estimatorChain.Append(estimator)); } } }
39.466667
155
0.671453
[ "MIT" ]
wtgodbe/machinelearning
src/Microsoft.ML.Data/DataLoadSave/CompositeReaderEstimator.cs
2,370
C#
using Microsoft.AspNetCore.Authorization; namespace Microsoft.Extensions.DependencyInjection { public static class Authorization { public static AuthorizationOptions SetupAuthorizationPolicies(this AuthorizationOptions options) { //https://docs.asp.net/en/latest/security/authorization/policies.html options.AddCloudscribeCoreDefaultPolicies(); options.AddCloudscribeLoggingDefaultPolicy(); options.AddCloudscribeCoreSimpleContentIntegrationDefaultPolicies(); // this is what the above extension adds //options.AddPolicy( // "BlogEditPolicy", // authBuilder => // { // //authBuilder.RequireClaim("blogId"); // authBuilder.RequireRole("Administrators"); // } // ); //options.AddPolicy( // "PageEditPolicy", // authBuilder => // { // authBuilder.RequireRole("Administrators"); // }); options.AddPolicy( "FileManagerPolicy", authBuilder => { authBuilder.RequireRole("Administrators", "Content Administrators"); }); options.AddPolicy( "FileManagerDeletePolicy", authBuilder => { authBuilder.RequireRole("Administrators", "Content Administrators"); }); // add other policies here return options; } } }
29.727273
104
0.525382
[ "Apache-2.0" ]
exeGesIS-SDM/content-templates
src/sourceDev.WebApp/Config/Authorization.cs
1,637
C#
using BBI.Game.Data; namespace Subsystem.Wrappers { public class CostAttributesWrapper : CostAttributes { public CostAttributesWrapper(CostAttributes other) { Resource1Cost = other.Resource1Cost; Resource2Cost = other.Resource2Cost; } public int Resource1Cost { get; set; } public int Resource2Cost { get; set; } } }
19.941176
52
0.743363
[ "MIT" ]
AGameAnx/Subsystem
Subsystem/Wrappers/Ability/CostAttributesWrapper.cs
341
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using NOtification_Backend.Logging; using NOtification_Backend.Connections; using System.Threading; namespace NOtification_Backend { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Controller.Controller con = Controller.Controller.Instance; } } }
22.375
71
0.670391
[ "MIT" ]
Kezuino/SMPT31
NOtification Backend/NOtification Backend/Program.cs
539
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace TSS { public class Player : MonoBehaviour { public Vector2 touch1, touch2, angle; public float r; public GameObject shot; public bool s; public IEnumerator CoolDown(){ WaitForSeconds w = new WaitForSeconds(.2f); WaitUntil cs = new WaitUntil(() => s); while(true){ yield return cs; yield return w; s = false; } } public void Move(Touch t){ touch1 = t.position; this.transform.position = touch1; } public void Aim(Touch t){ touch2 = t.position; angle = touch2 - touch1; angle.Normalize(); r = Vector2.SignedAngle(Vector2.right, angle); if(t.phase == TouchPhase.Ended){ r = 90; } this.transform.rotation = Quaternion.Euler(0,0,r); } public void Shoot(){ s = true; Vector3 pos = new Vector3(this.transform.position.x + angle.x, this.transform.position.y + angle.y, 0); GameObject bullet = Instantiate<GameObject>(shot, pos, Quaternion.Euler(0,0,r)); bullet.GetComponent<Rigidbody2D>().velocity = (angle * 600); } } }
26.568182
107
0.630453
[ "MIT" ]
Plet53/UnnamedMobileTwinStickShooterExperiment
Assets/Scripts/TSS.cs
1,169
C#
namespace UnionFind { public class WeightedQuickUnion : IUnionFind { private int componentCount; private int[] dots; private int[] componentSize; public WeightedQuickUnion(int N) { this.componentCount = N; dots = new int[N]; componentSize = new int[N]; for (int i=0; i<N; i++) { dots[i] = i; componentSize[i] = 1; } } public bool Connected(int p, int q) { return Find(p) == Find(q); } public int Count() { return componentCount; } public int Find(int p) { while (p != dots[p]) { p = dots[p]; } return p; } public void Union(int p, int q) { int pComponent = Find(p); int qComponent = Find(q); if (pComponent == qComponent) return; if (componentSize[pComponent] > componentSize[qComponent]) { dots[qComponent] = pComponent; componentSize[pComponent] += componentSize[qComponent]; } else { dots[pComponent] = qComponent; componentSize[qComponent] += componentSize[pComponent]; } componentCount--; } } }
17.333333
61
0.614423
[ "MIT" ]
doctral/Medium-Union-Find
UnionFind/WeightedQuickUnion.cs
1,042
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using Microsoft.Azure.Cosmos; using Microsoft.Health.Fhir.Core.Features.Search; namespace Microsoft.Health.Fhir.CosmosDb.Features.Search.Queries { public interface IQueryBuilder { QueryDefinition BuildSqlQuerySpec(SearchOptions searchOptions); QueryDefinition GenerateHistorySql(SearchOptions searchOptions); QueryDefinition GenerateReindexSql(SearchOptions searchOptions, string searchParameterHash); } }
40.25
101
0.587578
[ "MIT" ]
HiteshRamnani/fhir-server
src/Microsoft.Health.Fhir.CosmosDb/Features/Search/Queries/IQueryBuilder.cs
807
C#
// Copyright (c) 2014 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; namespace ICSharpCode.Decompiler.IL { [Flags] public enum InstructionFlags { None = 0, /// <summary> /// The instruction may read from local variables. /// </summary> MayReadLocals = 0x10, /// <summary> /// The instruction may write to local variables. /// </summary> /// <remarks> /// This flag is not set for indirect writes to local variables through pointers. /// Ensure you also check the SideEffect flag when checking for instructions that might write to locals. /// </remarks> MayWriteLocals = 0x20, /// <summary> /// The instruction may have side effects, such as accessing heap memory, /// performing system calls, writing to local variables through pointers, etc. /// </summary> /// <remarks> /// Throwing an exception or directly writing to local variables /// is not considered a side effect, and is modeled by separate flags. /// </remarks> SideEffect = 0x40, /// <summary> /// The instruction may throw an exception. /// </summary> MayThrow = 0x100, /// <summary> /// The instruction may exit with a branch or leave. /// </summary> MayBranch = 0x200, /// <summary> /// The instruction may jump to the closest containing <c>nullable.rewrap</c> instruction. /// </summary> MayUnwrapNull = 0x400, /// <summary> /// The instruction performs unconditional control flow, so that its endpoint is unreachable. /// </summary> /// <remarks> /// If EndPointUnreachable is set, either MayThrow or MayBranch should also be set /// (unless the instruction represents an infinite loop). /// </remarks> EndPointUnreachable = 0x800, /// <summary> /// The instruction contains some kind of internal control flow. /// </summary> /// <remarks> /// If this flag is not set, all descendants of the instruction are fully evaluated (modulo MayThrow/MayBranch/MayUnwrapNull) /// in left-to-right pre-order. /// /// Note that branch instructions don't have this flag set, because their control flow is not internal /// (and they don't have any unusual argument evaluation rules). /// </remarks> ControlFlow = 0x1000, } }
39.609756
127
0.712746
[ "MIT" ]
AraHaan/ILSpy
ICSharpCode.Decompiler/IL/InstructionFlags.cs
3,250
C#
using Ducksoft.SOA.Common.Utilities; using System.Collections.Generic; using System.Configuration; using System.Data.Entity; using System.Data.Entity.Core.EntityClient; using System.Data.SqlClient; using System.Linq; using System.Runtime.Serialization; namespace Ducksoft.SOA.Common.DataContracts { /// <summary> /// Class which stores database connection string related information. /// </summary> [DataContract(Name = "DbConnectionInfo", Namespace = "http://ducksoftware.co.uk/SOA/WCF/DataContracts")] public class DbConnectionInfo { /// <summary> /// The provider name /// </summary> private string providerName; /// <summary> /// Gets or sets the name of the provider. /// </summary> /// <value> /// The name of the provider. /// </value> [DataMember] public string ProviderName { get { return (providerName); } set { providerName = string.IsNullOrWhiteSpace(value) ? "System.Data.SqlClient" : value; } } /// <summary> /// Gets or sets the name of the server. /// </summary> /// <value> /// The name of the server. /// </value> [DataMember] public string ServerName { get; set; } /// <summary> /// Gets or sets the name of the database. /// </summary> /// <value> /// The name of the database. /// </value> [DataMember] public string DbName { get; set; } /// <summary> /// Gets or sets the name of the edmx model. /// </summary> /// <value> /// The name of the edmx model. /// </value> [DataMember] public string EdmxModelName { get; set; } /// <summary> /// Gets or sets the name of the redirect connect string. /// </summary> /// <value> /// The name of the redirect connect string. /// </value> [DataMember] public string ConnectStrName { get; set; } /// <summary> /// Initializes a new instance of the <see cref="DbConnectionInfo" /> class. /// </summary> public DbConnectionInfo() { } /// <summary> /// Initializes a new instance of the <see cref="DbConnectionInfo"/> class. /// </summary> /// <param name="custHdrCollection">The customer header collection.</param> public DbConnectionInfo(IDictionary<string, string> custHdrCollection) { if (null == custHdrCollection) return; var result = custHdrCollection.Keys.Intersect(ToDictonary().Keys) .ToDictionary(k => k, k => custHdrCollection[k]); foreach (var item in result) { if (nameof(ProviderName) == item.Key) { ProviderName = item.Value; } else if (nameof(ServerName) == item.Key) { ServerName = item.Value; } else if (nameof(DbName) == item.Key) { DbName = item.Value; } else if (nameof(EdmxModelName) == item.Key) { EdmxModelName = item.Value; } else if (nameof(ConnectStrName) == item.Key) { ConnectStrName = item.Value; } } } /// <summary> /// To the dictonary. /// </summary> /// <returns></returns> public IDictionary<string, string> ToDictonary() { return (new Dictionary<string, string> { { nameof(ProviderName), ProviderName }, { nameof(ServerName), ServerName }, { nameof(DbName), DbName }, { nameof(EdmxModelName), EdmxModelName }, { nameof(ConnectStrName), ConnectStrName } }); } /// <summary> /// Gets the SQL connection string. /// </summary> /// <returns></returns> public string GetSqlConnectionStr() { var sqlConnection = string.Empty; if (!string.IsNullOrWhiteSpace(ConnectStrName)) { sqlConnection = ConfigurationManager.ConnectionStrings[ConnectStrName].ConnectionString; return (sqlConnection); } //Hp --> Logic: Skip RedirectConnectStr from dictonary and check it has valid data? var isInvalid = ToDictonary() .Where(I => !I.Key.IsEqualTo(nameof(ConnectStrName))) .Any(I => string.IsNullOrWhiteSpace(I.Value)); if (isInvalid) { sqlConnection = string.Empty; } else { new SqlConnectionStringBuilder() { DataSource = ServerName, InitialCatalog = DbName, IntegratedSecurity = true, MultipleActiveResultSets = true }.ToString(); } return (sqlConnection); } /// <summary> /// Gets the EF connection string. /// </summary> /// <typeparam name="TEntities">The type of the entities.</typeparam> /// <returns></returns> public string GetEFConnectionStr<TEntities>() where TEntities : DbContext { var efConnection = string.Empty; var sqlConnection = GetSqlConnectionStr(); if (string.IsNullOrWhiteSpace(sqlConnection)) { return (efConnection); } if (!string.IsNullOrWhiteSpace(ConnectStrName)) { efConnection = new EntityConnectionStringBuilder(sqlConnection).ToString(); } else { var entityType = typeof(TEntities); var assemblyFullName = entityType.Assembly.GetName().FullName; var metaDataStr = (string.IsNullOrWhiteSpace(EdmxModelName)) ? @"res://*" : string.Format(@"res://{0}/{1}.csdl| res://{0}/{1}.ssdl| res://{0}/{1}.msl", assemblyFullName, EdmxModelName); efConnection = new EntityConnectionStringBuilder { Provider = ProviderName, ProviderConnectionString = sqlConnection, Metadata = metaDataStr } .ToString(); } return (efConnection); } } }
31.823256
95
0.498538
[ "MIT" ]
hpsanampudi/Ducksoft.Soa.Common
DataContracts/DbConnectionInfo.cs
6,844
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.470/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using System.Windows.Forms; namespace PaletteCreator.UX { public partial class TMSChromeForm : KryptonForm { #region Constructor /// <summary> /// Initialises a new instance of the <see cref="TMSChromeForm"/> class. /// </summary> public TMSChromeForm() { InitializeComponent(); } #endregion #region Properties /// <summary> /// Sets the override tool strip renderer. /// </summary> /// <value> /// The override tool strip renderer. /// </value> public ToolStripRenderer OverrideToolStripRenderer { set { tmsMenuStrip.Renderer = value; tmsStatusStrip.Renderer = value; tmsToolStrip.Renderer = value; tmsToolStripContainer.TopToolStripPanel.Renderer = value; tmsToolStripContainer.BottomToolStripPanel.Renderer = value; tmsToolStripContainer.LeftToolStripPanel.Renderer = value; tmsToolStripContainer.RightToolStripPanel.Renderer = value; tmsToolStripContainer.ContentPanel.Renderer = value; } } #endregion } }
26.20339
90
0.600906
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.470
Source/Krypton Toolkit Suite Extended/Applications/Palette Creator/UX/TMSChromeForm.cs
1,548
C#
using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Hosting; using System; using Microsoft.AspNetCore.Builder; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace App { public class Program { public static void Main() { Host.CreateDefaultBuilder() .ConfigureServices(svcs => svcs.AddRouting()) .ConfigureWebHostDefaults(builder => builder.Configure(app => app .UseDeveloperExceptionPage() .UseRouting() .UseEndpoints(endpoints => endpoints.MapGet("{foo}/{bar}", HandleAsync)))) .Build() .Run(); static Task HandleAsync(HttpContext httpContext) => Task.FromException(new InvalidOperationException("Manually thrown exception...")); } } }
31.785714
101
0.639326
[ "MIT" ]
hyperpc/AspNetCoreFxAdv
inside-asp-net-core-3/ch_16/S1601/App/Program.cs
892
C#
using Mokkit.Playground.SampleScenery; using Moq; namespace Mokkit.Playground.Setups { public class CoreSetup: IStageSetup<string> { public void SetupMocks(IMokkit<string> mokkit) { mokkit.Customize<Mock<IService1>>(mock => mock.Setup(service1 => service1.Call1())); mokkit.Customize<Mock<IService2>>(mock => mock.Setup(service2 => service2.Call2())); var svc1 = mokkit.Resolve(); } } }
28.8125
96
0.635575
[ "MIT" ]
GrafGenerator/mokkit
src/Mokkit.Playground/Setups/CoreSetup.cs
463
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EntityInspector.xaml.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace BlueprintEditor.Inspectors.Controls { using System; using System.Collections; using System.ComponentModel; using System.Windows; using BlueprintEditor.Controls; using BlueprintEditor.ViewModels; using Slash.Collections.AttributeTables; using Slash.Collections.Utils; using Slash.ECS.Configurations; using Slash.ECS.Inspector.Attributes; /// <summary> /// Interaction logic for EntityInspector.xaml /// </summary> public partial class EntityInspector { #region Fields private InspectorFactory inspectorFactory; private BlueprintViewModel selectedBlueprint; #endregion #region Constructors and Destructors public EntityInspector() { this.InitializeComponent(); this.DataContextChanged += this.OnDataContextChanged; DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty( BlueprintComboBox.SelectedBlueprintProperty, typeof(BlueprintComboBox)); dpd.AddValueChanged(this.CbBlueprint, this.OnSelectedBlueprintChanged); } #endregion #region Methods private object GetCurrentAttributeValue(InspectorPropertyAttribute inspectorProperty, out bool inherited) { object value; EntityConfiguration entityConfiguration = (EntityConfiguration)this.Value; if (entityConfiguration != null && entityConfiguration.Configuration.TryGetValue(inspectorProperty.Name, out value)) { inherited = false; } else { inherited = true; value = this.GetDefaultValue(inspectorProperty); } return value; } private object GetDefaultValue(InspectorPropertyAttribute inspectorProperty) { return this.selectedBlueprint != null ? this.selectedBlueprint.Blueprint.GetAttributeTable() .GetValueOrDefault(inspectorProperty.Name, inspectorProperty.Default) : null; } private void OnBlueprintChanged(BlueprintViewModel newBlueprint) { if (Equals(this.selectedBlueprint, newBlueprint)) { return; } this.selectedBlueprint = newBlueprint; // Update attribute table. this.UpdateAttributeTable(); // Set value. EntityConfiguration entityConfiguration = (EntityConfiguration)this.Value ?? new EntityConfiguration(); entityConfiguration.BlueprintId = newBlueprint != null ? newBlueprint.BlueprintId : string.Empty; this.Value = entityConfiguration; this.OnValueChanged(); } private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { InspectorPropertyData dataContext = (InspectorPropertyData)this.DataContext; this.inspectorFactory = new InspectorFactory( dataContext.EditorContext, dataContext.EditorContext != null ? dataContext.EditorContext.LocalizationContext : null); EntityConfiguration entityConfiguration = (EntityConfiguration)this.Value; if (entityConfiguration != null) { // Select correct blueprint view model. this.CbBlueprint.SelectedBlueprintId = entityConfiguration.BlueprintId; } this.UpdateAttributeTable(); } private void OnPropertyControlValueChanged(InspectorPropertyAttribute inspectorProperty, object newValue) { EntityConfiguration entityConfiguration = (EntityConfiguration)this.Value ?? new EntityConfiguration(); // Remove value if default value or inherited from blueprint. Otherwise set it. object defaultValue = this.GetDefaultValue(inspectorProperty); var defaultList = defaultValue as IList; var newList = newValue as IList; if (defaultList != null && newList != null && CollectionUtils.ListEqual(defaultList, newList)) { entityConfiguration.Configuration.RemoveValue(inspectorProperty.Name); } else if (Equals(newValue, defaultValue)) { entityConfiguration.Configuration.RemoveValue(inspectorProperty.Name); } else { entityConfiguration.Configuration.SetValue(inspectorProperty.Name, newValue); } this.OnValueChanged(); } private void OnSelectedBlueprintChanged(object sender, EventArgs e) { this.OnBlueprintChanged(this.CbBlueprint.SelectedBlueprint); } private void UpdateAttributeTable() { // Clear old attributes. this.AttributesPanel.Children.Clear(); if (this.selectedBlueprint == null) { return; } // Add inspectors for blueprint components. this.inspectorFactory.AddComponentInspectorsRecursively( this.selectedBlueprint, this.AttributesPanel, this.GetCurrentAttributeValue, this.OnPropertyControlValueChanged); } #endregion } }
35.077844
120
0.596961
[ "MIT" ]
SlashGames/slash-framework
Tools/BlueprintEditor/Slash.Tools.BlueprintEditor.WPF/Source/Inspectors/Controls/EntityInspector.xaml.cs
5,860
C#
////////////////////////////////////////////// // Apache 2.0 - 2016-2017 // Author : Derek Tremblay ([email protected]) ////////////////////////////////////////////// using System; using System.Text; using System.Windows.Input; using WpfHexaEditor.Core.Native; namespace WpfHexaEditor.Core { /// <summary> /// Static class for valid keyboard key. /// </summary> public static class KeyValidator { /// <summary> /// Check if is a numeric key as pressed /// </summary> public static bool IsNumericKey(Key key) { return key == Key.D0 || key == Key.D1 || key == Key.D2 || key == Key.D3 || key == Key.D4 || key == Key.D5 || key == Key.D6 || key == Key.D7 || key == Key.D8 || key == Key.D9 || key == Key.NumPad0 || key == Key.NumPad1 || key == Key.NumPad2 || key == Key.NumPad3 || key == Key.NumPad4 || key == Key.NumPad5 || key == Key.NumPad6 || key == Key.NumPad7 || key == Key.NumPad8 || key == Key.NumPad9; } /// <summary> /// Get if key is a Hexakey (alpha) /// </summary> /// <param name="key"></param> /// <returns></returns> public static bool IsHexKey(Key key) { return key == Key.A || key == Key.B || key == Key.C || key == Key.D || key == Key.E || key == Key.F || IsNumericKey(key); } /// <summary> /// Get the digit from key /// </summary> public static int GetDigitFromKey(Key key) { switch (key) { case Key.D0: case Key.NumPad0: return 0; case Key.D1: case Key.NumPad1: return 1; case Key.D2: case Key.NumPad2: return 2; case Key.D3: case Key.NumPad3: return 3; case Key.D4: case Key.NumPad4: return 4; case Key.D5: case Key.NumPad5: return 5; case Key.D6: case Key.NumPad6: return 6; case Key.D7: case Key.NumPad7: return 7; case Key.D8: case Key.NumPad8: return 8; case Key.D9: case Key.NumPad9: return 9; default: throw new ArgumentOutOfRangeException("Invalid key: " + key); } } public static bool IsIgnoredKey(Key key) { //ADD SOMES OTHER KEY FOR VALIDATED IN IBYTECONTROL //DELETE KEY FOR ADD OTHER FUNCTIONALITY... return key == Key.Tab || key == Key.Enter || key == Key.Return || key == Key.LWin || key == Key.RWin || key == Key.CapsLock || key == Key.LeftAlt || key == Key.RightAlt || key == Key.System || key == Key.LeftCtrl || key == Key.F1 || key == Key.F2 || key == Key.F3 || key == Key.F4 || key == Key.F5 || key == Key.F6 || key == Key.F7 || key == Key.F8 || key == Key.F9 || key == Key.F10 || key == Key.F11 || key == Key.F12 || key == Key.Home || key == Key.Insert || key == Key.End; } public static bool IsArrowKey(Key key) => key == Key.Up || key == Key.Down || key == Key.Left || key == Key.Right; public static bool IsBackspaceKey(Key key) => key == Key.Back; public static bool IsSubstractKey(Key key) => key == Key.Subtract || key == Key.OemMinus; public static bool IsDeleteKey(Key key) => key == Key.Delete; public static bool IsCapsLock(Key key) => key == Key.CapsLock; public static bool IsEscapeKey(Key key) => key == Key.Escape; public static bool IsUpKey(Key key) => key == Key.Up; public static bool IsWindowsKey(Key key) => key == Key.LWin || key == Key.RWin; public static bool IsDownKey(Key key) => key == Key.Down; public static bool IsRightKey(Key key) => key == Key.Right; public static bool IsLeftKey(Key key) => key == Key.Left; public static bool IsPageDownKey(Key key) => key == Key.PageDown; public static bool IsPageUpKey(Key key) => key == Key.PageUp; public static bool IsEnterKey(Key key) => key == Key.Enter; public static bool IsTabKey(Key key) => key == Key.Tab; public static bool IsCtrlCKey(Key key) => key == Key.C && Keyboard.Modifiers == ModifierKeys.Control; public static bool IsCtrlZKey(Key key) => key == Key.Z && Keyboard.Modifiers == ModifierKeys.Control; public static bool IsCtrlYKey(Key key) => key == Key.Y && Keyboard.Modifiers == ModifierKeys.Control; public static bool IsCtrlVKey(Key key) => key == Key.V && Keyboard.Modifiers == ModifierKeys.Control; public static bool IsCtrlAKey(Key key) => key == Key.A && Keyboard.Modifiers == ModifierKeys.Control; #region DllImport/methods for key detection (Thank to : Inbar Barkai for help) /// <summary> /// Capture character on different locale keyboards in WPF. Convert key to appropiate char? /// </summary> /// <remarks> /// Code from /// http://stackoverflow.com/questions/5825820/how-to-capture-the-character-on-different-locale-keyboards-in-wpf-c /// </remarks> /// <returns>return a char represent the key passed in parameter</returns> public static char GetCharFromKey(Key key) { var ch = ' '; var virtualKey = KeyInterop.VirtualKeyFromKey(key); var keyboardState = new byte[256]; NativeMethods.GetKeyboardState(keyboardState); var scanCode = NativeMethods.MapVirtualKey((uint) virtualKey, NativeMethods.MapType.MapvkVkToVsc); var stringBuilder = new StringBuilder(2); var result = NativeMethods.ToUnicode((uint) virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0); switch (result) { case -1: case 0: break; case 1: ch = stringBuilder[0]; break; default: ch = stringBuilder[0]; break; } return ch; } #endregion DllImport for key detection (Thank to : Inbar Barkai for help) } }
38.396648
123
0.495417
[ "Apache-2.0" ]
AuroraView/WPFHexEditorControl
WPFHexaEditor.Control/Core/KeyValidator.cs
6,875
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.ComponentModel; using System.Threading; namespace DS4Windows { public enum DsState : byte { [Description("Disconnected")] Disconnected = 0x00, [Description("Reserved")] Reserved = 0x01, [Description("Connected")] Connected = 0x02 }; public enum DsConnection : byte { [Description("None")] None = 0x00, [Description("Usb")] Usb = 0x01, [Description("Bluetooth")] Bluetooth = 0x02 }; public enum DsModel : byte { [Description("None")] None = 0, [Description("DualShock 3")] DS3 = 1, [Description("DualShock 4")] DS4 = 2, [Description("Generic Gamepad")] Generic = 3 } public enum DsBattery : byte { None = 0x00, Dying = 0x01, Low = 0x02, Medium = 0x03, High = 0x04, Full = 0x05, Charging = 0xEE, Charged = 0xEF }; public struct DualShockPadMeta { public byte PadId; public DsState PadState; public DsConnection ConnectionType; public DsModel Model; public PhysicalAddress PadMacAddress; public DsBattery BatteryStatus; public bool IsActive; } class UdpServer { public const int NUMBER_SLOTS = 4; private Socket udpSock; private uint serverId; private bool running; private byte[] recvBuffer = new byte[1024]; private SocketAsyncEventArgs[] argsList; private int listInd = 0; private ReaderWriterLockSlim poolLock = new ReaderWriterLockSlim(); private SemaphoreSlim _pool; private const int ARG_BUFFER_LEN = 80; public delegate void GetPadDetail(int padIdx, ref DualShockPadMeta meta); private GetPadDetail portInfoGet; public UdpServer(GetPadDetail getPadDetailDel) { portInfoGet = getPadDetailDel; _pool = new SemaphoreSlim(ARG_BUFFER_LEN); argsList = new SocketAsyncEventArgs[ARG_BUFFER_LEN]; for (int num = 0; num < ARG_BUFFER_LEN; num++) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(new byte[100], 0, 100); args.Completed += SocketEvent_Completed; argsList[num] = args; } } private void SocketEvent_Completed(object sender, SocketAsyncEventArgs e) { _pool.Release(); } private void CompletedSynchronousSocketEvent() { _pool.Release(); } enum MessageType { DSUC_VersionReq = 0x100000, DSUS_VersionRsp = 0x100000, DSUC_ListPorts = 0x100001, DSUS_PortInfo = 0x100001, DSUC_PadDataReq = 0x100002, DSUS_PadDataRsp = 0x100002, }; private const ushort MaxProtocolVersion = 1001; class ClientRequestTimes { DateTime allPads; DateTime[] padIds; Dictionary<PhysicalAddress, DateTime> padMacs; public DateTime AllPadsTime { get { return allPads; } } public DateTime[] PadIdsTime { get { return padIds; } } public Dictionary<PhysicalAddress, DateTime> PadMacsTime { get { return padMacs; } } public ClientRequestTimes() { allPads = DateTime.MinValue; padIds = new DateTime[4]; for (int i = 0; i < padIds.Length; i++) padIds[i] = DateTime.MinValue; padMacs = new Dictionary<PhysicalAddress, DateTime>(); } public void RequestPadInfo(byte regFlags, byte idToReg, PhysicalAddress macToReg) { if (regFlags == 0) allPads = DateTime.UtcNow; else { if ((regFlags & 0x01) != 0) //id valid { if (idToReg < padIds.Length) padIds[idToReg] = DateTime.UtcNow; } if ((regFlags & 0x02) != 0) //mac valid { padMacs[macToReg] = DateTime.UtcNow; } } } } private Dictionary<IPEndPoint, ClientRequestTimes> clients = new Dictionary<IPEndPoint, ClientRequestTimes>(); private int BeginPacket(byte[] packetBuf, ushort reqProtocolVersion = MaxProtocolVersion) { int currIdx = 0; packetBuf[currIdx++] = (byte)'D'; packetBuf[currIdx++] = (byte)'S'; packetBuf[currIdx++] = (byte)'U'; packetBuf[currIdx++] = (byte)'S'; Array.Copy(BitConverter.GetBytes((ushort)reqProtocolVersion), 0, packetBuf, currIdx, 2); currIdx += 2; Array.Copy(BitConverter.GetBytes((ushort)packetBuf.Length - 16), 0, packetBuf, currIdx, 2); currIdx += 2; Array.Clear(packetBuf, currIdx, 4); //place for crc currIdx += 4; Array.Copy(BitConverter.GetBytes((uint)serverId), 0, packetBuf, currIdx, 4); currIdx += 4; return currIdx; } private void FinishPacket(byte[] packetBuf) { Array.Clear(packetBuf, 8, 4); //uint crcCalc = Crc32Algorithm.Compute(packetBuf); uint seed = Crc32Algorithm.DefaultSeed; uint crcCalc = ~Crc32Algorithm.CalculateBasicHash(ref seed, ref packetBuf, 0, packetBuf.Length); Array.Copy(BitConverter.GetBytes((uint)crcCalc), 0, packetBuf, 8, 4); } private void SendPacket(IPEndPoint clientEP, byte[] usefulData, ushort reqProtocolVersion = MaxProtocolVersion) { byte[] packetData = new byte[usefulData.Length + 16]; int currIdx = BeginPacket(packetData, reqProtocolVersion); Array.Copy(usefulData, 0, packetData, currIdx, usefulData.Length); FinishPacket(packetData); //try { udpSock.SendTo(packetData, clientEP); } int temp = 0; poolLock.EnterWriteLock(); temp = listInd; listInd = ++listInd % ARG_BUFFER_LEN; SocketAsyncEventArgs args = argsList[temp]; poolLock.ExitWriteLock(); _pool.Wait(); args.RemoteEndPoint = clientEP; Array.Copy(packetData, args.Buffer, packetData.Length); //args.SetBuffer(packetData, 0, packetData.Length); bool sentAsync = false; try { sentAsync = udpSock.SendToAsync(args); if (!sentAsync) CompletedSynchronousSocketEvent(); } catch (Exception e) { } finally { if (!sentAsync) CompletedSynchronousSocketEvent(); } } private void ProcessIncoming(byte[] localMsg, IPEndPoint clientEP) { try { int currIdx = 0; if (localMsg[0] != 'D' || localMsg[1] != 'S' || localMsg[2] != 'U' || localMsg[3] != 'C') return; else currIdx += 4; uint protocolVer = BitConverter.ToUInt16(localMsg, currIdx); currIdx += 2; if (protocolVer > MaxProtocolVersion) return; uint packetSize = BitConverter.ToUInt16(localMsg, currIdx); currIdx += 2; if (packetSize < 0) return; packetSize += 16; //size of header if (packetSize > localMsg.Length) return; else if (packetSize < localMsg.Length) { byte[] newMsg = new byte[packetSize]; Array.Copy(localMsg, newMsg, packetSize); localMsg = newMsg; } uint crcValue = BitConverter.ToUInt32(localMsg, currIdx); //zero out the crc32 in the packet once we got it since that's whats needed for calculation localMsg[currIdx++] = 0; localMsg[currIdx++] = 0; localMsg[currIdx++] = 0; localMsg[currIdx++] = 0; uint crcCalc = Crc32Algorithm.Compute(localMsg); if (crcValue != crcCalc) return; uint clientId = BitConverter.ToUInt32(localMsg, currIdx); currIdx += 4; uint messageType = BitConverter.ToUInt32(localMsg, currIdx); currIdx += 4; if (messageType == (uint)MessageType.DSUC_VersionReq) { byte[] outputData = new byte[8]; int outIdx = 0; Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_VersionRsp), 0, outputData, outIdx, 4); outIdx += 4; Array.Copy(BitConverter.GetBytes((ushort)MaxProtocolVersion), 0, outputData, outIdx, 2); outIdx += 2; outputData[outIdx++] = 0; outputData[outIdx++] = 0; SendPacket(clientEP, outputData, 1001); } else if (messageType == (uint)MessageType.DSUC_ListPorts) { int numPadRequests = BitConverter.ToInt32(localMsg, currIdx); currIdx += 4; if (numPadRequests < 0 || numPadRequests > NUMBER_SLOTS) return; int requestsIdx = currIdx; for (int i = 0; i < numPadRequests; i++) { byte currRequest = localMsg[requestsIdx + i]; if (currRequest >= NUMBER_SLOTS) return; } byte[] outputData = new byte[16]; for (byte i = 0; i < numPadRequests; i++) { byte currRequest = localMsg[requestsIdx + i]; DualShockPadMeta padData = new DualShockPadMeta(); portInfoGet(currRequest, ref padData); int outIdx = 0; Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_PortInfo), 0, outputData, outIdx, 4); outIdx += 4; outputData[outIdx++] = (byte)padData.PadId; outputData[outIdx++] = (byte)padData.PadState; outputData[outIdx++] = (byte)padData.Model; outputData[outIdx++] = (byte)padData.ConnectionType; byte[] addressBytes = null; if (padData.PadMacAddress != null) addressBytes = padData.PadMacAddress.GetAddressBytes(); if (addressBytes != null && addressBytes.Length == 6) { outputData[outIdx++] = addressBytes[0]; outputData[outIdx++] = addressBytes[1]; outputData[outIdx++] = addressBytes[2]; outputData[outIdx++] = addressBytes[3]; outputData[outIdx++] = addressBytes[4]; outputData[outIdx++] = addressBytes[5]; } else { outputData[outIdx++] = 0; outputData[outIdx++] = 0; outputData[outIdx++] = 0; outputData[outIdx++] = 0; outputData[outIdx++] = 0; outputData[outIdx++] = 0; } outputData[outIdx++] = (byte)padData.BatteryStatus; outputData[outIdx++] = 0; SendPacket(clientEP, outputData, 1001); } } else if (messageType == (uint)MessageType.DSUC_PadDataReq) { byte regFlags = localMsg[currIdx++]; byte idToReg = localMsg[currIdx++]; PhysicalAddress macToReg = null; { byte[] macBytes = new byte[6]; Array.Copy(localMsg, currIdx, macBytes, 0, macBytes.Length); currIdx += macBytes.Length; macToReg = new PhysicalAddress(macBytes); } lock (clients) { if (clients.ContainsKey(clientEP)) clients[clientEP].RequestPadInfo(regFlags, idToReg, macToReg); else { var clientTimes = new ClientRequestTimes(); clientTimes.RequestPadInfo(regFlags, idToReg, macToReg); clients[clientEP] = clientTimes; } } } } catch (Exception e) { } } private void ReceiveCallback(IAsyncResult iar) { byte[] localMsg = null; EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0); try { //Get the received message. Socket recvSock = (Socket)iar.AsyncState; int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP); localMsg = new byte[msgLen]; Array.Copy(recvBuffer, localMsg, msgLen); } catch (Exception e) { } //Start another receive as soon as we copied the data StartReceive(); //Process the data if its valid if (localMsg != null) ProcessIncoming(localMsg, (IPEndPoint)clientEP); } private void StartReceive() { try { if (running) { //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(recvBuffer, 0, recvBuffer.Length, SocketFlags.None, ref newClientEP, ReceiveCallback, udpSock); } } catch (SocketException ex) { uint IOC_IN = 0x80000000; uint IOC_VENDOR = 0x18000000; uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; udpSock.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null); StartReceive(); } } public void Start(int port, string listenAddress = "") { if (running) { if (udpSock != null) { udpSock.Close(); udpSock = null; } running = false; } udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { IPAddress udpListenIPAddress; if (listenAddress == "127.0.0.1" || listenAddress == "") { // Listen on local looback interface (default option). Does not allow remote client connections udpListenIPAddress = IPAddress.Loopback; } else if (listenAddress == "0.0.0.0") { // Listen on all IPV4 interfaces. // Remote client connections allowed. If the local network is not "safe" then may not be a good idea, because at the moment incoming connections are not authenticated in any way udpListenIPAddress = IPAddress.Any; } else { // Listen on a specific hostname or IPV4 interface address. If the hostname has multiple interfaces then use the first IPV4 address because it is usually the primary IP addr. // Remote client connections allowed. IPAddress[] ipAddresses = Dns.GetHostAddresses(listenAddress); udpListenIPAddress = null; foreach (IPAddress ip4 in ipAddresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)) { udpListenIPAddress = ip4; break; } if (udpListenIPAddress == null) throw new SocketException(10049 /*WSAEADDRNOTAVAIL*/); } udpSock.Bind(new IPEndPoint(udpListenIPAddress, port)); } catch (SocketException ex) { udpSock.Close(); udpSock = null; throw ex; } byte[] randomBuf = new byte[4]; new Random().NextBytes(randomBuf); serverId = BitConverter.ToUInt32(randomBuf, 0); running = true; StartReceive(); } public void Stop() { running = false; if (udpSock != null) { udpSock.Close(); udpSock = null; } } private bool ReportToBuffer(DS4State hidReport, byte[] outputData, ref int outIdx) { unchecked { outputData[outIdx] = 0; if (hidReport.DpadLeft) outputData[outIdx] |= 0x80; if (hidReport.DpadDown) outputData[outIdx] |= 0x40; if (hidReport.DpadRight) outputData[outIdx] |= 0x20; if (hidReport.DpadUp) outputData[outIdx] |= 0x10; if (hidReport.Options) outputData[outIdx] |= 0x08; if (hidReport.R3) outputData[outIdx] |= 0x04; if (hidReport.L3) outputData[outIdx] |= 0x02; if (hidReport.Share) outputData[outIdx] |= 0x01; outputData[++outIdx] = 0; if (hidReport.Square) outputData[outIdx] |= 0x80; if (hidReport.Cross) outputData[outIdx] |= 0x40; if (hidReport.Circle) outputData[outIdx] |= 0x20; if (hidReport.Triangle) outputData[outIdx] |= 0x10; if (hidReport.R1) outputData[outIdx] |= 0x08; if (hidReport.L1) outputData[outIdx] |= 0x04; if (hidReport.R2Btn) outputData[outIdx] |= 0x02; if (hidReport.L2Btn) outputData[outIdx] |= 0x01; outputData[++outIdx] = (hidReport.PS) ? (byte)1 : (byte)0; outputData[++outIdx] = (hidReport.TouchButton) ? (byte)1 : (byte)0; //Left stick outputData[++outIdx] = hidReport.LX; outputData[++outIdx] = hidReport.LY; outputData[outIdx] = (byte)(255 - outputData[outIdx]); //invert Y by convention //Right stick outputData[++outIdx] = hidReport.RX; outputData[++outIdx] = hidReport.RY; outputData[outIdx] = (byte)(255 - outputData[outIdx]); //invert Y by convention //we don't have analog buttons on DS4 :( outputData[++outIdx] = hidReport.DpadLeft ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.DpadDown ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.DpadRight ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.DpadUp ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.Square ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.Cross ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.Circle ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.Triangle ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.R1 ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.L1 ? (byte)0xFF : (byte)0x00; outputData[++outIdx] = hidReport.R2; outputData[++outIdx] = hidReport.L2; outIdx++; //DS4 only: touchpad points for (int i = 0; i < 2; i++) { var tpad = (i == 0) ? hidReport.TrackPadTouch0 : hidReport.TrackPadTouch1; outputData[outIdx++] = tpad.IsActive ? (byte)1 : (byte)0; outputData[outIdx++] = (byte)tpad.Id; Array.Copy(BitConverter.GetBytes((ushort)tpad.X), 0, outputData, outIdx, 2); outIdx += 2; Array.Copy(BitConverter.GetBytes((ushort)tpad.Y), 0, outputData, outIdx, 2); outIdx += 2; } //motion timestamp if (hidReport.Motion != null) Array.Copy(BitConverter.GetBytes((ulong)hidReport.totalMicroSec), 0, outputData, outIdx, 8); else Array.Clear(outputData, outIdx, 8); outIdx += 8; //accelerometer if (hidReport.Motion != null) { Array.Copy(BitConverter.GetBytes((float)hidReport.Motion.accelXG), 0, outputData, outIdx, 4); outIdx += 4; Array.Copy(BitConverter.GetBytes((float)hidReport.Motion.accelYG), 0, outputData, outIdx, 4); outIdx += 4; Array.Copy(BitConverter.GetBytes((float)-hidReport.Motion.accelZG), 0, outputData, outIdx, 4); outIdx += 4; } else { Array.Clear(outputData, outIdx, 12); outIdx += 12; } //gyroscope if (hidReport.Motion != null) { Array.Copy(BitConverter.GetBytes((float)hidReport.Motion.angVelPitch), 0, outputData, outIdx, 4); outIdx += 4; Array.Copy(BitConverter.GetBytes((float)hidReport.Motion.angVelYaw), 0, outputData, outIdx, 4); outIdx += 4; Array.Copy(BitConverter.GetBytes((float)hidReport.Motion.angVelRoll), 0, outputData, outIdx, 4); outIdx += 4; } else { Array.Clear(outputData, outIdx, 12); outIdx += 12; } } return true; } public void NewReportIncoming(ref DualShockPadMeta padMeta, DS4State hidReport, byte[] outputData) { if (!running) return; var clientsList = new List<IPEndPoint>(); var now = DateTime.UtcNow; lock (clients) { var clientsToDelete = new List<IPEndPoint>(); foreach (var cl in clients) { const double TimeoutLimit = 5; if ((now - cl.Value.AllPadsTime).TotalSeconds < TimeoutLimit) clientsList.Add(cl.Key); else if ((padMeta.PadId < cl.Value.PadIdsTime.Length) && (now - cl.Value.PadIdsTime[(byte)padMeta.PadId]).TotalSeconds < TimeoutLimit) clientsList.Add(cl.Key); else if (cl.Value.PadMacsTime.ContainsKey(padMeta.PadMacAddress) && (now - cl.Value.PadMacsTime[padMeta.PadMacAddress]).TotalSeconds < TimeoutLimit) clientsList.Add(cl.Key); else //check if this client is totally dead, and remove it if so { bool clientOk = false; for (int i = 0; i < cl.Value.PadIdsTime.Length; i++) { var dur = (now - cl.Value.PadIdsTime[i]).TotalSeconds; if (dur < TimeoutLimit) { clientOk = true; break; } } if (!clientOk) { foreach (var dict in cl.Value.PadMacsTime) { var dur = (now - dict.Value).TotalSeconds; if (dur < TimeoutLimit) { clientOk = true; break; } } if (!clientOk) clientsToDelete.Add(cl.Key); } } } foreach (var delCl in clientsToDelete) { clients.Remove(delCl); } clientsToDelete.Clear(); clientsToDelete = null; } if (clientsList.Count <= 0) return; unchecked { //byte[] outputData = new byte[100]; int outIdx = BeginPacket(outputData, 1001); Array.Copy(BitConverter.GetBytes((uint)MessageType.DSUS_PadDataRsp), 0, outputData, outIdx, 4); outIdx += 4; outputData[outIdx++] = (byte)padMeta.PadId; outputData[outIdx++] = (byte)padMeta.PadState; outputData[outIdx++] = (byte)padMeta.Model; outputData[outIdx++] = (byte)padMeta.ConnectionType; { byte[] padMac = padMeta.PadMacAddress.GetAddressBytes(); outputData[outIdx++] = padMac[0]; outputData[outIdx++] = padMac[1]; outputData[outIdx++] = padMac[2]; outputData[outIdx++] = padMac[3]; outputData[outIdx++] = padMac[4]; outputData[outIdx++] = padMac[5]; } outputData[outIdx++] = (byte)padMeta.BatteryStatus; outputData[outIdx++] = padMeta.IsActive ? (byte)1 : (byte)0; Array.Copy(BitConverter.GetBytes((uint)hidReport.PacketCounter), 0, outputData, outIdx, 4); outIdx += 4; if (!ReportToBuffer(hidReport, outputData, ref outIdx)) return; else FinishPacket(outputData); foreach (var cl in clientsList) { //try { udpSock.SendTo(outputData, cl); } int temp = 0; poolLock.EnterWriteLock(); temp = listInd; listInd = ++listInd % ARG_BUFFER_LEN; SocketAsyncEventArgs args = argsList[temp]; poolLock.ExitWriteLock(); _pool.Wait(); args.RemoteEndPoint = cl; Array.Copy(outputData, args.Buffer, outputData.Length); bool sentAsync = false; try { sentAsync = udpSock.SendToAsync(args); } catch (SocketException ex) { } finally { if (!sentAsync) CompletedSynchronousSocketEvent(); } } } clientsList.Clear(); clientsList = null; } } }
38.574555
197
0.480034
[ "MIT" ]
JustForFunDeveloper/DS4Windows
DS4Windows/DS4Control/UdpServer.cs
28,200
C#
using GizmoFort.Connector.ERPNext.PublicTypes; using GizmoFort.Connector.ERPNext.WrapperTypes; using System.ComponentModel; namespace GizmoFort.Connector.ERPNext.ERPTypes.Purpose_of_travel { public class ERPPurpose_of_travel : ERPNextObjectBase { public ERPPurpose_of_travel() : this(new ERPObject(DocType.Purpose_of_travel)) { } public ERPPurpose_of_travel(ERPObject obj) : base(obj) { } public static ERPPurpose_of_travel Create(string purposeoftravel) { ERPPurpose_of_travel obj = new ERPPurpose_of_travel(); obj.purpose_of_travel = purposeoftravel; return obj; } public string purpose_of_travel { get { return data.purpose_of_travel; } set { data.purpose_of_travel = value; data.name = value; } } } //Enums go here }
26.4
90
0.635281
[ "MIT" ]
dmequus/gizmofort.connector.erpnext
Libs/GizmoFort.Connector.ERPNext/ERPTypes/Purpose_of_travel/ERPPurpose_of_travel.cs
924
C#
#pragma checksum "..\..\..\MyControler\Tabele.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "E7407B48DEB957545C6E8D97F777CAC9A98ADAF8C6E8993504CA4FA4A601388D" //------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ using MYDIPLOMA.MyControler; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Controls.Ribbon; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace MYDIPLOMA.MyControler { /// <summary> /// Tabele /// </summary> public partial class Tabele : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector { #line 15 "..\..\..\MyControler\Tabele.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Grid Container; #line default #line hidden #line 22 "..\..\..\MyControler\Tabele.xaml" [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] internal System.Windows.Controls.Button AddColumnBtn; #line default #line hidden private bool _contentLoaded; /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Uri resourceLocater = new System.Uri("/MYDIPLOMA;component/mycontroler/tabele.xaml", System.UriKind.Relative); #line 1 "..\..\..\MyControler\Tabele.xaml" System.Windows.Application.LoadComponent(this, resourceLocater); #line default #line hidden } [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) { switch (connectionId) { case 1: this.Container = ((System.Windows.Controls.Grid)(target)); return; case 2: this.AddColumnBtn = ((System.Windows.Controls.Button)(target)); #line 22 "..\..\..\MyControler\Tabele.xaml" this.AddColumnBtn.Click += new System.Windows.RoutedEventHandler(this.AddColumnBtn_Click); #line default #line hidden return; } this._contentLoaded = true; } } }
38.962963
160
0.645913
[ "MIT" ]
ademvelika/AReport
MYDIPLOMA/MYDIPLOMA/obj/Debug/MyControler/Tabele.g.cs
4,210
C#
using RunSetcanRun.Combats; using RunSetcanRun.Controllers; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace RunSetcanRun.Managers { public class CheckpointManager : MonoBehaviour { [SerializeField] CheckpointController[] _checkpointControllers; Health _health; private void Awake() { _checkpointControllers = GetComponentsInChildren<CheckpointController>(); _health = FindObjectOfType<PlayerController>().GetComponent<Health>(); } private void Start() { _health.OnHealthChanged += HandleHealthChanged; } private void HandleHealthChanged(int currentHealth, int maxHealth) { _health.transform.position = _checkpointControllers.LastOrDefault(x => x.IsPassed).transform.position; } } }
27.121212
114
0.683799
[ "Unlicense" ]
smtzengin/SetcanProject
RunSetcanRun/Assets/GameFolders/Scripts/Concretes/Managers/CheckpointManager.cs
895
C#
using System; namespace EntityFramework.Repository { public interface IUnitOfWorkSession<TContext> : IDisposable where TContext : IDbContext { void Commit(); } }
20
64
0.65
[ "MIT" ]
philieu/EntityFramework.Repository
EntityFramework.Repository/IUnitOfWorkSession.cs
202
C#
using System; using System.Collections.Generic; namespace BibliId.Web.Models.Entities { public partial class TokenRevocation { public int Id { get; set; } public int AccountId { get; set; } public string TokenHash { get; set; } public string Reason { get; set; } public DateTime NaturalExpirationTime { get; set; } public DateTime RevokeTime { get; set; } public Account Account { get; set; } } }
26
59
0.630342
[ "MIT" ]
BibliTech/Roslyn.ViewModels
BibliTech.Roslyn.ViewModels.Demo/Entities/TokenRevocation.cs
470
C#
using MLAgents.InferenceBrain; namespace MLAgents.Sensor { public enum SensorCompressionType { None, PNG, } /// <summary> /// Sensor interface for generating observations. /// For custom implementations, it is recommended to SensorBase instead. /// </summary> public interface ISensor { /// <summary> /// Returns the size of the observations that will be generated. /// For example, a sensor that observes the velocity of a rigid body (in 3D) would return new {3}. /// A sensor that returns an RGB image would return new [] {Width, Height, 3} /// </summary> /// <returns></returns> int[] GetFloatObservationShape(); /// <summary> /// Write the observation data directly to the TensorProxy. /// This is considered an advanced interface; for a simpler approach, use SensorBase and override WriteFloats instead. /// </summary> /// <param name="tensorProxy"></param> /// <param name="agentIndex"></param> void WriteToTensor(TensorProxy tensorProxy, int agentIndex); /// <summary> /// Return a compressed representation of the observation. For small observations, this should generally not be /// implemented. However, compressing large observations (such as visual results) can significantly improve /// model training time. /// </summary> /// <returns></returns> byte[] GetCompressedObservation(); /// <summary> /// Return the compression type being used. If no compression is used, return SensorCompressionType.None /// </summary> /// <returns></returns> SensorCompressionType GetCompressionType(); /// <summary> /// Get the name of the sensor. This is used to ensure deterministic sorting of the sensors on an Agent, /// so the naming must be consistent across all sensors and agents. /// </summary> /// <returns>The name of the sensor</returns> string GetName(); } }
37.854545
126
0.626801
[ "Apache-2.0" ]
Hustacds/ml-agents
UnitySDK/Assets/ML-Agents/Scripts/Sensor/ISensor.cs
2,082
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace NewtonsMethod { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { functionComboBox.Text = "x^2 - 4"; } private void goButton_Click(object sender, EventArgs e) { rootsListBox.Items.Clear(); double xmin = double.Parse(xMinTextBox.Text); double xmax = double.Parse(xMaxTextBox.Text); int numTests = int.Parse(numTestsTextBox.Text); double maxError = double.Parse(maxErrorTextBox.Text); Func<double, double> F = null; Func<double, double> Fprime = null; if (functionComboBox.SelectedIndex == 0) { F = X2; Fprime = X2prime; } else if (functionComboBox.SelectedIndex == 1) { F = X3; Fprime = X3prime; } else if (functionComboBox.SelectedIndex == 2) { F = X4; Fprime = X4prime; } List<double> x0s; List<double> roots = FindRoots(F, Fprime, xmin, xmax, numTests, maxError, 1000, out x0s); foreach (double root in roots) rootsListBox.Items.Add(root); // Draw the curve. DrawCurve(F, xmin, xmax, roots, x0s); } // Find roots for the equation within the range xmin <= x <= xmax. private List<double> FindRoots(Func<double, double> F, Func<double, double> Fprime, double xmin, double xmax, int numTests, double maxError, double maxTrials, out List<double> x0s) { x0s = new List<double>(); List<double> roots = new List<double>(); double dx = (xmax - xmin) / (numTests - 1); for (int i = 0; i < numTests; i++) { double x = xmin + dx * i; x0s.Add(x); double root = NewtonsMethod(F, Fprime, x, maxError, maxTrials); if (!double.IsNaN(root) && !roots.Contains(root, maxError)) roots.Add(root); } return roots; } // Search this interval for a root. private double NewtonsMethod( Func<double, double> F, Func<double, double> FPrime, double x, double maxError, double maxTrials) { for (int trial = 0; trial < maxTrials; trial++) { x = x - F(x) / FPrime(x); double y = F(x); double error = Math.Abs(y); if (error < maxError) return x; } return double.NaN; } private double X2(double x) { return x * x - 4; } private double X2prime(double x) { return 2 * x; } private double X3(double x) { return x * x * x - 3 * x * x + 3; } private double X3prime(double x) { return 3 * x * x - 6 * x; } private double X4(double x) { return (x * x * x * x + 2 * x * x * x - 12 * x * x - 2 * x + 6) / 10; } private double X4prime(double x) { return (4 * x * x * x + 6 * x * x - 24 * x - 2) / 10; } private void DrawCurve(Func<double, double> F, double xmin, double xmax, List<double> roots, List<double> x0s) { int wid = graphPictureBox.ClientSize.Width; int hgt = graphPictureBox.ClientSize.Height; Bitmap bm = new Bitmap(wid, hgt); using (Graphics gr = Graphics.FromImage(bm)) { gr.Clear(Color.White); gr.SmoothingMode = SmoothingMode.AntiAlias; float scale = (float)(wid / (xmax - xmin)); gr.ScaleTransform(scale, -scale); gr.TranslateTransform(wid / 2, hgt / 2, MatrixOrder.Append); using (Pen pen = new Pen(Color.Black, 0)) { // Draw the axes. gr.DrawLine(pen, -10000, 0, 10000, 0); gr.DrawLine(pen, 0, -10000, 0, 10000); // Draw the x0s. pen.Color = Color.Red; foreach (double x in x0s) { gr.DrawLine(pen, (float)x, -1, (float)x, 1); } // Draw the curve. pen.Color = Color.Blue; // Make a point list. List<PointF> points = new List<PointF>(); float dx = (float)((xmax - xmin) / wid); for (float x = (float)xmin; x <= xmax; x += dx) { points.Add(new PointF(x, (float)F(x))); } gr.DrawLines(pen, points.ToArray()); // Draw the roots. pen.Color = Color.Red; float gap = 3 * dx; foreach (double root in roots) { float x = (float)root; float y = (float)F(root); RectangleF rect = new RectangleF( x - gap, y - gap, 2 * gap, 2 * gap); gr.DrawEllipse(pen, rect); } } } graphPictureBox.Image = bm; } } }
31.834225
81
0.451201
[ "MIT" ]
PacktPublishing/Improving-your-C-Sharp-Skills
Chapter15/NewtonsMethod/Form1.cs
5,955
C#
using System; using System.Diagnostics; using System.IO; using System.Linq; namespace NLUL.Core.Client.Runtime { public class UserInstalledWine : IRuntime { /// <summary> /// Name of the runtime. /// </summary> public string Name => "WINE"; /// <summary> /// Whether the emulator is supported on the current platform. /// </summary> public bool IsSupported => true; /// <summary> /// Whether the emulator can be automatically installed. /// </summary> public bool CanInstall => false; /// <summary> /// Whether the emulator is installed. /// </summary> /// <returns></returns> public bool IsInstalled => Environment.GetEnvironmentVariable("PATH").Split(":").Any(directory => File.Exists(Path.Combine(directory, "wine"))); /// <summary> /// The message to display to the user if the runtime /// isn't installed and can't be automatically installed. /// </summary> public string ManualRuntimeInstallMessage => "WINE must be installed."; /// <summary> /// Attempts to install the emulator. /// </summary> public void Install() { throw new NotImplementedException("WINE must be installed."); } /// <summary> /// Runs an application in the emulator. /// </summary> /// <param name="executablePath">Path of the executable to run.</param> /// <param name="workingDirectory">Working directory to run the executable in.</param> /// <returns>The process of the runtime.</returns> public Process RunApplication(string executablePath, string workingDirectory) { var clientProcess = new Process { StartInfo = { FileName = "wine", Arguments = executablePath, WorkingDirectory = workingDirectory, CreateNoWindow = true, RedirectStandardOutput = true, } }; clientProcess.StartInfo.EnvironmentVariables.Add("WINEDLLOVERRIDES","dinput8.dll=n,b"); clientProcess.StartInfo.EnvironmentVariables.Add("WINEPREFIX",Path.Combine(workingDirectory, "..", "WinePrefix")); return clientProcess; } } }
34.785714
152
0.565503
[ "MIT" ]
Frozenreflex/Nexus-LU-Launcher
NLUL.Core/Client/Runtime/UserInstalledWine.cs
2,435
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Hippo.SuperMarket.WebApp { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); IocConfig.ConfigIoc(); } } }
22.65
60
0.679912
[ "MIT" ]
voceanl/HSuperMarket
HSuperMarket/Hippo.SuperMarket.WebApp/Global.asax.cs
455
C#
// Copyright (c) 2020 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using Android.App; using Android.Runtime; namespace ReactiveUI { /// <summary> /// This is a Fragment that is both an Activity and has ReactiveObject powers /// (i.e. you can call RaiseAndSetIfChanged). /// </summary> /// <typeparam name="TViewModel">The view model type.</typeparam> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same class names within.")] [Obsolete("This class was deprecated in API level 28. Use the ReactiveFragment in ReactiveUI.AndroidX (recommended) or ReactiveUI.AndroidSupport for consistent behavior across all devices and access to Lifecycle.", false)] public class ReactiveFragment<TViewModel> : ReactiveFragment, IViewFor<TViewModel>, ICanActivate where TViewModel : class { private TViewModel? _viewModel; /// <summary> /// Initializes a new instance of the <see cref="ReactiveFragment{TViewModel}"/> class. /// </summary> protected ReactiveFragment() { } /// <summary> /// Initializes a new instance of the <see cref="ReactiveFragment{TViewModel}"/> class. /// </summary> /// <param name="handle">The handle.</param> /// <param name="ownership">The ownership.</param> protected ReactiveFragment(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } /// <inheritdoc/> public TViewModel? ViewModel { get => _viewModel; set => this.RaiseAndSetIfChanged(ref _viewModel, value); } /// <inheritdoc/> object? IViewFor.ViewModel { get => _viewModel; set => _viewModel = (TViewModel?)value!; } } /// <summary> /// This is a Fragment that is both an Activity and has ReactiveObject powers /// (i.e. you can call RaiseAndSetIfChanged). /// </summary> [SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleType", Justification = "Classes with the same class names within.")] [Obsolete("This class was deprecated in API level 28. Use the ReactiveFragment in ReactiveUI.AndroidX (recommended) or ReactiveUI.AndroidSupport for consistent behavior across all devices and access to Lifecycle.", false)] public class ReactiveFragment : Fragment, IReactiveNotifyPropertyChanged<ReactiveFragment>, IReactiveObject, IHandleObservableErrors { private readonly Subject<Unit> _activated = new Subject<Unit>(); private readonly Subject<Unit> _deactivated = new Subject<Unit>(); /// <summary> /// Initializes a new instance of the <see cref="ReactiveFragment"/> class. /// </summary> protected ReactiveFragment() { } /// <summary> /// Initializes a new instance of the <see cref="ReactiveFragment"/> class. /// </summary> /// <param name="handle">The handle.</param> /// <param name="ownership">The ownership.</param> protected ReactiveFragment(IntPtr handle, JniHandleOwnership ownership) : base(handle, ownership) { } /// <inheritdoc/> public event PropertyChangingEventHandler? PropertyChanging; /// <inheritdoc/> public event PropertyChangedEventHandler? PropertyChanged; /// <inheritdoc /> public IObservable<IReactivePropertyChangedEventArgs<ReactiveFragment>> Changing => this.GetChangingObservable(); /// <inheritdoc /> public IObservable<IReactivePropertyChangedEventArgs<ReactiveFragment>> Changed => this.GetChangedObservable(); /// <inheritdoc/> public IObservable<Exception> ThrownExceptions => this.GetThrownExceptionsObservable(); /// <summary> /// Gets the activated. /// </summary> /// <value> /// The activated. /// </value> public IObservable<Unit> Activated => _activated.AsObservable(); /// <summary> /// Gets a signal when the fragment is deactivated. /// </summary> /// <value> /// The deactivated. /// </value> public IObservable<Unit> Deactivated => _deactivated.AsObservable(); /// <inheritdoc/> void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) { PropertyChanging?.Invoke(this, args); } /// <inheritdoc/> void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) { PropertyChanged?.Invoke(this, args); } /// <summary> /// When this method is called, an object will not fire change /// notifications (neither traditional nor Observable notifications) /// until the return value is disposed. /// </summary> /// <returns>An object that, when disposed, reenables change /// notifications.</returns> public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this); /// <inheritdoc/> public override void OnPause() { base.OnPause(); _deactivated.OnNext(Unit.Default); } /// <inheritdoc/> public override void OnResume() { base.OnResume(); _activated.OnNext(Unit.Default); } /// <inheritdoc/> protected override void Dispose(bool disposing) { if (disposing) { _activated?.Dispose(); _deactivated?.Dispose(); } base.Dispose(disposing); } } }
36.964286
226
0.632528
[ "MIT" ]
Evangelink/ReactiveUI
src/ReactiveUI/Platforms/android/ReactiveFragment.cs
6,212
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Android.App; // 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("DemoXamarin.Android")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DemoXamarin.Android")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // 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")] // Add some common permissions, these can be removed if not needed [assembly: UsesPermission(Android.Manifest.Permission.Internet)] [assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
36.714286
84
0.757198
[ "MIT" ]
Shaw6157/ToyLibrary
DemoXamarinCloud/DemoXamarin/DemoXamarin.Android/Properties/AssemblyInfo.cs
1,288
C#
#if MODULE_AUDIO || PACKAGE_DOCS_GENERATION using UnityEngine.Localization.Events; namespace UnityEngine.Localization.Components { /// <summary> /// Component that can be used to Localize an [AudioClip](https://docs.unity3d.com/ScriptReference/AudioClip.html) asset. /// Provides an update event <see cref="LocalizedAssetEvent{TObject, TReference, TEvent}.OnUpdateAsset"/> that can be used to automatically /// update the clip whenever the <see cref="Settings.LocalizationSettings.SelectedLocale"/> or <see cref="LocalizedAssetBehaviour{TObject, TReference}.AssetReference"/> changes. /// </summary> /// <example> /// This example shows how a Localized Audio Control panel could be created. /// The example show how it is possible to switch between different Localized Audio clips. /// ![](../manual/images/scripting/LocalizedAudioChanger.png) /// <code source="../../DocCodeSamples.Tests/LocalizedAudioChanger.cs"/> /// </example> /// <remarks> /// This component can also be added through the **Localize** menu item in the [Audio Source](https://docs.unity3d.com/Manual/class-AudioSource.html) context menu. /// Adding it this way will also automatically configure the Update Asset events to update the [Audio Source](https://docs.unity3d.com/Manual/class-AudioSource.html). /// </remarks> [AddComponentMenu("Localization/Asset/Localize Audio Clip Event")] public class LocalizeAudioClipEvent : LocalizedAssetEvent<AudioClip, LocalizedAudioClip, UnityEventAudioClip> { } } #endif
53.827586
181
0.735426
[ "MIT" ]
WeLikeIke/DubitaC
Source/Library/PackageCache/[email protected]/Runtime/Component Localizers/LocalizeAudioClipEvent.cs
1,561
C#
// ReSharper disable RedundantUsingDirective // ReSharper disable DoNotCallOverridableMethodsInConstructor // ReSharper disable InconsistentNaming // ReSharper disable PartialTypeWithSinglePart // ReSharper disable PartialMethodWithSinglePart // ReSharper disable RedundantNameQualifier // ReSharper disable UnusedMember.Global #pragma warning disable 1591 // Ignore "Missing XML Comment" warning using System; using System.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; namespace Geco.Tests.Database.Model { [GeneratedCode("Geco", "1.0.5.0")] public partial class Shift { // Key Properties public byte ShiftID { get; set; } // Scalar Properties public string Name { get; set; } public TimeSpan StartTime { get; set; } public TimeSpan EndTime { get; set; } public DateTime ModifiedDate { get; set; } // Reverse navigation public List<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; } public Shift() { EmployeeDepartmentHistories = new List<EmployeeDepartmentHistory>(); } } }
32.307692
88
0.723016
[ "Apache-2.0" ]
raminrahimzada/Geco
Test/Geco.Tests/Database/Model/Shift.cs
1,260
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Charlotte.Tools; using System.Collections; namespace Charlotte { public partial class TreeSheetWin : Form { private TreeView TV; public TreeSheetWin(TreeView tv) { this.TV = tv; InitializeComponent(); this.MinimumSize = this.Size; this.South.Text = Ground.OpenedRootDir; this.SouthEast.Text = ""; ExtraTools.SetEnabledDoubleBuffer(this.MainSheet); } private void TreeSheetWin_Load(object sender, EventArgs e) { if (Ground.TreeSheetWin_W != -1) { this.Left = Ground.TreeSheetWin_L; this.Top = Ground.TreeSheetWin_T; this.Width = Ground.TreeSheetWin_W; this.Height = Ground.TreeSheetWin_H; } } private void TreeSheetWin_Shown(object sender, EventArgs e) { this.MS_Init(); this.MS_Load(this.TV); } private void TreeSheetWin_FormClosing(object sender, FormClosingEventArgs e) { // noop } private void TreeSheetWin_FormClosed(object sender, FormClosedEventArgs e) { if (this.WindowState == FormWindowState.Normal) { Ground.TreeSheetWin_L = this.Left; Ground.TreeSheetWin_T = this.Top; Ground.TreeSheetWin_W = this.Width; Ground.TreeSheetWin_H = this.Height; } this.MS_Save(this.TV); } private void 閉じるToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void MainSheet_CellContentClick(object sender, DataGridViewCellEventArgs e) { // noop } // // このへんから MainSheet 用 // // 列インデックス > private const int MS_COL_CHECK = 0; // < 列インデックス private void MS_Init() { this.MainSheet.RowCount = 0; this.MainSheet.ColumnCount = 0; this.MS_AddColumn("", 50, true); this.MS_AddColumn("パス", 300); this.MS_AddColumn("ローカル名", 200); this.MS_AddColumn("拡張子", 100); this.MS_AddColumn("サイズ", 100, false, true); } private void MS_AddColumn(string title, int width, bool checkBox = false, bool rightAlign = false) { DataGridViewColumn column; if (checkBox) column = new DataGridViewCheckBoxColumn(); else column = new DataGridViewTextBoxColumn(); column.HeaderText = title; column.Width = width; column.SortMode = DataGridViewColumnSortMode.Programmatic; if (rightAlign) column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; this.MainSheet.Columns.Add(column); } private void MS_Load(TreeView tv) { using (new Utils.UISuspend(this.MainSheet)) { List<MS_Record> records = this.GetRecords(tv.Nodes); this.MainSheet.RowCount = 0; this.MainSheet.RowCount = records.Count; ProgressDlg.Perform(interlude => { int rowidx_denom = Math.Max(1, records.Count / 31); for (int rowidx = 0; rowidx < records.Count; rowidx++) { if (rowidx % rowidx_denom == 0) interlude((rowidx * 100.0 / records.Count) + " %"); MS_Record record = records[rowidx]; DataGridViewRow row = this.MainSheet.Rows[rowidx]; int c = 0; row.Cells[c++].Value = record.Checked; row.Cells[c++].Value = record.FilePath; row.Cells[c++].Value = Path.GetFileName(record.FilePath); row.Cells[c++].Value = Path.GetExtension(record.FilePath); row.Cells[c++].Value = Ground.TreeSheet_CheckFileSize ? Utils.TryGetFileSize(Path.Combine(Ground.RootDir, record.FilePath), -1L) : -2L; row.Tag = record.Node; } }); this.SouthEast.Text = "" + this.MainSheet.RowCount; // 暫定 } this.MainSheet.ClearSelection(); } private void MS_Save(TreeView tv) { foreach (DataGridViewRow row in this.MainSheet.Rows) { ((TreeNode)row.Tag).Checked = (bool)row.Cells[0].Value; } } private class MS_Record { public bool Checked; public string FilePath; public TreeNode Node; } private void MainSheet_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { int colidx = e.ColumnIndex; if (colidx < 0 || this.MainSheet.ColumnCount <= colidx) return; SortOrder order = this.MainSheet.Columns[colidx].HeaderCell.SortGlyphDirection; if (order == SortOrder.Ascending) order = SortOrder.Descending; else order = SortOrder.Ascending; this.MS_Sort(colidx, order); for (int ci = 0; ci < this.MainSheet.ColumnCount; ci++) this.MainSheet.Columns[ci].HeaderCell.SortGlyphDirection = ci == colidx ? order : SortOrder.None; } private void MS_Sort(int colidx, SortOrder order) { this.MS_Sort((a, b) => this.MS_CellComp( "" + a.Cells[colidx].Value, "" + b.Cells[colidx].Value, this.MainSheet.Columns[colidx] ) * (order == SortOrder.Ascending ? 1 : -1)); } private int MS_CellComp(string a, string b, DataGridViewColumn column) { if (column.DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleRight) return LongTools.Comp(long.Parse(a), long.Parse(b)); return StringTools.CompIgnoreCase(a, b); } private void MS_Sort(Comparison<DataGridViewRow> comp) { this.MainSheet.Sort(new MS_Comp() { Comp = comp, }); this.MainSheet.ClearSelection(); } private class MS_Comp : IComparer { public Comparison<DataGridViewRow> Comp; public int Compare(object a, object b) { return Comp((DataGridViewRow)a, (DataGridViewRow)b); } } private void MainSheet_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex != -1 && e.ColumnIndex == MS_COL_CHECK) { bool value = (bool)this.MainSheet.Rows[e.RowIndex].Cells[MS_COL_CHECK].Value; value = value == false; this.MainSheet.Rows[e.RowIndex].Cells[MS_COL_CHECK].Value = value; } } private IEnumerable<DataGridViewRow> MS_GetSelectedRows() { foreach (DataGridViewRow row in this.MainSheet.Rows) if (row.Selected) yield return row; } // // このへんまで MainSheet 用 // private List<MS_Record> GetRecords(TreeNodeCollection rootNodes) { List<MS_Record> dest = new List<MS_Record>(); this.CollectRecord(rootNodes, "", dest); return dest; } private void CollectRecord(TreeNodeCollection nodes, string prefix, List<MS_Record> dest) { foreach (TreeNode node in nodes) { if (((NodeTag)node.Tag).DirFlag) { CollectRecord(node.Nodes, prefix + node.Text + "\\", dest); } else { dest.Add(new MS_Record() { Checked = node.Checked, FilePath = prefix + node.Text, Node = node, }); } } } private void 選択解除ToolStripMenuItem_Click(object sender, EventArgs e) { this.MainSheet.ClearSelection(); } private void 選択されている行にチェックを入れるToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in this.MS_GetSelectedRows()) { row.Cells[MS_COL_CHECK].Value = true; } } private void 選択されている行のチェックを外すToolStripMenuItem_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in this.MS_GetSelectedRows()) { row.Cells[MS_COL_CHECK].Value = false; } } } }
23.96633
101
0.681933
[ "MIT" ]
stackprobe/Annex
Bodewig/Chroco/MkList/MkList/TreeSheetWin.cs
7,286
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for ComplianceExecutionSummary Object /// </summary> public class ComplianceExecutionSummaryUnmarshaller : IUnmarshaller<ComplianceExecutionSummary, XmlUnmarshallerContext>, IUnmarshaller<ComplianceExecutionSummary, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> ComplianceExecutionSummary IUnmarshaller<ComplianceExecutionSummary, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public ComplianceExecutionSummary Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; ComplianceExecutionSummary unmarshalledObject = new ComplianceExecutionSummary(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ExecutionId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ExecutionId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ExecutionTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.ExecutionTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("ExecutionType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.ExecutionType = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ComplianceExecutionSummaryUnmarshaller _instance = new ComplianceExecutionSummaryUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ComplianceExecutionSummaryUnmarshaller Instance { get { return _instance; } } } }
37.942308
192
0.621896
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/ComplianceExecutionSummaryUnmarshaller.cs
3,946
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace MergeSpectra { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.818182
66
0.573705
[ "Apache-2.0" ]
Jamejarrs/WALICDH
source/seabreeze-3.0.11/util/MergeSpectra/src/Program.cs
504
C#
using Microsoft.Extensions.Primitives; namespace Handyman.Azure.Functions.Http.ApiVersioning { public class ValidationContext { public string ErrorMessage { get; set; } public bool Optional { get; internal set; } public string MatchedVersion { get; set; } public StringValues ValidVersions { get; internal set; } public string Version { get; internal set; } } }
31.923077
64
0.679518
[ "MIT" ]
JonasSamuelsson/Handyman
src/Handyman.Azure.Functions/src/Http/ApiVersioning/ValidationParams.cs
417
C#
using System; using System.Drawing; using System.Collections; namespace Crainiate.Diagramming.Layouts { internal class GridNode { public int X; public int Y; public GridNode() { } public GridNode(int x, int y) { X = x; Y = y; } } }
11.391304
39
0.641221
[ "BSD-2-Clause" ]
digitalmavica/opendiagram
Previous_Versions/Version_4.1/OpenDiagram.Diagramming/Open.Diagramming.Layouts/GridNode.cs
262
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using Debug = System.Diagnostics.Debug; using StringBuilder = System.Text.StringBuilder; public class Clicountingd2 { public int count(string[] g) { var n = g.Length; var id = new int[n, n]; var k = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { id[i, j] = -1; if (g[i][j] == '?') id[i, j] = k++; } var ans = new int[1 << k]; for (int mask = 0; mask < 1 << n; mask++) { var ok = true; var flag = 0; var cnt = 0; for (int i = 0; i < n; i++) { if ((mask >> i & 1) == 0) continue; cnt++; for (int j = i + 1; j < n; j++) { if ((mask >> j & 1) == 0) continue; if (g[i][j] == '1') continue; else if (g[i][j] == '0') ok = false; else flag |= 1 << id[i, j]; } } if (ok) ans[flag] = Math.Max(ans[flag], cnt); } for (int i = 0; i < 1 << k; i++) { for (int j = 0; j < k; j++) ans[i | (1 << j)] = Math.Max(ans[i | (1 << j)], ans[i]); } return ans.Sum(); } static public T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } static public void Swap<T>(ref T a, ref T b) { var tmp = a; a = b; b = tmp; } // CUT begin public int Naive_Test(string[] g) { return 0; } // CUT end } static public class EnumerableEX { static public string AsString(this IEnumerable<char> e) { return new string(e.ToArray()); } static public string AsJoinedString<T>(this IEnumerable<T> e, string s = " ") { return string.Join(s, e); } } // CUT begin public partial class Tester: AbstractTester { static public T[] Enumerate<T>(int n, Func<int, T> f) { var a = new T[n]; for (int i = 0; i < n; ++i) a[i] = f(i); return a; } public Random rand = new Random(0); public void OnInit() { //Tests.Add(null); } } // CUT end
30.662162
130
0.446011
[ "MIT" ]
Camypaper/TopCoder
workspace/SRM 696/Clicountingd2.cs
2,269
C#
using FlavBattle.Core; using FlavBattle.State; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIManager : MonoBehaviour { public FormationPanel FormationPanel; public ArmyPanel ArmyPanel; public ActionButtonsPanel ActionButtonsPanel; public ArmyEditWindow ArmyEditWindow; public MonoBehaviour[] MapUI; public event EventHandler<IArmy> ArmyModified; public event EventHandler<Unit> UnitReplaced; public event EventHandler<IArmy> ArmyDeployed; private GameEventManager _gameEvents; void Start() { ArmyEditWindow.Hide(); ArmyPanel.Hide(); ArmyEditWindow.ArmyModified += HandleArmyModified; ArmyEditWindow.UnitReplaced += HandleUnitReplaced; ArmyEditWindow.ArmyDeployed += HandleArmyDeployed; _gameEvents = Instances.Current.Managers.GameEvents; _gameEvents.CombatStartedEvent += HandleCombatStartedEvent; _gameEvents.CombatEndedEvent += HandleCombatEndedEvent; UpdateSelectedArmyUI(null); } private void HandleArmyDeployed(object sender, IArmy army) { ArmyDeployed?.Invoke(this, army); } private void HandleCombatEndedEvent(object sender, CombatEndedEventArgs e) { ShowMapUI(); } private void HandleCombatStartedEvent(object sender, CombatStartedEventArgs e) { HideMapUI(); } private void HideMapUI() { FormationPanel.Hide(); foreach (var ui in MapUI) { ui.Hide(); } } private void ShowMapUI() { foreach (var ui in MapUI) { ui.Show(); } } private void HandleUnitReplaced(object sender, Unit e) { UnitReplaced?.Invoke(this, e); } private void HandleArmyModified(object sender, IArmy e) { ArmyModified?.Invoke(this, e); ArmyPanel.UpdatePanelContents(); } public void ToggleArmyPanel() { ArmyPanel.ToggleActive(); } public void ShowArmyEditWindow(IArmy army) { if (!ArmyEditWindow.IsShowing()) { Sounds.Play(UISoundType.Open); ArmyEditWindow.Show(); ArmyPanel.Hide(); ArmyEditWindow.SetMode(ArmyEditWindow.Mode.DeployedArmy); ArmyEditWindow.SetArmy(army); } } public void ShowGarrisonWindow(IArmy[] storedArmies, Unit[] storedUnits) { if (!ArmyEditWindow.IsShowing()) { Sounds.Play(UISoundType.Open); ArmyEditWindow.Show(); ArmyPanel.Hide(); ArmyEditWindow.SetMode(ArmyEditWindow.Mode.Garrison); ArmyEditWindow.SetArmy(null); UpdateGarrisonWindow(storedArmies, storedUnits); } } public void UpdateGarrisonWindow(IArmy[] storedArmies, Unit[] storedUnits) { ArmyEditWindow.SetArmyPanelContents(storedArmies); ArmyEditWindow.SetUnitPanelContents(storedUnits); } public void HideArmyEditWindow() { Sounds.Play(UISoundType.Close); ArmyEditWindow.Hide(); _gameEvents.TriggerMapEvent(MapEventType.MapUnpaused); } /// <summary> /// Handles all necessary events resulting from an /// army being created and deployed. /// </summary> public void ArmyCreated(Army army) { if (army.IsPlayerArmy) { ArmyPanel.AddArmy(army); } } public void UpdateSelectedArmyUI(Army selected) { if (selected == null) { this.FormationPanel.Hide(); this.ActionButtonsPanel.Hide(); } else { this.FormationPanel.Show(); this.FormationPanel.SetArmy(selected); this.ActionButtonsPanel.Show(); this.ActionButtonsPanel.SetArmy(selected); } this.ArmyPanel.SetSelectedArmy(selected); } }
26
83
0.605891
[ "MIT" ]
Flavkupe/FlavBattle
Assets/Scripts/UI/UIManager.cs
4,110
C#
// // PaketApplicationPath.cs // // Author: // Matt Ward <[email protected]> // // Copyright (c) 2015 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System.IO; namespace MonoDevelop.Paket { public class PaketApplicationPath { public static PaketApplicationPath GetPath () { string directory = Path.GetDirectoryName (typeof(PaketApplicationPath).Assembly.Location); string fileName = Path.Combine (directory, "paket.exe"); return new PaketApplicationPath (fileName); } PaketApplicationPath (string fileName) { ApplicationPath = fileName; } public string ApplicationPath { get; private set; } public override string ToString () { return ApplicationPath; } } }
32.018182
93
0.745599
[ "MIT" ]
mrward/monodevelop-paket-addin
src/MonoDevelop.Paket/MonoDevelop.Paket/PaketApplicationPath.cs
1,763
C#
// ----------------------------------------------------------------------------- // GENERATED CODE - DO NOT EDIT // ----------------------------------------------------------------------------- using System; using System.Linq; using System.Collections.Generic; using Hl7.Fhir.Model; using Hl7.Fhir.Utility; using System.Xml.Serialization; using System.Xml; using System.Xml.Linq; using System.Threading; namespace Hl7.Fhir.CustomSerializer { public partial class FhirCustomXmlReader { public void Parse(Hl7.Fhir.Model.Contract.ActionSubjectComponent result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken) { // skip ignored elements while (ShouldSkipNodeType(reader.NodeType)) if (!reader.Read()) return; if (reader.MoveToFirstAttribute()) { do { switch (reader.Name) { case "id": result.ElementId = reader.Value; break; } } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } if (reader.IsEmptyElement) return; // otherwise proceed to read all the other nodes while (reader.Read()) { if (cancellationToken.IsCancellationRequested) return; if (reader.IsStartElement()) { switch (reader.Name) { case "extension": var newItem_extension = new Hl7.Fhir.Model.Extension(); Parse(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 20 result.Extension.Add(newItem_extension); break; case "modifierExtension": var newItem_modifierExtension = new Hl7.Fhir.Model.Extension(); Parse(newItem_modifierExtension, reader, outcome, locationPath + ".modifierExtension["+result.ModifierExtension.Count+"]", cancellationToken); // 30 result.ModifierExtension.Add(newItem_modifierExtension); break; case "reference": var newItem_reference = new Hl7.Fhir.Model.ResourceReference(); Parse(newItem_reference, reader, outcome, locationPath + ".reference["+result.Reference.Count+"]", cancellationToken); // 40 result.Reference.Add(newItem_reference); break; case "role": result.Role = new Hl7.Fhir.Model.CodeableConcept(); Parse(result.Role as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".role", cancellationToken); // 50 break; default: // Property not found HandlePropertyNotFound(reader, outcome, locationPath + "." + reader.Name); break; } } else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement) { break; } } } public async System.Threading.Tasks.Task ParseAsync(Hl7.Fhir.Model.Contract.ActionSubjectComponent result, XmlReader reader, OperationOutcome outcome, string locationPath, CancellationToken cancellationToken) { // skip ignored elements while (ShouldSkipNodeType(reader.NodeType)) if (!await reader.ReadAsync().ConfigureAwait(false)) return; if (reader.MoveToFirstAttribute()) { do { switch (reader.Name) { case "id": result.ElementId = reader.Value; break; } } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } if (reader.IsEmptyElement) return; // otherwise proceed to read all the other nodes while (await reader.ReadAsync().ConfigureAwait(false)) { if (cancellationToken.IsCancellationRequested) return; if (reader.IsStartElement()) { switch (reader.Name) { case "extension": var newItem_extension = new Hl7.Fhir.Model.Extension(); await ParseAsync(newItem_extension, reader, outcome, locationPath + ".extension["+result.Extension.Count+"]", cancellationToken); // 20 result.Extension.Add(newItem_extension); break; case "modifierExtension": var newItem_modifierExtension = new Hl7.Fhir.Model.Extension(); await ParseAsync(newItem_modifierExtension, reader, outcome, locationPath + ".modifierExtension["+result.ModifierExtension.Count+"]", cancellationToken); // 30 result.ModifierExtension.Add(newItem_modifierExtension); break; case "reference": var newItem_reference = new Hl7.Fhir.Model.ResourceReference(); await ParseAsync(newItem_reference, reader, outcome, locationPath + ".reference["+result.Reference.Count+"]", cancellationToken); // 40 result.Reference.Add(newItem_reference); break; case "role": result.Role = new Hl7.Fhir.Model.CodeableConcept(); await ParseAsync(result.Role as Hl7.Fhir.Model.CodeableConcept, reader, outcome, locationPath + ".role", cancellationToken); // 50 break; default: // Property not found await HandlePropertyNotFoundAsync(reader, outcome, locationPath + "." + reader.Name); break; } } else if (reader.NodeType == XmlNodeType.EndElement || reader.IsStartElement() && reader.IsEmptyElement) { break; } } } } }
34.241611
210
0.659153
[ "BSD-3-Clause" ]
brianpos/fhir-net-web-api
src/Hl7.Fhir.Custom.Serializers/Generated/FhirCustomXmlReader.Contract.ActionSubjectComponent.cs
5,104
C#
using System; using System.Collections.Generic; namespace Gloson.Collections.Generic { //------------------------------------------------------------------------------------------------------------------- // /// <summary> /// Comparer Builder /// </summary> // //------------------------------------------------------------------------------------------------------------------- public static partial class ComparerBuilder { #region Internal Classes private sealed class EmptyComparer<T> : IComparer<T> { public int Compare(T x, T y) => 0; } #endregion Internal Classes #region Public /// <summary> /// From Func /// </summary> public static IComparer<T> FromFunc<T>(Func<T, T, int> compare) { if (compare is null) throw new ArgumentNullException(nameof(compare)); return Comparer<T>.Create((x, y) => compare(x, y)); } /// <summary> /// Nulls First /// </summary> public static IComparer<T> NullsFirst<T>() { return Comparer<T>.Create((x, y) => { if (ReferenceEquals(x, y)) return 0; else if (x is null) return -1; else if (y is null) return 1; return 0; }); } /// <summary> /// Nulls Last /// </summary> public static IComparer<T> NullsLast<T>() { return Comparer<T>.Create((x, y) => { if (ReferenceEquals(x, y)) return 0; else if (x is null) return 1; else if (y is null) return -1; return 0; }); } /// <summary> /// Empty (all are equal to one another) /// </summary> public static IComparer<T> Empty<T>() => new EmptyComparer<T>(); /// <summary> /// Default /// </summary> public static IComparer<T> Default<T>() => Comparer<T>.Default; /// <summary> /// Default (Required) /// </summary> public static IComparer<T> DefaultRequired<T>() { IComparer<T> result = Comparer<T>.Default; if (result is null) throw new InvalidOperationException($"Type {typeof(T).Name} doesn't have any default Comparer."); return result; } #endregion Public } //------------------------------------------------------------------------------------------------------------------- // /// <summary> /// Comparer Extensions /// </summary> // //------------------------------------------------------------------------------------------------------------------- public static partial class ComparerExtensions { #region Inner Classes private class ReversedComparer<T> : IComparer<T> { private readonly IComparer<T> m_Comparer; public ReversedComparer(IComparer<T> comparer) { m_Comparer = comparer; } public int Compare(T x, T y) { int result = m_Comparer.Compare(x, y); if (result < 0) return 1; else if (result > 0) return -1; else return 0; } } private class ThenByComparer<T> : IComparer<T> { private readonly IComparer<T> m_First; private readonly IComparer<T> m_Next; public ThenByComparer(IComparer<T> first, IComparer<T> next) { m_First = first; m_Next = next; } public int Compare(T x, T y) { int result = m_First.Compare(x, y); return result != 0 ? result : m_Next.Compare(x, y); } } private class ThenByDescendingComparer<T> : IComparer<T> { private readonly IComparer<T> m_First; private readonly IComparer<T> m_Next; public ThenByDescendingComparer(IComparer<T> first, IComparer<T> next) { m_First = first; m_Next = next; } public int Compare(T x, T y) { int result = m_First.Compare(x, y); if (result != 0) return result; result = m_Next.Compare(x, y); if (result < 0) return 1; else if (result > 0) return -1; else return 0; } } #endregion Inner Classes #region Public /// <summary> /// Reverse /// </summary> public static IComparer<T> Reverse<T>(this IComparer<T> comparer) { if (comparer is null) throw new ArgumentNullException(nameof(comparer)); return new ReversedComparer<T>(comparer); } /// <summary> /// Then By /// </summary> public static IComparer<T> ThenBy<T>(this IComparer<T> comparer, IComparer<T> nextComparer) { if (comparer is null) throw new ArgumentNullException(nameof(comparer)); else if (nextComparer is null) throw new ArgumentNullException(nameof(nextComparer)); if (comparer == nextComparer) return comparer; return new ThenByComparer<T>(comparer, nextComparer); } /// <summary> /// Then By Descending /// </summary> public static IComparer<T> ThenByDescending<T>(this IComparer<T> comparer, IComparer<T> nextComparer) { if (comparer is null) throw new ArgumentNullException(nameof(comparer)); else if (nextComparer is null) throw new ArgumentNullException(nameof(nextComparer)); if (comparer == nextComparer) return comparer; return new ThenByDescendingComparer<T>(comparer, nextComparer); } #endregion Public } }
25.200935
119
0.526052
[ "MIT" ]
Dmitry-Bychenko/Gloson.Standard.Solution
Gloson.Standard/Collections/Generic/Gloson.Collections.Generic.Comparers.cs
5,395
C#