hexsha
stringlengths
40
40
size
int64
30
1.05M
ext
stringclasses
24 values
lang
stringclasses
5 values
max_stars_repo_path
stringlengths
4
355
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
float64
1
208k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
355
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
355
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
30
1.05M
avg_line_length
float64
2.67
1.04M
max_line_length
int64
9
1.04M
alphanum_fraction
float64
0.01
1
3d5240c49e77a5bfe37496da1b3c9050cac49bca
3,249
cs
C#
Serenity.Core/Authorization/Authorization.cs
awesomegithubusername/Serenity
7dc6b630f5ce0187135348bbff2a378d21ccc458
[ "MIT" ]
1
2021-02-24T23:13:39.000Z
2021-02-24T23:13:39.000Z
Serenity.Core/Authorization/Authorization.cs
awesomegithubusername/Serenity
7dc6b630f5ce0187135348bbff2a378d21ccc458
[ "MIT" ]
null
null
null
Serenity.Core/Authorization/Authorization.cs
awesomegithubusername/Serenity
7dc6b630f5ce0187135348bbff2a378d21ccc458
[ "MIT" ]
2
2020-12-01T09:19:53.000Z
2021-11-18T12:54:52.000Z
using Serenity.Abstractions; using Serenity.Services; using System; namespace Serenity { /// <summary> /// Provides a common access point for authorization related services /// </summary> public static class Authorization { /// <summary> /// Returns true if user is logged in. /// </summary> /// <remarks> /// Uses the IAuthorizationService dependency. /// </remarks> public static bool IsLoggedIn { get { return Dependency.Resolve<IAuthorizationService>().IsLoggedIn; } } /// <summary> /// Returns user definition for currently logged user. /// </summary> /// <remarks> /// Uses IUserRetrieveService to get definition of current user by /// its username. /// </remarks> public static IUserDefinition UserDefinition { get { var username = Username; if (username == null) return null; return Dependency.Resolve<IUserRetrieveService>().ByUsername(username); } } /// <summary> /// Returns currently logged user ID /// </summary> /// <remarks> /// This is a shortcut to UserDefinition.UserId. /// </remarks> public static string UserId { get { var user = UserDefinition; return user == null ? null : user.Id; } } /// <summary> /// Returns currently logged username. /// </summary> /// <remarks>Uses IAuthorizationService dependency.</remarks> public static string Username { get { return Dependency.Resolve<IAuthorizationService>().Username; } } /// <summary> /// Returns true if current user has given permission. /// </summary> /// <param name="permission">Permission key (e.g. Administration)</param> public static bool HasPermission(string permission) { return Dependency.Resolve<IPermissionService>().HasPermission(permission); } /// <summary> /// Checks if there is a currently logged user and throws a validation error with /// "NotLoggedIn" error code if not. /// </summary> public static void ValidateLoggedIn() { if (!IsLoggedIn) throw new ValidationError("NotLoggedIn", null, Serenity.Core.Texts.Authorization.NotLoggedIn); } /// <summary> /// Checks if current user has given permission and throws a validation error with /// "AccessDenied" error code if not. /// </summary> /// <param name="permission"></param> public static void ValidatePermission(string permission) { if (!HasPermission(permission)) throw new ValidationError("AccessDenied", null, Serenity.Core.Texts.Authorization.AccessDenied); } } }
31.852941
113
0.524469
3d53a13b1b60f5ece5b3b44cd8af98b4817d338f
2,218
cshtml
C#
Project1/StoreWebApp/Views/Stores/History.cshtml
042020-dotnet-uta/michaelHall-repo1
d372c145df81c085f7d345f381114df127baa31a
[ "MIT" ]
null
null
null
Project1/StoreWebApp/Views/Stores/History.cshtml
042020-dotnet-uta/michaelHall-repo1
d372c145df81c085f7d345f381114df127baa31a
[ "MIT" ]
null
null
null
Project1/StoreWebApp/Views/Stores/History.cshtml
042020-dotnet-uta/michaelHall-repo1
d372c145df81c085f7d345f381114df127baa31a
[ "MIT" ]
null
null
null
@model IEnumerable<StoreWebApp.Models.Order> @{ ViewData["Title"] = "Store Order History"; } @{ int index = 1;} @foreach (var item in Model) { if (index == 1) { <h1> Order History for @Html.DisplayFor(modelItem => item.Product.Store.Location) </h1> } index++; } @if (index == 1) { <h1> Store Order History </h1> } <table class="table text-white"> <thead> <tr> <th> @Html.DisplayNameFor(model => model.Customer.FirstName) </th> <th> @Html.DisplayNameFor(model => model.Customer.LastName) </th> <th> @Html.DisplayNameFor(model => model.Product.ProductName) </th> <th> @Html.DisplayNameFor(model => model.Quantity) </th> <th> @Html.DisplayNameFor(model => model.Product.Price) </th> <th> @Html.DisplayNameFor(model => model.Timestamp) </th> <th></th> </tr> </thead> <tbody> @{ int count = 0;} @foreach (var item in Model) { count++; <tr> <td> @Html.DisplayFor(modelItem => item.Customer.FirstName) </td> <td> @Html.DisplayFor(modelItem => item.Customer.LastName) </td> <td> @Html.DisplayFor(modelItem => item.Product.ProductName) </td> <td> @Html.DisplayFor(modelItem => item.Quantity) </td> <td> @{decimal total = item.Quantity * item.Product.Price;} $@total </td> <td> @Html.DisplayFor(modelItem => item.Timestamp) </td> </tr> } @if (count == 0) { <tr> This store has not had any orders placed yet. </tr> } </tbody> </table> <div> <a asp-action="Index">Back to Store Page</a> </div>
24.373626
75
0.419748
3d5514efc6e1c2206255d220fef1a1f72658e552
3,485
cs
C#
Ess3.Library/S3/Delete.cs
Kingloo/Ess3
cc95032b8670145d0aef7cdabc27393bed546682
[ "Unlicense" ]
null
null
null
Ess3.Library/S3/Delete.cs
Kingloo/Ess3
cc95032b8670145d0aef7cdabc27393bed546682
[ "Unlicense" ]
null
null
null
Ess3.Library/S3/Delete.cs
Kingloo/Ess3
cc95032b8670145d0aef7cdabc27393bed546682
[ "Unlicense" ]
null
null
null
using System.Net; using System.Threading; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; using Ess3.Library.Interfaces; using Ess3.Library.Model; namespace Ess3.Library.S3 { public static class Delete { public static Task<bool> FileAsync(IAccount account, Ess3Bucket bucket, Ess3File file) => FileAsync(account, bucket, file, CancellationToken.None); public static async Task<bool> FileAsync(IAccount account, Ess3Bucket bucket, Ess3File file, CancellationToken token) { DeleteObjectRequest request = new DeleteObjectRequest { BucketName = bucket.BucketName, Key = file.Key }; using IAmazonS3 client = new AmazonS3Client(account.GetCredentials(), bucket.RegionEndpoint); DeleteObjectResponse? response = await Helpers .RunWithCatchAsync<DeleteObjectRequest, DeleteObjectResponse>(client.DeleteObjectAsync, request, token) .ConfigureAwait(false); return (response?.HttpStatusCode ?? HttpStatusCode.BadRequest) == HttpStatusCode.OK; // I don't know what status code translates to success } public static Task<bool> DirectoryAsync(IAccount account, Ess3Bucket bucket, Ess3Directory directory, bool failOnHasItems) => DirectoryAsync(account, bucket, directory, failOnHasItems, CancellationToken.None); public static async Task<bool> DirectoryAsync(IAccount account, Ess3Bucket bucket, Ess3Directory directory, bool failOnHasItems, CancellationToken token) { if (BucketHasItems(bucket) && failOnHasItems) { return false; } DeleteObjectsRequest request = CreateDirectoryDeletionRequest(bucket, directory); using IAmazonS3 client = new AmazonS3Client(account.GetCredentials(), bucket.RegionEndpoint); DeleteObjectsResponse? response = await Helpers .RunWithCatchAsync<DeleteObjectsRequest, DeleteObjectsResponse>(client.DeleteObjectsAsync, request, token) .ConfigureAwait(false); return (response?.HttpStatusCode ?? HttpStatusCode.BadRequest) == HttpStatusCode.OK; // I don't know which status code translates to success } private static bool BucketHasItems(Ess3Bucket bucket) { //return bucket.Directories.Count + bucket.Files.Count > 0; return bucket.Ess3Objects.Count > 0; } private static DeleteObjectsRequest CreateDirectoryDeletionRequest(Ess3Bucket bucket, Ess3Directory directory) { DeleteObjectsRequest request = new DeleteObjectsRequest { BucketName = bucket.BucketName }; // delete the directory key itself request.AddKey(directory.Key); // delete every subdirectory key //foreach (Ess3Directory eachDirectory in bucket.Directories) //{ // request.AddKey(eachDirectory.Key); //} // delete every file key on the directory //foreach (Ess3File eachFile in bucket.Files) //{ // request.AddKey(eachFile.Key); //} foreach (Ess3Object each in bucket.Ess3Objects) { request.AddKey(each.Key); } return request; } } }
37.074468
161
0.635294
3d56f703606770dcfd1506d7f79742f05158e7ad
3,632
cs
C#
Source/ASBMessageTool/SendingMessages/SendersConfigs.cs
grzegorz-wolszczak/asb-message-tool
0f21fb53de19ae63c39979d4a1c9d25ccd47c544
[ "BSD-3-Clause" ]
null
null
null
Source/ASBMessageTool/SendingMessages/SendersConfigs.cs
grzegorz-wolszczak/asb-message-tool
0f21fb53de19ae63c39979d4a1c9d25ccd47c544
[ "BSD-3-Clause" ]
null
null
null
Source/ASBMessageTool/SendingMessages/SendersConfigs.cs
grzegorz-wolszczak/asb-message-tool
0f21fb53de19ae63c39979d4a1c9d25ccd47c544
[ "BSD-3-Clause" ]
null
null
null
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using ASBMessageTool.SendingMessages.Gui; namespace ASBMessageTool.SendingMessages; public sealed class SendersConfigs : INotifyPropertyChanged { private SenderConfigViewModel _currentSelectedItem; private readonly ObservableCollection<SenderConfigViewModel> _senderConfigViewModels; private readonly Dictionary<SenderConfigViewModel, SenderConfigStandaloneWindowViewer> _windowsForItems = new(); private readonly ISenderConfigWindowFactory _senderConfigWindowFactory; private readonly SenderConfigViewModelFactory _senderConfigViewModelFactory; private readonly SenderConfigModelFactory _senderConfigModelFactory; public SendersConfigs( ObservableCollection<SenderConfigViewModel> senderConfigViewModels, ISenderConfigWindowFactory senderConfigWindowFactory, SenderConfigViewModelFactory senderConfigViewModelFactory, SenderConfigModelFactory senderConfigModelFactory) { _senderConfigViewModels = senderConfigViewModels; _senderConfigWindowFactory = senderConfigWindowFactory; _senderConfigViewModelFactory = senderConfigViewModelFactory; _senderConfigModelFactory = senderConfigModelFactory; } public void AddNewForModelItem(SenderConfigModel senderConfigModel) { var windowForSenderConfig = _senderConfigWindowFactory.CreateWindowForConfig(); var viewModel = _senderConfigViewModelFactory.Create(senderConfigModel, windowForSenderConfig); windowForSenderConfig.SetDataContext(viewModel); SendersConfigsVMs.Add(viewModel); _windowsForItems.Add(viewModel, windowForSenderConfig); } public event PropertyChangedEventHandler PropertyChanged; public IList<SenderConfigViewModel> SendersConfigsVMs => _senderConfigViewModels; public SenderConfigViewModel CurrentSelectedConfigModelItem { get => _currentSelectedItem; set { if (value == _currentSelectedItem) return; _currentSelectedItem = value; OnPropertyChanged(); } } private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void AddNew() { AddNewForModelItem(_senderConfigModelFactory.Create()); } public void Remove(SenderConfigViewModel item) { _windowsForItems[item].DeleteWindow(); _senderConfigViewModels.Remove(item); _windowsForItems.Remove(item); } public bool CanMoveUp(SenderConfigViewModel item) { if (item is null) return false; return _senderConfigViewModels.IndexOf(item) > 0; } public void MoveConfigUp(SenderConfigViewModel item) { if (!CanMoveUp(item)) return; var oldIndex = _senderConfigViewModels.IndexOf(item); _senderConfigViewModels.Move(oldIndex, oldIndex - 1); } public bool CanMoveDown(SenderConfigViewModel item) { if (item is null) return false; return _senderConfigViewModels.IndexOf(item) < _senderConfigViewModels.Count - 1; } public void MoveConfigDown(SenderConfigViewModel item) { if (!CanMoveDown(item)) return; var oldIndex = _senderConfigViewModels.IndexOf(item); _senderConfigViewModels.Move(oldIndex, oldIndex + 1); } }
35.960396
117
0.72467
3d57d883d7f5f4b62ed0455ae336fe0f348e74ad
13,587
cs
C#
Database/Tables/BasicElements/TimeBasedProfile.cs
vitorbellotto/LoadProfileGenerator
2fa694a9fe93c5ad6c5aa05416f9f99cb3a1da69
[ "MIT" ]
null
null
null
Database/Tables/BasicElements/TimeBasedProfile.cs
vitorbellotto/LoadProfileGenerator
2fa694a9fe93c5ad6c5aa05416f9f99cb3a1da69
[ "MIT" ]
null
null
null
Database/Tables/BasicElements/TimeBasedProfile.cs
vitorbellotto/LoadProfileGenerator
2fa694a9fe93c5ad6c5aa05416f9f99cb3a1da69
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------- // <copyright> // // Copyright (c) TU Chemnitz, Prof. Technische Thermodynamik // Written by Noah Pflugradt. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the distribution. // All advertising materials mentioning features or use of this software must display the following acknowledgement: // “This product includes software developed by the TU Chemnitz, Prof. Technische Thermodynamik and its contributors.” // Neither the name of the University nor the names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, S // PECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; L // OSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // </copyright> //----------------------------------------------------------------------- #region assign using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using Automation; using Automation.ResultFiles; using Common; using Database.Database; using JetBrains.Annotations; #endregion namespace Database.Tables.BasicElements { public enum TimeProfileType { Relative = 0, Absolute = 1 } public class TimeBasedProfile : DBBaseElement { public const string TableName = "tblTimeBasedProfile"; [JetBrains.Annotations.NotNull] private string _dataSource; private TimeProfileType _timeProfileType; public TimeBasedProfile([JetBrains.Annotations.NotNull] string name, [CanBeNull] int? pID, [JetBrains.Annotations.NotNull] string connectionString, TimeProfileType timeProfileType, [JetBrains.Annotations.NotNull] string dataSource, StrGuid guid) : base(name, TableName, connectionString, guid) { _timeProfileType = timeProfileType; ObservableDatapoints = new ObservableCollection<TimeDataPoint>(); ID = pID; _dataSource = dataSource; TypeDescription = "Time profile"; } public int DatapointsCount => ObservableDatapoints.Count; [JetBrains.Annotations.NotNull] [UsedImplicitly] public string DataSource { get => _dataSource; set => SetValueWithNotify(value, ref _dataSource, nameof(DataSource)); } public TimeSpan Duration { get { var ts = new TimeSpan(0); foreach (var timeDataPoint in ObservableDatapoints) { if (timeDataPoint.Time > ts) { ts = timeDataPoint.Time; } } return ts; } } public double Maxiumum { get { var maxval = double.MinValue; foreach (var point in ObservableDatapoints) { if (point.Value > maxval) { maxval = point.Value; } } return maxval; } } [JetBrains.Annotations.NotNull] [UsedImplicitly] public string NameWithTime => Name + " [" + GetMaximumTime() + "]"; [ItemNotNull] [JetBrains.Annotations.NotNull] public ObservableCollection<TimeDataPoint> ObservableDatapoints { get; } [UsedImplicitly] public TimeProfileType TimeProfileType { get => _timeProfileType; set { SetValueWithNotify(value, ref _timeProfileType, nameof(TimeProfileType)); OnPropertyChanged(nameof(ValueTypeLabel)); } } [JetBrains.Annotations.NotNull] [UsedImplicitly] public string ValueTypeLabel => CalculateValueTypeLabel(); public void AddNewTimepoint(TimeSpan ts, double value, bool saveAndSort = true) { var tp = new TimeDataPoint(ts, value, null, IntID, ConnectionString, System.Guid.NewGuid().ToStrGuid()); lock (ObservableDatapoints) { ObservableDatapoints.Add(tp); } if (saveAndSort) { SaveToDB(); lock (ObservableDatapoints) { ObservableDatapoints.Sort(); } OnPropertyChanged(nameof(Duration)); } } [JetBrains.Annotations.NotNull] private static TimeBasedProfile AssignFields([JetBrains.Annotations.NotNull] DataReader dr, [JetBrains.Annotations.NotNull] string connectionString, bool ignoreMissingFields, [JetBrains.Annotations.NotNull] AllItemCollections aic) { var id = dr.GetIntFromLong("ID"); var name = dr.GetString("Name"); var timeprofiletypeid = dr.GetIntFromLong("TimeProfileType", false, ignoreMissingFields); var dataSource = dr.GetString("DataSource", false, string.Empty, ignoreMissingFields); var guid = GetGuid(dr, ignoreMissingFields); return new TimeBasedProfile(name, id, connectionString, (TimeProfileType) timeprofiletypeid, dataSource,guid); } [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public static TimeSpan CalculateMinimumTimespan() => new TimeSpan(0, 1, 0); // no need anymore for the entire minimum-timespan-thing since // there is the function to go both to finer and coarser time resolutions public double CalculateSecondsPercent() { double value = 0; for (var i = 1; i < ObservableDatapoints.Count; i++) { var ts = ObservableDatapoints[i].Time - ObservableDatapoints[i - 1].Time; value += ts.TotalSeconds * ObservableDatapoints[i - 1].Value / 100; } return value; } public double CalculateSecondsSum() { double value = 0; for (var i = 1; i < ObservableDatapoints.Count; i++) { var ts = ObservableDatapoints[i].Time - ObservableDatapoints[i - 1].Time; value += ts.TotalSeconds * ObservableDatapoints[i - 1].Value; } return value; } [JetBrains.Annotations.NotNull] private string CalculateValueTypeLabel() { switch (TimeProfileType) { case TimeProfileType.Relative: return "Value [%]"; case TimeProfileType.Absolute: return "Value"; default: throw new LPGException("Forgotten Time Profile Type. Please report"); } } [JetBrains.Annotations.NotNull] [UsedImplicitly] public static DBBase CreateNewItem([JetBrains.Annotations.NotNull] Func<string, bool> isNameTaken, [JetBrains.Annotations.NotNull] string connectionString) => new TimeBasedProfile(FindNewName(isNameTaken, "New profile "), null, connectionString, TimeProfileType.Relative, "unknown", System.Guid.NewGuid().ToStrGuid()); public void DeleteAllTimepoints() { DeleteAllForOneParent(IntID, "TimeBasedProfileID", TimeDataPoint.TableName, ConnectionString); lock (ObservableDatapoints) { ObservableDatapoints.Clear(); } OnPropertyChanged(nameof(Duration)); } public override void DeleteFromDB() { base.DeleteFromDB(); DeleteAllTimepoints(); } public void DeleteTimepoint([JetBrains.Annotations.NotNull] TimeDataPoint tp) { tp.DeleteFromDB(); lock (ObservableDatapoints) { ObservableDatapoints.Remove(tp); } OnPropertyChanged(nameof(Duration)); } [JetBrains.Annotations.NotNull] private string GetMaximumTime() => Duration.ToString(); public override DBBase ImportFromGenericItem(DBBase toImport, Simulator dstSim) => ImportFromItem((TimeBasedProfile)toImport,dstSim); public override List<UsedIn> CalculateUsedIns(Simulator sim) { var result = new List<UsedIn>(); foreach (var action in sim.DeviceActions.Items) { foreach (var profile in action.Profiles) { if (profile.Timeprofile == this) { result.Add(new UsedIn(action, "Device Action - " + action.Name)); } } } foreach (var affordance in sim.Affordances.Items) { foreach (var affordanceDevice in affordance.AffordanceDevices) { if (affordanceDevice.TimeProfile == this) { result.Add(new UsedIn(affordance, "Affordance - " + affordanceDevice.Name)); } } if (affordance.PersonProfile == this) { result.Add(new UsedIn(affordance, "Affordance - Person Profile")); } } foreach (var hht in sim.HouseholdTraits.Items) { foreach (var dev in hht.Autodevs) { if (dev.TimeProfile == this) { result.Add(new UsedIn(hht, "Household Trait - " + dev.Name)); } } } return result; } [JetBrains.Annotations.NotNull] [UsedImplicitly] public static DBBase ImportFromItem([JetBrains.Annotations.NotNull] TimeBasedProfile item, [JetBrains.Annotations.NotNull] Simulator dstSimulator) { var tbp = new TimeBasedProfile(item.Name, null, dstSimulator.ConnectionString, item.TimeProfileType, item.DataSource,item.Guid); tbp.SaveToDB(); foreach (var point in item.ObservableDatapoints) { tbp.AddNewTimepoint(point.Time, point.Value, false); } return tbp; } private static bool IsCorrectParent([JetBrains.Annotations.NotNull] DBBase parent, [JetBrains.Annotations.NotNull] DBBase child) { var hd = (TimeDataPoint) child; if (parent.ID == hd.ProfileID) { var tp = (TimeBasedProfile) parent; lock (tp.ObservableDatapoints) { tp.ObservableDatapoints.Add(hd); } return true; } return false; } protected override bool IsItemLoadedCorrectly(out string message) { message = ""; return true; } public static void LoadFromDatabase([ItemNotNull] [JetBrains.Annotations.NotNull] ObservableCollection<TimeBasedProfile> result, [JetBrains.Annotations.NotNull] string connectionString, bool ignoreMissingTables) { var aic = new AllItemCollections(); LoadAllFromDatabase(result, connectionString, TableName, AssignFields, aic, ignoreMissingTables, true); var timeDataPoints = new ObservableCollection<TimeDataPoint>(); TimeDataPoint.LoadFromDatabase(timeDataPoints, connectionString, ignoreMissingTables); SetSubitems(new List<DBBase>(result), new List<DBBase>(timeDataPoints), IsCorrectParent, ignoreMissingTables); foreach (var profile in result) { lock (profile.ObservableDatapoints) { profile.ObservableDatapoints.Sort(); } } // cleanup } public override void SaveToDB() { base.SaveToDB(); foreach (var tp in ObservableDatapoints) { tp.SaveToDB(); } } public void SaveToDB([JetBrains.Annotations.NotNull] Action<int> reportProgress) { var i = 0; base.SaveToDB(); lock (ObservableDatapoints) { foreach (var tp in ObservableDatapoints) { tp.SaveToDB(); i++; reportProgress(i); } } } protected override void SetSqlParameters(Command cmd) { cmd.AddParameter("Name", "@myname", Name); cmd.AddParameter("TimeProfileType", _timeProfileType); cmd.AddParameter("DataSource", _dataSource); } public override string ToString() => Name + "\t Datapoints:" + ObservableDatapoints.Count; } }
40.924699
193
0.601163
3d58d7fc3c49066e003c63502396284f21227fd5
12,662
cs
C#
City/ControlsClientDeprecated/DomainClient/HarsiddhiTempleClient.cs
vladkar/pulse-project-open
d48166922038e6ede5f67e191393f6b9417d0eea
[ "MIT" ]
1
2020-11-30T05:12:44.000Z
2020-11-30T05:12:44.000Z
City/ControlsClientDeprecated/DomainClient/HarsiddhiTempleClient.cs
vladkar/pulse-project-open
d48166922038e6ede5f67e191393f6b9417d0eea
[ "MIT" ]
2
2019-12-13T07:54:23.000Z
2019-12-28T23:30:00.000Z
City/ControlsClientDeprecated/DomainClient/HarsiddhiTempleClient.cs
vladkar/pulse-project-open
d48166922038e6ede5f67e191393f6b9417d0eea
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using City.Snapshot; using City.Snapshot.Navfield; using City.Snapshot.PulseAgent; using City.Snapshot.Snapshot; using City.UIFrames.Converter; using City.UIFrames.Converter.Models; using Fusion.Core.Mathematics; using Fusion.Drivers.Graphics; using Fusion.Engine.Common; using Fusion.Engine.Frames; using Fusion.Engine.Graphics.GIS; using Fusion.Engine.Graphics.GIS.DataSystem.MapSources.Projections; using Fusion.Engine.Graphics.GIS.GlobeMath; using Fusion.Engine.Input; using Pulse.Common.Utils; using Pulse.MultiagentEngine.Map; namespace City.ControlsClient.DomainClient { public class HarsiddhiTempleClient : AbstractPulseAgentClient { private PolyGisLayer _krestMap; // private PolyGisLayer _itmoBilds; private HeatMapLayer _heatMap; private PointsGisLayer _geoAgents; private TextGisLayer _textLayer; private ModelLayer _mapAgents; private LinesGisLayer _obstacleLayer; private LinesGisLayer _poiLayer; private LinesGisLayer _portalLayer; private LinesGisLayer _navfieldLayer; //TODO extract UI logic to base class private PulseAgentUI _aui; private ICommandSnapshot _currentCommand = null; public override Frame AddControlsToUI() { var gi = Game.GameInterface as CustomGameInterface; if (gi == null) return null; var ui = gi.ui; _aui = new PulseAgentUI(); _aui.PropertyChanged += (sender, args) => { _currentCommand = GetCommand(_aui, args.PropertyName); }; var controlElements = Generator.getControlElement(_aui, ui); return controlElements; } protected override void InitializeControl() { } protected override void LoadControl(ControlInfo controlInfo) { //base.LoadLevel(controlInfo); //TODO // _krestMap = PolyGisLayer.CreateFromUtmFbxModel(Game, "HARSIDDHI.FBX"); // _krestMap.Flags = (int)(PolyGisLayer.PolyFlags.VERTEX_SHADER | PolyGisLayer.PolyFlags.PIXEL_SHADER | PolyGisLayer.PolyFlags.XRAY); // _krestMap.IsVisible = true; _heatMap = HeatMapLayer.GenerateHeatMapWithRegularGrid(Game, 30.210857, 30.229397, 59.975717, 59.957073, 10, 256, 256, new MercatorProjection()); _heatMap.MaxHeatMapLevel = 25; _heatMap.InterpFactor = 1.0f; _heatMap.IsVisible = true; // GisLayers.Add(_krestMap); GisLayers.Add(_heatMap); _geoAgents = new PointsGisLayer(Game, 10000, false) { ImageSizeInAtlas = new Vector2(36, 36), TextureAtlas = Game.Content.Load<Texture2D>("circles.tga"), SizeMultiplier = 0.3f, ZOrder = 1600 }; _mapAgents = new ModelLayer(Game, new DVector2(30.21175, 59.972952), "human_agent", 10000) { ZOrder = 1500, ScaleFactor = 30 }; _textLayer = new TextGisLayer(Game, 10000, null); _textLayer.ZOrder = 1600; // _textLayer.Scale = 100; _textLayer.IsVisible = true; _textLayer.MaxZoom = 6378.5978289702416; _textLayer.MinZoom = 6378.2349263436372; GisLayers.Add(_textLayer); GisLayers.Add(_geoAgents); GisLayers.Add(_mapAgents); //lines var geoutil = new GeoCartesUtil(PulseMap.MapInfo.MinGeo, PulseMap.MapInfo.MetersPerMapUnit); //obstacles _obstacleLayer = new LinesGisLayer(Game, 10000); _obstacleLayer.Flags = (int)(LinesGisLayer.LineFlags.THIN_LINE); _obstacleLayer.ZOrder = 1000; GisLayers.Add(_obstacleLayer); var obstacles = PulseMap.Levels.Values.First().Obstacles; var obstLines = obstacles.SelectMany(o => { var t = new List<PulseVector2>(); for (int i = 0; i < o.Length - 1; i++) { t.Add(o[i]); t.Add(o[i + 1]); } return t; }).ToArray(); for (int i = 0; i < obstLines.Length; i += 1) { var geoPoint = geoutil.GetGeoCoords(obstLines[i]); _obstacleLayer.PointsCpu[i] = new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(geoPoint.Lon), Lat = DMathUtil.DegreesToRadians(geoPoint.Lat), Color = new Color4(0.5f, 0.5f, 0.5f, 1.0f), Tex0 = new Vector4(0.001f, 0.0f, 0.0f, 0.0f) // Tex0.X - half width, }; } _obstacleLayer.UpdatePointsBuffer(); _obstacleLayer.IsVisible = true; //pois _poiLayer = new LinesGisLayer(Game, 1000); _poiLayer.Flags = (int)(LinesGisLayer.LineFlags.THIN_LINE); _poiLayer.ZOrder = 900; GisLayers.Add(_poiLayer); var pois = PulseMap.Levels.Values.First().PointsOfInterest; var poiLines = pois.SelectMany(o => { var t = new List<PulseVector2>(); for (int i = 0; i < o.Polygon.Length - 1; i++) { t.Add(o.Polygon[i]); t.Add(o.Polygon[i + 1]); } t.Add(o.Polygon.Last()); t.Add(o.Polygon.First()); return t; }).ToArray(); for (int i = 0; i < poiLines.Length; i += 1) { var geoPoint = geoutil.GetGeoCoords(poiLines[i]); _poiLayer.PointsCpu[i] = new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(geoPoint.Lon), Lat = DMathUtil.DegreesToRadians(geoPoint.Lat), Color = new Color4(1f, 1f, 0.0f, 1.0f), Tex0 = new Vector4(0.001f, 0.0f, 0.0f, 0.0f) // Tex0.X - half width, }; } _poiLayer.UpdatePointsBuffer(); _poiLayer.IsVisible = true; //portals _portalLayer = new LinesGisLayer(Game, 1000); _portalLayer.Flags = (int)(LinesGisLayer.LineFlags.THIN_LINE); _portalLayer.ZOrder = 1100; GisLayers.Add(_portalLayer); var portals = PulseMap.Levels.Values.First().ExternalPortals; var prtLines = portals.SelectMany(o => { var t = new List<PulseVector2>(); for (int i = 0; i < o.Polygon.Length - 1; i++) { t.Add(o.Polygon[i]); t.Add(o.Polygon[i + 1]); } t.Add(o.Polygon.Last()); t.Add(o.Polygon.First()); return t; }).ToArray(); for (int i = 0; i < prtLines.Length; i += 1) { var geoPoint = geoutil.GetGeoCoords(prtLines[i]); _portalLayer.PointsCpu[i] = new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(geoPoint.Lon), Lat = DMathUtil.DegreesToRadians(geoPoint.Lat), Color = new Color4(1f, 0.0f, 0.0f, 1.0f), Tex0 = new Vector4(0.001f, 0.0f, 0.0f, 0.0f) // Tex0.X - half width, }; } _portalLayer.UpdatePointsBuffer(); _portalLayer.IsVisible = true; _navfieldLayer = new LinesGisLayer(Game, 100000); _navfieldLayer.Flags = (int)(LinesGisLayer.LineFlags.THIN_LINE); _navfieldLayer.IsVisible = true; GisLayers.Add(_navfieldLayer); } private bool _nfFlaf = false; protected override ICommandSnapshot UpdateControl(GameTime gameTime) { var s = CurrentSnapShot as PulseSnapshot; if (s != null) { var count = Math.Min(s.Agents.Count, _geoAgents.PointsCpu.Length); for (int i = 0; i < count; i++) { var point = new DVector2(DMathUtil.DegreesToRadians(s.Agents[i].Y), DMathUtil.DegreesToRadians(s.Agents[i].X)); _geoAgents.PointsCpu[i] = new Gis.GeoPoint { Lon = point.X, Lat = point.Y, Color = Color.White, Tex0 = new Vector4(0, 0, 0.002f, 3.14f) }; _textLayer.GeoTextArray[i] = new TextGisLayer.GeoText { Color = Color.Yellow, LonLat = point, Text = s.Agents[i].Id.ToString() }; // _heatMap.AddValue(s.Agents[i].Y, s.Agents[i].X, 10.0f); } _geoAgents.UpdatePointsBuffer(); _geoAgents.PointsCountToDraw = count; _textLayer.LinesCountToDraw = count; _heatMap.UpdateHeatMap(); } if (s.Extensions.Count > 0) { var nfext = s.Extensions.Values.First() as NavfieldSnapshotExtension; if (nfext != null && _nfFlaf == false) { if (nfext.Grid.Length > 3) _nfFlaf = true; var geoutil = new GeoCartesUtil(PulseMap.MapInfo.MinGeo, PulseMap.MapInfo.MetersPerMapUnit); var arrows = nfext.Grid; var arrowLine = new List<PulseVector2>(); for (int i = 0; i < nfext.Grid.Length; i++) { for (int j = 0; j < nfext.Grid[0].Length; j++) { var gridbl = new PulseVector2(4.62417, 3.8723); var arrowOffset = new PulseVector2(i*nfext.Size + nfext.Size/2, j*nfext.Size + nfext.Size/2); var arrowStart = gridbl + nfext.BottomLeft + arrowOffset; var arrowEnd = arrowStart + new PulseVector2(0, nfext.Size/2).RotateRadians(nfext.Grid[i][j]); // var arrowEnd = arrowEndN.; arrowLine.Add(arrowStart); arrowLine.Add(arrowEnd); } } for (int i = 0; i < arrowLine.Count; i += 1) { var geoPoint = geoutil.GetGeoCoords(arrowLine[i]); _navfieldLayer.PointsCpu[i] = new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(geoPoint.Lon), Lat = DMathUtil.DegreesToRadians(geoPoint.Lat), Color = new Color4(0.0f, 0.0f, 1.0f, 1.0f), Tex0 = new Vector4(0.001f, 0.0f, 0.0f, 0.0f) // Tex0.X - half width, }; } _navfieldLayer.IsVisible = true; _navfieldLayer.UpdatePointsBuffer(); } } if (_currentCommand != null) { var tmp = _currentCommand; _currentCommand = null; return tmp; } return null; } private ICommandSnapshot GetCommand(PulseAgentUI aui, string propertyName) { switch (propertyName) { case "simfps": return new CommandSnapshot { Command = propertyName, Args = new[] { aui.Fps } }; case "flow": return new CommandSnapshot {Command = propertyName, Args = new[] { aui.Slider.ToString()}}; case "sf": return new CommandSnapshot { Command = propertyName, Args = new[] { aui.RepulsiveAgentField, aui.RepulsiveAgentFactorField, aui.RepulsiveObstacleField, aui.RepulsiveObstacleFactorField } }; default: return null; } } public override string UserInfo() { return ""; } } }
35.567416
157
0.503633
3d5c2dd8a6dc8f0d40e3a4c1f68217a5eff6941e
1,486
cs
C#
Net/UserTokenManager.cs
niuniuzhu/RC
344a84c4979facc6d0f3ab880c2f6282cf7d010e
[ "MIT" ]
2
2018-05-20T00:56:48.000Z
2021-08-30T20:56:12.000Z
Net/UserTokenManager.cs
niuniuzhu/RC
344a84c4979facc6d0f3ab880c2f6282cf7d010e
[ "MIT" ]
null
null
null
Net/UserTokenManager.cs
niuniuzhu/RC
344a84c4979facc6d0f3ab880c2f6282cf7d010e
[ "MIT" ]
1
2022-03-14T10:42:03.000Z
2022-03-14T10:42:03.000Z
using System.Collections; using System.Collections.Generic; using RC.Core.Misc; namespace RC.Net { public class UserTokenManager<T> : IEnumerable<T> where T : IUserToken { private readonly List<T> _tokens = new List<T>(); private readonly Dictionary<ushort, T> _idToTokens = new Dictionary<ushort, T>(); private readonly UserTokenPool<T> _userTokenPool = new UserTokenPool<T>(); public T this[int index] => this._tokens[index]; public int count => this._tokens.Count; public void Dispose() { this._userTokenPool.Dispose(); } public void Clear() { int c = this._tokens.Count; for ( int i = 0; i < c; i++ ) this._userTokenPool.Push( this._tokens[i] ); this._tokens.Clear(); this._idToTokens.Clear(); } public T Create() { T token = this._userTokenPool.Pop(); this._tokens.Add( token ); this._idToTokens.Add( token.id, token ); return token; } public void Destroy( int index ) { T token = this._tokens[index]; this._tokens.RemoveAt( index ); this._idToTokens.Remove( token.id ); this._userTokenPool.Push( token ); } public T Get( ushort tokenID ) { if ( !this._idToTokens.TryGetValue( tokenID, out T token ) ) { Logger.Warn( $"Usertoken {tokenID} not found" ); return default( T ); } return token; } public IEnumerator<T> GetEnumerator() { return this._tokens.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
22.515152
83
0.664872
3d5c3f59f5d020d8b7019659e2023571febd290a
1,791
cs
C#
src/Analysis/Codelyzer.Analysis.Build/Models/ProjectBuildResult.cs
QPC-database/codelyzer
34252ac19a5826623d399795b3fdc4ab4cd9a028
[ "Apache-2.0" ]
1
2021-07-10T14:47:26.000Z
2021-07-10T14:47:26.000Z
src/Analysis/Codelyzer.Analysis.Build/Models/ProjectBuildResult.cs
QPC-database/codelyzer
34252ac19a5826623d399795b3fdc4ab4cd9a028
[ "Apache-2.0" ]
null
null
null
src/Analysis/Codelyzer.Analysis.Build/Models/ProjectBuildResult.cs
QPC-database/codelyzer
34252ac19a5826623d399795b3fdc4ab4cd9a028
[ "Apache-2.0" ]
null
null
null
using Codelyzer.Analysis.Model; using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Codelyzer.Analysis.Build { public class ProjectBuildResult : IDisposable { public string ProjectPath { get; set; } public string ProjectRootPath { get; set; } public List<string> SourceFiles { get; private set; } public List<SourceFileBuildResult> SourceFileBuildResults { get; private set; } public List<string> BuildErrors { get; set; } public Project Project { get; set; } public Compilation PrePortCompilation { get; set; } public Compilation Compilation { get; set; } public ExternalReferences ExternalReferences { get; set; } public string TargetFramework { get; set; } public List<string> TargetFrameworks { get; set; } public List<string> PreportReferences { get; set; } public string ProjectGuid { get; set; } public string ProjectType { get; set; } public bool IsSyntaxAnalysis { get; set; } public ProjectBuildResult() { SourceFileBuildResults = new List<SourceFileBuildResult>(); SourceFiles = new List<string>(); TargetFrameworks = new List<string>(); PreportReferences = new List<string>(); } public bool IsBuildSuccess() { return BuildErrors.Count == 0; } internal void AddSourceFile(string filePath) { var wsPath = Path.GetRelativePath(ProjectRootPath, filePath); SourceFiles.Add(wsPath); } public void Dispose() { Compilation = null; PrePortCompilation = null; } } }
32.563636
87
0.619765
3d5dbb0b3e4fff87ee7d5e87e452283edf00f807
2,515
cs
C#
src/TorchSharp/NN/Activation/Softshrink.cs
mfagerlund/TorchSharp
43910a3c841a96be5e7b625b6f8b827e106793e3
[ "MIT" ]
10
2018-10-12T17:04:10.000Z
2018-10-15T14:42:04.000Z
src/TorchSharp/NN/Activation/Softshrink.cs
mfagerlund/TorchSharp
43910a3c841a96be5e7b625b6f8b827e106793e3
[ "MIT" ]
1
2021-11-09T16:35:53.000Z
2021-11-09T16:35:53.000Z
src/TorchSharp/NN/Activation/Softshrink.cs
mfagerlund/TorchSharp
43910a3c841a96be5e7b625b6f8b827e106793e3
[ "MIT" ]
1
2022-01-27T14:59:48.000Z
2022-01-27T14:59:48.000Z
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. using System; using System.Runtime.InteropServices; using static TorchSharp.torch; namespace TorchSharp { using Modules; namespace Modules { /// <summary> /// This class is used to represent a Softshrink module. /// </summary> public class Softshrink : torch.nn.Module { internal Softshrink(IntPtr handle, IntPtr boxedHandle) : base(handle, boxedHandle) { } [DllImport("LibTorchSharp")] private static extern IntPtr THSNN_Softshrink_forward(torch.nn.Module.HType module, IntPtr tensor); public override Tensor forward(Tensor tensor) { var res = THSNN_Softshrink_forward(handle, tensor.Handle); if (res == IntPtr.Zero) { torch.CheckForErrors(); } return new Tensor(res); } public override string GetName() { return typeof(Softshrink).Name; } } } public static partial class torch { public static partial class nn { [DllImport("LibTorchSharp")] extern static IntPtr THSNN_Softshrink_ctor(double lambd, out IntPtr pBoxedModule); /// <summary> /// Softshrink /// </summary> /// <param name="lambda"> the λ value for the Softshrink formulation. Default: 0.5</param> /// <returns></returns> static public Softshrink Softshrink(double lambda = 0.5) { var handle = THSNN_Softshrink_ctor(lambda, out var boxedHandle); if (handle == IntPtr.Zero) { torch.CheckForErrors(); } return new Softshrink(handle, boxedHandle); } public static partial class functional { /// <summary> /// Softshrink /// </summary> /// <param name="x">The input tensor</param> /// <param name="lambda">The λ value for the Softshrink formulation. Default: 0.5</param> /// <returns></returns> static public Tensor Softshrink(Tensor x, double lambda = 0.5) { using (var m = nn.Softshrink(lambda)) { return m.forward(x); } } } } } }
34.452055
130
0.539563
3d5e932570ec6abc6cf0e75df854cf8f88022349
11,648
cs
C#
archive/Changesets/beta/Tests/MBF.TestAutomation/Matrix/RowKeysPaddedDoubleBvtTestCases.cs
jdm7dv/Microsoft-Biology-Foundation
4873300d957cb46694392c480301b319b55f58b8
[ "Apache-2.0" ]
null
null
null
archive/Changesets/beta/Tests/MBF.TestAutomation/Matrix/RowKeysPaddedDoubleBvtTestCases.cs
jdm7dv/Microsoft-Biology-Foundation
4873300d957cb46694392c480301b319b55f58b8
[ "Apache-2.0" ]
null
null
null
archive/Changesets/beta/Tests/MBF.TestAutomation/Matrix/RowKeysPaddedDoubleBvtTestCases.cs
jdm7dv/Microsoft-Biology-Foundation
4873300d957cb46694392c480301b319b55f58b8
[ "Apache-2.0" ]
null
null
null
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** using System; using System.IO; using System.Threading.Tasks; using MBF.Matrix; using MBF.TestAutomation.Util; using MBF.Util.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace MBF.TestAutomation.Matrix { /// <summary> /// Bvt test cases to confirm the features of Dense Matrix /// </summary> [TestClass] public class RowKeysPaddedDoubleBvtTestCases { #region Global Variables Utility _utilityObj = new Utility(@"TestUtils\MatrixTestsConfig.xml"); #endregion Global Variables #region Constructor /// <summary> /// Static constructor to open log and make other settings needed for test /// </summary> static RowKeysPaddedDoubleBvtTestCases() { Trace.Set(Trace.SeqWarnings); if (!ApplicationLog.Ready) { ApplicationLog.Open("mbf.automation.log"); } } #endregion #region Test Cases /// <summary> /// Validates GetInstanceFromDenseAnsi method /// Input : Valid values for RowKeysPaddedDouble /// Validation : GetInstance From DenseAnsi /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRowKeysPDGetInstanceFromPaddedDouble() { DenseMatrix<string, string, double> denseMatObj = GetDenseMatrix(); ParallelOptions parOptObj = new ParallelOptions(); denseMatObj.WritePaddedDouble(Constants.FastQTempTxtFileName, parOptObj); using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromPaddedDouble( Constants.FastQTempTxtFileName, parOptObj)) { Assert.AreEqual(denseMatObj.ColCount, rkpdObj.ColCount); Assert.AreEqual(denseMatObj.RowCount, rkpdObj.RowCount); Assert.AreEqual(denseMatObj.RowKeys.Count, rkpdObj.RowKeys.Count); Assert.AreEqual(denseMatObj.ColKeys.Count, rkpdObj.ColKeys.Count); } if (File.Exists(Constants.FastQTempTxtFileName)) File.Delete(Constants.FastQTempTxtFileName); Console.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromPaddedDouble() method successful"); ApplicationLog.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromPaddedDouble() method successful"); } /// <summary> /// Validates GetInstanceFromDenseAnsi method with file-access /// Input : Valid values for RowKeysPaddedDouble /// Validation : GetInstance From DenseAnsi with file-access /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRowKeysPDGetInstanceFromPaddedDoubleFileAccess() { DenseMatrix<string, string, double> denseMatObj = GetDenseMatrix(); ParallelOptions parOptObj = new ParallelOptions(); denseMatObj.WritePaddedDouble(Constants.FastQTempTxtFileName, parOptObj); using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromPaddedDouble( Constants.FastQTempTxtFileName, parOptObj, FileAccess.ReadWrite, FileShare.ReadWrite)) { Assert.AreEqual(denseMatObj.ColCount, rkpdObj.ColCount); Assert.AreEqual(denseMatObj.RowCount, rkpdObj.RowCount); Assert.AreEqual(denseMatObj.RowKeys.Count, rkpdObj.RowKeys.Count); Assert.AreEqual(denseMatObj.ColKeys.Count, rkpdObj.ColKeys.Count); } if (File.Exists(Constants.FastQTempTxtFileName)) File.Delete(Constants.FastQTempTxtFileName); Console.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromPaddedDouble(file-access) method successful"); ApplicationLog.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromPaddedDouble(file-access) method successful"); } /// <summary> /// Validates GetInstanceFromDenseAnsi method /// Input : Valid values for RowKeysPaddedDouble /// Validation : GetInstance From DenseAnsi /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRowKeysPDGetInstanceFromRowKeys() { DenseMatrix<string, string, double> denseMatObj = GetDenseMatrix(); ParallelOptions parOptObj = new ParallelOptions(); denseMatObj.WritePaddedDouble(Constants.FastQTempTxtFileName, parOptObj); using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromPaddedDouble(Constants.FastQTempTxtFileName, parOptObj)) { rkpdObj.WriteRowKeys(Constants.KeysTempFile); } using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromRowKeys( Constants.KeysTempFile, parOptObj)) { Assert.AreEqual(denseMatObj.ColCount, rkpdObj.ColCount); Assert.AreEqual(denseMatObj.RowCount, rkpdObj.RowCount); Assert.AreEqual(denseMatObj.RowKeys.Count, rkpdObj.RowKeys.Count); Assert.AreEqual(denseMatObj.ColKeys.Count, rkpdObj.ColKeys.Count); } if (File.Exists(Constants.FastQTempTxtFileName)) File.Delete(Constants.FastQTempTxtFileName); if (File.Exists(Constants.KeysTempFile)) File.Delete(Constants.KeysTempFile); Console.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromRowKeysPaddedDouble() method successful"); ApplicationLog.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromRowKeysPaddedDouble() method successful"); } /// <summary> /// Validates GetInstanceFromDenseAnsi method with file-access /// Input : Valid values for RowKeysPaddedDouble /// Validation : GetInstance From DenseAnsi with file-access /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void ValidateRowKeysPDGetInstanceFromRowKeysFileAccess() { DenseMatrix<string, string, double> denseMatObj = GetDenseMatrix(); ParallelOptions parOptObj = new ParallelOptions(); denseMatObj.WritePaddedDouble(Constants.FastQTempTxtFileName, parOptObj); using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromPaddedDouble(Constants.FastQTempTxtFileName, parOptObj)) { rkpdObj.WriteRowKeys(Constants.KeysTempFile); } using (RowKeysPaddedDouble rkpdObj = RowKeysPaddedDouble.GetInstanceFromRowKeys( Constants.KeysTempFile, parOptObj, FileAccess.Read, FileShare.Read)) { Assert.AreEqual(denseMatObj.ColCount, rkpdObj.ColCount); Assert.AreEqual(denseMatObj.RowCount, rkpdObj.RowCount); Assert.AreEqual(denseMatObj.RowKeys.Count, rkpdObj.RowKeys.Count); Assert.AreEqual(denseMatObj.ColKeys.Count, rkpdObj.ColKeys.Count); } if (File.Exists(Constants.FastQTempTxtFileName)) File.Delete(Constants.FastQTempTxtFileName); if (File.Exists(Constants.KeysTempFile)) File.Delete(Constants.KeysTempFile); Console.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromRowKeysPaddedDouble(file-access) method successful"); ApplicationLog.WriteLine( "RowKeysPaddedDouble BVT : Validation of GetInstanceFromRowKeysPaddedDouble(file-access) method successful"); } #endregion #region Helper Methods /// <summary> /// Gets the two D array from the xml /// </summary> /// <param name="nodeName">Node Name of the xml to be parsed</param> /// <param name="maxRows">Maximum rows</param> /// <param name="maxColumns">Maximum columns</param> /// <returns>2 D Array</returns> double[,] GetTwoDArray(string nodeName, out int maxRows, out int maxColumns) { string[] rowArray = _utilityObj._xmlUtil.GetTextValues(nodeName, Constants.RowsNode); // Gets the max number columns in the array maxColumns = 0; maxRows = rowArray.Length; for (int i = 0; i < maxRows; i++) { string[] colArray = rowArray[i].Split(','); if (maxColumns < colArray.Length) maxColumns = colArray.Length; } // Creates a 2 D with max row and column length double[,] twoDArray = new double[maxRows, maxColumns]; for (int i = 0; i < maxRows; i++) { string[] colArray = rowArray[i].Split(','); for (int j = 0; j < colArray.Length; j++) { twoDArray[i, j] = double.Parse(colArray[j], (IFormatProvider)null); } } return twoDArray; } /// <summary> /// Gets the key sequence with the max length specified /// </summary> /// <param name="maxKey">Max length of the key sequence</param> /// <param name="isRow">If Row, append R else append C</param> /// <returns>Key Sequence Array</returns> static string[] GetKeySequence(int maxKey, bool isRow) { string[] keySeq = new string[maxKey]; string tempSeq = string.Empty; if (isRow) tempSeq = "R"; else tempSeq = "C"; for (int i = 0; i < maxKey; i++) { keySeq[i] = tempSeq + i.ToString((IFormatProvider)null); } return keySeq; } /// <summary> /// Creates a DenseMatrix instance and returns the same. /// </summary> /// <returns>DenseMatrix Instance</returns> DenseMatrix<string, string, double> GetDenseMatrix() { int maxRows = 0; int maxColumns = 0; double[,] twoDArray = GetTwoDArray(Constants.SimpleMatrixNodeName, out maxRows, out maxColumns); string[] rowKeySeq = GetKeySequence(maxRows, true); string[] colKeySeq = GetKeySequence(maxColumns, false); DenseMatrix<string, string, double> denseMatrixObj = new DenseMatrix<string, string, double>(twoDArray, rowKeySeq, colKeySeq, double.NaN); return denseMatrixObj; } #endregion; } }
38.697674
125
0.594609
3d5eb3f4bbfaf538375ac0895b3a94fb8c73c205
3,253
cs
C#
sdk/search/Azure.Search.Documents/src/Generated/Models/CommonGramTokenFilter.cs
jessicl-ms/azure-sdk-for-net
5a5591b0a1a8a6ff4c8e8e3156a98a34c52020b5
[ "MIT" ]
1
2022-02-17T12:18:20.000Z
2022-02-17T12:18:20.000Z
sdk/search/Azure.Search.Documents/src/Generated/Models/CommonGramTokenFilter.cs
jessicl-ms/azure-sdk-for-net
5a5591b0a1a8a6ff4c8e8e3156a98a34c52020b5
[ "MIT" ]
1
2018-08-21T16:56:36.000Z
2018-08-21T16:56:36.000Z
sdk/search/Azure.Search.Documents/src/Generated/Models/CommonGramTokenFilter.cs
jessicl-ms/azure-sdk-for-net
5a5591b0a1a8a6ff4c8e8e3156a98a34c52020b5
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Linq; namespace Azure.Search.Documents.Models { /// <summary> Construct bigrams for frequently occurring terms while indexing. Single terms are still indexed too, with bigrams overlaid. This token filter is implemented using Apache Lucene. </summary> public partial class CommonGramTokenFilter : TokenFilter { /// <summary> Initializes a new instance of CommonGramTokenFilter. </summary> /// <param name="name"> The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. </param> /// <param name="commonWords"> The set of common words. </param> public CommonGramTokenFilter(string name, IEnumerable<string> commonWords) : base(name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (commonWords == null) { throw new ArgumentNullException(nameof(commonWords)); } CommonWords = commonWords.ToArray(); ODataType = "#Microsoft.Azure.Search.CommonGramTokenFilter"; } /// <summary> Initializes a new instance of CommonGramTokenFilter. </summary> /// <param name="oDataType"> Identifies the concrete type of the token filter. </param> /// <param name="name"> The name of the token filter. It must only contain letters, digits, spaces, dashes or underscores, can only start and end with alphanumeric characters, and is limited to 128 characters. </param> /// <param name="commonWords"> The set of common words. </param> /// <param name="ignoreCase"> A value indicating whether common words matching will be case insensitive. Default is false. </param> /// <param name="useQueryMode"> A value that indicates whether the token filter is in query mode. When in query mode, the token filter generates bigrams and then removes common words and single terms followed by a common word. Default is false. </param> internal CommonGramTokenFilter(string oDataType, string name, IList<string> commonWords, bool? ignoreCase, bool? useQueryMode) : base(oDataType, name) { CommonWords = commonWords; IgnoreCase = ignoreCase; UseQueryMode = useQueryMode; ODataType = oDataType ?? "#Microsoft.Azure.Search.CommonGramTokenFilter"; } /// <summary> The set of common words. </summary> public IList<string> CommonWords { get; } /// <summary> A value indicating whether common words matching will be case insensitive. Default is false. </summary> public bool? IgnoreCase { get; set; } /// <summary> A value that indicates whether the token filter is in query mode. When in query mode, the token filter generates bigrams and then removes common words and single terms followed by a common word. Default is false. </summary> public bool? UseQueryMode { get; set; } } }
57.070175
261
0.681217
3d605d599864ef5c74ac1274d4dc52d03be22d6a
21,967
cs
C#
BundleMasterRuntime/AssetComponentUpdate.cs
xingchenxuup/BundleMaster
0bc04b0797a8d17c5868781c855c9911c05135cd
[ "Apache-2.0" ]
null
null
null
BundleMasterRuntime/AssetComponentUpdate.cs
xingchenxuup/BundleMaster
0bc04b0797a8d17c5868781c855c9911c05135cd
[ "Apache-2.0" ]
2
2022-02-17T06:53:09.000Z
2022-03-07T03:14:18.000Z
BundleMasterRuntime/AssetComponentUpdate.cs
xingchenxuup/BundleMaster
0bc04b0797a8d17c5868781c855c9911c05135cd
[ "Apache-2.0" ]
null
null
null
using System; using System.IO; using System.Collections.Generic; using System.Globalization; using System.Text; using ET; using UnityEngine.Networking; namespace BM { public static partial class AssetComponent { /// <summary> /// 检查分包是否需要更新 /// </summary> /// <param name="bundlePackageNames">所有分包的名称以及是否验证文件CRC</param> public static async ETTask<UpdateBundleDataInfo> CheckAllBundlePackageUpdate(Dictionary<string, bool> bundlePackageNames) { UpdateBundleDataInfo updateBundleDataInfo = new UpdateBundleDataInfo(); if (AssetComponentConfig.AssetLoadMode != AssetLoadMode.Build) { updateBundleDataInfo.NeedUpdate = false; if (AssetComponentConfig.AssetLoadMode == AssetLoadMode.Local) { AssetComponentConfig.HotfixPath = AssetComponentConfig.LocalBundlePath; } else { #if !UNITY_EDITOR AssetLogHelper.LogError("AssetLoadMode = AssetLoadMode.Develop 只能在编辑器下运行"); #endif } return updateBundleDataInfo; } updateBundleDataInfo.UpdateTime = DateTime.Now.ToString(CultureInfo.CurrentCulture); //开始处理每个分包的更新信息 foreach (var bundlePackageInfo in bundlePackageNames) { string bundlePackageName = bundlePackageInfo.Key; string remoteVersionLog = await GetRemoteBundlePackageVersionLog(bundlePackageName); if (remoteVersionLog == null) { continue; } //创建各个分包对应的文件夹 if (!Directory.Exists(Path.Combine(AssetComponentConfig.HotfixPath, bundlePackageName))) { Directory.CreateDirectory(Path.Combine(AssetComponentConfig.HotfixPath, bundlePackageName)); } //获取CRCLog string crcLogPath = Path.Combine(AssetComponentConfig.HotfixPath, bundlePackageName, "CRCLog.txt"); updateBundleDataInfo.PackageCRCDictionary.Add(bundlePackageName, new Dictionary<string, uint>()); if (File.Exists(crcLogPath)) { using (StringReader stringReader = new StringReader(crcLogPath)) { string crcLog = await stringReader.ReadToEndAsync(); string[] crcLogData = crcLog.Split('\n'); for (int j = 0; j < crcLogData.Length; j++) { string crcLine = crcLogData[j]; if (string.IsNullOrWhiteSpace(crcLine)) { continue; } string[] info = crcLine.Split('|'); if (info.Length != 3) { continue; } if (!uint.TryParse(info[1], out uint crc)) { continue; } //如果存在重复就覆盖 if (updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].ContainsKey(info[0])) { updateBundleDataInfo.PackageCRCDictionary[bundlePackageName][info[0]] = crc; } else { updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].Add(info[0], crc); } } } } else { CreateUpdateLogFile(crcLogPath, null); } updateBundleDataInfo.PackageCRCFile.Add(bundlePackageName, new StreamWriter(crcLogPath, true)); //获取本地的VersionLog string localVersionLogExistPath = BundleFileExistPath(bundlePackageName, "VersionLogs.txt"); ETTask logTcs = ETTask.Create(); string localVersionLog; using (UnityWebRequest webRequest = UnityWebRequest.Get(localVersionLogExistPath)) { UnityWebRequestAsyncOperation weq = webRequest.SendWebRequest(); weq.completed += (o) => { logTcs.SetResult(); }; await logTcs; #if UNITY_2020_1_OR_NEWER if (webRequest.result != UnityWebRequest.Result.Success) #else if (!string.IsNullOrEmpty(webRequest.error)) #endif { localVersionLog = "INIT|0"; } else { localVersionLog = webRequest.downloadHandler.text; } } if (bundlePackageInfo.Value) { await CalcNeedUpdateBundleFileCRC(updateBundleDataInfo, bundlePackageName, remoteVersionLog, localVersionLog); } else { await CalcNeedUpdateBundle(updateBundleDataInfo, bundlePackageName, remoteVersionLog, localVersionLog); } } if (updateBundleDataInfo.NeedUpdateSize > 0) { updateBundleDataInfo.NeedUpdate = true; } else { foreach (StreamWriter sw in updateBundleDataInfo.PackageCRCFile.Values) { sw.Close(); sw.Dispose(); } updateBundleDataInfo.PackageCRCFile.Clear(); } return updateBundleDataInfo; } /// <summary> /// 获取所哟需要更新的Bundle的文件(不检查文件CRC) /// </summary> private static async ETTask CalcNeedUpdateBundle(UpdateBundleDataInfo updateBundleDataInfo, string bundlePackageName, string remoteVersionLog, string localVersionLog) { string[] remoteVersionData = remoteVersionLog.Split('\n'); string[] localVersionData = localVersionLog.Split('\n'); int remoteVersion = int.Parse(remoteVersionData[0].Split('|')[1]); int localVersion = int.Parse(localVersionData[0].Split('|')[1]); updateBundleDataInfo.PackageToVersion.Add(bundlePackageName, new int[2]{localVersion, remoteVersion}); if (localVersion > remoteVersion) { AssetLogHelper.LogError("本地版本号优先与远程版本号 " + localVersion + ">" + remoteVersion + "\n" + "localBundleTime: " + localVersionData[0].Split('|')[0] + "\n" + "remoteBundleTime: " + remoteVersionData[0].Split('|')[0] + "\n" + "Note: 发送了版本回退或者忘了累进版本号"); } //判断StreamingAsset下资源 string streamingAssetLogPath = Path.Combine(AssetComponentConfig.LocalBundlePath, bundlePackageName, "VersionLogs.txt"); #if UNITY_IOS || UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX streamingAssetLogPath = "file://" + streamingAssetLogPath; #endif ETTask streamingLogTcs = ETTask.Create(); string streamingLog; using (UnityWebRequest webRequest = UnityWebRequest.Get(streamingAssetLogPath)) { UnityWebRequestAsyncOperation weq = webRequest.SendWebRequest(); weq.completed += (o) => { streamingLogTcs.SetResult(); }; await streamingLogTcs; #if UNITY_2020_1_OR_NEWER if (webRequest.result != UnityWebRequest.Result.Success) #else if (!string.IsNullOrEmpty(webRequest.error)) #endif { streamingLog = "INIT|0"; } else { streamingLog = webRequest.downloadHandler.text; } } //添加streaming文件CRC信息 Dictionary<string, uint> streamingCRC = new Dictionary<string, uint>(); string[] streamingLogData = streamingLog.Split('\n'); for (int i = 1; i < streamingLogData.Length; i++) { string streamingDataLine = streamingLogData[i]; if (!string.IsNullOrWhiteSpace(streamingDataLine)) { string[] info = streamingDataLine.Split('|'); uint crc = uint.Parse(info[2]); if (!updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].ContainsKey(info[0])) { updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].Add(info[0], crc); } streamingCRC.Add(info[0], crc); } } //添加本地文件CRC信息 for (int i = 1; i < localVersionData.Length; i++) { string localVersionDataLine = localVersionData[i]; if (!string.IsNullOrWhiteSpace(localVersionDataLine)) { string[] info = localVersionDataLine.Split('|'); if (updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].ContainsKey(info[0])) { updateBundleDataInfo.PackageCRCDictionary[bundlePackageName][info[0]] = uint.Parse(info[2]); } else { updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].Add(info[0], uint.Parse(info[2])); } } } //创建最后需要返回的数据 Dictionary<string, long> needUpdateBundles = new Dictionary<string, long>(); for (int i = 1; i < remoteVersionData.Length; i++) { string remoteVersionDataLine = remoteVersionData[i]; if (!string.IsNullOrWhiteSpace(remoteVersionDataLine)) { string[] info = remoteVersionDataLine.Split('|'); if (updateBundleDataInfo.PackageCRCDictionary[bundlePackageName].TryGetValue(info[0], out uint crc)) { if (crc == uint.Parse(info[2])) { if (streamingCRC.TryGetValue(info[0], out uint streamingCrc)) { if (crc != streamingCrc) { if (!File.Exists(Path.Combine(AssetComponentConfig.HotfixPath, bundlePackageName, info[0]))) { needUpdateBundles.Add(info[0], long.Parse(info[1])); } } } else { if (!File.Exists(Path.Combine(AssetComponentConfig.HotfixPath, bundlePackageName, info[0]))) { needUpdateBundles.Add(info[0], long.Parse(info[1])); } } continue; } } needUpdateBundles.Add(info[0], long.Parse(info[1])); } } updateBundleDataInfo.PackageNeedUpdateBundlesInfos.Add(bundlePackageName, needUpdateBundles); foreach (long needUpdateBundleSize in needUpdateBundles.Values) { updateBundleDataInfo.NeedUpdateSize += needUpdateBundleSize; updateBundleDataInfo.NeedDownLoadBundleCount++; } } /// <summary> /// 获取所有需要更新的Bundle的文件(计算文件CRC) /// </summary> private static async ETTask CalcNeedUpdateBundleFileCRC(UpdateBundleDataInfo updateBundleDataInfo, string bundlePackageName, string remoteVersionLog, string localVersionLog) { string[] remoteVersionData = remoteVersionLog.Split('\n'); string[] localVersionData = localVersionLog.Split('\n'); int remoteVersion = int.Parse(remoteVersionData[0].Split('|')[1]); int localVersion = int.Parse(localVersionData[0].Split('|')[1]); updateBundleDataInfo.PackageToVersion.Add(bundlePackageName, new int[2]{localVersion, remoteVersion}); if (localVersion > remoteVersion) { AssetLogHelper.LogError("本地版本号优先与远程版本号 " + localVersion + ">" + remoteVersion + "\n" + "localBundleTime: " + localVersionData[0].Split('|')[0] + "\n" + "remoteBundleTime: " + remoteVersionData[0].Split('|')[0] + "\n" + "Note: 发送了版本回退或者忘了累进版本号"); } //创建最后需要返回的数据 Dictionary<string, long> needUpdateBundles = new Dictionary<string, long>(); _checkCount = remoteVersionData.Length - 1; Queue<int> loopQueue = new Queue<int>(); //loopSize依据资源大小调节, 如果资源太大loopSize也调很大, 会撑爆内存, 调大只会节约一点点时间(目的是如果有进度条每个循环更新一下进度条) int loopSize = 5; for (int i = 0; i < _checkCount / loopSize; i++) { loopQueue.Enqueue(loopSize); } if (_checkCount % loopSize > 0) { loopQueue.Enqueue(_checkCount % loopSize); } int loop = loopQueue.Count; for (int i = 0; i < loop; i++) { _checkCount = loopQueue.Dequeue(); int count = _checkCount; ETTask finishTcs = ETTask.Create(); for (int j = 0; j < count; j++) { CheckFileCRC(remoteVersionData[i * loopSize + j + 1], bundlePackageName, needUpdateBundles, finishTcs).Coroutine(); } await finishTcs; _checkCount = 0; } updateBundleDataInfo.PackageNeedUpdateBundlesInfos.Add(bundlePackageName, needUpdateBundles); foreach (long needUpdateBundleSize in needUpdateBundles.Values) { updateBundleDataInfo.NeedUpdateSize += needUpdateBundleSize; updateBundleDataInfo.NeedDownLoadBundleCount++; } } private static int _checkCount = 0; private static async ETTask CheckFileCRC(string remoteVersionDataLine, string bundlePackageName, Dictionary<string, long> needUpdateBundles, ETTask finishTcs) { if (!string.IsNullOrWhiteSpace(remoteVersionDataLine)) { string[] info = remoteVersionDataLine.Split('|'); //如果文件不存在直接加入更新 string filePath = BundleFileExistPath(bundlePackageName, info[0]); uint fileCRC32 = await VerifyHelper.GetFileCRC32(filePath); //判断是否和远程一样, 不一样直接加入更新 if (uint.Parse(info[2]) != fileCRC32) { needUpdateBundles.Add(info[0], long.Parse(info[1])); } } _checkCount--; if (_checkCount <= 0) { finishTcs.SetResult(); } } /// <summary> /// 下载更新 /// </summary> public static async ETTask DownLoadUpdate(UpdateBundleDataInfo updateBundleDataInfo) { if (AssetComponentConfig.AssetLoadMode != AssetLoadMode.Build) { AssetLogHelper.LogError("AssetLoadMode != AssetLoadMode.Build 不需要更新"); return; } Dictionary<string, Queue<DownLoadTask>> packageDownLoadTask = new Dictionary<string, Queue<DownLoadTask>>(); ETTask downLoading = ETTask.Create(); //准备需要下载的内容的初始化信息 foreach (var packageNeedUpdateBundlesInfo in updateBundleDataInfo.PackageNeedUpdateBundlesInfos) { Queue<DownLoadTask> downLoadTaskQueue = new Queue<DownLoadTask>(); string packageName = packageNeedUpdateBundlesInfo.Key; packageDownLoadTask.Add(packageName, downLoadTaskQueue); string downLoadPackagePath = Path.Combine(AssetComponentConfig.HotfixPath, packageName); if (!Directory.Exists(downLoadPackagePath)) { Directory.CreateDirectory(downLoadPackagePath); } foreach (var updateBundlesInfo in packageNeedUpdateBundlesInfo.Value) { DownLoadTask downLoadTask = new DownLoadTask(); downLoadTask.UpdateBundleDataInfo = updateBundleDataInfo; downLoadTask.DownLoadingKey = downLoading; downLoadTask.PackageDownLoadTask = packageDownLoadTask; downLoadTask.PackegName = packageName; downLoadTask.DownLoadPackagePath = downLoadPackagePath; downLoadTask.FileName = updateBundlesInfo.Key; downLoadTask.FileSize = updateBundlesInfo.Value; downLoadTaskQueue.Enqueue(downLoadTask); } } //开启下载 for (int i = 0; i < AssetComponentConfig.MaxDownLoadCount; i++) { foreach (Queue<DownLoadTask> downLoadTaskQueue in packageDownLoadTask.Values) { if (downLoadTaskQueue.Count > 0) { downLoadTaskQueue.Dequeue().DownLoad().Coroutine(); break; } } } await downLoading; //下载完成关闭CRCLog文件 foreach (StreamWriter sw in updateBundleDataInfo.PackageCRCFile.Values) { sw.Close(); sw.Dispose(); } updateBundleDataInfo.PackageCRCFile.Clear(); //所有分包都下载完成了就处理分包的Log文件 foreach (string packageName in updateBundleDataInfo.PackageNeedUpdateBundlesInfos.Keys) { byte[] fileLogsData = await DownloadBundleHelper.DownloadDataByUrl(Path.Combine(AssetComponentConfig.BundleServerUrl, packageName, "FileLogs.txt")); byte[] dependLogsData = await DownloadBundleHelper.DownloadDataByUrl(Path.Combine(AssetComponentConfig.BundleServerUrl, packageName, "DependLogs.txt")); byte[] versionLogsData = await DownloadBundleHelper.DownloadDataByUrl(Path.Combine(AssetComponentConfig.BundleServerUrl, packageName, "VersionLogs.txt")); if (fileLogsData == null || dependLogsData == null || versionLogsData == null) { AssetLogHelper.LogError("获取Log表失败, PackageName: " + packageName); continue; } CreateUpdateLogFile(Path.Combine(AssetComponentConfig.HotfixPath, packageName, "FileLogs.txt"), System.Text.Encoding.UTF8.GetString(fileLogsData)); CreateUpdateLogFile(Path.Combine(AssetComponentConfig.HotfixPath, packageName, "DependLogs.txt"), System.Text.Encoding.UTF8.GetString(dependLogsData)); CreateUpdateLogFile(Path.Combine(AssetComponentConfig.HotfixPath, packageName, "VersionLogs.txt"), System.Text.Encoding.UTF8.GetString(versionLogsData)); } AssetLogHelper.LogError("下载完成"); } } public class DownLoadTask { public UpdateBundleDataInfo UpdateBundleDataInfo; public ETTask DownLoadingKey; public Dictionary<string, Queue<DownLoadTask>> PackageDownLoadTask; /// <summary> /// 下载的资源分包名称 /// </summary> public string PackegName; /// <summary> /// 分包所在路径 /// </summary> public string DownLoadPackagePath; /// <summary> /// 下载的文件的名称 /// </summary> public string FileName; /// <summary> /// 下载的文件的大小 /// </summary> public long FileSize; public async ETTask DownLoad() { string url = Path.Combine(AssetComponentConfig.BundleServerUrl, PackegName, UnityWebRequest.EscapeURL(FileName)); byte[] data = await DownloadBundleHelper.DownloadDataByUrl(url); using (FileStream fs = new FileStream(Path.Combine(DownLoadPackagePath, FileName), FileMode.Create)) { //大于2M用异步 if (data.Length > 2097152) { await fs.WriteAsync(data, 0, data.Length); } else { fs.Write(data, 0, data.Length); } fs.Close(); } UpdateBundleDataInfo.AddCRCFileInfo(PackegName, FileName, VerifyHelper.GetCRC32(data)); UpdateBundleDataInfo.FinishUpdateSize += data.Length; UpdateBundleDataInfo.FinishDownLoadBundleCount++; foreach (Queue<DownLoadTask> downLoadTaskQueue in PackageDownLoadTask.Values) { if (downLoadTaskQueue.Count > 0) { downLoadTaskQueue.Dequeue().DownLoad().Coroutine(); return; } } //说明下载完成了 if (UpdateBundleDataInfo.FinishDownLoadBundleCount < UpdateBundleDataInfo.NeedDownLoadBundleCount) { return; } UpdateBundleDataInfo.FinishUpdate = true; DownLoadingKey.SetResult(); } } }
45.199588
181
0.529476
3d60683b124ca05b8017f2fe43bce4446421f8f0
2,489
cs
C#
Kooboo.CMS/Kooboo.CMS.Modules/Kooboo.CMS.Modules.CMIS/Services/IPolicyService.cs
syberside/CMS
9b4e785e7f6324c9ade56f79a81dac33ec4292e7
[ "BSD-3-Clause" ]
288
2015-01-02T08:42:16.000Z
2021-09-29T14:01:59.000Z
Kooboo.CMS/Kooboo.CMS.Modules/Kooboo.CMS.Modules.CMIS/Services/IPolicyService.cs
syberside/CMS
9b4e785e7f6324c9ade56f79a81dac33ec4292e7
[ "BSD-3-Clause" ]
45
2015-01-13T13:32:02.000Z
2021-05-03T23:33:52.000Z
Kooboo.CMS/Kooboo.CMS.Modules/Kooboo.CMS.Modules.CMIS/Services/IPolicyService.cs
syberside/CMS
9b4e785e7f6324c9ade56f79a81dac33ec4292e7
[ "BSD-3-Clause" ]
171
2015-01-03T15:00:36.000Z
2021-01-08T01:52:47.000Z
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Modules.CMIS.Models; using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace Kooboo.CMS.Modules.CMIS.Services { /// <summary> /// The Policy Services are used to apply or remove a policy object to a controllablePolicy object. /// </summary> [ServiceContract(Namespace = "http://docs.oasis-open.org/ns/cmis/core/200908/", Name = "PolicyService")] [XmlSerializerFormat] public interface IPolicyService { /// <summary> /// Applies a specified policy to an object. /// </summary> /// <param name="repositoryId">Required. The identifier for the repository. </param> /// <param name="policyId">Required. The identifier for the policy to be applied. </param> /// <param name="objectId">Required. The identifier of the object. </param> [OperationContract(Name = "applyPolicy")] applyPolicyResponse ApplyPolicy(applyPolicyRequest request); /// <summary> /// Removes a specified policy from an object. /// </summary> /// <param name="repositoryId">Required. The identifier for the repository. </param> /// <param name="policyId">Required. The identifier for the policy to be applied. </param> /// <param name="objectId">Required. The identifier of the object. </param> [OperationContract(Name = "removePolicy")] removePolicyResponse RemovePolicy(removePolicyRequest request); /// <summary> /// Gets the list of policies currently applied to the specified object. /// </summary> /// <param name="repositoryId">Required. The identifier for the repository. </param> /// <param name="objectId">Required. The identifier of the object. </param> /// <param name="filter">Optional. Value indicating which properties for objects MUST be returned. This filter is a list of property query names and NOT a list of property ids. The query names of secondary type properties MUST follow the pattern <secondaryTypeQueryName>.<propertyQueryName>.Example: cmis:name,amount,worflow.stage.</param> /// <returns></returns> [OperationContract(Name = "getAppliedPolicies")] getAppliedPoliciesResponse GetAppliedPolicies(getAppliedPoliciesRequest request); } }
46.092593
346
0.682603
3d60907204e283fc25c565c5e918c7df1c45464d
3,961
cs
C#
src/Merchello.Web/Models/ContentEditing/ShipmentDisplay.cs
cfallesen/Merchello
65f1b061895e60f90d3a05c02a7cea0c7ef6fb54
[ "MIT" ]
null
null
null
src/Merchello.Web/Models/ContentEditing/ShipmentDisplay.cs
cfallesen/Merchello
65f1b061895e60f90d3a05c02a7cea0c7ef6fb54
[ "MIT" ]
null
null
null
src/Merchello.Web/Models/ContentEditing/ShipmentDisplay.cs
cfallesen/Merchello
65f1b061895e60f90d3a05c02a7cea0c7ef6fb54
[ "MIT" ]
null
null
null
namespace Merchello.Web.Models.ContentEditing { using System; using System.Collections.Generic; /// <summary> /// The shipment display. /// </summary> public class ShipmentDisplay { /// <summary> /// Gets or sets the key. /// </summary> public Guid Key { get; set; } /// <summary> /// Gets or sets the shipped date. /// </summary> public DateTime ShippedDate { get; set; } /// <summary> /// Gets or sets the version key. /// </summary> public Guid VersionKey { get; set; } /// <summary> /// Gets or sets the from organization. /// </summary> public string FromOrganization { get; set; } /// <summary> /// Gets or sets the from name. /// </summary> public string FromName { get; set; } /// <summary> /// Gets or sets the from address 1. /// </summary> public string FromAddress1 { get; set; } /// <summary> /// Gets or sets the from address 2. /// </summary> public string FromAddress2 { get; set; } /// <summary> /// Gets or sets the from locality. /// </summary> public string FromLocality { get; set; } /// <summary> /// Gets or sets the from region. /// </summary> public string FromRegion { get; set; } /// <summary> /// Gets or sets the from postal code. /// </summary> public string FromPostalCode { get; set; } /// <summary> /// Gets or sets the from country code. /// </summary> public string FromCountryCode { get; set; } /// <summary> /// Gets or sets a value indicating whether from is commercial. /// </summary> public bool FromIsCommercial { get; set; } /// <summary> /// Gets or sets the to organization. /// </summary> public string ToOrganization { get; set; } /// <summary> /// Gets or sets the to name. /// </summary> public string ToName { get; set; } /// <summary> /// Gets or sets the to address 1. /// </summary> public string ToAddress1 { get; set; } /// <summary> /// Gets or sets the to address 2. /// </summary> public string ToAddress2 { get; set; } /// <summary> /// Gets or sets the to locality. /// </summary> public string ToLocality { get; set; } /// <summary> /// Gets or sets the to region. /// </summary> public string ToRegion { get; set; } /// <summary> /// Gets or sets the to postal code. /// </summary> public string ToPostalCode { get; set; } /// <summary> /// Gets or sets the to country code. /// </summary> public string ToCountryCode { get; set; } /// <summary> /// Gets or sets a value indicating whether to is commercial. /// </summary> public bool ToIsCommercial { get; set; } /// <summary> /// Gets or sets the ship method key. /// </summary> public Guid? ShipMethodKey { get; set; } /// <summary> /// Gets or sets the phone. /// </summary> public string Phone { get; set; } /// <summary> /// Gets or sets the email. /// </summary> public string Email { get; set; } /// <summary> /// Gets or sets the carrier. /// </summary> public string Carrier { get; set; } /// <summary> /// Gets or sets the tracking code. /// </summary> public string TrackingCode { get; set; } /// <summary> /// Gets or sets the items. /// </summary> public IEnumerable<OrderLineItemDisplay> Items { get; set; } } }
27.130137
71
0.499116
3d62ea7026143cbd6555f073e592dfd333120ad7
9,214
cs
C#
src/Stl.Fusion.EntityFramework/Compatibility/EntityFrameworkServiceCollectionExtensions.cs
servicetitan/Stl
0e70d98f6de413bfde0bf7ecd8237085d63c2ace
[ "MIT" ]
null
null
null
src/Stl.Fusion.EntityFramework/Compatibility/EntityFrameworkServiceCollectionExtensions.cs
servicetitan/Stl
0e70d98f6de413bfde0bf7ecd8237085d63c2ace
[ "MIT" ]
null
null
null
src/Stl.Fusion.EntityFramework/Compatibility/EntityFrameworkServiceCollectionExtensions.cs
servicetitan/Stl
0e70d98f6de413bfde0bf7ecd8237085d63c2ace
[ "MIT" ]
null
null
null
#if NETSTANDARD2_0 // 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 Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection; /// <summary> /// Extension methods for setting up Entity Framework related services in an <see cref="IServiceCollection" />. /// </summary> public static class EntityFrameworkServiceCollectionExtensions { private static void AddPoolingOptions<TContext>( IServiceCollection serviceCollection, Action<IServiceProvider, DbContextOptionsBuilder> optionsAction, int poolSize) where TContext : DbContext { if (poolSize <= 0) throw new ArgumentOutOfRangeException(nameof(poolSize), CoreStrings.InvalidPoolSize); CheckContextConstructors<TContext>(); AddCoreServices<TContext>( serviceCollection, (sp, ob) => { optionsAction(sp, ob); var extension = (ob.Options.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension()) .WithMaxPoolSize(poolSize); ((IDbContextOptionsBuilderInfrastructure)ob).AddOrUpdateExtension(extension); }, ServiceLifetime.Singleton); } /// <summary> /// <para> /// Registers an <see cref="IDbContextFactory{TContext}" /> in the <see cref="IServiceCollection" /> to create instances /// of given <see cref="DbContext" /> type where instances are pooled for reuse. /// </para> /// <para> /// Registering a factory instead of registering the context type directly allows for easy creation of new /// <see cref="DbContext" /> instances. /// Registering a factory is recommended for Blazor applications and other situations where the dependency /// injection scope is not aligned with the context lifetime. /// </para> /// <para> /// Use this method when using dependency injection in your application, such as with Blazor. /// For applications that don't use dependency injection, consider creating <see cref="DbContext" /> /// instances directly with its constructor. The <see cref="DbContext.OnConfiguring" /> method can then be /// overridden to configure a connection string and other options. /// </para> /// <para> /// For more information on how to use this method, see the Entity Framework Core documentation at https://aka.ms/efdocs. /// For more information on using dependency injection, see https://go.microsoft.com/fwlink/?LinkId=526890. /// </para> /// </summary> /// <typeparam name="TContext"> The type of <see cref="DbContext" /> to be created by the factory. </typeparam> /// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param> /// <param name="optionsAction"> /// <para> /// A required action to configure the <see cref="DbContextOptions" /> for the context. When using /// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" /> /// will not be called. /// </para> /// </param> /// <param name="poolSize"> /// Sets the maximum number of instances retained by the pool. /// </param> /// <returns> /// The same service collection so that multiple calls can be chained. /// </returns> public static IServiceCollection AddPooledDbContextFactory<TContext>( this IServiceCollection serviceCollection, Action<DbContextOptionsBuilder> optionsAction, int poolSize = 128) where TContext : DbContext { if (optionsAction == null) throw new ArgumentNullException(nameof(optionsAction)); return AddPooledDbContextFactory<TContext>(serviceCollection, (_, ob) => optionsAction(ob), poolSize); } /// <summary> /// <para> /// Registers an <see cref="IDbContextFactory{TContext}" /> in the <see cref="IServiceCollection" /> to create instances /// of given <see cref="DbContext" /> type where instances are pooled for reuse. /// </para> /// <para> /// Registering a factory instead of registering the context type directly allows for easy creation of new /// <see cref="DbContext" /> instances. /// Registering a factory is recommended for Blazor applications and other situations where the dependency /// injection scope is not aligned with the context lifetime. /// </para> /// <para> /// Use this method when using dependency injection in your application, such as with Blazor. /// For applications that don't use dependency injection, consider creating <see cref="DbContext" /> /// instances directly with its constructor. The <see cref="DbContext.OnConfiguring" /> method can then be /// overridden to configure a connection string and other options. /// </para> /// <para> /// For more information on how to use this method, see the Entity Framework Core documentation at https://aka.ms/efdocs. /// For more information on using dependency injection, see https://go.microsoft.com/fwlink/?LinkId=526890. /// </para> /// </summary> /// <typeparam name="TContext"> The type of <see cref="DbContext" /> to be created by the factory. </typeparam> /// <param name="serviceCollection"> The <see cref="IServiceCollection" /> to add services to. </param> /// <param name="optionsAction"> /// <para> /// A required action to configure the <see cref="DbContextOptions" /> for the context. When using /// context pooling, options configuration must be performed externally; <see cref="DbContext.OnConfiguring" /> /// will not be called. /// </para> /// </param> /// <param name="poolSize"> /// Sets the maximum number of instances retained by the pool. /// </param> /// <returns> /// The same service collection so that multiple calls can be chained. /// </returns> public static IServiceCollection AddPooledDbContextFactory<TContext>( this IServiceCollection serviceCollection, Action<IServiceProvider, DbContextOptionsBuilder> optionsAction, int poolSize = 128) where TContext : DbContext { if (serviceCollection == null) throw new ArgumentNullException(nameof(serviceCollection)); if (optionsAction == null) throw new ArgumentNullException(nameof(optionsAction)); AddPoolingOptions<TContext>(serviceCollection, optionsAction, poolSize); serviceCollection.TryAddSingleton<DbContextPool<TContext>>(); serviceCollection.TryAddSingleton<IDbContextFactory<TContext>, PooledDbContextFactory<TContext>>(); return serviceCollection; } private static void AddCoreServices<TContextImplementation>( IServiceCollection serviceCollection, Action<IServiceProvider, DbContextOptionsBuilder>? optionsAction, ServiceLifetime optionsLifetime) where TContextImplementation : DbContext { serviceCollection.TryAdd( new ServiceDescriptor( typeof(DbContextOptions<TContextImplementation>), p => CreateDbContextOptions<TContextImplementation>(p, optionsAction), optionsLifetime)); serviceCollection.Add( new ServiceDescriptor( typeof(DbContextOptions), p => p.GetRequiredService<DbContextOptions<TContextImplementation>>(), optionsLifetime)); } private static DbContextOptions<TContext> CreateDbContextOptions<TContext>( IServiceProvider applicationServiceProvider, Action<IServiceProvider, DbContextOptionsBuilder>? optionsAction) where TContext : DbContext { var builder = new DbContextOptionsBuilder<TContext>( new DbContextOptions<TContext>(new Dictionary<Type, IDbContextOptionsExtension>())); builder.UseApplicationServiceProvider(applicationServiceProvider); optionsAction?.Invoke(applicationServiceProvider, builder); return builder.Options; } private static void CheckContextConstructors<TContext>() where TContext : DbContext { var declaredConstructors = typeof(TContext).GetTypeInfo().DeclaredConstructors.ToList(); if (declaredConstructors.Count == 1 && declaredConstructors[0].GetParameters().Length == 0) { throw new ArgumentException(CoreStrings.DbContextMissingConstructor(typeof(TContext).ShortDisplayName())); } } } #endif
47.494845
133
0.663555
3d65e4137b6a707ce93022a3fe14da80841c17c8
2,925
cs
C#
sdk/dotnet/Aws/Outputs/ElastigroupMultipleMetricsMetric.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
4
2019-12-21T20:50:43.000Z
2021-12-01T20:57:38.000Z
sdk/dotnet/Aws/Outputs/ElastigroupMultipleMetricsMetric.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
103
2019-12-09T22:03:16.000Z
2022-03-30T17:07:34.000Z
sdk/dotnet/Aws/Outputs/ElastigroupMultipleMetricsMetric.cs
pulumi/pulumi-spotinst
75592d6293d63f6cec703722f2e02ff1fb1cca44
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.SpotInst.Aws.Outputs { [OutputType] public sealed class ElastigroupMultipleMetricsMetric { /// <summary> /// A list of dimensions describing qualities of the metric. /// *`name` - (Required) the dimension name. /// *`value` - (Optional) the dimension value. /// </summary> public readonly ImmutableArray<Outputs.ElastigroupMultipleMetricsMetricDimension> Dimensions; /// <summary> /// Percentile statistic. Valid values: `"p0.1"` - `"p100"`. /// </summary> public readonly string? ExtendedStatistic; /// <summary> /// The name of the metric, with or without spaces. /// </summary> public readonly string MetricName; /// <summary> /// The record set name. /// </summary> public readonly string Name; /// <summary> /// The namespace for the alarm's associated metric. /// </summary> public readonly string Namespace; /// <summary> /// The metric statistics to return. For information about specific statistics go to [Statistics](http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/index.html?CHAP_TerminologyandKeyConcepts.html#Statistic) in the Amazon CloudWatch Developer Guide. /// </summary> public readonly string? Statistic; /// <summary> /// The unit for the alarm's associated metric. Valid values: `"percent`, `"seconds"`, `"microseconds"`, `"milliseconds"`, `"bytes"`, `"kilobytes"`, `"megabytes"`, `"gigabytes"`, `"terabytes"`, `"bits"`, `"kilobits"`, `"megabits"`, `"gigabits"`, `"terabits"`, `"count"`, `"bytes/second"`, `"kilobytes/second"`, `"megabytes/second"`, `"gigabytes/second"`, `"terabytes/second"`, `"bits/second"`, `"kilobits/second"`, `"megabits/second"`, `"gigabits/second"`, `"terabits/second"`, `"count/second"`, `"none"`. /// </summary> public readonly string? Unit; [OutputConstructor] private ElastigroupMultipleMetricsMetric( ImmutableArray<Outputs.ElastigroupMultipleMetricsMetricDimension> dimensions, string? extendedStatistic, string metricName, string name, string @namespace, string? statistic, string? unit) { Dimensions = dimensions; ExtendedStatistic = extendedStatistic; MetricName = metricName; Name = name; Namespace = @namespace; Statistic = statistic; Unit = unit; } } }
40.068493
513
0.61641
3d661de268da4039907c7a0246018430b946ab76
4,685
cs
C#
src/Web/Controllers/ColorsController.cs
EZtouch/CarRental
1a43802ce9597e217478592710897670b59e667b
[ "Apache-2.0" ]
2
2020-08-01T20:31:00.000Z
2020-08-08T19:56:09.000Z
src/Web/Controllers/ColorsController.cs
EZtouch/CarRental
1a43802ce9597e217478592710897670b59e667b
[ "Apache-2.0" ]
null
null
null
src/Web/Controllers/ColorsController.cs
EZtouch/CarRental
1a43802ce9597e217478592710897670b59e667b
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using EZtouch.CarRentalHub.ApplicationCore.Entities; using EZtouch.CarRentalHub.Infrastructure.Data; namespace EZtouch.CarRentalHub.Controllers { public class ColorsController : Controller { private readonly RentalDBContext _context; public ColorsController(RentalDBContext context) { _context = context; } // GET: Colors public async Task<IActionResult> Index() { return View(await _context.Colors.ToListAsync()); } // GET: Colors/red public async Task<IActionResult> Filter(string id) { return View("Index", await _context.Colors.Where(color => color.Name.ToLower().Contains(id.ToLower())).ToListAsync()); } // GET: Colors/Details/5 public async Task<IActionResult> Details(short? id) { if (id == null) { return NotFound(); } var color = await _context.Colors .SingleOrDefaultAsync(m => m.ColorId == id); if (color == null) { return NotFound(); } return View(color); } // GET: Colors/Create public IActionResult Create() { return View(); } // POST: Colors/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("ColorId,Name,Code")] Color color) { if (ModelState.IsValid) { _context.Add(color); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(color); } // GET: Colors/Edit/5 public async Task<IActionResult> Edit(short? id) { if (id == null) { return NotFound(); } var color = await _context.Colors.SingleOrDefaultAsync(m => m.ColorId == id); if (color == null) { return NotFound(); } return View(color); } // POST: Colors/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(short id, [Bind("ColorId,Name,Code")] Color color) { if (id != color.ColorId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(color); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ColorExists(color.ColorId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(color); } // GET: Colors/Delete/5 public async Task<IActionResult> Delete(short? id) { if (id == null) { return NotFound(); } var color = await _context.Colors .SingleOrDefaultAsync(m => m.ColorId == id); if (color == null) { return NotFound(); } return View(color); } // POST: Colors/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(short id) { var color = await _context.Colors.SingleOrDefaultAsync(m => m.ColorId == id); _context.Colors.Remove(color); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ColorExists(short id) { return _context.Colors.Any(e => e.ColorId == id); } } }
29.28125
130
0.511206
3d6678f0588994e5a653d60901281046306c8572
20,403
cs
C#
src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs
frandesc/roslyn
72a99a8279c9ccbb2ef3a99d5a8bf116a14ebf3b
[ "MIT" ]
17,923
2015-01-14T23:40:37.000Z
2022-03-31T18:10:52.000Z
src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs
open-dotnet/roslyn
2e26701b0d1cb1a902a24f4ad8b8c5fe70514581
[ "MIT" ]
48,991
2015-01-15T00:29:35.000Z
2022-03-31T23:48:56.000Z
src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.cs
open-dotnet/roslyn
2e26701b0d1cb1a902a24f4ad8b8c5fe70514581
[ "MIT" ]
5,209
2015-01-14T23:40:24.000Z
2022-03-30T20:15:03.000Z
// 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.Immutable; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch { using static BinaryOperatorKind; internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> { // Match the following pattern which can be safely converted to switch statement // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // C#, VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // C#, VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // C#, VB // internal abstract class Analyzer { public abstract bool CanConvert(IConditionalOperation operation); public abstract bool HasUnreachableEndPoint(IOperation operation); /// <summary> /// Holds the expression determined to be used as the target expression of the switch /// </summary> /// <remarks> /// Note that this is initially unset until we find a non-constant expression. /// </remarks> private SyntaxNode _switchTargetExpression = null!; private readonly ISyntaxFacts _syntaxFacts; protected Analyzer(ISyntaxFacts syntaxFacts, Feature features) { _syntaxFacts = syntaxFacts; Features = features; } public Feature Features { get; } public bool Supports(Feature feature) => (Features & feature) != 0; public (ImmutableArray<AnalyzedSwitchSection>, SyntaxNode TargetExpression) AnalyzeIfStatementSequence(ReadOnlySpan<IOperation> operations) { using var _ = ArrayBuilder<AnalyzedSwitchSection>.GetInstance(out var sections); if (!ParseIfStatementSequence(operations, sections, out var defaultBodyOpt)) { return default; } if (defaultBodyOpt is object) { sections.Add(new AnalyzedSwitchSection(labels: default, defaultBodyOpt, defaultBodyOpt.Syntax)); } RoslynDebug.Assert(_switchTargetExpression is object); return (sections.ToImmutable(), _switchTargetExpression); } // Tree to parse: // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // private bool ParseIfStatementSequence(ReadOnlySpan<IOperation> operations, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { if (operations.Length > 1 && operations[0] is IConditionalOperation { WhenFalse: null } op && HasUnreachableEndPoint(op.WhenTrue)) { if (!ParseIfStatement(op, sections, out defaultBodyOpt)) { return false; } if (!ParseIfStatementSequence(operations[1..], sections, out defaultBodyOpt)) { var nextStatement = operations[1]; if (nextStatement is IReturnOperation { ReturnedValue: { } } or IThrowOperation { Exception: { } }) { defaultBodyOpt = nextStatement; } } return true; } if (operations.Length > 0) { return ParseIfStatement(operations[0], sections, out defaultBodyOpt); } defaultBodyOpt = null; return false; } // Tree to parse: // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // private bool ParseIfStatement(IOperation operation, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { switch (operation) { case IConditionalOperation op when CanConvert(op): var section = ParseSwitchSection(op); if (section is null) { break; } sections.Add(section); if (op.WhenFalse is null) { defaultBodyOpt = null; } else if (!ParseIfStatementOrBlock(op.WhenFalse, sections, out defaultBodyOpt)) { defaultBodyOpt = op.WhenFalse; } return true; } defaultBodyOpt = null; return false; } private bool ParseIfStatementOrBlock(IOperation op, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { return op is IBlockOperation block ? ParseIfStatementSequence(block.Operations.AsSpan(), sections, out defaultBodyOpt) : ParseIfStatement(op, sections, out defaultBodyOpt); } private AnalyzedSwitchSection? ParseSwitchSection(IConditionalOperation operation) { using var _ = ArrayBuilder<AnalyzedSwitchLabel>.GetInstance(out var labels); if (!ParseSwitchLabels(operation.Condition, labels)) { return null; } return new AnalyzedSwitchSection(labels.ToImmutable(), operation.WhenTrue, operation.Syntax); } // Tree to parse: // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // private bool ParseSwitchLabels(IOperation operation, ArrayBuilder<AnalyzedSwitchLabel> labels) { if (operation is IBinaryOperation { OperatorKind: ConditionalOr } op) { if (!ParseSwitchLabels(op.LeftOperand, labels)) { return false; } operation = op.RightOperand; } var label = ParseSwitchLabel(operation); if (label is null) { return false; } labels.Add(label); return true; } private AnalyzedSwitchLabel? ParseSwitchLabel(IOperation operation) { using var _ = ArrayBuilder<TExpressionSyntax>.GetInstance(out var guards); var pattern = ParsePattern(operation, guards); if (pattern is null) return null; return new AnalyzedSwitchLabel(pattern, guards.ToImmutable()); } private enum ConstantResult { /// <summary> /// None of operands were constant. /// </summary> None, /// <summary> /// Signifies that the left operand is the constant. /// </summary> Left, /// <summary> /// Signifies that the right operand is the constant. /// </summary> Right, } private ConstantResult DetermineConstant(IBinaryOperation op) { return (op.LeftOperand, op.RightOperand) switch { var (e, v) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Right, var (v, e) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Left, _ => ConstantResult.None, }; } // Tree to parse: // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // VB // private AnalyzedPattern? ParsePattern(IOperation operation, ArrayBuilder<TExpressionSyntax> guards) { switch (operation) { case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.RangePattern) && GetRangeBounds(op) is (TExpressionSyntax lower, TExpressionSyntax higher): return new AnalyzedPattern.Range(lower, higher); case IBinaryOperation { OperatorKind: BinaryOperatorKind.Equals } op: return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Constant(left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Constant(right), _ => null }; case IBinaryOperation { OperatorKind: NotEquals } op when Supports(Feature.InequalityPattern): return ParseRelationalPattern(op); case IBinaryOperation op when Supports(Feature.RelationalPattern) && IsRelationalOperator(op.OperatorKind): return ParseRelationalPattern(op); // Check this below the cases that produce Relational/Ranges. We would prefer to use those if // available before utilizing a CaseGuard. case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.AndPattern | Feature.CaseGuard): { var leftPattern = ParsePattern(op.LeftOperand, guards); if (leftPattern == null) return null; if (Supports(Feature.AndPattern)) { var guardCount = guards.Count; var rightPattern = ParsePattern(op.RightOperand, guards); if (rightPattern != null) return new AnalyzedPattern.And(leftPattern, rightPattern); // Making a pattern out of the RHS didn't work. Reset the guards back to where we started. guards.Count = guardCount; } if (Supports(Feature.CaseGuard) && op.RightOperand.Syntax is TExpressionSyntax node) { guards.Add(node); return leftPattern; } return null; } case IIsTypeOperation op when Supports(Feature.IsTypePattern) && CheckTargetExpression(op.ValueOperand) && op.Syntax is TIsExpressionSyntax node: return new AnalyzedPattern.Type(node); case IIsPatternOperation op when Supports(Feature.SourcePattern) && CheckTargetExpression(op.Value) && op.Pattern.Syntax is TPatternSyntax pattern: return new AnalyzedPattern.Source(pattern); case IParenthesizedOperation op: return ParsePattern(op.Operand, guards); } return null; } private AnalyzedPattern? ParseRelationalPattern(IBinaryOperation op) { return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Relational(Flip(op.OperatorKind), left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Relational(op.OperatorKind, right), _ => null }; } private enum BoundKind { /// <summary> /// Not a range bound. /// </summary> None, /// <summary> /// Signifies that the lower-bound of a range pattern /// </summary> Lower, /// <summary> /// Signifies that the higher-bound of a range pattern /// </summary> Higher, } private (SyntaxNode Lower, SyntaxNode Higher) GetRangeBounds(IBinaryOperation op) { if (op is not { LeftOperand: IBinaryOperation left, RightOperand: IBinaryOperation right }) { return default; } return (GetRangeBound(left), GetRangeBound(right)) switch { ({ Kind: BoundKind.Lower } low, { Kind: BoundKind.Higher } high) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), ({ Kind: BoundKind.Higher } high, { Kind: BoundKind.Lower } low) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), _ => default }; bool CheckTargetExpression(IOperation left, IOperation right) => _syntaxFacts.AreEquivalent(left.Syntax, right.Syntax) && this.CheckTargetExpression(left); } private static (BoundKind Kind, IOperation Expression, IOperation Value) GetRangeBound(IBinaryOperation op) { return op.OperatorKind switch { // 5 <= i LessThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Lower, op.RightOperand, op.LeftOperand), // i <= 5 LessThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Higher, op.LeftOperand, op.RightOperand), // 5 >= i GreaterThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Higher, op.RightOperand, op.LeftOperand), // i >= 5 GreaterThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Lower, op.LeftOperand, op.RightOperand), _ => default }; } /// <summary> /// Changes the direction the operator is pointing /// </summary> private static BinaryOperatorKind Flip(BinaryOperatorKind operatorKind) { return operatorKind switch { LessThan => GreaterThan, LessThanOrEqual => GreaterThanOrEqual, GreaterThanOrEqual => LessThanOrEqual, GreaterThan => LessThan, NotEquals => NotEquals, var v => throw ExceptionUtilities.UnexpectedValue(v) }; } private static bool IsRelationalOperator(BinaryOperatorKind operatorKind) { switch (operatorKind) { case LessThan: case LessThanOrEqual: case GreaterThanOrEqual: case GreaterThan: return true; default: return false; } } private static bool IsConstant(IOperation operation) { // Constants do not propagate to conversions return operation is IConversionOperation op ? IsConstant(op.Operand) : operation.ConstantValue.HasValue; } private bool CheckTargetExpression(IOperation operation) { if (operation is IConversionOperation { IsImplicit: false } op) { // Unwrap explicit casts because switch will emit those anyways operation = op.Operand; } var expression = operation.Syntax; // If we have not figured the switch expression yet, // we will assume that the first expression is the one. if (_switchTargetExpression is null) { _switchTargetExpression = expression; return true; } return _syntaxFacts.AreEquivalent(expression, _switchTargetExpression); } } [Flags] internal enum Feature { None = 0, // VB/C# 9.0 features RelationalPattern = 1, // VB features InequalityPattern = 1 << 1, RangePattern = 1 << 2, // C# 7.0 features SourcePattern = 1 << 3, IsTypePattern = 1 << 4, CaseGuard = 1 << 5, // C# 8.0 features SwitchExpression = 1 << 6, // C# 9.0 features OrPattern = 1 << 7, AndPattern = 1 << 8, TypePattern = 1 << 9, } } }
42.773585
164
0.479586
3d66a70da24c79e6ac7e0e13f6ea836e5abf37b1
3,884
cs
C#
src/Iot.Mocks/MockReliableQueue.cs
eltociear/service-fabric-dotnet-iot
3c9192496d98c26a3a89f104ea5989fe90135d57
[ "MIT" ]
115
2015-11-19T21:55:12.000Z
2021-11-15T02:27:03.000Z
src/Iot.Mocks/MockReliableQueue.cs
eltociear/service-fabric-dotnet-iot
3c9192496d98c26a3a89f104ea5989fe90135d57
[ "MIT" ]
23
2015-11-26T12:00:39.000Z
2022-03-15T09:17:04.000Z
src/Iot.Mocks/MockReliableQueue.cs
eltociear/service-fabric-dotnet-iot
3c9192496d98c26a3a89f104ea5989fe90135d57
[ "MIT" ]
114
2015-11-24T11:34:11.000Z
2021-08-05T03:01:05.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Iot.Mocks { using System; using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data; using Microsoft.ServiceFabric.Data.Collections; public class MockReliableQueue<T> : IReliableQueue<T> { private ConcurrentQueue<T> queue = new ConcurrentQueue<T>(); public Task EnqueueAsync(ITransaction tx, T item, TimeSpan timeout, CancellationToken cancellationToken) { this.queue.Enqueue(item); return Task.FromResult(true); } public Task EnqueueAsync(ITransaction tx, T item) { this.queue.Enqueue(item); return Task.FromResult(true); } public Task<ConditionalValue<T>> TryDequeueAsync(ITransaction tx, TimeSpan timeout, CancellationToken cancellationToken) { T item; bool result = this.queue.TryDequeue(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task<ConditionalValue<T>> TryDequeueAsync(ITransaction tx) { T item; bool result = this.queue.TryDequeue(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, LockMode lockMode, TimeSpan timeout, CancellationToken cancellationToken) { T item; bool result = this.queue.TryPeek(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, LockMode lockMode) { T item; bool result = this.queue.TryPeek(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx, TimeSpan timeout, CancellationToken cancellationToken) { T item; bool result = this.queue.TryPeek(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task<ConditionalValue<T>> TryPeekAsync(ITransaction tx) { T item; bool result = this.queue.TryPeek(out item); return Task.FromResult((ConditionalValue<T>) Activator.CreateInstance(typeof(ConditionalValue<T>), result, item)); } public Task ClearAsync() { while (!this.queue.IsEmpty) { T result; this.queue.TryDequeue(out result); } return Task.FromResult(true); } public Task<IAsyncEnumerable<T>> CreateEnumerableAsync(ITransaction tx) { return Task.FromResult<IAsyncEnumerable<T>>(new MockAsyncEnumerable<T>(this.queue)); } public Task<long> GetCountAsync(ITransaction tx) { return Task.FromResult<long>(this.queue.Count); } public Uri Name { get; set; } public Task<long> GetCountAsync() { return Task.FromResult((long) this.queue.Count); } } }
35.633028
145
0.592173
3d6a7102c1385e5380cce377a150393d9990ccc4
5,995
cs
C#
source/Host/Startup.cs
uQr/IdentityManager
c039c2b4c69e436decfb68e79047990c9bbcdc2b
[ "Apache-2.0" ]
472
2015-03-15T16:15:59.000Z
2022-02-16T21:05:48.000Z
source/Host/Startup.cs
codematrix/IdentityManager
c039c2b4c69e436decfb68e79047990c9bbcdc2b
[ "Apache-2.0" ]
188
2015-03-16T02:12:34.000Z
2017-12-20T10:05:35.000Z
source/Host/Startup.cs
codematrix/IdentityManager
c039c2b4c69e436decfb68e79047990c9bbcdc2b
[ "Apache-2.0" ]
240
2015-03-15T12:29:43.000Z
2022-02-16T21:05:52.000Z
/* * Copyright 2014 Dominick Baier, Brock Allen * * 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 Owin; using System.Collections; using System.Collections.Generic; using System.Security.Claims; using IdentityManager.Configuration; using IdentityManager.Core.Logging; using IdentityManager.Extensions; using IdentityManager.Host.IdSvr; using IdentityManager.Host.InMemoryService; using IdentityManager.Logging; using Microsoft.Owin.Logging; using Microsoft.Owin; using IdentityManager.Host; using System.Threading.Tasks; using System.IdentityModel.Tokens; using Microsoft.Owin.Security.Cookies; //[assembly: OwinStartup(typeof(StartupWithLocalhostSecurity))] [assembly: OwinStartup(typeof(StartupWithHostCookiesSecurity))] namespace IdentityManager.Host { public class StartupWithLocalhostSecurity { public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider()); // this configures IdentityManager // we're using a Map just to test hosting not at the root app.Map("/idm", idm => { var factory = new IdentityManagerServiceFactory(); var rand = new System.Random(); var users = Users.Get(rand.Next(5000, 20000)); var roles = Roles.Get(rand.Next(15)); factory.Register(new Registration<ICollection<InMemoryUser>>(users)); factory.Register(new Registration<ICollection<InMemoryRole>>(roles)); factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>(); idm.UseIdentityManager(new IdentityManagerOptions { Factory = factory, }); }); } } public class StartupWithHostCookiesSecurity { public void Configuration(IAppBuilder app) { LogProvider.SetCurrentLogProvider(new TraceSourceLogProvider()); JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>(); app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions { AuthenticationType = "Cookies", }); app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions { AuthenticationType = "oidc", Authority = "https://localhost:44337/ids", ClientId = "idmgr_client", RedirectUri = "https://localhost:44337", ResponseType = "id_token", UseTokenLifetime = false, Scope = "openid idmgr", SignInAsAuthenticationType = "Cookies", Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications { SecurityTokenValidated = n => { n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); return Task.FromResult(0); }, RedirectToIdentityProvider = async n => { if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest) { var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies"); if (result != null) { var id_token = result.Identity.Claims.GetValue("id_token"); if (id_token != null) { n.ProtocolMessage.IdTokenHint = id_token; n.ProtocolMessage.PostLogoutRedirectUri = "https://localhost:44337/idm"; } } } } } }); app.Map("/idm", idm => { var factory = new IdentityManagerServiceFactory(); var rand = new System.Random(); var users = Users.Get(rand.Next(5000, 20000)); var roles = Roles.Get(rand.Next(15)); factory.Register(new Registration<ICollection<InMemoryUser>>(users)); factory.Register(new Registration<ICollection<InMemoryRole>>(roles)); factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>(); idm.UseIdentityManager(new IdentityManagerOptions { Factory = factory, SecurityConfiguration = new HostSecurityConfiguration { HostAuthenticationType = "Cookies", AdditionalSignOutType = "oidc" } }); }); // this configures an embedded IdentityServer to act as an external authentication provider // when using IdentityManager in Token security mode. normally you'd configure this elsewhere. app.Map("/ids", ids => { IdSvrConfig.Configure(ids); }); } } }
40.506757
134
0.584987
3d6cf5848e42df7c9bda4523a8dbf81838a30949
58,051
cs
C#
src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs
jeremyVignelles/aspnetcore
72444f90d1e9cb8ff2e7364168eea9baec6e8e92
[ "Apache-2.0" ]
10
2021-06-09T02:22:29.000Z
2021-07-07T14:13:48.000Z
src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs
seanwallawalla-forks/aspnetcore
0ecf4c1bd9526c36356a0f259d90aafdf0756fcd
[ "Apache-2.0" ]
50
2021-07-21T19:42:37.000Z
2022-03-28T20:07:38.000Z
src/Http/Routing/test/UnitTests/Template/TemplateBinderTests.cs
seanwallawalla-forks/aspnetcore
0ecf4c1bd9526c36356a0f259d90aafdf0756fcd
[ "Apache-2.0" ]
1
2020-12-16T04:50:09.000Z
2020-12-16T04:50:09.000Z
// 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.Generic; using System.Linq; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Routing.Constraints; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.AspNetCore.Routing.TestObjects; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Routing.Template.Tests { public class TemplateBinderTests { public static TheoryData EmptyAndNullDefaultValues => new TheoryData<string, RouteValueDictionary, RouteValueDictionary, string> { { "Test/{val1}/{val2}", new RouteValueDictionary(new {val1 = "", val2 = ""}), new RouteValueDictionary(new {val2 = "SomeVal2"}), null }, { "Test/{val1}/{val2}", new RouteValueDictionary(new {val1 = "", val2 = ""}), new RouteValueDictionary(new {val1 = "a"}), "/Test/a" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "", val3 = ""}), new RouteValueDictionary(new {val2 = "a"}), null }, { "Test/{val1}/{val2}", new RouteValueDictionary(new {val1 = "", val2 = ""}), new RouteValueDictionary(new {val1 = "a", val2 = "b"}), "/Test/a/b" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "", val2 = "", val3 = ""}), new RouteValueDictionary(new {val1 = "a", val2 = "b", val3 = "c"}), "/Test/a/b/c" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "", val2 = "", val3 = ""}), new RouteValueDictionary(new {val1 = "a", val2 = "b"}), "/Test/a/b" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "", val2 = "", val3 = ""}), new RouteValueDictionary(new {val1 = "a"}), "/Test/a" }, { "Test/{val1}", new RouteValueDictionary(new {val1 = "42", val2 = "", val3 = ""}), new RouteValueDictionary(), "/Test" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "42", val2 = (string)null, val3 = (string)null}), new RouteValueDictionary(), "/Test" }, { "Test/{val1}/{val2}/{val3}/{val4}", new RouteValueDictionary(new {val1 = "21", val2 = "", val3 = "", val4 = ""}), new RouteValueDictionary(new {val1 = "42", val2 = "11", val3 = "", val4 = ""}), "/Test/42/11" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "21", val2 = "", val3 = ""}), new RouteValueDictionary(new {val1 = "42"}), "/Test/42" }, { "Test/{val1}/{val2}/{val3}/{val4}", new RouteValueDictionary(new {val1 = "21", val2 = "", val3 = "", val4 = ""}), new RouteValueDictionary(new {val1 = "42", val2 = "11"}), "/Test/42/11" }, { "Test/{val1}/{val2}/{val3}", new RouteValueDictionary(new {val1 = "21", val2 = (string)null, val3 = (string)null}), new RouteValueDictionary(new {val1 = "42"}), "/Test/42" }, { "Test/{val1}/{val2}/{val3}/{val4}", new RouteValueDictionary(new {val1 = "21", val2 = (string)null, val3 = (string)null, val4 = (string)null}), new RouteValueDictionary(new {val1 = "42", val2 = "11"}), "/Test/42/11" }, }; [Theory] [MemberData(nameof(EmptyAndNullDefaultValues))] public void Binding_WithEmptyAndNull_DefaultValues( string template, RouteValueDictionary defaults, RouteValueDictionary values, string expected) { // Arrange var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues: null, values: values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); Assert.Equal(expected, boundTemplate); } } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}-{region}", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "xx", region = "yy" }), "/language/xx-yy"); } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-{region}a", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "xx", region = "yy" }), "/language/xx-yya"); } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}-{region}", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "xx", region = "yy" }), "/language/axx-yy"); } public static TheoryData OptionalParamValues => new TheoryData<string, RouteValueDictionary, RouteValueDictionary, RouteValueDictionary, string> { // defaults // ambient values // values { "Test/{val1}/{val2}.{val3?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2"}), new RouteValueDictionary(new {val3 = "someval3"}), new RouteValueDictionary(new {val3 = "someval3"}), "/Test/someval1/someval2.someval3" }, { "Test/{val1}/{val2}.{val3?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2"}), new RouteValueDictionary(new {val3 = "someval3a"}), new RouteValueDictionary(new {val3 = "someval3v"}), "/Test/someval1/someval2.someval3v" }, { "Test/{val1}/{val2}.{val3?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2"}), new RouteValueDictionary(new {val3 = "someval3a"}), new RouteValueDictionary(), "/Test/someval1/someval2.someval3a" }, { "Test/{val1}/{val2}.{val3?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2"}), new RouteValueDictionary(), new RouteValueDictionary(new {val3 = "someval3v"}), "/Test/someval1/someval2.someval3v" }, { "Test/{val1}/{val2}.{val3?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2"}), new RouteValueDictionary(), new RouteValueDictionary(), "/Test/someval1/someval2" }, { "Test/{val1}.{val2}.{val3}.{val4?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2" }), new RouteValueDictionary(), new RouteValueDictionary(new {val4 = "someval4", val3 = "someval3" }), "/Test/someval1.someval2." + "someval3.someval4" }, { "Test/{val1}.{val2}.{val3}.{val4?}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2" }), new RouteValueDictionary(), new RouteValueDictionary(new {val3 = "someval3" }), "/Test/someval1.someval2." + "someval3" }, { "Test/.{val2?}", new RouteValueDictionary(new { }), new RouteValueDictionary(), new RouteValueDictionary(new {val2 = "someval2" }), "/Test/.someval2" }, { "Test/{val1}.{val2}", new RouteValueDictionary(new {val1 = "someval1", val2 = "someval2" }), new RouteValueDictionary(), new RouteValueDictionary(new {val3 = "someval3" }), "/Test/someval1.someval2?" + "val3=someval3" }, }; [Theory] [MemberData(nameof(OptionalParamValues))] public void GetVirtualPathWithMultiSegmentWithOptionalParam( string template, RouteValueDictionary defaults, RouteValueDictionary ambientValues, RouteValueDictionary values, string expected) { // Arrange var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues: ambientValues, values: values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); Assert.Equal(expected, boundTemplate); } } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}-{region}a", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "xx", region = "yy" }), "/language/axx-yya"); } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnNeitherEndDoesNotMatch() { RunTest( "language/a{lang}-{region}a", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "", region = "yy" }), null); } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnNeitherEndDoesNotMatch2() { RunTest( "language/a{lang}-{region}a", null, new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "xx", region = "" }), null); } [Fact] public void GetVirtualPathWithSimpleMultiSegmentParamsOnBothEndsMatches() { RunTest( "language/{lang}", null, new RouteValueDictionary(new { lang = "en" }), new RouteValueDictionary(new { lang = "xx" }), "/language/xx"); } [Fact] public void GetVirtualPathWithSimpleMultiSegmentParamsOnLeftEndMatches() { RunTest( "language/{lang}-", null, new RouteValueDictionary(new { lang = "en" }), new RouteValueDictionary(new { lang = "xx" }), "/language/xx-"); } [Fact] public void GetVirtualPathWithSimpleMultiSegmentParamsOnRightEndMatches() { RunTest( "language/a{lang}", null, new RouteValueDictionary(new { lang = "en" }), new RouteValueDictionary(new { lang = "xx" }), "/language/axx"); } [Fact] public void GetVirtualPathWithSimpleMultiSegmentParamsOnNeitherEndMatches() { RunTest( "language/a{lang}a", null, new RouteValueDictionary(new { lang = "en" }), new RouteValueDictionary(new { lang = "xx" }), "/language/axxa"); } [Fact] public void GetVirtualPathWithMultiSegmentStandardMvcRouteMatches() { RunTest( "{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { action = "Index", id = (string)null }), new RouteValueDictionary(new { controller = "home", action = "list", id = (string)null }), new RouteValueDictionary(new { controller = "products" }), "/products.mvc"); } [Fact] public void GetVirtualPathWithMultiSegmentParamsOnBothEndsWithDefaultValuesMatches() { RunTest( "language/{lang}-{region}", new RouteValueDictionary(new { lang = "xx", region = "yy" }), new RouteValueDictionary(new { lang = "en", region = "US" }), new RouteValueDictionary(new { lang = "zz" }), "/language/zz-yy"); } [Fact] public void GetUrlWithDefaultValue() { // URL should be found but excluding the 'id' parameter, which has only a default value. RunTest( "{controller}/{action}/{id}", new RouteValueDictionary(new { id = "defaultid" }), new RouteValueDictionary(new { controller = "home", action = "oldaction" }), new RouteValueDictionary(new { action = "newaction" }), "/home/newaction"); } [Fact] public void GetVirtualPathWithEmptyStringRequiredValueReturnsNull() { RunTest( "foo/{controller}", null, new RouteValueDictionary(new { }), new RouteValueDictionary(new { controller = "" }), null); } [Fact] public void GetVirtualPathWithNullRequiredValueReturnsNull() { RunTest( "foo/{controller}", null, new RouteValueDictionary(new { }), new RouteValueDictionary(new { controller = (string)null }), null); } [Fact] public void GetVirtualPathWithRequiredValueReturnsPath() { RunTest( "foo/{controller}", null, new RouteValueDictionary(new { }), new RouteValueDictionary(new { controller = "home" }), "/foo/home"); } [Fact] public void GetUrlWithNullDefaultValue() { // URL should be found but excluding the 'id' parameter, which has only a default value. RunTest( "{controller}/{action}/{id}", new RouteValueDictionary(new { id = (string)null }), new RouteValueDictionary(new { controller = "home", action = "oldaction", id = (string)null }), new RouteValueDictionary(new { action = "newaction" }), "/home/newaction"); } [Fact] public void GetVirtualPathCanFillInSeparatedParametersWithDefaultValues() { RunTest( "{controller}/{language}-{locale}", new RouteValueDictionary(new { language = "en", locale = "US" }), new RouteValueDictionary(), new RouteValueDictionary(new { controller = "Orders" }), "/Orders/en-US"); } [Fact] public void GetVirtualPathWithUnusedNullValueShouldGenerateUrlAndIgnoreNullValue() { RunTest( "{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { action = "Index", id = "" }), new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }), new RouteValueDictionary(new { controller = "Home", action = "TestAction", id = "1", format = (string)null }), "/Home.mvc/TestAction/1"); } [Fact] public void GetUrlWithMissingValuesDoesntMatch() { RunTest( "{controller}/{action}/{id}", null, new { controller = "home", action = "oldaction" }, new { action = "newaction" }, null); } [Fact] public void GetUrlWithEmptyRequiredValuesReturnsNull() { RunTest( "{p1}/{p2}/{p3}", null, new { p1 = "v1", }, new { p2 = "", p3 = "" }, null); } [Fact] public void GetUrlWithEmptyOptionalValuesReturnsShortUrl() { RunTest( "{p1}/{p2}/{p3}", new { p2 = "d2", p3 = "d3" }, new { p1 = "v1", }, new { p2 = "", p3 = "" }, "/v1"); } [Fact] public void GetUrlShouldIgnoreValuesAfterChangedParameter() { RunTest( "{controller}/{action}/{id}", new { action = "Index", id = (string)null }, new { controller = "orig", action = "init", id = "123" }, new { action = "new", }, "/orig/new"); } [Fact] public void GetUrlWithNullForMiddleParameterIgnoresRemainingParameters() { RunTest( "UrlGeneration1/{controller}.mvc/{action}/{category}/{year}/{occasion}/{SafeParam}", new { year = 1995, occasion = "Christmas", action = "Play", SafeParam = "SafeParamValue" }, new { controller = "UrlRouting", action = "Play", category = "Photos", year = "2008", occasion = "Easter", SafeParam = "SafeParamValue" }, new { year = (string)null, occasion = "Hola" }, "/UrlGeneration1/UrlRouting.mvc/Play/" + "Photos/1995/Hola"); } [Fact] public void GetUrlWithEmptyStringForMiddleParameterIgnoresRemainingParameters() { var ambientValues = new RouteValueDictionary(); ambientValues.Add("controller", "UrlRouting"); ambientValues.Add("action", "Play"); ambientValues.Add("category", "Photos"); ambientValues.Add("year", "2008"); ambientValues.Add("occasion", "Easter"); ambientValues.Add("SafeParam", "SafeParamValue"); var values = new RouteValueDictionary(); values.Add("year", String.Empty); values.Add("occasion", "Hola"); RunTest( "UrlGeneration1/{controller}.mvc/{action}/{category}/{year}/{occasion}/{SafeParam}", new RouteValueDictionary(new { year = 1995, occasion = "Christmas", action = "Play", SafeParam = "SafeParamValue" }), ambientValues, values, "/UrlGeneration1/UrlRouting.mvc/" + "Play/Photos/1995/Hola"); } [Fact] public void GetUrlWithEmptyStringForMiddleParameterShouldUseDefaultValue() { var ambientValues = new RouteValueDictionary(); ambientValues.Add("Controller", "Test"); ambientValues.Add("Action", "Fallback"); ambientValues.Add("param1", "fallback1"); ambientValues.Add("param2", "fallback2"); ambientValues.Add("param3", "fallback3"); var values = new RouteValueDictionary(); values.Add("controller", "subtest"); values.Add("param1", "b"); RunTest( "{controller}.mvc/{action}/{param1}", new RouteValueDictionary(new { action = "Default" }), ambientValues, values, "/subtest.mvc/Default/b"); } [Fact] public void GetUrlVerifyEncoding() { var values = new RouteValueDictionary(); values.Add("controller", "#;?:@&=+$,"); values.Add("action", "showcategory"); values.Add("id", 123); values.Add("so?rt", "de?sc"); values.Add("maxPrice", 100); RunTest( "{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { controller = "Home" }), new RouteValueDictionary(new { controller = "home", action = "Index", id = (string)null }), values, "/%23;%3F%3A@%26%3D%2B$,.mvc/showcategory/123?so%3Frt=de%3Fsc&maxPrice=100"); } [Fact] public void GetUrlGeneratesQueryStringForNewValuesAndEscapesQueryString() { var values = new RouteValueDictionary(new { controller = "products", action = "showcategory", id = 123, maxPrice = 100 }); values.Add("so?rt", "de?sc"); RunTest( "{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { controller = "Home" }), new RouteValueDictionary(new { controller = "home", action = "Index", id = (string)null }), values, "/products.mvc/showcategory/123" + "?so%3Frt=de%3Fsc&maxPrice=100"); } [Fact] public void GetUrlGeneratesQueryStringForNewValuesButIgnoresNewValuesThatMatchDefaults() { RunTest( "{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { controller = "Home", Custom = "customValue" }), new RouteValueDictionary(new { controller = "Home", action = "Index", id = (string)null }), new RouteValueDictionary( new { controller = "products", action = "showcategory", id = 123, sort = "desc", maxPrice = 100, custom = "customValue" }), "/products.mvc/showcategory/123" + "?sort=desc&maxPrice=100"); } [Fact] public void GetVirtualPathEncodesParametersAndLiterals() { RunTest( "bl%og/{controller}/he llo/{action}", null, new RouteValueDictionary(new { controller = "ho%me", action = "li st" }), new RouteValueDictionary(), "/bl%25og/ho%25me/he%20llo/li%20st"); } [Fact] public void GetVirtualDoesNotEncodeLeadingSlashes() { RunTest( "{controller}/{action}", null, new RouteValueDictionary(new { controller = "/home", action = "/my/index" }), new RouteValueDictionary(), "/home/%2Fmy%2Findex"); } [Fact] public void GetUrlWithCatchAllWithValue() { RunTest( "{p1}/{*p2}", new RouteValueDictionary(new { id = "defaultid" }), new RouteValueDictionary(new { p1 = "v1" }), new RouteValueDictionary(new { p2 = "v2a/v2b" }), "/v1/v2a%2Fv2b"); } [Fact] public void GetUrlWithCatchAllWithEmptyValue() { RunTest( "{p1}/{*p2}", new RouteValueDictionary(new { id = "defaultid" }), new RouteValueDictionary(new { p1 = "v1" }), new RouteValueDictionary(new { p2 = "" }), "/v1"); } [Fact] public void GetUrlWithCatchAllWithNullValue() { RunTest( "{p1}/{*p2}", new RouteValueDictionary(new { id = "defaultid" }), new RouteValueDictionary(new { p1 = "v1" }), new RouteValueDictionary(new { p2 = (string)null }), "/v1"); } [Fact] public void GetUrlWithLeadingTildeSlash() { RunTest( "~/foo", null, null, new RouteValueDictionary(new { }), "/foo"); } [Fact] public void GetUrlWithLeadingSlash() { RunTest( "/foo", null, null, new RouteValueDictionary(new { }), "/foo"); } [Fact] public void TemplateBinder_KeepsExplicitlySuppliedRouteValues_OnFailedRouteMatch() { // Arrange var template = "{area?}/{controller=Home}/{action=Index}/{id?}"; var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults: null); var ambientValues = new RouteValueDictionary(); var routeValues = new RouteValueDictionary(new { controller = "Test", action = "Index" }); // Act var templateValuesResult = binder.GetValues(ambientValues, routeValues); var boundTemplate = binder.BindValues(templateValuesResult.AcceptedValues); // Assert Assert.Null(boundTemplate); Assert.Equal(2, templateValuesResult.CombinedValues.Count); object routeValue; Assert.True(templateValuesResult.CombinedValues.TryGetValue("controller", out routeValue)); Assert.Equal("Test", routeValue?.ToString()); Assert.True(templateValuesResult.CombinedValues.TryGetValue("action", out routeValue)); Assert.Equal("Index", routeValue?.ToString()); } #if ROUTE_COLLECTION [Fact] public void GetUrlShouldValidateOnlyAcceptedParametersAndUserDefaultValuesForInvalidatedParameters() { // Arrange var rd = CreateRouteData(); rd.Values.Add("Controller", "UrlRouting"); rd.Values.Add("Name", "MissmatchedValidateParams"); rd.Values.Add("action", "MissmatchedValidateParameters2"); rd.Values.Add("ValidateParam1", "special1"); rd.Values.Add("ValidateParam2", "special2"); IRouteCollection rc = new DefaultRouteCollection(); rc.Add(CreateRoute( "UrlConstraints/Validation.mvc/Input5/{action}/{ValidateParam1}/{ValidateParam2}", new RouteValueDictionary(new { Controller = "UrlRouting", Name = "MissmatchedValidateParams", ValidateParam2 = "valid" }), new RouteValueDictionary(new { ValidateParam1 = "valid.*", ValidateParam2 = "valid.*" }))); rc.Add(CreateRoute( "UrlConstraints/Validation.mvc/Input5/{action}/{ValidateParam1}/{ValidateParam2}", new RouteValueDictionary(new { Controller = "UrlRouting", Name = "MissmatchedValidateParams" }), new RouteValueDictionary(new { ValidateParam1 = "special.*", ValidateParam2 = "special.*" }))); var values = CreateRouteValueDictionary(); values.Add("Name", "MissmatchedValidateParams"); values.Add("ValidateParam1", "valid1"); // Act var vpd = rc.GetVirtualPath(GetHttpContext("/app1", "", ""), values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app1/UrlConstraints/Validation.mvc/Input5/MissmatchedValidateParameters2/valid1", vpd.VirtualPath); } [Fact] public void GetUrlWithRouteThatHasExtensionWithSubsequentDefaultValueIncludesExtensionButNotDefaultValue() { // Arrange var rd = CreateRouteData(); rd.Values.Add("controller", "Bank"); rd.Values.Add("action", "MakeDeposit"); rd.Values.Add("accountId", "7770"); IRouteCollection rc = new DefaultRouteCollection(); rc.Add(CreateRoute( "{controller}.mvc/Deposit/{accountId}", new RouteValueDictionary(new { Action = "DepositView" }))); // Note: This route was in the original bug, but it turns out that this behavior is incorrect. With the // recent fix to Route (in this changelist) this route would have been selected since we have values for // all three required parameters. //rc.Add(new Route { // Url = "{controller}.mvc/{action}/{accountId}", // RouteHandler = new DummyRouteHandler() //}); // This route should be chosen because the requested action is List. Since the default value of the action // is List then the Action should not be in the URL. However, the file extension should be included since // it is considered "safe." rc.Add(CreateRoute( "{controller}.mvc/{action}", new RouteValueDictionary(new { Action = "List" }))); var values = CreateRouteValueDictionary(); values.Add("Action", "List"); // Act var vpd = rc.GetVirtualPath(GetHttpContext("/app1", "", ""), values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app1/Bank.mvc", vpd.VirtualPath); } [Fact] public void GetUrlWithRouteThatHasDifferentControllerCaseShouldStillMatch() { // Arrange var rd = CreateRouteData(); rd.Values.Add("controller", "Bar"); rd.Values.Add("action", "bbb"); rd.Values.Add("id", null); IRouteCollection rc = new DefaultRouteCollection(); rc.Add(CreateRoute("PrettyFooUrl", new RouteValueDictionary(new { controller = "Foo", action = "aaa", id = (string)null }))); rc.Add(CreateRoute("PrettyBarUrl", new RouteValueDictionary(new { controller = "Bar", action = "bbb", id = (string)null }))); rc.Add(CreateRoute("{controller}/{action}/{id}", new RouteValueDictionary(new { action = "Index", id = (string)null }))); var values = CreateRouteValueDictionary(); values.Add("Action", "aaa"); values.Add("Controller", "foo"); // Act var vpd = rc.GetVirtualPath(GetHttpContext("/app1", "", ""), values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app1/PrettyFooUrl", vpd.VirtualPath); } [Fact] public void GetUrlWithNoChangedValuesShouldProduceSameUrl() { // Arrange var rd = CreateRouteData(); rd.Values.Add("controller", "Home"); rd.Values.Add("action", "Index"); rd.Values.Add("id", null); IRouteCollection rc = new DefaultRouteCollection(); rc.Add(CreateRoute("{controller}.mvc/{action}/{id}", new RouteValueDictionary(new { action = "Index", id = (string)null }))); rc.Add(CreateRoute("{controller}/{action}/{id}", new RouteValueDictionary(new { action = "Index", id = (string)null }))); var values = CreateRouteValueDictionary(); values.Add("Action", "Index"); // Act var vpd = rc.GetVirtualPath(GetHttpContext("/app1", "", ""), values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app1/Home.mvc", vpd.VirtualPath); } [Fact] public void GetUrlAppliesConstraintsRulesToChooseRoute() { // Arrange var rd = CreateRouteData(); rd.Values.Add("controller", "Home"); rd.Values.Add("action", "Index"); rd.Values.Add("id", null); IRouteCollection rc = new DefaultRouteCollection(); rc.Add(CreateRoute( "foo.mvc/{action}", new RouteValueDictionary(new { controller = "Home" }), new RouteValueDictionary(new { controller = "Home", action = "Contact", httpMethod = CreateHttpMethodConstraint("get") }))); rc.Add(CreateRoute( "{controller}.mvc/{action}", new RouteValueDictionary(new { action = "Index" }), new RouteValueDictionary(new { controller = "Home", action = "(Index|About)", httpMethod = CreateHttpMethodConstraint("post") }))); var values = CreateRouteValueDictionary(); values.Add("Action", "Index"); // Act var vpd = rc.GetVirtualPath(GetHttpContext("/app1", "", ""), values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app1/Home.mvc", vpd.VirtualPath); } [Fact] public void GetUrlWithValuesThatAreCompletelyDifferentFromTheCurrentRoute() { // Arrange HttpContext context = GetHttpContext("/app", null, null); IRouteCollection rt = new DefaultRouteCollection(); rt.Add(CreateRoute("date/{y}/{m}/{d}", null)); rt.Add(CreateRoute("{controller}/{action}/{id}", null)); var rd = CreateRouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "dostuff"); var values = CreateRouteValueDictionary(); values.Add("y", "2007"); values.Add("m", "08"); values.Add("d", "12"); // Act var vpd = rt.GetVirtualPath(context, values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app/date/2007/08/12", vpd.VirtualPath); } [Fact] public void GetUrlWithValuesThatAreCompletelyDifferentFromTheCurrentRouteAsSecondRoute() { // Arrange HttpContext context = GetHttpContext("/app", null, null); IRouteCollection rt = new DefaultRouteCollection(); rt.Add(CreateRoute("{controller}/{action}/{id}")); rt.Add(CreateRoute("date/{y}/{m}/{d}")); var rd = CreateRouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "dostuff"); var values = CreateRouteValueDictionary(); values.Add("y", "2007"); values.Add("m", "08"); values.Add("d", "12"); // Act var vpd = rt.GetVirtualPath(context, values); // Assert Assert.NotNull(vpd); Assert.Equal<string>("/app/date/2007/08/12", vpd.VirtualPath); } [Fact] public void GetVirtualPathUsesCurrentValuesNotInRouteToMatch() { // Arrange HttpContext context = GetHttpContext("/app", null, null); TemplateRoute r1 = CreateRoute( "ParameterMatching.mvc/{Action}/{product}", new RouteValueDictionary(new { Controller = "ParameterMatching", product = (string)null }), null); TemplateRoute r2 = CreateRoute( "{controller}.mvc/{action}", new RouteValueDictionary(new { Action = "List" }), new RouteValueDictionary(new { Controller = "Action|Bank|Overridden|DerivedFromAction|OverrideInvokeActionAndExecute|InvalidControllerName|Store|HtmlHelpers|(T|t)est|UrlHelpers|Custom|Parent|Child|TempData|ViewFactory|LocatingViews|AccessingDataInViews|ViewOverrides|ViewMasterPage|InlineCompileError|CustomView" }), null); var rd = CreateRouteData(); rd.Values.Add("controller", "Bank"); rd.Values.Add("Action", "List"); var valuesDictionary = CreateRouteValueDictionary(); valuesDictionary.Add("action", "AttemptLogin"); // Act for first route var vpd = r1.GetVirtualPath(context, valuesDictionary); // Assert Assert.NotNull(vpd); Assert.Equal<string>("ParameterMatching.mvc/AttemptLogin", vpd.VirtualPath); // Act for second route vpd = r2.GetVirtualPath(context, valuesDictionary); // Assert Assert.NotNull(vpd); Assert.Equal<string>("Bank.mvc/AttemptLogin", vpd.VirtualPath); } #endif #if DATA_TOKENS [Fact] public void GetVirtualPathWithDataTokensCopiesThemFromRouteToVirtualPathData() { // Arrange HttpContext context = GetHttpContext("/app", null, null); TemplateRoute r = CreateRoute("{controller}/{action}", null, null, new RouteValueDictionary(new { foo = "bar", qux = "quux" })); var rd = CreateRouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "index"); var valuesDictionary = CreateRouteValueDictionary(); // Act var vpd = r.GetVirtualPath(context, valuesDictionary); // Assert Assert.NotNull(vpd); Assert.Equal<string>("home/index", vpd.VirtualPath); Assert.Equal(r, vpd.Route); Assert.Equal<int>(2, vpd.DataTokens.Count); Assert.Equal("bar", vpd.DataTokens["foo"]); Assert.Equal("quux", vpd.DataTokens["qux"]); } #endif #if ROUTE_FORMAT_HELPER [Fact] public void UrlWithEscapedOpenCloseBraces() { RouteFormatHelper("foo/{{p1}}", "foo/{p1}"); } [Fact] public void UrlWithEscapedOpenBraceAtTheEnd() { RouteFormatHelper("bar{{", "bar{"); } [Fact] public void UrlWithEscapedOpenBraceAtTheBeginning() { RouteFormatHelper("{{bar", "{bar"); } [Fact] public void UrlWithRepeatedEscapedOpenBrace() { RouteFormatHelper("foo{{{{bar", "foo{{bar"); } [Fact] public void UrlWithEscapedCloseBraceAtTheEnd() { RouteFormatHelper("bar}}", "bar}"); } [Fact] public void UrlWithEscapedCloseBraceAtTheBeginning() { RouteFormatHelper("}}bar", "}bar"); } [Fact] public void UrlWithRepeatedEscapedCloseBrace() { RouteFormatHelper("foo}}}}bar", "foo}}bar"); } private static void RouteFormatHelper(string routeUrl, string requestUrl) { var defaults = new RouteValueDictionary(new { route = "matched" }); var r = CreateRoute(routeUrl, defaults, null); GetRouteDataHelper(r, requestUrl, defaults); GetVirtualPathHelper(r, new RouteValueDictionary(), null, Uri.EscapeUriString(requestUrl)); } #endif #if CONSTRAINTS [Fact] public void GetVirtualPathWithNonParameterConstraintReturnsUrlWithoutQueryString() { // DevDiv Bugs 199612: UrlRouting: UrlGeneration should not append parameter to query string if it is a Constraint parameter and not a Url parameter RunTest( "{Controller}.mvc/{action}/{end}", null, new RouteValueDictionary(new { foo = CreateHttpMethodConstraint("GET") }), new RouteValueDictionary(), new RouteValueDictionary(new { controller = "Orders", action = "Index", end = "end", foo = "GET" }), "Orders.mvc/Index/end"); } [Fact] public void GetVirtualPathWithValidCustomConstraints() { // Arrange HttpContext context = GetHttpContext("/app", null, null); CustomConstraintTemplateRoute r = new CustomConstraintTemplateRoute("{controller}/{action}", null, new RouteValueDictionary(new { action = 5 })); var rd = CreateRouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "index"); var valuesDictionary = CreateRouteValueDictionary(); // Act var vpd = r.GetVirtualPath(context, valuesDictionary); // Assert Assert.NotNull(vpd); Assert.Equal<string>("home/index", vpd.VirtualPath); Assert.Equal(r, vpd.Route); Assert.NotNull(r.ConstraintData); Assert.Equal(5, r.ConstraintData.Constraint); Assert.Equal("action", r.ConstraintData.ParameterName); Assert.Equal("index", r.ConstraintData.ParameterValue); } [Fact] public void GetVirtualPathWithInvalidCustomConstraints() { // Arrange HttpContext context = GetHttpContext("/app", null, null); CustomConstraintTemplateRoute r = new CustomConstraintTemplateRoute("{controller}/{action}", null, new RouteValueDictionary(new { action = 5 })); var rd = CreateRouteData(); rd.Values.Add("controller", "home"); rd.Values.Add("action", "list"); var valuesDictionary = CreateRouteValueDictionary(); // Act var vpd = r.GetVirtualPath(context, valuesDictionary); // Assert Assert.Null(vpd); Assert.NotNull(r.ConstraintData); Assert.Equal(5, r.ConstraintData.Constraint); Assert.Equal("action", r.ConstraintData.ParameterName); Assert.Equal("list", r.ConstraintData.ParameterValue); } #endif private static void RunTest( string template, RouteValueDictionary defaults, RouteValueDictionary ambientValues, RouteValueDictionary values, string expected) { // Arrange var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults); // Act & Assert var result = binder.GetValues(ambientValues, values); if (result == null) { if (expected == null) { return; } else { Assert.NotNull(result); } } var boundTemplate = binder.BindValues(result.AcceptedValues); if (expected == null) { Assert.Null(boundTemplate); } else { Assert.NotNull(boundTemplate); // We want to chop off the query string and compare that using an unordered comparison var expectedParts = new PathAndQuery(expected); var actualParts = new PathAndQuery(boundTemplate); Assert.Equal(expectedParts.Path, actualParts.Path); if (expectedParts.Parameters == null) { Assert.Null(actualParts.Parameters); } else { Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count); foreach (var kvp in expectedParts.Parameters) { string value; Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value)); Assert.Equal(kvp.Value, value); } } } } private static void RunTest( string template, object defaults, object ambientValues, object values, string expected) { RunTest( template, new RouteValueDictionary(defaults), new RouteValueDictionary(ambientValues), new RouteValueDictionary(values), expected); } [Theory] [InlineData(null, null, true)] [InlineData("", null, true)] [InlineData(null, "", true)] [InlineData("blog", null, false)] [InlineData(null, "store", false)] [InlineData("Cool", "cool", true)] [InlineData("Co0l", "cool", false)] public void RoutePartsEqualTest(object left, object right, bool expected) { // Arrange & Act & Assert if (expected) { Assert.True(TemplateBinder.RoutePartsEqual(left, right)); } else { Assert.False(TemplateBinder.RoutePartsEqual(left, right)); } } [Fact] public void GetValues_SuccessfullyMatchesRouteValues_ForExplicitEmptyStringValue_AndNullDefault() { // Arrange var expected = "/Home/Index"; var template = "Home/Index"; var defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", area = (string)null }); var ambientValues = new RouteValueDictionary(new { controller = "Rail", action = "Schedule", area = "Travel" }); var explicitValues = new RouteValueDictionary(new { controller = "Home", action = "Index", area = "" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults); // Act1 var result = binder.GetValues(ambientValues, explicitValues); // Assert1 Assert.NotNull(result); // Act2 var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert2 Assert.NotNull(boundTemplate); Assert.Equal(expected, boundTemplate); } [Fact] public void GetValues_SuccessfullyMatchesRouteValues_ForExplicitNullValue_AndEmptyStringDefault() { // Arrange var expected = "/Home/Index"; var template = "Home/Index"; var defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", area = "" }); var ambientValues = new RouteValueDictionary(new { controller = "Rail", action = "Schedule", area = "Travel" }); var explicitValues = new RouteValueDictionary(new { controller = "Home", action = "Index", area = (string)null }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), TemplateParser.Parse(template), defaults); // Act1 var result = binder.GetValues(ambientValues, explicitValues); // Assert1 Assert.NotNull(result); // Act2 var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert2 Assert.NotNull(boundTemplate); Assert.Equal(expected, boundTemplate); } [Fact] public void BindValues_ParameterTransformer() { // Arrange var expected = "/ConventionalTransformerRoute/conventional-transformer/Param/my-value"; var template = "ConventionalTransformerRoute/conventional-transformer/Param/{param:length(500):slugify?}"; var defaults = new RouteValueDictionary(new { controller = "ConventionalTransformer", action = "Param" }); var ambientValues = new RouteValueDictionary(new { controller = "ConventionalTransformer", action = "Param" }); var explicitValues = new RouteValueDictionary(new { controller = "ConventionalTransformer", action = "Param", param = "MyValue" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), RoutePatternFactory.Parse( template, defaults, parameterPolicies: null, requiredValues: new { area = (string)null, action = "Param", controller = "ConventionalTransformer", page = (string)null }), defaults, requiredKeys: defaults.Keys, parameterPolicies: new (string, IParameterPolicy)[] { ("param", new LengthRouteConstraint(500)), ("param", new SlugifyParameterTransformer()), }); // Act var result = binder.GetValues(ambientValues, explicitValues); var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert Assert.Equal(expected, boundTemplate); } [Fact] public void BindValues_AmbientAndExplicitValuesDoNotMatch_Success() { // Arrange var expected = "/Travel/Flight"; var template = "{area}/{controller}/{action}"; var defaults = new RouteValueDictionary(new { action = "Index" }); var ambientValues = new RouteValueDictionary(new { area = "Travel", controller = "Rail", action = "Index" }); var explicitValues = new RouteValueDictionary(new { controller = "Flight", action = "Index" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), RoutePatternFactory.Parse( template, defaults, parameterPolicies: null, requiredValues: new { area = "Travel", action = "SomeAction", controller = "Flight", page = (string)null }), defaults, requiredKeys: new string[] { "area", "action", "controller", "page" }, parameterPolicies: null); // Act var result = binder.GetValues(ambientValues, explicitValues); var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert Assert.Equal(expected, boundTemplate); } [Fact] public void BindValues_LinkingFromPageToAController_Success() { // Arrange var expected = "/LG2/SomeAction"; var template = "{controller=Home}/{action=Index}/{id?}"; var defaults = new RouteValueDictionary(); var ambientValues = new RouteValueDictionary(new { page = "/LGAnotherPage", id = "17" }); var explicitValues = new RouteValueDictionary(new { controller = "LG2", action = "SomeAction" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), RoutePatternFactory.Parse( template, defaults, parameterPolicies: null, requiredValues: new { area = (string)null, action = "SomeAction", controller = "LG2", page = (string)null }), defaults, requiredKeys: new string[] { "area", "action", "controller", "page" }, parameterPolicies: null); // Act var result = binder.GetValues(ambientValues, explicitValues); var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert Assert.Equal(expected, boundTemplate); } // Regression test for dotnet/aspnetcore#4212 // // An ambient value should be used to satisfy a required value even if if we're discarding // ambient values. [Fact] public void BindValues_LinkingFromPageToAControllerInAreaWithAmbientArea_Success() { // Arrange var expected = "/Admin/LG2/SomeAction"; var template = "{area}/{controller=Home}/{action=Index}/{id?}"; var defaults = new RouteValueDictionary(); var ambientValues = new RouteValueDictionary(new { area = "Admin", page = "/LGAnotherPage", id = "17" }); var explicitValues = new RouteValueDictionary(new { controller = "LG2", action = "SomeAction" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), RoutePatternFactory.Parse( template, defaults, parameterPolicies: null, requiredValues: new { area = "Admin", action = "SomeAction", controller = "LG2", page = (string)null }), defaults, requiredKeys: new string[] { "area", "action", "controller", "page" }, parameterPolicies: null); // Act var result = binder.GetValues(ambientValues, explicitValues); var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert Assert.Equal(expected, boundTemplate); } [Fact] public void BindValues_HasUnmatchingAmbientValues_Discard() { // Arrange var expected = "/Admin/LG3/SomeAction?anothervalue=5"; var template = "Admin/LG3/SomeAction/{id?}"; var defaults = new RouteValueDictionary(new { controller = "LG3", action = "SomeAction", area = "Admin" }); var ambientValues = new RouteValueDictionary(new { controller = "LG1", action = "LinkToAnArea", id = "17" }); var explicitValues = new RouteValueDictionary(new { controller = "LG3", area = "Admin", action = "SomeAction", anothervalue = "5" }); var binder = new TemplateBinder( UrlEncoder.Default, new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()), RoutePatternFactory.Parse( template, defaults, parameterPolicies: null, requiredValues: new { area = "Admin", action = "SomeAction", controller = "LG3", page = (string)null }), defaults, requiredKeys: new string[] { "area", "action", "controller", "page" }, parameterPolicies: null); // Act var result = binder.GetValues(ambientValues, explicitValues); var boundTemplate = binder.BindValues(result.AcceptedValues); // Assert Assert.Equal(expected, boundTemplate); } private class PathAndQuery { public PathAndQuery(string uri) { var queryIndex = uri.IndexOf("?", StringComparison.Ordinal); if (queryIndex == -1) { Path = uri; } else { Path = uri.Substring(0, queryIndex); var query = uri.Substring(queryIndex + 1); Parameters = query .Split(new char[] { '&' }, StringSplitOptions.None) .Select(s => s.Split(new char[] { '=' }, StringSplitOptions.None)) .ToDictionary(pair => pair[0], pair => pair[1]); } } public string Path { get; private set; } public Dictionary<string, string> Parameters { get; private set; } } } }
39.410048
332
0.520422
3d6e9c7b04fcfeaaa705817a72f70d691bbfb434
7,871
cs
C#
Assets/TextMesh Pro/Editor/TMPro_CreateSpriteAssetMenu.cs
McDirty/Cup_Stacking
0917444176df6b17f47a549f1ef737a43f8c62a0
[ "MIT" ]
null
null
null
Assets/TextMesh Pro/Editor/TMPro_CreateSpriteAssetMenu.cs
McDirty/Cup_Stacking
0917444176df6b17f47a549f1ef737a43f8c62a0
[ "MIT" ]
null
null
null
Assets/TextMesh Pro/Editor/TMPro_CreateSpriteAssetMenu.cs
McDirty/Cup_Stacking
0917444176df6b17f47a549f1ef737a43f8c62a0
[ "MIT" ]
null
null
null
using UnityEngine; using UnityEditor; using System.Linq; using System.IO; using System.Collections; using System.Collections.Generic; namespace TMPro.EditorUtilities { public static class TMPro_CreateSpriteAssetMenu { [MenuItem("Assets/Create/TextMeshPro - Sprite Asset", false, 100)] public static void CreateTextMeshProObjectPerform() { Object target = Selection.activeObject; // Make sure the selection is a texture. if (target == null || target.GetType() != typeof(Texture2D)) return; Texture2D sourceTex = target as Texture2D; // Get the path to the selected texture. string filePathWithName = AssetDatabase.GetAssetPath(sourceTex); string fileNameWithExtension = Path.GetFileName(filePathWithName); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName); string filePath = filePathWithName.Replace(fileNameWithExtension, ""); // Check if Sprite Asset already exists SpriteAsset spriteAsset = AssetDatabase.LoadAssetAtPath(filePath + fileNameWithoutExtension + ".asset", typeof(SpriteAsset)) as SpriteAsset; bool isNewAsset = spriteAsset == null ? true : false; if (isNewAsset) { // Create new Sprite Asset using this texture spriteAsset = ScriptableObject.CreateInstance<SpriteAsset>(); AssetDatabase.CreateAsset(spriteAsset, filePath + fileNameWithoutExtension + ".asset"); // Assign new Sprite Sheet texture to the Sprite Asset. spriteAsset.spriteSheet = sourceTex; spriteAsset.spriteInfoList = GetSpriteInfo(sourceTex); //spriteAsset.UpdateSpriteArray(sourceTex); //spriteSheet.hideFlags = HideFlags.HideInHierarchy; //AssetDatabase.AddObjectToAsset(spriteSheet, spriteAsset); //spriteAsset.spriteSheetWidth = sourceTex.width; //spriteAsset.spriteSheetHeight = sourceTex.height; } else { spriteAsset.spriteInfoList = UpdateSpriteInfo(spriteAsset); } // Get the Sprites contained in the Sprite Sheet EditorUtility.SetDirty(spriteAsset); //spriteAsset.sprites = sprites; // Set source texture back to Not Readable. //texImporter.isReadable = false; AssetDatabase.SaveAssets(); //AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset)); // Re-import font asset to get the new updated version. //AssetDatabase.Refresh(); } private static List<SpriteInfo> GetSpriteInfo(Texture source) { //Debug.Log("Creating new Sprite Asset."); string filePath = UnityEditor.AssetDatabase.GetAssetPath(source); // Get all the Sprites sorted by Index Sprite[] sprites = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray(); List<SpriteInfo> spriteInfoList = new List<SpriteInfo>(); for (int i = 0; i < sprites.Length; i++) { SpriteInfo spriteInfo = new SpriteInfo(); Sprite sprite = sprites[i]; //spriteInfo.fileID = UnityEditor.Unsupported.GetLocalIdentifierInFile(sprite.GetInstanceID()); spriteInfo.id = i; spriteInfo.name = sprite.name; spriteInfo.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteInfo.name); Rect spriteRect = sprite.rect; spriteInfo.x = spriteRect.x; spriteInfo.y = spriteRect.y; spriteInfo.width = spriteRect.width; spriteInfo.height = spriteRect.height; // Compute Sprite pivot position Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2)); spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height); //spriteInfo.sprite = sprite; // Properties the can be modified spriteInfo.xAdvance = spriteRect.width; spriteInfo.scale = 1.0f; spriteInfo.xOffset = 0; spriteInfo.yOffset = 0; spriteInfoList.Add(spriteInfo); } return spriteInfoList; } // Update existing SpriteInfo private static List<SpriteInfo> UpdateSpriteInfo(SpriteAsset spriteAsset) { //Debug.Log("Updating Sprite Asset."); string filePath = UnityEditor.AssetDatabase.GetAssetPath(spriteAsset.spriteSheet); // Get all the Sprites sorted Left to Right / Top to Bottom Sprite[] sprites = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray(); for (int i = 0; i < sprites.Length; i++) { Sprite sprite = sprites[i]; // Check if sprite already exists in the SpriteInfoList int index = spriteAsset.spriteInfoList.FindIndex(item => item.name == sprite.name); //Debug.Log("") // Use existing SpriteInfo is it already exists SpriteInfo spriteInfo = index == -1 ? new SpriteInfo() : spriteAsset.spriteInfoList[index]; Rect spriteRect = sprite.rect; spriteInfo.name = sprite.name; spriteInfo.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteInfo.name); spriteInfo.x = spriteRect.x; spriteInfo.y = spriteRect.y; spriteInfo.width = spriteRect.width; spriteInfo.height = spriteRect.height; // Get Sprite Pivot Vector2 pivot = new Vector2(0 - (sprite.bounds.min.x) / (sprite.bounds.extents.x * 2), 0 - (sprite.bounds.min.y) / (sprite.bounds.extents.y * 2)); // The position of the pivot influences the Offset position. spriteInfo.pivot = new Vector2(0 - pivot.x * spriteRect.width, spriteRect.height - pivot.y * spriteRect.height); if (index == -1) { // Find the next available index for this Sprite int[] ids = spriteAsset.spriteInfoList.Select(item => item.id).ToArray(); int id = 0; for (int j = 0; j < ids.Length; j++ ) { if (ids[0] != 0) break; if (j > 0 && (ids[j] - ids[j - 1]) > 1) { id = ids[j - 1] + 1; break; } id = j + 1; } //spriteInfo.fileID = fileID; spriteInfo.id = id; spriteInfo.xAdvance = spriteRect.width; spriteInfo.scale = 1.0f; spriteInfo.xOffset = 0; spriteInfo.yOffset = 0; spriteAsset.spriteInfoList.Add(spriteInfo); } else { spriteAsset.spriteInfoList[index] = spriteInfo; } } return spriteAsset.spriteInfoList; } } }
38.965347
199
0.557108
3d7067c55cde612bc35ad341893cc66b87c526b3
14,376
cs
C#
FakeItEasy-3.2.0-patch/tests/FakeItEasy.Tests/NullGuardedAssertion.cs
DynamicsValue/365saturday
5a9984be5c14cddd981fe7d2b10a3f4f354014a3
[ "MIT" ]
10
2018-01-27T20:15:16.000Z
2019-07-11T22:04:23.000Z
FakeItEasy-3.2.0-patch/tests/FakeItEasy.Tests/NullGuardedAssertion.cs
DynamicsValue/365saturday
5a9984be5c14cddd981fe7d2b10a3f4f354014a3
[ "MIT" ]
1
2018-10-01T16:48:24.000Z
2018-10-02T07:57:11.000Z
FakeItEasy-3.2.0-patch/tests/FakeItEasy.Tests/NullGuardedAssertion.cs
DynamicsValue/365saturday
5a9984be5c14cddd981fe7d2b10a3f4f354014a3
[ "MIT" ]
7
2018-01-27T12:14:25.000Z
2020-09-13T14:41:55.000Z
namespace FakeItEasy.Tests { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FakeItEasy.Tests.TestHelpers; using FluentAssertions.Execution; public static class NullGuardedAssertion { public static NullGuardedConstraint Should(this Expression<Action> call) { return new NullGuardedConstraint(call); } /// <summary> /// Validates that calls are properly null guarded. /// </summary> public class NullGuardedConstraint { private readonly Expression<Action> call; private ConstraintState state; internal NullGuardedConstraint(Expression<Action> call) { Guard.AgainstNull(call, nameof(call)); this.call = call; } public void BeNullGuarded() { var matches = this.Matches(this.call); if (matches) { return; } var builder = new StringBuilderOutputWriter(); this.WriteDescriptionTo(builder); builder.WriteLine(); this.WriteActualValueTo(builder); var reason = builder.Builder.ToString(); Execute.Assertion.FailWith(reason); } private static ConstraintState CreateCall(Expression<Action> methodCall) { var methodExpression = methodCall.Body as MethodCallExpression; if (methodExpression != null) { return new MethodCallConstraintState(methodExpression); } return new ConstructorCallConstraintState((NewExpression)methodCall.Body); } private static object GetValueProducedByExpression(Expression expression) { if (expression == null) { return null; } var lambda = Expression.Lambda(expression); return lambda.Compile().DynamicInvoke(); } private void WriteDescriptionTo(StringBuilderOutputWriter builder) { builder.Write("Expected calls to "); this.state.WriteTo(builder); builder.Write(" to be null guarded."); } private void WriteActualValueTo(StringBuilderOutputWriter builder) { builder.Write( "When called with the following arguments the method did not throw the appropriate exception:"); builder.WriteLine(); this.state.WriteFailingCallsDescriptions(builder); } private bool Matches(Expression<Action> expression) { this.state = CreateCall(expression); return this.state.Matches(); } private abstract class ConstraintState { protected readonly IEnumerable<ArgumentInfo> ValidArguments; private IEnumerable<CallThatShouldThrow> unguardedCalls; protected ConstraintState(IEnumerable<ArgumentInfo> arguments) { this.ValidArguments = arguments; } protected abstract string CallDescription { get; } private IEnumerable<object> ArgumentValues { get { return this.ValidArguments.Select(x => x.Value); } } public bool Matches() { this.unguardedCalls = this.GetArgumentsForCallsThatAreNotProperlyNullGuarded(); return !this.unguardedCalls.Any(); } public void WriteTo(StringBuilderOutputWriter builder) { builder.Write(this.CallDescription); builder.Write("("); WriteArgumentList(builder, this.ValidArguments); builder.Write(")"); } public void WriteFailingCallsDescriptions(StringBuilderOutputWriter builder) { using (builder.Indent()) { foreach (var call in this.unguardedCalls) { call.WriteFailingCallDescription(builder); builder.WriteLine(); } } } protected static IEnumerable<ArgumentInfo> GetArgumentInfos(IEnumerable<Expression> callArgumentsValues, ParameterInfo[] callArguments) { var result = new List<ArgumentInfo>(); int index = 0; foreach (var argument in callArgumentsValues) { result.Add(new ArgumentInfo() { ArgumentType = callArguments[index].ParameterType, Name = callArguments[index].Name, Value = GetValueProducedByExpression(argument) }); index++; } return result; } protected abstract void PerformCall(object[] arguments); private static bool IsNullableType(Type type) { return !type.GetTypeInformation().IsValueType || (type.GetTypeInformation().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } private static void WriteArgumentList(StringBuilderOutputWriter builder, IEnumerable<ArgumentInfo> arguments) { int lengthWhenStarting = builder.Builder.Length; foreach (var argument in arguments) { if (builder.Builder.Length > lengthWhenStarting) { builder.Write(", "); } WriteArgument(builder, argument); } } private static void WriteArgument(StringBuilderOutputWriter builder, ArgumentInfo argument) { builder.Write("["); builder.Write(argument.ArgumentType.Name); builder.Write("]"); builder.Write(" "); builder.Write(argument.Name); } private IEnumerable<CallThatShouldThrow> GetArgumentsForCallsThatAreNotProperlyNullGuarded() { var result = new List<CallThatShouldThrow>(); foreach (var callThatShouldThrow in this.GetArgumentPermutationsThatShouldThrow()) { try { this.PerformCall(callThatShouldThrow.Arguments); result.Add(callThatShouldThrow); } catch (TargetInvocationException ex) { callThatShouldThrow.SetThrownException(ex.InnerException); var nullException = ex.InnerException as ArgumentNullException; if (nullException == null || !callThatShouldThrow.ArgumentName.Equals(nullException.ParamName)) { result.Add(callThatShouldThrow); } } } return result; } private IEnumerable<CallThatShouldThrow> GetArgumentPermutationsThatShouldThrow() { var result = new List<CallThatShouldThrow>(); int index = 0; foreach (var argument in this.ValidArguments) { if (argument.Value != null && IsNullableType(argument.ArgumentType)) { var permutation = new CallThatShouldThrow { ArgumentName = argument.Name, Arguments = this.ArgumentValues.Take(index) .Concat(default(object)) .Concat(this.ArgumentValues.Skip(index + 1)) .ToArray() }; result.Add(permutation); } index++; } return result; } protected struct ArgumentInfo { public string Name { get; set; } public Type ArgumentType { get; set; } public object Value { get; set; } } private class CallThatShouldThrow { private Exception thrown; public string ArgumentName { get; set; } public object[] Arguments { get; set; } public void SetThrownException(Exception value) { this.thrown = value; } public void WriteFailingCallDescription(StringBuilderOutputWriter builder) { builder.Write("("); this.WriteArgumentList(builder); builder.Write(") "); this.WriteFailReason(builder); } private void WriteArgumentList(StringBuilderOutputWriter builder) { int lengthWhenStarting = builder.Builder.Length; foreach (var argument in this.Arguments) { if (builder.Builder.Length > lengthWhenStarting) { builder.Write(", "); } builder.WriteArgumentValue(argument); } } private void WriteFailReason(StringBuilderOutputWriter description) { if (this.thrown == null) { description.Write("did not throw any exception."); } else { var argumentNullException = this.thrown as ArgumentNullException; if (argumentNullException != null) { description.Write( $@"threw ArgumentNullException with wrong argument name, it should be ""{this.ArgumentName}""."); } else { description.Write($"threw unexpected {this.thrown.GetType()}."); } } } } } private class MethodCallConstraintState : ConstraintState { private readonly object target; private readonly MethodInfo method; public MethodCallConstraintState(MethodCallExpression expression) : base(GetExpressionArguments(expression)) { this.method = expression.Method; this.target = NullGuardedConstraint.GetValueProducedByExpression(expression.Object); } #if FEATURE_NETCORE_REFLECTION protected override string CallDescription => this.method.DeclaringType.Name + "." + this.method.Name; #else protected override string CallDescription => this.method.ReflectedType.Name + "." + this.method.Name; #endif protected override void PerformCall(object[] arguments) { this.method.Invoke(this.target, arguments); } private static IEnumerable<ArgumentInfo> GetExpressionArguments(MethodCallExpression expression) { return ConstraintState.GetArgumentInfos(expression.Arguments, expression.Method.GetParameters()); } } private class ConstructorCallConstraintState : ConstraintState { private readonly ConstructorInfo constructorInfo; public ConstructorCallConstraintState(NewExpression expression) : base(GetArgumentInfos(expression)) { this.constructorInfo = expression.Constructor; } #if FEATURE_NETCORE_REFLECTION protected override string CallDescription => this.constructorInfo.DeclaringType.ToString() + ".ctor"; #else protected override string CallDescription => this.constructorInfo.ReflectedType.ToString() + ".ctor"; #endif protected override void PerformCall(object[] arguments) { this.constructorInfo.Invoke(arguments); } private static IEnumerable<ArgumentInfo> GetArgumentInfos(NewExpression expression) { return GetArgumentInfos(expression.Arguments, expression.Constructor.GetParameters()); } } } } }
39.278689
152
0.469254
3d712dcb5070662c30e175ec5cd1a1d29456f649
9,338
cs
C#
XenAdmin/Core/FormFontFixer.cs
wdxgy136/xenadmin-yeesan
47a6c1b199ac76e510e33821955b2c2685eb3653
[ "BSD-2-Clause" ]
null
null
null
XenAdmin/Core/FormFontFixer.cs
wdxgy136/xenadmin-yeesan
47a6c1b199ac76e510e33821955b2c2685eb3653
[ "BSD-2-Clause" ]
null
null
null
XenAdmin/Core/FormFontFixer.cs
wdxgy136/xenadmin-yeesan
47a6c1b199ac76e510e33821955b2c2685eb3653
[ "BSD-2-Clause" ]
1
2021-04-22T09:24:35.000Z
2021-04-22T09:24:35.000Z
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * * Based loosely upon code copyrighted as below. * */ /* * Copyright (c) 2008, TeX HeX (http://www.texhex.info/) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Xteq Systems (http://www.xteq.com/) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Original idea and code (3 lines :-) by Benjamin Hollis: http://brh.numbera.com/blog/index.php/2007/04/11/setting-the-correct-default-font-in-net-windows-forms-apps/ */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace XenAdmin.Core { public static class FormFontFixer { [AttributeUsage(AttributeTargets.Class)] public class PreserveFonts : Attribute { public bool Preserve; public PreserveFonts(bool preserve) { Preserve = preserve; } } //This list contains the fonts we want to replace. private static readonly List<string> FontReplaceList = new List<string>(new[] {"Microsoft Sans Serif", "Tahoma", "Verdana", "Segoe UI", "Meiryo", "Meiryo UI", "MS UI Gothic", "Arial", "\u5b8b\u4f53"}); /// <summary> /// May be null, implying that the fonts cannot be fixed. /// </summary> public static Font DefaultFont; static FormFontFixer() { //Basically the font name we want to use should be easy to choose by using the SystemFonts class. However, this class //is hard-coded (!!) and doesn't seem to work right. On XP, it will mostly return "Microsoft Sans Serif" except //for the DialogFont property (=Tahoma) but on Vista, this class will return "Tahoma" instead of "SegoeUI" for this property! //Therefore we will do the following: If we are running on a OS below XP, we will exit because the only font available //will be MS Sans Serif. On XP, we gonna use "Tahoma", and any other OS we will use the value of the MessageBoxFont //property because this seems to be set correctly on Vista an above. DefaultFont = Environment.OSVersion.Platform == PlatformID.Win32Windows || Environment.OSVersion.Version.Major < 5 ? null : // 95, 98, and NT can't be fixed. Environment.OSVersion.Version.Major < 6 ? SystemFonts.DialogFont : // 2K (5.0), XP (5.1), 2K3 and XP Pro (5.2), using Tahoma by default SystemFonts.MessageBoxFont; // Vista and above, using SegoeUI by default } public static void Fix(Form form) { if (DefaultFont == null) return; RegisterAndReplace(form); } private static void RegisterAndReplace(Control c) { if (ShouldPreserveFonts(c)) return; if (c is ToolStrip) { ToolStrip t = (ToolStrip)c; Register(t); Replace(t); foreach (ToolStripItem d in t.Items) Replace(d); } else { Register(c); Replace(c); foreach (Control d in c.Controls) RegisterAndReplace(d); } } private static bool ShouldPreserveFonts(Control c) { Type t = c.GetType(); object [] arr = t.GetCustomAttributes(typeof(PreserveFonts), true); return arr.Length > 0 && ((PreserveFonts)arr[0]).Preserve; } private static void Deregister(Control c) { c.ControlAdded -= c_ControlAdded; c.ControlRemoved -= c_ControlRemoved; foreach (Control d in c.Controls) Deregister(d); } private static void Deregister(ToolStrip c) { c.ItemAdded -= c_ItemAdded; } private static void Register(Control c) { if (!IsLeaf(c)) { c.ControlAdded -= c_ControlAdded; c.ControlAdded += c_ControlAdded; c.ControlRemoved -= c_ControlRemoved; c.ControlRemoved += c_ControlRemoved; } } private static void Register(ToolStrip c) { c.ItemAdded -= c_ItemAdded; c.ItemAdded += c_ItemAdded; } static void c_ControlAdded(object sender, ControlEventArgs e) { RegisterAndReplace(e.Control); } static void c_ControlRemoved(object sender, ControlEventArgs e) { Deregister(e.Control); } static void c_ItemAdded(object sender, ToolStripItemEventArgs e) { Replace(e.Item); } private static bool IsLeaf(Control c) { return c is Button || c is Label || c is TextBox || c is ComboBox || c is ListBox; } private static void Replace(Control c) { c.Font = ReplacedFont(c.Font); } private static void Replace(ToolStripItem c) { c.Font = ReplacedFont(c.Font); } private static Font ReplacedFont(Font f) { //only replace fonts that use one the "system fonts" we have declared if (FontReplaceList.IndexOf(f.Name) > -1) { //Now check the size, when the size is 9 or below it's the default font size and we do not keep the size since //SegoeUI has a complete different spacing (and thus size) than MS SansS or Tahoma. //Also check if there are any styles applied on the font (e.g. Italic) which we need to apply to the new //font as well. bool UseDefaultSize = f.Size >= 8 && f.Size <= 9; bool UseDefaultStyle = !f.Italic && !f.Strikeout && !f.Underline && !f.Bold; //if everything is set to defaults, we can use our prepared font right away if (UseDefaultSize && UseDefaultStyle) { return DefaultFont; } else { //There are non default properties set so //there is some work we need to do... return new Font(DefaultFont.FontFamily, UseDefaultSize ? DefaultFont.SizeInPoints : f.SizeInPoints, f.Style); } } else { return f; } } } }
38.270492
211
0.616942
3d735b768a4b379c3ae763f2df80d5f09cf30416
2,068
cs
C#
Exercise 3/ETagMiddleware.cs
skarum/microservices-in-netcore-exercises
48e3411b55cd2390cfa95ddd5217edcd4147ed72
[ "MIT" ]
1
2019-09-13T12:25:17.000Z
2019-09-13T12:25:17.000Z
Exercise 3/ETagMiddleware.cs
skarum/microservices-in-netcore-exercises
48e3411b55cd2390cfa95ddd5217edcd4147ed72
[ "MIT" ]
null
null
null
Exercise 3/ETagMiddleware.cs
skarum/microservices-in-netcore-exercises
48e3411b55cd2390cfa95ddd5217edcd4147ed72
[ "MIT" ]
1
2019-09-02T19:19:14.000Z
2019-09-02T19:19:14.000Z
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; using System.IO; using System.Security.Cryptography; using System.Threading.Tasks; namespace Exercise_4 { public class ETagMiddleware { private readonly RequestDelegate _next; public ETagMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var response = context.Response; var originalStream = response.Body; using (var ms = new MemoryStream()) { response.Body = ms; await _next(context); if (IsEtagSupported(response)) { string checksum = CalculateChecksum(ms); response.Headers[HeaderNames.ETag] = checksum; if (context.Request.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var etag) && checksum == etag) { response.StatusCode = StatusCodes.Status304NotModified; return; } } ms.Position = 0; await ms.CopyToAsync(originalStream); } } private static bool IsEtagSupported(HttpResponse response) { if (response.StatusCode != StatusCodes.Status200OK) return false; //if (response.Body.Length > 1024) // return false; if (response.Headers.ContainsKey(HeaderNames.ETag)) return false; return true; } private static string CalculateChecksum(MemoryStream ms) { string checksum = ""; using (var algo = SHA1.Create()) { ms.Position = 0; byte[] bytes = algo.ComputeHash(ms); checksum = WebEncoders.Base64UrlEncode(bytes); } return checksum; } } }
27.210526
119
0.529497
3d7389ca97a09a722610a7f65c57686bb8147e30
6,436
cs
C#
commercetools.Sdk/commercetools.Sdk.HttpApi/ApiExceptionFactory.cs
onepiecefreak3/commercetools-dotnet-core-sdk
c8ed9b476965a56827fd8e4421448826c4fe51c0
[ "Apache-2.0" ]
null
null
null
commercetools.Sdk/commercetools.Sdk.HttpApi/ApiExceptionFactory.cs
onepiecefreak3/commercetools-dotnet-core-sdk
c8ed9b476965a56827fd8e4421448826c4fe51c0
[ "Apache-2.0" ]
null
null
null
commercetools.Sdk/commercetools.Sdk.HttpApi/ApiExceptionFactory.cs
onepiecefreak3/commercetools-dotnet-core-sdk
c8ed9b476965a56827fd8e4421448826c4fe51c0
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using commercetools.Sdk.HttpApi.Domain.Exceptions; using commercetools.Sdk.HttpApi.Extensions; using commercetools.Sdk.Serialization; using Microsoft.AspNetCore.Http; namespace commercetools.Sdk.HttpApi { /// <summary> /// Responsible for Creating HTTP Exceptions based on the status code return from unsuccessful requests /// </summary> public class ApiExceptionFactory : IApiExceptionFactory { private readonly IClientConfiguration clientConfiguration; private readonly ISerializerService serializerService; private List<HttpResponseExceptionResponsibility> responsibilities; public ApiExceptionFactory(IClientConfiguration clientConfiguration, ISerializerService serializerService) { this.clientConfiguration = clientConfiguration; this.serializerService = serializerService; this.FillResponsibilities(); } /// <summary> /// Create API Exception based on status code /// </summary> /// <param name="request">The http Request</param> /// <param name="response">The http Response</param> /// <returns>General Api Exception or any exception inherit from it based on the status code</returns> public ApiException CreateApiException(HttpRequestMessage request, HttpResponseMessage response) { ApiException apiException = null; string content = response.ExtractResponseBody(); var responsibility = this.responsibilities.FirstOrDefault(r => r.Predicate(response)); if (responsibility?.ExceptionCreator != null) { apiException = responsibility.ExceptionCreator(response); } // set the common info for all exception types if (apiException != null) { apiException.Request = request; apiException.Response = response; apiException.ProjectKey = this.clientConfiguration.ProjectKey; if (!string.IsNullOrEmpty(content) && response.Content.Headers.ContentType.MediaType == "application/json") { var errorResponse = this.serializerService.Deserialize<HttpApiErrorResponse>(content); if (errorResponse.Errors != null) { apiException.ErrorResponse = errorResponse; } } } return apiException; } /// <summary> /// Fill responsibilities which factory will use to create the exception /// each responsibility contains predicate and func, so when the http response meet the criteria of the predicate, then we use delegate Func to create the exception /// </summary> private void FillResponsibilities() { this.responsibilities = new List<HttpResponseExceptionResponsibility>(); // Add responsibilities based on status code WhenStatus(403, response => new ForbiddenException()); WhenStatus(500, response => new InternalServerErrorException()); WhenStatus(502, response => new BadGatewayException()); WhenStatus(503, response => new ServiceUnavailableException()); WhenStatus(504, response => new GatewayTimeoutException()); WhenStatus(413, response => new RequestEntityTooLargeException()); WhenStatus(404, response => new NotFoundException()); WhenStatus(409, response => new ConcurrentModificationException()); WhenStatus(401, response => { var exception = response.ExtractResponseBody().Contains("invalid_token") ? new InvalidTokenException() : new UnauthorizedException(); return exception; }); WhenStatus(400, response => { if (response.ExtractResponseBody().Contains("invalid_scope")) { return new InvalidTokenException(); } else { return new ErrorResponseException(); } }); // Add the other responsibilities When(response => response.IsServiceNotAvailable(), response => new ServiceUnavailableException()); When(response => true, response => new ApiException()); } /// <summary> /// Add Responsibility when the Response meet the criteria of the predicate /// </summary> /// <param name="predicate">predicate which we check if the response message meet it's criteria</param> /// <param name="exceptionCreator">delegate function we use to create the right exception based on the status</param> private void When(Predicate<HttpResponseMessage> predicate, Func<HttpResponseMessage, ApiException> exceptionCreator) { this.AddResponsibility(predicate, exceptionCreator); } /// <summary> /// Add Responsibility when the Response status equal to the passed status /// </summary> /// <param name="status">response status code</param> /// <param name="exceptionCreator">delegate func to create the right exception</param> private void WhenStatus(int status, Func<HttpResponseMessage, ApiException> exceptionCreator) { this.AddResponsibility(response => (int)response.StatusCode == status, exceptionCreator); } /// <summary> /// Add Responsibility to responsibilities list /// </summary> /// <param name="predicate">predicate which we check if the response message meet it's criteria</param> /// <param name="exceptionCreator">delegate function we use to create the right exception based on the status</param> private void AddResponsibility(Predicate<HttpResponseMessage> predicate, Func<HttpResponseMessage, ApiException> exceptionCreator) { if (this.responsibilities == null) { return; } var responsibility = new HttpResponseExceptionResponsibility(predicate, exceptionCreator); this.responsibilities.Add(responsibility); } } }
45.323944
172
0.630827
3d73cfc519975d114d3a01411f2100937b515800
4,002
cs
C#
TameRoslyn/TameRoslynSyntaxGen/TameClassOrStructConstraintSyntax.cs
ToCSharp/TameRoslyn
7de3f5cb02a19b91e34138852be8113de434e4ba
[ "Apache-2.0" ]
6
2017-05-16T06:19:52.000Z
2021-06-04T02:20:14.000Z
TameRoslyn/TameRoslynSyntaxGen/TameClassOrStructConstraintSyntax.cs
ToCSharp/TameRoslyn
7de3f5cb02a19b91e34138852be8113de434e4ba
[ "Apache-2.0" ]
null
null
null
TameRoslyn/TameRoslynSyntaxGen/TameClassOrStructConstraintSyntax.cs
ToCSharp/TameRoslyn
7de3f5cb02a19b91e34138852be8113de434e4ba
[ "Apache-2.0" ]
2
2017-05-17T09:20:18.000Z
2021-05-06T08:26:16.000Z
// Copyright (c) Oleg Zudov. 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.Generic; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Zu.TameRoslyn.Syntax { public partial class TameClassOrStructConstraintSyntax : TameTypeParameterConstraintSyntax { public new static string TypeName = "ClassOrStructConstraintSyntax"; private SyntaxToken _classOrStructKeyword; private bool _classOrStructKeywordIsChanged; private string _classOrStructKeywordStr; public TameClassOrStructConstraintSyntax(string code) { Node = SyntaxFactoryStr.ParseClassOrStructConstraint(code); AddChildren(); } public TameClassOrStructConstraintSyntax(ClassOrStructConstraintSyntax node) { Node = node; AddChildren(); } public TameClassOrStructConstraintSyntax() { ClassOrStructKeywordStr = DefaultValues.ClassOrStructConstraintSyntaxClassOrStructKeywordStr; } public override string RoslynTypeName => TypeName; public SyntaxToken ClassOrStructKeyword { get { if (_classOrStructKeywordIsChanged) { _classOrStructKeyword = SyntaxFactoryStr.ParseSyntaxToken(ClassOrStructKeywordStr); _classOrStructKeywordIsChanged = false; } return _classOrStructKeyword; } set { if (_classOrStructKeyword != value) { _classOrStructKeyword = value; _classOrStructKeywordIsChanged = false; IsChanged = true; } } } public string ClassOrStructKeywordStr { get { if (_classOrStructKeywordIsChanged) return _classOrStructKeywordStr; return _classOrStructKeywordStr = _classOrStructKeyword.Text; } set { if (_classOrStructKeywordStr != value) { _classOrStructKeywordStr = value; IsChanged = true; _classOrStructKeywordIsChanged = true; } } } public override void Clear() { base.Clear(); } public new void AddChildren() { base.AddChildren(); Kind = Node.Kind(); _classOrStructKeyword = ((ClassOrStructConstraintSyntax) Node).ClassOrStructKeyword; _classOrStructKeywordIsChanged = false; } public override void SetNotChanged() { base.SetNotChanged(); IsChanged = false; } public SyntaxKind GetKind() { if (Kind != SyntaxKind.None) return Kind; if (ClassOrStructKeywordStr.Contains("class")) return SyntaxKind.ClassConstraint; if (ClassOrStructKeywordStr.Contains("struct")) return SyntaxKind.StructConstraint; throw new NotImplementedException(); } public override SyntaxNode MakeSyntaxNode() { var res = SyntaxFactory.ClassOrStructConstraint(GetKind(), ClassOrStructKeyword); IsChanged = false; return res; } public override IEnumerable<TameBaseRoslynNode> GetChildren() { yield break; } public override IEnumerable<TameBaseRoslynNode> GetTameFields() { yield break; } public override IEnumerable<(string filedName, string value)> GetStringFields() { yield return ("ClassOrStructKeywordStr", ClassOrStructKeywordStr); } } }
31.761905
158
0.589455
3d7444bcaf037715a11a69d2090304a49d807d57
19,379
cshtml
C#
Data/Views/Client/Index.cshtml
lurienanofab/data
e7cda0304b2b7d1fb30a7ca08447bb080430fff2
[ "MIT" ]
null
null
null
Data/Views/Client/Index.cshtml
lurienanofab/data
e7cda0304b2b7d1fb30a7ca08447bb080430fff2
[ "MIT" ]
null
null
null
Data/Views/Client/Index.cshtml
lurienanofab/data
e7cda0304b2b7d1fb30a7ca08447bb080430fff2
[ "MIT" ]
null
null
null
@using Data.Models.Admin; @model ClientModel @{ Layout = "~/Views/Shared/_LayoutBootstrap.cshtml"; ViewBag.Title = "Client"; } @section styles{ <style> .dataTables_wrapper { margin-top: 10px; } .dataTables_length label { font-weight: normal; white-space: nowrap; } .dataTables_length label select { display: inline; width: 70px; } .dataTables_filter label { width: 100%; font-weight: normal; text-align: right; } .dataTables_info { margin-top: 10px; } .dataTables_paginate { margin-top: 10px; } .dataTables_paginate ul { margin: 0; } </style> } <div class="container-fluid"> <div class="client" style="margin-bottom: 20px;"> <div class="page-header"> <h1>Configure Clients for <span style="color: #0033ff;">@Model.GetOrgName()</span></h1> </div> <form role="form"> <div class="row"> <div class="col-md-6"> <div class="form-group"> @Html.LabelFor(x => x.OrgID, "Organization", new { @class = "control-label" }) @Html.DropDownListFor(x => x.OrgID, Model.GetOrgSelectItems(), new { @class = "form-control org-select" }) <div class="org-error" style="color: #ff0000"></div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div style="border: solid 1px #ccc; border-radius: 4px; padding: 15px;"> <table class="table table-striped client-list" style="margin-bottom: 0;"> <thead> <tr> <th>Client Name</th> <th style="width: 90px;">&nbsp;</th> </tr> </thead> <tbody> @foreach (var c in Model.GetClients()) { <tr data-index="@c.PageIndex"> @if (c.ClientID > 0) { <td>@c.DisplayName</td> <td style="white-space: nowrap;"> <a href="@Url.Action("ClientEdit", new { ClientOrgID = c.ClientOrgID })" style="margin-right: 5px;"><img src="@Url.Content("~/Content/images/edit.png")" border="0" title="Edit @c.DisplayName" /></a> <a href="@Url.Action("ClientDelete", new { ClientOrgID = c.ClientOrgID })"><img src="@Url.Content("~/Content/images/delete.png")" border="0" title="Delete @c.DisplayName" /></a> @if (c.HasDryBox) { <img src="@Url.Content("~/Content/images/drybox.png")" border="0" title="DryBox reserved with account: @c.DryBoxAccount" style="margin-left: 5px;" /> } </td> } else { <td colspan="2">&nbsp;</td> } </tr> } @*@if (Model.GetClientListItems().Count() == 0) { <tr> <td colspan="2" style="font-style: italic; color: #606060;"> No active clients found </td> </tr> }*@ </tbody> <tfoot> <tr> <td colspan="2"> <div style="float: left;"> <button type="button" class="btn btn-xs btn-primary add-existing-client" style="width: 80px;">Add Existing</button> </div> <div style="float: right;"> <button type="button" class="btn btn-xs btn-primary add-new-client" style="width: 80px;" onclick="window.location = '@Url.Action("ClientEdit")'; return false;">Add New</button> </div> </td> </tr> </tfoot> </table> </div> </div> </div> </form> <div style="margin-top: 10px;"> <a href="@Url.Action("Index", "Home")">&larr; Return to Main Page</a> </div> </div> </div> @section scripts{ <script> $.fn.dataTableExt.oApi.fnExtStylePagingInfo = function (oSettings) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength) }; }; $.fn.dataTableExt.oPagination.bootstrap = { "fnInit": function (oSettings, nPaging, fnCallbackDraw) { var numPages = 3; //this is the number of page buttons to display between the back and forward buttons var oPaging = oSettings.oInstance.fnExtStylePagingInfo(); var node = $(nPaging); var list = $("<ul/>", { "class": "pagination" }); //previous list.append($("<li/>", { "class": "paginate_button previous" }).append($("<a/>", { "href": "#", "title": "Previous" }).html("&larr;").on("click", function (e) { e.preventDefault(); oSettings.oApi._fnPageChange(oSettings, "previous"); fnCallbackDraw(oSettings); }))); //first page list.append($("<li/>", { "class": "paginate_button first" }).append($("<a/>", { "href": "#", "title": "First" }).html("1").on("click", function (e) { e.preventDefault(); oSettings.oApi._fnPageChange(oSettings, "first"); fnCallbackDraw(oSettings); }))); //back list.append($("<li/>", { "class": "paginate_button back" }).append($("<a/>", { "href": "#", "title": "Back" }).html("...").on("click", function (e) { e.preventDefault(); }))); //pages for (var x = 0; x < numPages; x++) { list.append($("<li/>", { "class": "paginate_button page" }).append($("<a/>", { "href": "#", "data-index": x + 1 }).html(x + 2).on("click", function (e) { e.preventDefault(); oSettings.oApi._fnPageChange(oSettings, $(this).data("index")); fnCallbackDraw(oSettings); }))); } //forward list.append($("<li/>", { "class": "paginate_button forward" }).append($("<a/>", { "href": "#", "title": "Forward" }).html("...").on("click", function (e) { e.preventDefault(); }))); //last page list.append($("<li/>", { "class": "paginate_button last" }).append($("<a/>", { "href": "#", "title": "Last" }).html(oPaging.iTotalPages).on("click", function (e) { e.preventDefault(); oSettings.oApi._fnPageChange(oSettings, "last"); fnCallbackDraw(oSettings); }))); //next list.append($("<li/>", { "class": "paginate_button next" }).append($("<a/>", { "href": "#", "title": "Next" }).html("&rarr;").on("click", function (e) { e.preventDefault(); oSettings.oApi._fnPageChange(oSettings, "next"); fnCallbackDraw(oSettings); }))); node.append(list); node.append($("<div/>", { "class": "now-showing" }).css({ "color": "#808080", "font-style": "italic" })); }, "fnUpdate": function (oSettings, fnCallbackDraw) { var numPages = 3; //the number of page buttons to display between the back and forward buttons var oPaging = oSettings.oInstance.fnExtStylePagingInfo(); var an = oSettings.aanFeatures.p; if ($.isArray(an)) { $.each(an, function (index, item) { var node = $(item); var list = $("ul.pagination", node); if (oPaging.iTotalPages > 1) { //display the last button and change it's text to current iTotalPages $("li.last", list).show().find("a").html(oPaging.iTotalPages); //we want to show the first and last buttons and pageNum additional buttons, if there are pageNum additional pages //or fewer then we don't need to show the forward button. If there are less than pageNum additional pages than we //need to hide the appropriate number of page buttons. var pageCount = oPaging.iTotalPages - 2 //the # of pages not including first and last //console.log({ pageCount: pageCount, numPages: numPages, iPage: oPaging.iPage }); //everything must be based on iPage which is the current page index if (oPaging.iPage <= numPages) $("li.back", list).hide(); else $("li.back", list).show(); if (oPaging.iPage >= oPaging.iTotalPages - numPages + 1) $("li.forward", list).hide(); else $("li.forward", list).show(); //check to see if we should hide any page buttons if (pageCount <= numPages) { for (var x = 0; x < numPages; x++) { if (x < pageCount) $("li.page", list).eq(x).show(); else $("li.page", list).eq(x).hide(); } } else $("li.page", list).show(); //show them all //re-number the page buttons //need some special case handling when iPage is the first or last if (oPaging.iPage == 0) { } else if (oPaging.iPage == oPaging.iTotalPages - 1) { } else { var m = oPaging.iPage % (numPages + 1); var startIndex = oPaging.iPage - m + 1; var pages = []; for (var x = 0; x < numPages; x++) pages.push(startIndex + x); console.log({ "m": m, "iPage": oPaging.iPage, "pages": pages.join(',') }); } var m = oPaging.iPage % numPages; //console.log({ 'iPage': oPaging.iPage, 'm': m }); var startIndex = oPaging.iPage - m + 1; //for (var x = 0; x < numPages; x++) { // var num = 0; // if (m == 0) { // num = oPaging.iPage + x + 2; // } // //if (oPaging.iPage < numPages) { // // console.log('a'); // // num = oPaging.iPage + x + 2 - m; // //} else { // // console.log('b'); // // if (m == 0) // // num = oPaging.iPage + x - 1 + m; // // else // // num = oPaging.iPage + x + m; // //} // console.log(num); // $("li.page", list).eq(x).find("a").html(num); //} //if (pageCount <= numPages) { // $("li.back", list).hide(); // $("li.forward", list).hide(); // //check to see if we should hide any page buttons // for (var x = 0; x < numPages; x++) { // if (x < pageCount) // $("li.page", list).eq(x).show(); // else // $("li.page", list).eq(x).hide(); // } //} //else { // //pageCount is greater than numPages, so we should show the forward button unless we are close to the last page // //and also make sure all the page buttons are visible // if (oPaging.iPage < oPaging.iTotalPages - numPages) // $("li.forward", list).show(); // else // $("li.forward", list).hide(); // $("li.page", list).show(); // if (oPaging.iPage > pageCount) // $("li.back", list).show(); // else // $("li.back", list).hide(); //} } else { $("li.back", list).hide(); $("li.forward", list).hide(); $("li.page", list).hide(); $("li.last", list).hide(); } $("div.now-showing", node).html("page " + (oPaging.iPage + 1) + "/" + oPaging.iTotalPages); }) } } } $(".client").each(function () { var $self = $(this); var index = 0; var selectGroup = function (index) { $(".client-list tbody tr", $self).hide(); $(".client-list tbody tr[data-index='" + index + "']", $self).show(); } $(".client-list", $self).dataTable({ "pagingType": "bootstrap", "columns": [null, { "sortable": false, "width": "100px" }], "language": { "search": "", "emptyTable": '<span style="color: #808080; font-style: italic;">No active clients were found</span>' }, "dom": "<'row'<'col-xs-7'l><'col-xs-5'f>><'row'<'col-md-12't>><'row'<'col-md-12'i>><'row'<'col-md-12'p>>", "lengthMenu": [[2, 3, 4, 5, 10, 25, 50, 100, -1], [2, 3, 4, 5, 10, 25, 50, 100, "All"]], "initComplete": function () { $(".dataTables_length select", $self).addClass("form-control"); $(".dataTables_filter label", $self).css({ "font-weight": "normal", "width": "100%", "text-align": "right" }); $(".dataTables_filter label [type='search']", $self).addClass("form-control").attr("placeholder", "Search").css({ "width": "100%" }); } }); $self.on("change", ".org-select", function (e) { var select = $(this); var id = select.val(); var err = false; $.ajax({ "url": "@Url.Content("~/client/session")", "type": "POST", "data": { "OrgID": id, "Command": "SetOrgID" }, "error": function (jqXHR, textStatus, errorThrown) { err = true; var response = $(jqXHR.responseText) var message = ""; $.each(response, function (index, value) { if (value.localName == "title") { message = $(value).text(); return false; } }); $(".org-error", $self).html($("<div/>").css("margin-top", "5px").html(message)); }, "complete": function (jqXHR, textStatus) { if (!err) window.location.reload(); } }); }).on("change", ".paging-select", function (e) { index = $(this).val(); selectGroup(index); }).on("click", ".pager .previous", function (e) { e.preventDefault(); index--; if (index < 0) index = $(".paging-select option").length - 1; $(".paging-select", $self).val(index); selectGroup(index); }).on("click", ".pager .next", function (e) { e.preventDefault(); index++; if (index >= $(".paging-select option").length) index = 0; $(".paging-select", $self).val(index); selectGroup(index); }); if ($(".paging-select option", $self).length > 0) selectGroup(index); else $(".paging", $self).hide(); }); </script> }
46.361244
246
0.375045
3d75361433273f6a36695cc8ebdecaec180f267d
4,915
cs
C#
FluentAvalonia/UI/Controls/CommandBar/CommandBarButton.cs
timunie/FluentAvalonia
fcfc26f20fc2826c68102e67e0149d052591ce3f
[ "MIT" ]
null
null
null
FluentAvalonia/UI/Controls/CommandBar/CommandBarButton.cs
timunie/FluentAvalonia
fcfc26f20fc2826c68102e67e0149d052591ce3f
[ "MIT" ]
null
null
null
FluentAvalonia/UI/Controls/CommandBar/CommandBarButton.cs
timunie/FluentAvalonia
fcfc26f20fc2826c68102e67e0149d052591ce3f
[ "MIT" ]
null
null
null
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.LogicalTree; using Avalonia.Styling; using FluentAvalonia.UI.Input; using System; namespace FluentAvalonia.UI.Controls { public class CommandBarButton : Button, ICommandBarElement, IStyleable { Type IStyleable.StyleKey => typeof(CommandBarButton); public static readonly DirectProperty<CommandBarButton, bool> IsInOverflowProperty = AvaloniaProperty.RegisterDirect<CommandBarButton, bool>(nameof(IsInOverflow), x => x.IsInOverflow); public static readonly StyledProperty<IconElement> IconProperty = AvaloniaProperty.Register<CommandBarButton, IconElement>(nameof(Icon)); public static readonly StyledProperty<string> LabelProperty = AvaloniaProperty.Register<CommandBarButton, string>(nameof(Label)); public static readonly DirectProperty<CommandBarButton, int> DynamicOverflowOrderProperty = AvaloniaProperty.RegisterDirect<CommandBarButton, int>(nameof(DynamicOverflowOrder), x => x.DynamicOverflowOrder, (x, v) => x.DynamicOverflowOrder = v); public static readonly StyledProperty<CornerRadius> CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner<CommandBarButton>(); public static readonly StyledProperty<bool> IsCompactProperty = AvaloniaProperty.Register<CommandBarButton, bool>(nameof(IsCompact)); public bool IsCompact { get => GetValue(IsCompactProperty); set => SetValue(IsCompactProperty, value); } public bool IsInOverflow { get => _isInOverflow; internal set { if (SetAndRaise(IsInOverflowProperty, ref _isInOverflow, value)) { PseudoClasses.Set(":overflow", value); } } } public IconElement Icon { get => GetValue(IconProperty); set => SetValue(IconProperty, value); } public string Label { get => GetValue(LabelProperty); set => SetValue(LabelProperty, value); } public int DynamicOverflowOrder { get => _dynamicOverflowOrder; set => SetAndRaise(DynamicOverflowOrderProperty, ref _dynamicOverflowOrder, value); } public CornerRadius CornerRadius { get => GetValue(CornerRadiusProperty); set => SetValue(CornerRadiusProperty, value); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == IconProperty) { PseudoClasses.Set(":icon", change.NewValue.GetValueOrDefault() != null); } else if (change.Property == LabelProperty) { PseudoClasses.Set(":label", change.NewValue.GetValueOrDefault() != null); } else if (change.Property == FlyoutProperty) { if (change.OldValue.GetValueOrDefault() is FlyoutBase oldFB) { oldFB.Closed -= OnFlyoutClosed; oldFB.Opened -= OnFlyoutOpened; } if (change.NewValue.GetValueOrDefault() is FlyoutBase newFB) { newFB.Closed += OnFlyoutClosed; newFB.Opened += OnFlyoutOpened; PseudoClasses.Set(":flyout", true); PseudoClasses.Set(":submenuopen", newFB.IsOpen); } else { PseudoClasses.Set(":flyout", false); PseudoClasses.Set(":submenuopen", false); } } else if (change.Property == HotKeyProperty) { PseudoClasses.Set(":hotkey", change.NewValue.GetValueOrDefault() != null); } else if (change.Property == IsCompactProperty) { PseudoClasses.Set(":compact", change.NewValue.GetValueOrDefault<bool>()); } else if (change.Property == CommandProperty) { if (change.OldValue.GetValueOrDefault() is XamlUICommand xamlComOld) { if (Label == xamlComOld.Label) { Label = null; } if (Icon is IconSourceElement ise && ise.IconSource == xamlComOld.IconSource) { Icon = null; } if (HotKey == xamlComOld.HotKey) { HotKey = null; } if (ToolTip.GetTip(this).ToString() == xamlComOld.Description) { ToolTip.SetTip(this, null); } } if (change.NewValue.GetValueOrDefault() is XamlUICommand xamlCom) { if (string.IsNullOrEmpty(Label)) { Label = xamlCom.Label; } if (Icon == null) { Icon = new IconSourceElement { IconSource = xamlCom.IconSource }; } if (HotKey == null) { HotKey = xamlCom.HotKey; } if (ToolTip.GetTip(this) == null) { ToolTip.SetTip(this, xamlCom.Description); } } } } protected override void OnClick() { base.OnClick(); if (IsInOverflow) { var cb = this.FindLogicalAncestorOfType<CommandBar>(); if (cb != null) { cb.IsOpen = false; } } } private void OnFlyoutOpened(object sender, EventArgs e) { PseudoClasses.Set(":submenuopen", true); } private void OnFlyoutClosed(object sender, EventArgs e) { PseudoClasses.Set(":submenuopen", false); } private bool _isInOverflow; private int _dynamicOverflowOrder; } }
25.335052
93
0.686267
3d759523b426b602d90ef42ca63e7249f9b3e3bb
14,860
cs
C#
h3net/Code/GeoCoord.cs
RichardVasquez/h3netOld
8aa2abb2152eea1d8f9773480498531566433e75
[ "Apache-2.0" ]
null
null
null
h3net/Code/GeoCoord.cs
RichardVasquez/h3netOld
8aa2abb2152eea1d8f9773480498531566433e75
[ "Apache-2.0" ]
null
null
null
h3net/Code/GeoCoord.cs
RichardVasquez/h3netOld
8aa2abb2152eea1d8f9773480498531566433e75
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018, Richard Vasquez * * 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. * * Original version written in C, Copyright 2016-2017 Uber Technologies, Inc. * C version licensed under the Apache License, Version 2.0 (the "License"); * C Source code available at: https://github.com/uber/h3 * */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace H3Net.Code { /// <summary> /// Functions for working with lat/lon coordinates. /// </summary> /// <!-- Based off 3.1.1 --> [DebuggerDisplay("Lat: {lat} Lon: {lon}")] public class GeoCoord { public double lat; public double lon; public GeoCoord(double _lat, double _lon) { lat = _lat; lon = _lon; } public GeoCoord() { } /// <summary> /// Normalizes radians to a value between 0.0 and two PI. /// </summary> /// <param name="rads">The input radans value</param> /// <returns>The normalized radians value</returns> /// <!-- Based off 3.1.1 --> public static double _posAngleRads(double rads) { var tmp = rads < 0.0 ? rads + Constants.M_2PI : rads; if (rads >= Constants.M_2PI) { tmp -= Constants.M_2PI; } return tmp; } /// <summary> /// Determines if the components of two spherical coordinates are within some /// threshold distance of each other. /// </summary> /// <param name="p1">The first spherical coordinates</param> /// <param name="p2">The second spherical coordinates</param> /// <param name="threshold">The threshold distance</param> /// <returns> /// Whether or not the two coordinates are within the threshold distance /// of each other /// </returns> /// <!-- Based off 3.1.1 --> public static bool geoAlmostEqualThreshold(GeoCoord p1, GeoCoord p2, double threshold) { return Math.Abs(p1.lat - p2.lat) < threshold && Math.Abs(p1.lon - p2.lon) < threshold; } /// <summary> /// Determines if the components of two spherical coordinates are within our /// standard epsilon distance of each other. /// </summary> /// <param name="p1">The first spherical coordinates.</param> /// <param name="p2">The second spherical coordinates.</param> /// <returns> /// Whether or not the two coordinates are within the epsilon distance /// of each other. /// </returns> /// <!-- Based off 3.1.1 --> public static bool geoAlmostEqual(GeoCoord v1, GeoCoord v2) { return geoAlmostEqualThreshold(v1, v2, Constants.EPSILON_RAD); } /// <summary> /// Set the components of spherical coordinates in decimal degrees. /// </summary> /// <param name="p">The spherical coordinates</param> /// <param name="latDegs">The desired latitude in decimal degrees</param> /// <param name="lonDegs">The desired longitude in decimal degrees</param> /// <!-- Based off 3.1.1 --> public static void setGeoDegs(ref GeoCoord p, double latDegs, double lonDegs) { _setGeoRads(ref p, degsToRads(latDegs), degsToRads(lonDegs)); } /// <summary> /// Set the components of spherical coordinates in radians. /// </summary> /// <param name="p">The spherical coordinates</param> /// <param name="latDegs">The desired latitude in decimal radians</param> /// <param name="lonDegs">The desired longitude in decimal radians</param> /// <!-- Based off 3.1.1 --> public static void _setGeoRads(ref GeoCoord p, double latRads, double lonRads) { p.lat = latRads; p.lon = lonRads; } /// <summary> /// Convert from decimal degrees to radians. /// </summary> /// <param name="degrees">The decimal degrees</param> /// <returns>The corresponding radians</returns> /// <!-- Based off 3.1.1 --> public static double degsToRads(double degrees) { return degrees * Constants.M_PI_180; } /// <summary> /// Convert fro radians to decimal degrees. /// </summary> /// <param name="radians">The radians</param> /// <returns>The corresponding decimal degrees</returns> /// <!-- Based off 3.1.1 --> public static double radsToDegs(double radians) { return radians * Constants.M_180_PI; } /// <summary> /// Makes sure latitudes are in the proper bounds /// </summary> /// <param name="lat">The original lat value</param> /// <returns>The corrected lat value</returns> /// <!-- Based off 3.1.1 --> public static double constrainLat(double lat) { while (lat > Constants.M_PI_2) { lat -= Constants.M_PI; } return lat; } /// <summary> /// Makes sure longitudes are in the proper bounds /// </summary> /// <param name="lng">The origin lng value</param> /// <returns>The corrected lng value</returns> /// <!-- Based off 3.1.1 --> public static double constrainLng(double lng) { while (lng > Constants.M_PI) { lng = lng - (2 * Constants.M_PI); } while (lng < -Constants.M_PI) { lng = lng + (2 * Constants.M_PI); } return lng; } /// <summary> /// Find the great circle distance in radians between two spherical coordinates. /// </summary> /// <param name="p1">The first spherical coordinates</param> /// <param name="p2">The second spherical coordinates</param> /// <returns>The great circle distance between p1 and p2</returns> /// <!-- Based off 3.1.1 --> public static double _geoDistRads(GeoCoord p1, GeoCoord p2) { // use spherical triangle with p1 at A, p2 at B, and north pole at C double bigC = Math.Abs(p2.lon - p1.lon); if (bigC > Constants.M_PI) // assume we want the complement { // note that in this case they can't both be negative double lon1 = p1.lon; if (lon1 < 0.0) lon1 += 2.0 * Constants.M_PI; double lon2 = p2.lon; if (lon2 < 0.0) lon2 += 2.0 * Constants.M_PI; bigC = Math.Abs(lon2 - lon1); } double b = Constants.M_PI_2 - p1.lat; double a = Constants.M_PI_2 - p2.lat; // use law of cosines to find c double cosc = Math.Cos(a) * Math.Cos(b) + Math.Sin(a) * Math.Sin(b) * Math.Cos(bigC); if (cosc > 1.0) { cosc = 1.0; } if (cosc < -1.0) { cosc = -1.0; } return Math.Acos(cosc); } /// <summary> /// Find the great circle distance in kilometers between two spherical /// coordinates /// </summary> /// <param name="p1">The first spherical coordinates</param> /// <param name="p2">The distance in kilometers between p1 and p2</param> /// <!-- Based off 3.1.1 --> public static double _geoDistKm(GeoCoord p1, IEnumerable<GeoCoord> p2) { return Constants.EARTH_RADIUS_KM * _geoDistRads(p1, p2.First( )); } /// <summary> /// Determines the azimuth to p2 from p1 in radians /// </summary> /// <param name="p1">The first spherical coordinates</param> /// <param name="p2">The second spherical coordinates</param> /// <returns>The azimuth in radians from p1 to p2</returns> /// <!-- Based off 3.1.1 --> public static double _geoAzimuthRads(GeoCoord p1, GeoCoord p2) { return Math.Atan2 ( Math.Cos(p2.lat) * Math.Sin(p2.lon - p1.lon), Math.Cos(p1.lat) * Math.Sin(p2.lat) - Math.Sin(p1.lat) * Math.Cos(p2.lat) * Math.Cos(p2.lon - p1.lon) ); } /// <summary> /// Computes the point on the sphere a specified azimuth and distance from /// another point. /// </summary> /// <param name="p1">The first spherical coordinates.</param> /// <param name="az">The desired azimuth from p1.</param> /// <param name="distance">The desired distance from p1, must be non-negative.</param> /// <param name="p2"> /// The spherical coordinates at the desired azimuth and distance from p1. /// </param> /// <!-- Based off 3.1.1 --> public static void _geoAzDistanceRads(ref GeoCoord p1, double az, double distance, ref GeoCoord p2) { if (distance < Constants.EPSILON) { p2 = p1; return; } double sinlat, sinlon, coslon; az = _posAngleRads(az); // check for due north/south azimuth if (az < Constants.EPSILON || Math.Abs(az - Constants.M_PI) <Constants. EPSILON) { if (az < Constants.EPSILON) // due north p2.lat = p1.lat + distance; else // due south p2.lat = p1.lat - distance; if (Math.Abs(p2.lat - Constants.M_PI_2) < Constants.EPSILON) // north pole { p2.lat = Constants.M_PI_2; p2.lon = 0.0; } else if (Math.Abs(p2.lat + Constants.M_PI_2) < Constants.EPSILON) // south pole { p2.lat = -Constants.M_PI_2; p2.lon = 0.0; } else p2.lon = constrainLng(p1.lon); } else // not due north or south { sinlat = Math.Sin(p1.lat) * Math.Cos(distance) + Math.Cos(p1.lat) * Math.Sin(distance) * Math.Cos(az); if (sinlat > 1.0) sinlat = 1.0; if (sinlat < -1.0) sinlat = -1.0; p2.lat =Math.Asin(sinlat); if (Math.Abs(p2.lat - Constants.M_PI_2) < Constants.EPSILON) // north pole { p2.lat = Constants.M_PI_2; p2.lon = 0.0; } else if (Math.Abs(p2.lat + Constants.M_PI_2) < Constants.EPSILON) // south pole { p2.lat = -Constants.M_PI_2; p2.lon = 0.0; } else { sinlon = Math.Sin(az) * Math.Sin(distance) / Math.Cos(p2.lat); coslon = (Math.Cos(distance) - Math.Sin(p1.lat) * Math.Sin(p2.lat)) / Math.Cos(p1.lat) / Math.Cos(p2.lat); if (sinlon > 1.0) {sinlon = 1.0;} if (sinlon < -1.0) {sinlon = -1.0;} if (coslon > 1.0) {sinlon = 1.0;} if (coslon < -1.0) {sinlon = -1.0;} p2.lon = constrainLng(p1.lon + Math.Atan2(sinlon, coslon)); } } } /* * The following functions provide meta information about the H3 hexagons at * each zoom level. Since there are only 16 total levels, these are current * handled with hardwired static values, but it may be worthwhile to put these * static values into another file that can be autogenerated by source code in * the future. */ public static double hexAreaKm2(int res) { double[] areas = { 4250546.848, 607220.9782, 86745.85403, 12392.26486, 1770.323552, 252.9033645, 36.1290521, 5.1612932, 0.7373276, 0.1053325, 0.0150475, 0.0021496, 0.0003071, 0.0000439, 0.0000063, 0.0000009}; return areas[res]; } public static double hexAreaM2(int res) { double[] areas = { 4.25055E+12, 6.07221E+11, 86745854035, 12392264862, 1770323552, 252903364.5, 36129052.1, 5161293.2, 737327.6, 105332.5, 15047.5, 2149.6, 307.1, 43.9, 6.3, 0.9}; return areas[res]; } public static double edgeLengthKm(int res) { double[] lens = { 1107.712591, 418.6760055, 158.2446558, 59.81085794, 22.6063794, 8.544408276, 3.229482772, 1.220629759, 0.461354684, 0.174375668, 0.065907807, 0.024910561, 0.009415526, 0.003559893, 0.001348575, 0.000509713 }; return lens[res]; } public static double edgeLengthM(int res) { double[] lens = { 1107712.591, 418676.0055, 158244.6558, 59810.85794, 22606.3794, 8544.408276, 3229.482772, 1220.629759, 461.3546837, 174.3756681, 65.90780749, 24.9105614, 9.415526211, 3.559893033, 1.348574562, 0.509713273 }; return lens[res]; } /// <summary> /// Number of unique valid H3Indexes at given resolution. /// </summary> /// <!-- Based off 3.1.1 --> public static long numHexagons(int res) { long[] nums = { 122L, 842L, 5882L, 41162L, 288122L, 2016842L, 14117882L, 98825162L, 691776122L, 4842432842L, 33897029882L, 237279209162L, 1660954464122L, 11626681248842L, 81386768741882L, 569707381193162L }; return nums[res]; } } }
37.057357
107
0.514805
3d75dcc2cc5b28aea1802bd686fad596cd42b8be
10,825
cs
C#
emulator/Bizhawk/BizHawk-master/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs
CognitiaAI/StreetFighterRL
2b902ee7bb502336e1ba3f74ebeb09d843a75e73
[ "MIT" ]
1
2022-02-02T21:33:37.000Z
2022-02-02T21:33:37.000Z
emulator/Bizhawk/BizHawk-master/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs
CognitiaAI/StreetFighterRL
2b902ee7bb502336e1ba3f74ebeb09d843a75e73
[ "MIT" ]
null
null
null
emulator/Bizhawk/BizHawk-master/BizHawk.Emulation.Cores/Consoles/PC Engine/PCEngine.cs
CognitiaAI/StreetFighterRL
2b902ee7bb502336e1ba3f74ebeb09d843a75e73
[ "MIT" ]
1
2022-02-02T18:30:49.000Z
2022-02-02T18:30:49.000Z
using System; using System.Collections.Generic; using BizHawk.Common.BufferExtensions; using BizHawk.Emulation.Common; using BizHawk.Emulation.Cores.Components; using BizHawk.Emulation.Cores.Components.H6280; using BizHawk.Emulation.DiscSystem; namespace BizHawk.Emulation.Cores.PCEngine { public enum NecSystemType { TurboGrafx, TurboCD, SuperGrafx } [Core( "PCEHawk", "Vecna", isPorted: false, isReleased: true)] public sealed partial class PCEngine : IEmulator, ISaveRam, IStatable, IInputPollable, IDebuggable, ISettable<PCEngine.PCESettings, PCEngine.PCESyncSettings>, IDriveLight, ICodeDataLogger { [CoreConstructor("PCE", "SGX")] public PCEngine(CoreComm comm, GameInfo game, byte[] rom, object settings, object syncSettings) { MemoryCallbacks = new MemoryCallbackSystem(); CoreComm = comm; switch (game.System) { default: case "PCE": SystemId = "PCE"; Type = NecSystemType.TurboGrafx; break; case "SGX": SystemId = "SGX"; Type = NecSystemType.SuperGrafx; break; } Settings = (PCESettings)settings ?? new PCESettings(); _syncSettings = (PCESyncSettings)syncSettings ?? new PCESyncSettings(); Init(game, rom); _controllerDeck = new PceControllerDeck( _syncSettings.Port1, _syncSettings.Port2, _syncSettings.Port3, _syncSettings.Port4, _syncSettings.Port5); } public PCEngine(CoreComm comm, GameInfo game, Disc disc, object Settings, object syncSettings) { CoreComm = comm; MemoryCallbacks = new MemoryCallbackSystem(); DriveLightEnabled = true; SystemId = "PCECD"; Type = NecSystemType.TurboCD; this.disc = disc; this.Settings = (PCESettings)Settings ?? new PCESettings(); _syncSettings = (PCESyncSettings)syncSettings ?? new PCESyncSettings(); GameInfo biosInfo; byte[] rom = CoreComm.CoreFileProvider.GetFirmwareWithGameInfo("PCECD", "Bios", true, out biosInfo, "PCE-CD System Card not found. Please check the BIOS settings in Config->Firmwares."); if (biosInfo.Status == RomStatus.BadDump) { CoreComm.ShowMessage( "The PCE-CD System Card you have selected is known to be a bad dump. This may cause problems playing PCE-CD games.\n\n" + "It is recommended that you find a good dump of the system card. Sorry to be the bearer of bad news!"); } else if (biosInfo.NotInDatabase) { CoreComm.ShowMessage( "The PCE-CD System Card you have selected is not recognized in our database. That might mean it's a bad dump, or isn't the correct rom."); } else if (biosInfo["BIOS"] == false) { // zeromus says: someone please write a note about how this could possibly happen. // it seems like this is a relic of using gameDB for storing whether something is a bios? firmwareDB should be handling it now. CoreComm.ShowMessage( "The PCE-CD System Card you have selected is not a BIOS image. You may have selected the wrong rom. FYI-Please report this to developers, I don't think this error message should happen."); } if (biosInfo["SuperSysCard"]) { game.AddOption("SuperSysCard"); } if (game["NeedSuperSysCard"] && game["SuperSysCard"] == false) { CoreComm.ShowMessage( "This game requires a version 3.0 System card and won't run with the system card you've selected. Try selecting a 3.0 System Card in the firmware configuration."); throw new Exception(); } game.FirmwareHash = rom.HashSHA1(); Init(game, rom); // the default RomStatusDetails don't do anything with Disc CoreComm.RomStatusDetails = string.Format("{0}\r\nDisk partial hash:{1}", game.Name, new DiscSystem.DiscHasher(disc).OldHash()); _controllerDeck = new PceControllerDeck( _syncSettings.Port1, _syncSettings.Port2, _syncSettings.Port3, _syncSettings.Port4, _syncSettings.Port5); } // ROM private byte[] RomData; private int RomLength; private Disc disc; // Machine public NecSystemType Type; internal HuC6280 Cpu; public VDC VDC1, VDC2; public VCE VCE; private VPC VPC; private ScsiCDBus SCSI; private ADPCM ADPCM; private IController _controller; public HuC6280PSG PSG; internal CDAudio CDAudio; private SoundMixer SoundMixer; private bool TurboGrafx => Type == NecSystemType.TurboGrafx; private bool SuperGrafx => Type == NecSystemType.SuperGrafx; private bool TurboCD => Type == NecSystemType.TurboCD; // BRAM private bool BramEnabled = false; private bool BramLocked = true; private byte[] BRAM; // Memory system private byte[] Ram; // PCE= 8K base ram, SGX= 64k base ram private byte[] CDRam; // TurboCD extra 64k of ram private byte[] SuperRam; // Super System Card 192K of additional RAM private byte[] ArcadeRam; // Arcade Card 2048K of additional RAM private bool ForceSpriteLimit; // 21,477,270 Machine clocks / sec // 7,159,090 Cpu cycles / sec private ITraceable Tracer { get; set; } private void Init(GameInfo game, byte[] rom) { Cpu = new HuC6280(MemoryCallbacks); VCE = new VCE(); VDC1 = new VDC(this, Cpu, VCE); PSG = new HuC6280PSG(); SCSI = new ScsiCDBus(this, disc); Cpu.Logger = s => Tracer.Put(s); if (TurboGrafx) { Ram = new byte[0x2000]; Cpu.ReadMemory21 = ReadMemory; Cpu.WriteMemory21 = WriteMemory; Cpu.WriteVDC = VDC1.WriteVDC; _soundProvider = new FakeSyncSound(PSG, 735); CDAudio = new CDAudio(null, 0); } else if (SuperGrafx) { VDC2 = new VDC(this, Cpu, VCE); VPC = new VPC(this, VDC1, VDC2, VCE, Cpu); Ram = new byte[0x8000]; Cpu.ReadMemory21 = ReadMemorySGX; Cpu.WriteMemory21 = WriteMemorySGX; Cpu.WriteVDC = VDC1.WriteVDC; _soundProvider = new FakeSyncSound(PSG, 735); CDAudio = new CDAudio(null, 0); } else if (TurboCD) { Ram = new byte[0x2000]; CDRam = new byte[0x10000]; ADPCM = new ADPCM(this, SCSI); Cpu.ReadMemory21 = ReadMemoryCD; Cpu.WriteMemory21 = WriteMemoryCD; Cpu.WriteVDC = VDC1.WriteVDC; CDAudio = new CDAudio(disc); SetCDAudioCallback(); PSG.MaxVolume = short.MaxValue * 3 / 4; SoundMixer = new SoundMixer(PSG, CDAudio, ADPCM); _soundProvider = new FakeSyncSound(SoundMixer, 735); Cpu.ThinkAction = (cycles) => { SCSI.Think(); ADPCM.Think(cycles); }; } if (rom.Length == 0x60000) { // 384k roms require special loading code. Why ;_; // In memory, 384k roms look like [1st 256k][Then full 384k] RomData = new byte[0xA0000]; var origRom = rom; for (int i = 0; i < 0x40000; i++) RomData[i] = origRom[i]; for (int i = 0; i < 0x60000; i++) RomData[i + 0x40000] = origRom[i]; RomLength = RomData.Length; } else if (rom.Length > 1024 * 1024) { // If the rom is bigger than 1 megabyte, switch to Street Fighter 2 mapper Cpu.ReadMemory21 = ReadMemorySF2; Cpu.WriteMemory21 = WriteMemorySF2; RomData = rom; RomLength = RomData.Length; // user request: current value of the SF2MapperLatch on the tracelogger Cpu.Logger = (s) => Tracer.Put(new TraceInfo { Disassembly = $"{SF2MapperLatch:X1}:{s}", RegisterInfo = "" }); } else { // normal rom. RomData = rom; RomLength = RomData.Length; } if (game["BRAM"] || Type == NecSystemType.TurboCD) { BramEnabled = true; BRAM = new byte[2048]; // pre-format BRAM. damn are we helpful. BRAM[0] = 0x48; BRAM[1] = 0x55; BRAM[2] = 0x42; BRAM[3] = 0x4D; BRAM[4] = 0x00; BRAM[5] = 0x88; BRAM[6] = 0x10; BRAM[7] = 0x80; } if (game["SuperSysCard"]) { SuperRam = new byte[0x30000]; } if (game["ArcadeCard"]) { ArcadeRam = new byte[0x200000]; ArcadeCard = true; ArcadeCardRewindHack = Settings.ArcadeCardRewindHack; for (int i = 0; i < 4; i++) { ArcadePage[i] = new ArcadeCardPage(); } } if (game["PopulousSRAM"]) { PopulousRAM = new byte[0x8000]; Cpu.ReadMemory21 = ReadMemoryPopulous; Cpu.WriteMemory21 = WriteMemoryPopulous; } // the gamedb can force sprite limit on, ignoring settings if (game["ForceSpriteLimit"] || game.NotInDatabase) { ForceSpriteLimit = true; } if (game["CdVol"]) { CDAudio.MaxVolume = int.Parse(game.OptionValue("CdVol")); } if (game["PsgVol"]) { PSG.MaxVolume = int.Parse(game.OptionValue("PsgVol")); } if (game["AdpcmVol"]) { ADPCM.MaxVolume = int.Parse(game.OptionValue("AdpcmVol")); } // the gamedb can also force equalizevolumes on if (TurboCD && (Settings.EqualizeVolume || game["EqualizeVolumes"] || game.NotInDatabase)) { SoundMixer.EqualizeVolumes(); } // Ok, yes, HBlankPeriod's only purpose is game-specific hax. // 1) At least they're not coded directly into the emulator, but instead data-driven. // 2) The games which have custom HBlankPeriods work without it, the override only // serves to clean up minor gfx anomalies. // 3) There's no point in haxing the timing with incorrect values in an attempt to avoid this. // The proper fix is cycle-accurate/bus-accurate timing. That isn't coming to the C# // version of this core. Let's just acknolwedge that the timing is imperfect and fix // it in the least intrusive and most honest way we can. if (game["HBlankPeriod"]) { VDC1.HBlankCycles = game.GetIntValue("HBlankPeriod"); } // This is also a hack. Proper multi-res/TV emulation will be a native-code core feature. if (game["MultiResHack"]) { VDC1.MultiResHack = game.GetIntValue("MultiResHack"); } Cpu.ResetPC(); Tracer = new TraceBuffer { Header = Cpu.TraceHeader }; var ser = new BasicServiceProvider(this); ServiceProvider = ser; ser.Register<ITraceable>(Tracer); ser.Register<IDisassemblable>(Cpu); ser.Register<IVideoProvider>((IVideoProvider)VPC ?? VDC1); ser.Register<ISoundProvider>(_soundProvider); SetupMemoryDomains(); } private int _frame; private static Dictionary<string, int> SizesFromHuMap(IEnumerable<HuC6280.MemMapping> mm) { Dictionary<string, int> sizes = new Dictionary<string, int>(); foreach (var m in mm) { if (!sizes.ContainsKey(m.Name) || m.MaxOffs >= sizes[m.Name]) { sizes[m.Name] = m.MaxOffs; } } var keys = new List<string>(sizes.Keys); foreach (var key in keys) { // becase we were looking at offsets, and each bank is 8192 big, we need to add that size sizes[key] += 8192; } return sizes; } private void CheckSpriteLimit() { bool spriteLimit = ForceSpriteLimit | Settings.SpriteLimit; VDC1.PerformSpriteLimit = spriteLimit; if (VDC2 != null) { VDC2.PerformSpriteLimit = spriteLimit; } } private ISoundProvider _soundProvider; private string Region { get; set; } } }
29.657534
193
0.673533
3d78cb44955faa79d8552a4e5fbf6d4051505600
3,793
cs
C#
Core/Utilities/SecTime.cs
AeroNexus/AspireStudio
ab10db3d2dcfbce94ef25baa3d5b3248f36efbc9
[ "Apache-2.0" ]
2
2015-02-26T16:15:37.000Z
2020-06-19T14:37:23.000Z
Core/Utilities/SecTime.cs
AeroNexus/AspireStudio
ab10db3d2dcfbce94ef25baa3d5b3248f36efbc9
[ "Apache-2.0" ]
null
null
null
Core/Utilities/SecTime.cs
AeroNexus/AspireStudio
ab10db3d2dcfbce94ef25baa3d5b3248f36efbc9
[ "Apache-2.0" ]
null
null
null
using System; using System.Text; namespace Aspire.Core.Utilities { public struct SecTime { private int mSec, mUSec; static SecTime infinite = new SecTime(-1, 0); public static SecTime Infinite { get { return infinite; } } public SecTime(int sec, int uSec) { mSec = sec; mUSec = uSec; } public SecTime(double seconds) { mSec = (int)seconds; mUSec = (int)((seconds-mSec)*1000000); } public SecTime(SecTime rhs) { mSec = rhs.mSec; mUSec = rhs.mUSec; } public int this[int i] { get { return i == 0 ? mSec : mUSec; } set { if (i == 0) mSec = value; else if (i == 1) mUSec = value; } } public override bool Equals(object obj) { if (obj == null) return false; return ((SecTime)obj).mSec == mSec && ((SecTime)obj).mUSec == mUSec; } public override int GetHashCode() { return mSec+mUSec; } static public SecTime Milliseconds(int ms) { return new SecTime(0, ms * 1000); } public static SecTime operator+(SecTime lhs, SecTime rhs) { SecTime result; result.mUSec = lhs.mUSec + rhs.mUSec; if (result.mUSec > 1000000) { result.mUSec -= 1000000; result.mSec = lhs.mSec + 1 + rhs.mSec; } else result.mSec = lhs.mSec + rhs.mSec; return result; } public static SecTime operator+(SecTime lhs, int rhs) { SecTime result; result.mUSec = lhs.mUSec; result.mSec = lhs.mSec + rhs; return result; } public static SecTime operator-(SecTime lhs, SecTime rhs) { SecTime result; result.mUSec = lhs.mUSec - rhs.mUSec; if (result.mUSec > 0) result.mSec = lhs.mSec - rhs.mSec; else { result.mUSec += 1000000; result.mSec = lhs.mSec - 1 - rhs.mSec; } return result; } public static SecTime operator-(SecTime lhs, int rhs) { SecTime result; result.mUSec = lhs.mUSec; result.mSec = lhs.mSec - rhs; return result; } public static bool operator>(SecTime lhs, int rhsUsec) { return lhs.mSec >= 0 || lhs.mUSec > rhsUsec; } public static bool operator<(SecTime lhs, SecTime rhs) { if (lhs.mSec < rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec < rhs.mUSec) return true; return false; } public static bool operator<=(SecTime lhs, SecTime rhs) { if (lhs.mSec < rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec <= rhs.mUSec) return true; return false; } public static bool operator>(SecTime lhs, SecTime rhs) { if (lhs.mSec > rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec > rhs.mUSec) return true; return false; } public static bool operator>=(SecTime lhs, SecTime rhs) { if (lhs.mSec > rhs.mSec) return true; else if (lhs.mSec == rhs.mSec && lhs.mUSec >= rhs.mUSec) return true; return false; } public static bool operator<(SecTime lhs, int rhsUsec) { return lhs.mSec <= 0 || lhs.mUSec < rhsUsec; } public bool IsInfinite { get { return mSec == -1; } } public int Seconds { get { return mSec; } set { mSec = value; } } public int USeconds { get { return mUSec; } set { mUSec = value; } } public void Set(int seconds, int microSeconds) { mSec = seconds; mUSec = microSeconds; } public double ToDouble { get { return mUSec*0.000001 + mSec; } } public int ToMicroSeconds { get { return mSec*1000000+mUSec; } } public int ToMilliSeconds { get { return mSec*1000+mUSec/1000; } } public override string ToString() { int dSec = mSec; int dUsec = mUSec; var sb = new StringBuilder(); if ( dSec < 0 ) { dSec++; if ( dSec == 0) sb.Append('-'); dUsec = 1000000 - dUsec; } sb.AppendFormat("{0}.{1,6:D6}", dSec, dUsec); return sb.ToString(); } } }
19.963158
82
0.612444
3d7b6e93eb3d3aeb9013b996289e85338f9106ff
3,407
cs
C#
sdk/dotnet/PrivateLink/Inputs/EndpointPrivateServiceConnectionGetArgs.cs
henriktao/pulumi-azure
f1cbcf100b42b916da36d8fe28be3a159abaf022
[ "ECL-2.0", "Apache-2.0" ]
109
2018-06-18T00:19:44.000Z
2022-02-20T05:32:57.000Z
sdk/dotnet/PrivateLink/Inputs/EndpointPrivateServiceConnectionGetArgs.cs
henriktao/pulumi-azure
f1cbcf100b42b916da36d8fe28be3a159abaf022
[ "ECL-2.0", "Apache-2.0" ]
663
2018-06-18T21:08:46.000Z
2022-03-31T20:10:11.000Z
sdk/dotnet/PrivateLink/Inputs/EndpointPrivateServiceConnectionGetArgs.cs
henriktao/pulumi-azure
f1cbcf100b42b916da36d8fe28be3a159abaf022
[ "ECL-2.0", "Apache-2.0" ]
41
2018-07-19T22:37:38.000Z
2022-03-14T10:56:26.000Z
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Azure.PrivateLink.Inputs { public sealed class EndpointPrivateServiceConnectionGetArgs : Pulumi.ResourceArgs { /// <summary> /// Does the Private Endpoint require Manual Approval from the remote resource owner? Changing this forces a new resource to be created. /// </summary> [Input("isManualConnection", required: true)] public Input<bool> IsManualConnection { get; set; } = null!; /// <summary> /// Specifies the Name of the Private Service Connection. Changing this forces a new resource to be created. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// The Service Alias of the Private Link Enabled Remote Resource which this Private Endpoint should be connected to. One of `private_connection_resource_id` or `private_connection_resource_alias` must be specified. Changing this forces a new resource to be created. /// </summary> [Input("privateConnectionResourceAlias")] public Input<string>? PrivateConnectionResourceAlias { get; set; } /// <summary> /// The ID of the Private Link Enabled Remote Resource which this Private Endpoint should be connected to. One of `private_connection_resource_id` or `private_connection_resource_alias` must be specified. Changing this forces a new resource to be created. For a web app or function app slot, the parent web app should be used in this field instead of a reference to the slot itself. /// </summary> [Input("privateConnectionResourceId")] public Input<string>? PrivateConnectionResourceId { get; set; } /// <summary> /// (Computed) The private IP address associated with the private endpoint, note that you will have a private IP address assigned to the private endpoint even if the connection request was `Rejected`. /// </summary> [Input("privateIpAddress")] public Input<string>? PrivateIpAddress { get; set; } /// <summary> /// A message passed to the owner of the remote resource when the private endpoint attempts to establish the connection to the remote resource. The request message can be a maximum of `140` characters in length. Only valid if `is_manual_connection` is set to `true`. /// </summary> [Input("requestMessage")] public Input<string>? RequestMessage { get; set; } [Input("subresourceNames")] private InputList<string>? _subresourceNames; /// <summary> /// A list of subresource names which the Private Endpoint is able to connect to. `subresource_names` corresponds to `group_id`. Changing this forces a new resource to be created. /// </summary> public InputList<string> SubresourceNames { get => _subresourceNames ?? (_subresourceNames = new InputList<string>()); set => _subresourceNames = value; } public EndpointPrivateServiceConnectionGetArgs() { } } }
50.102941
390
0.682125
3d7c47fff11e3483c8e24edf8bf8f314334b0965
23,605
cs
C#
HemNetCore.IRepository/Base/IBaseRepository.cs
hemming123/HemNetCore
8f749564a99c178d5c3811224c95a4eaae6aeb31
[ "MIT" ]
null
null
null
HemNetCore.IRepository/Base/IBaseRepository.cs
hemming123/HemNetCore
8f749564a99c178d5c3811224c95a4eaae6aeb31
[ "MIT" ]
null
null
null
HemNetCore.IRepository/Base/IBaseRepository.cs
hemming123/HemNetCore
8f749564a99c178d5c3811224c95a4eaae6aeb31
[ "MIT" ]
null
null
null
using HemNetCore.Model; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace HemNetCore.IRepository.Base { /// <summary> /// 基类接口,其他接口继承该接口 /// </summary> /// <typeparam name="TEntity"></typeparam> public interface IBaseRepository<TEntity> where TEntity : class { #region 事务 /// <summary> /// 弃用事务 /// </summary> void BeginTran(); /// <summary> /// 提交事务 /// </summary> void CommitTran(); /// <summary> /// 回滚事务 /// </summary> void RollbackTran(); #endregion #region 添加 /// <summary> /// 添加 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<int> Add(TEntity model); /// <summary> /// 批量添加 /// </summary> /// <param name="listEntity"></param> /// <returns></returns> Task<int> Add(List<TEntity> listEntity); /// <summary> /// 写入实体数据 /// </summary> /// <param name="entity">实体类</param> /// <param name="insertColumns">指定只插入列</param> /// <returns>返回自增量列</returns> Task<int> Add(TEntity entity, Expression<Func<TEntity, object>> insertColumns = null); #endregion #region 修改 /// <summary> /// 更新实体数据 /// </summary> /// <param name="entity">博文实体类</param> /// <returns></returns> Task<bool> Update(TEntity entity); /// <summary> /// 根据model,更新,带where条件 /// </summary> /// <param name="entity"></param> /// <param name="strWhere"></param> /// <returns></returns> Task<bool> Update(TEntity entity, string strWhere); /// <summary> /// 根据Model,更新,不带where条件 /// </summary> /// <param name="operateAnonymousObjects"></param> /// <returns></returns> Task<bool> Update(object operateAnonymousObjects); /// <summary> /// 根据model,更新,指定列 /// </summary> /// <param name="entity"></param> /// <param name="lstColumns"></param> /// <param name="lstIgnoreColumns"></param> /// <param name="strWhere"></param> /// <returns></returns> Task<bool> Update(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string strWhere = ""); /// <summary> /// SQL语句更新,带参数 /// </summary> /// <param name="strSql"></param> /// <param name="parameters"></param> /// <returns></returns> Task<bool> Update(string strSql, SugarParameter[] parameters = null); /// <summary> /// 按查询条件更新 /// </summary> /// <param name="where"></param> /// <param name="columns"></param> /// <returns></returns> Task<bool> Update(Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, TEntity>> columns); /// <summary> /// 批量更新 /// </summary> /// <param name="entityList"></param> /// <returns></returns> Task<bool> Update(List<TEntity> entityList); #endregion #region 删除 /// <summary> /// 根据id 删除某一实体 /// </summary> /// <param name="id"></param> /// <returns></returns> Task<bool> DeleteById(object id); /// <summary> /// 根据对象,删除某一实体 /// </summary> /// <param name="model"></param> /// <returns></returns> Task<bool> Delete(TEntity model); /// <summary> /// 根据id数组,删除实体list /// </summary> /// <param name="ids"></param> /// <returns></returns> Task<bool> DeleteByIds(object[] ids); #endregion #region 查询 /// <summary> /// 根据Id查询实体 /// </summary> /// <param name="objId"></param> /// <returns></returns> Task<TEntity> QueryById(object objId); Task<TEntity> QueryById(object objId, bool blnUseCache = false); /// <summary> /// 根据id数组查询实体list /// </summary> /// <param name="lstIds"></param> /// <returns></returns> Task<List<TEntity>> QueryByIDs(object[] lstIds); /// <summary> /// 查询 /// </summary> /// <returns></returns> Task<List<TEntity>> Query(); /// <summary> /// 带sql where查询 /// </summary> /// <param name="strWhere"></param> /// <returns></returns> Task<List<TEntity>> Query(string strWhere); /// <summary> /// 根据表达式查询 /// </summary> /// <param name="whereExpression"></param> /// <returns></returns> Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression); /// <summary> /// 根据表达式,指定返回对象模型,查询 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="expression"></param> /// <returns></returns> Task<List<TResult>> Query<TResult>(Expression<Func<TEntity, TResult>> expression); /// <summary> /// 根据表达式,指定返回对象模型,排序,查询 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="expression"></param> /// <param name="whereExpression"></param> /// <param name="strOrderByFileds"></param> /// <returns></returns> Task<List<TResult>> Query<TResult>(Expression<Func<TEntity, TResult>> expression, Expression<Func<TEntity, bool>> whereExpression, string strOrderByFileds); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string strOrderByFileds); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true); Task<List<TEntity>> Query(string strWhere, string strOrderByFileds); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int intTop, string strOrderByFileds); Task<List<TEntity>> Query(string strWhere, int intTop, string strOrderByFileds); Task<List<TEntity>> QuerySql(string strSql, SugarParameter[] parameters = null); Task<DataTable> QueryTable(string strSql, SugarParameter[] parameters = null); Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex, int intPageSize, string strOrderByFileds); Task<List<TEntity>> Query(string strWhere, int intPageIndex, int intPageSize, string strOrderByFileds); /// <summary> /// 2表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<TResult>> QueryMuch<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression, Expression<Func<T, T2, TResult>> selectExpression, Expression<Func<T, T2, bool>> whereLambda = null); /// <summary> /// 1表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<TResult>> QueryMuch<T, T2, T3, TResult>(Expression<Func<T, T2, T3, object[]>> joinExpression, Expression<Func<T, T2, T3, TResult>> selectExpression, Expression<Func<T, T2, T3, bool>> whereLambda = null); /// <summary> /// 4表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<TResult>> QueryMuch<T, T2, T3, T4, TResult>(Expression<Func<T, T2, T3, T4, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, bool>> whereLambda = null); /// <summary> /// 5表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, TResult>(Expression<Func<T, T2, T3, T4, T5, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, bool>> whereLambda = null); /// <summary> /// 6表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5,T6, TResult>(Expression<Func<T, T2, T3, T4, T5,T6, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5,T6, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5,T6, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 7表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6,T7, TResult>(Expression<Func<T, T2, T3, T4, T5, T6,T7, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6,T7, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6,T7, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 8表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6, T7,T8, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8,object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7,T8, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7,T8, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 9表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6, T7, T8, T9,TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 10表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="T10"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6, T7, T8, T9,T10, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9,T10, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9,T10, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9,T10, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 11表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="T10"></typeparam> /// <typeparam name="T11"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6, T7, T8, T9, T10,T11, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10,T11, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10,T11, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 12表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="T10"></typeparam> /// <typeparam name="T11"></typeparam> /// <typeparam name="T12"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12,TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,T12, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11,T12, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 13表联查 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="T3"></typeparam> /// <typeparam name="T4"></typeparam> /// <typeparam name="T5"></typeparam> /// <typeparam name="T6"></typeparam> /// <typeparam name="T7"></typeparam> /// <typeparam name="T8"></typeparam> /// <typeparam name="T9"></typeparam> /// <typeparam name="T10"></typeparam> /// <typeparam name="T11"></typeparam> /// <typeparam name="T12"></typeparam> /// <typeparam name="T13"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereLambda"></param> /// <returns></returns> // Task<List<TResult>> QueryMuch<T, T2, T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, TResult>> selectExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, bool>> whereLambda = null) where T : class, new(); /// <summary> /// 根据表达式,排序字段,分页查询 /// </summary> /// <param name="whereExpression"></param> /// <param name="intPageIndex"></param> /// <param name="intPageSize"></param> /// <param name="strOrderByFileds"></param> /// <returns></returns> Task<PagedModel<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); /// <summary> /// 2表联查-分页 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereExpression"></param> /// <param name="intPageIndex"></param> /// <param name="intPageSize"></param> /// <param name="strOrderByFileds"></param> /// <returns></returns> Task<PagedModel<TResult>> QueryTabsPage<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression, Expression<Func<T, T2, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression = null, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); Task<PagedModel<TResult>> QueryTabsPage<T, T2, T3, TResult>(Expression<Func<T, T2, T3, object[]>> joinExpression, Expression<Func<T, T2, T3, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression = null, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); Task<PagedModel<TResult>> QueryTabsPage<T, T2, T3, T4, TResult>(Expression<Func<T, T2, T3, T4, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression = null, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); Task<PagedModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, TResult>(Expression<Func<T, T2, T3, T4, T5, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression = null, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5,T6, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, T6,T7, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, T6, T7,T8, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, T6, T7, T8,T9, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, T6, T7, T8, T9,T10, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); //Task<PageModel<TResult>> QueryTabsPage<T, T2, T3, T4, T5, T6, T7, T8, T9, T10,T11, TResult>(Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, object[]>> joinExpression, Expression<Func<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); /// <summary> /// 两表联合查询-分页-分组 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="T2"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="joinExpression"></param> /// <param name="selectExpression"></param> /// <param name="whereExpression"></param> /// <param name="groupExpression"></param> /// <param name="intPageIndex"></param> /// <param name="intPageSize"></param> /// <param name="strOrderByFileds"></param> /// <returns></returns> Task<PagedModel<TResult>> QueryTabsPage<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression, Expression<Func<T, T2, TResult>> selectExpression, Expression<Func<TResult, bool>> whereExpression, Expression<Func<T, object>> groupExpression,int intPageIndex = 1, int intPageSize = 20, string strOrderByFileds = null); #endregion } }
47.590726
413
0.5767
3d7cabda270ee82a567f56d1aced509d5a8b7b04
3,331
cs
C#
WmcSoft.Core/Collections/Generic/RandomBag.cs
vjacquet/WmcSoft
fea61a0d5f8a06f59155be8e3f7010504dd9bd9b
[ "MIT" ]
3
2016-06-06T14:08:30.000Z
2021-05-08T14:24:07.000Z
WmcSoft.Core/Collections/Generic/RandomBag.cs
vjacquet/WmcSoft
fea61a0d5f8a06f59155be8e3f7010504dd9bd9b
[ "MIT" ]
null
null
null
WmcSoft.Core/Collections/Generic/RandomBag.cs
vjacquet/WmcSoft
fea61a0d5f8a06f59155be8e3f7010504dd9bd9b
[ "MIT" ]
1
2021-04-18T04:58:24.000Z
2021-04-18T04:58:24.000Z
#region Licence /**************************************************************************** Copyright 1999-2016 Vincent J. Jacquet. All rights reserved. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. ****************************************************************************/ #endregion using System; using System.Collections.Generic; namespace WmcSoft.Collections.Generic { /// <summary> /// Represents a bag of items for which items are enumerated in random order. /// </summary> /// <typeparam name="T">The type of the elements in the bag.</typeparam> public class RandomBag<T> : Bag<T> { #region RandomAdapter class /// <summary> /// Adapter to always take the last item and thus removing RandomBag randomness... /// </summary> class RandomAdapter : Random { public override int Next(int minValue, int maxValue) { return maxValue - 1; } public override int Next(int maxValue) { return maxValue - 1; } public override int Next() { throw new NotSupportedException(); } public override void NextBytes(byte[] buffer) { throw new NotSupportedException(); } public override double NextDouble() { throw new NotSupportedException(); } } static readonly Random Default = new RandomAdapter(); #endregion private readonly Random _random; public RandomBag() : this(Default) { } public RandomBag(int capacity) : this(capacity, Default) { } public RandomBag(IEnumerable<T> collection) : this(collection, Default) { } public RandomBag(Random random) : base() { _random = random; } public RandomBag(int capacity, Random random) : base(capacity) { _random = random; } public RandomBag(IEnumerable<T> collection, Random random) : base(collection) { _random = random; } public T Pick() { var last = Count; return PopAt(_random.Next(last)); } public override Enumerator GetEnumerator() { var array = new T[Count]; CopyTo(array, 0); array.Shuffle(_random); return new Enumerator(this, array); } } }
28.228814
90
0.550585
3d7d779fd626ef088d43e5d36885eccc817730ee
17,018
cs
C#
packages/itextsharp-all-5.5.10/itextsharp-src-core/srcbc/crypto/digests/SHA3Digest.cs
mdalaminmiah/Diagnostic-Bill-management-System
be5c09f6c97d83e1732976975fb91fb9968c30e5
[ "MIT" ]
1
2019-07-10T17:08:36.000Z
2019-07-10T17:08:36.000Z
packages/itextsharp-all-5.5.10/itextsharp-src-core/srcbc/crypto/digests/SHA3Digest.cs
mdalaminmiah/Diagnostic-Bill-management-System
be5c09f6c97d83e1732976975fb91fb9968c30e5
[ "MIT" ]
null
null
null
packages/itextsharp-all-5.5.10/itextsharp-src-core/srcbc/crypto/digests/SHA3Digest.cs
mdalaminmiah/Diagnostic-Bill-management-System
be5c09f6c97d83e1732976975fb91fb9968c30e5
[ "MIT" ]
1
2020-01-22T12:54:15.000Z
2020-01-22T12:54:15.000Z
using System; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Digests { /// <summary> /// Implementation of SHA-3 based on following KeccakNISTInterface.c from http://keccak.noekeon.org/ /// </summary> /// <remarks> /// Following the naming conventions used in the C source code to enable easy review of the implementation. /// </remarks> public class Sha3Digest : IDigest { private static readonly ulong[] KeccakRoundConstants = KeccakInitializeRoundConstants(); private static readonly int[] KeccakRhoOffsets = KeccakInitializeRhoOffsets(); private static ulong[] KeccakInitializeRoundConstants() { ulong[] keccakRoundConstants = new ulong[24]; byte LFSRState = 0x01; for (int i = 0; i < 24; i++) { keccakRoundConstants[i] = 0; for (int j = 0; j < 7; j++) { int bitPosition = (1 << j) - 1; // LFSR86540 bool loBit = (LFSRState & 0x01) != 0; if (loBit) { keccakRoundConstants[i] ^= 1UL << bitPosition; } bool hiBit = (LFSRState & 0x80) != 0; LFSRState <<= 1; if (hiBit) { LFSRState ^= 0x71; } } } return keccakRoundConstants; } private static int[] KeccakInitializeRhoOffsets() { int[] keccakRhoOffsets = new int[25]; int x, y, t, newX, newY; int rhoOffset = 0; keccakRhoOffsets[(((0) % 5) + 5 * ((0) % 5))] = rhoOffset; x = 1; y = 0; for (t = 1; t < 25; t++) { //rhoOffset = ((t + 1) * (t + 2) / 2) % 64; rhoOffset = (rhoOffset + t) & 63; keccakRhoOffsets[(((x) % 5) + 5 * ((y) % 5))] = rhoOffset; newX = (0 * x + 1 * y) % 5; newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } return keccakRhoOffsets; } private byte[] state = new byte[(1600 / 8)]; private byte[] dataQueue = new byte[(1536 / 8)]; private int rate; private int bitsInQueue; private int fixedOutputLength; private bool squeezing; private int bitsAvailableForSqueezing; private byte[] chunk; private byte[] oneByte; private void ClearDataQueueSection(int off, int len) { for (int i = off; i != off + len; i++) { dataQueue[i] = 0; } } public Sha3Digest() { Init(0); } public Sha3Digest(int bitLength) { Init(bitLength); } public Sha3Digest(Sha3Digest source) { Array.Copy(source.state, 0, this.state, 0, source.state.Length); Array.Copy(source.dataQueue, 0, this.dataQueue, 0, source.dataQueue.Length); this.rate = source.rate; this.bitsInQueue = source.bitsInQueue; this.fixedOutputLength = source.fixedOutputLength; this.squeezing = source.squeezing; this.bitsAvailableForSqueezing = source.bitsAvailableForSqueezing; this.chunk = Arrays.Clone(source.chunk); this.oneByte = Arrays.Clone(source.oneByte); } public virtual string AlgorithmName { get { return "SHA3-" + fixedOutputLength; } } public virtual int GetDigestSize() { return fixedOutputLength / 8; } public virtual void Update(byte input) { oneByte[0] = input; DoUpdate(oneByte, 0, 8L); } public virtual void BlockUpdate(byte[] input, int inOff, int len) { DoUpdate(input, inOff, len * 8L); } public virtual int DoFinal(byte[] output, int outOff) { Squeeze(output, outOff, fixedOutputLength); Reset(); return GetDigestSize(); } public virtual void Reset() { Init(fixedOutputLength); } /** * Return the size of block that the compression function is applied to in bytes. * * @return internal byte length of a block. */ public virtual int GetByteLength() { return rate / 8; } private void Init(int bitLength) { switch (bitLength) { case 0: case 288: InitSponge(1024, 576); break; case 224: InitSponge(1152, 448); break; case 256: InitSponge(1088, 512); break; case 384: InitSponge(832, 768); break; case 512: InitSponge(576, 1024); break; default: throw new ArgumentException("must be one of 224, 256, 384, or 512.", "bitLength"); } } private void DoUpdate(byte[] data, int off, long databitlen) { if ((databitlen % 8) == 0) { Absorb(data, off, databitlen); } else { Absorb(data, off, databitlen - (databitlen % 8)); byte[] lastByte = new byte[1]; lastByte[0] = (byte)(data[off + (int)(databitlen / 8)] >> (int)(8 - (databitlen % 8))); Absorb(lastByte, off, databitlen % 8); } } private void InitSponge(int rate, int capacity) { if (rate + capacity != 1600) { throw new InvalidOperationException("rate + capacity != 1600"); } if ((rate <= 0) || (rate >= 1600) || ((rate % 64) != 0)) { throw new InvalidOperationException("invalid rate value"); } this.rate = rate; // this is never read, need to check to see why we want to save it // this.capacity = capacity; this.fixedOutputLength = 0; Arrays.Fill(this.state, (byte)0); Arrays.Fill(this.dataQueue, (byte)0); this.bitsInQueue = 0; this.squeezing = false; this.bitsAvailableForSqueezing = 0; this.fixedOutputLength = capacity / 2; this.chunk = new byte[rate / 8]; this.oneByte = new byte[1]; } private void AbsorbQueue() { KeccakAbsorb(state, dataQueue, rate / 8); bitsInQueue = 0; } private void Absorb(byte[] data, int off, long databitlen) { long i, j, wholeBlocks; if ((bitsInQueue % 8) != 0) { throw new InvalidOperationException("attempt to absorb with odd length queue."); } if (squeezing) { throw new InvalidOperationException("attempt to absorb while squeezing."); } i = 0; while (i < databitlen) { if ((bitsInQueue == 0) && (databitlen >= rate) && (i <= (databitlen - rate))) { wholeBlocks = (databitlen - i) / rate; for (j = 0; j < wholeBlocks; j++) { Array.Copy(data, (int)(off + (i / 8) + (j * chunk.Length)), chunk, 0, chunk.Length); //displayIntermediateValues.displayBytes(1, "Block to be absorbed", curData, rate / 8); KeccakAbsorb(state, chunk, chunk.Length); } i += wholeBlocks * rate; } else { int partialBlock = (int)(databitlen - i); if (partialBlock + bitsInQueue > rate) { partialBlock = rate - bitsInQueue; } int partialByte = partialBlock % 8; partialBlock -= partialByte; Array.Copy(data, off + (int)(i / 8), dataQueue, bitsInQueue / 8, partialBlock / 8); bitsInQueue += partialBlock; i += partialBlock; if (bitsInQueue == rate) { AbsorbQueue(); } if (partialByte > 0) { int mask = (1 << partialByte) - 1; dataQueue[bitsInQueue / 8] = (byte)(data[off + ((int)(i / 8))] & mask); bitsInQueue += partialByte; i += partialByte; } } } } private void PadAndSwitchToSqueezingPhase() { if (bitsInQueue + 1 == rate) { dataQueue[bitsInQueue / 8] |= (byte)(1U << (bitsInQueue % 8)); AbsorbQueue(); ClearDataQueueSection(0, rate / 8); } else { ClearDataQueueSection((bitsInQueue + 7) / 8, rate / 8 - (bitsInQueue + 7) / 8); dataQueue[bitsInQueue / 8] |= (byte)(1U << (bitsInQueue % 8)); } dataQueue[(rate - 1) / 8] |= (byte)(1U << ((rate - 1) % 8)); AbsorbQueue(); //displayIntermediateValues.displayText(1, "--- Switching to squeezing phase ---"); if (rate == 1024) { KeccakExtract1024bits(state, dataQueue); bitsAvailableForSqueezing = 1024; } else { KeccakExtract(state, dataQueue, rate / 64); bitsAvailableForSqueezing = rate; } //displayIntermediateValues.displayBytes(1, "Block available for squeezing", dataQueue, bitsAvailableForSqueezing / 8); squeezing = true; } private void Squeeze(byte[] output, int offset, long outputLength) { long i; int partialBlock; if (!squeezing) { PadAndSwitchToSqueezingPhase(); } if ((outputLength % 8) != 0) { throw new InvalidOperationException("outputLength not a multiple of 8"); } i = 0; while (i < outputLength) { if (bitsAvailableForSqueezing == 0) { KeccakPermutation(state); if (rate == 1024) { KeccakExtract1024bits(state, dataQueue); bitsAvailableForSqueezing = 1024; } else { KeccakExtract(state, dataQueue, rate / 64); bitsAvailableForSqueezing = rate; } //displayIntermediateValues.displayBytes(1, "Block available for squeezing", dataQueue, bitsAvailableForSqueezing / 8); } partialBlock = bitsAvailableForSqueezing; if ((long)partialBlock > outputLength - i) { partialBlock = (int)(outputLength - i); } Array.Copy(dataQueue, (rate - bitsAvailableForSqueezing) / 8, output, offset + (int)(i / 8), partialBlock / 8); bitsAvailableForSqueezing -= partialBlock; i += partialBlock; } } private static void FromBytesToWords(ulong[] stateAsWords, byte[] state) { for (int i = 0; i < (1600 / 64); i++) { stateAsWords[i] = 0; int index = i * (64 / 8); for (int j = 0; j < (64 / 8); j++) { stateAsWords[i] |= ((ulong)state[index + j] & 0xff) << ((8 * j)); } } } private static void FromWordsToBytes(byte[] state, ulong[] stateAsWords) { for (int i = 0; i < (1600 / 64); i++) { int index = i * (64 / 8); for (int j = 0; j < (64 / 8); j++) { state[index + j] = (byte)(stateAsWords[i] >> (8 * j)); } } } private void KeccakPermutation(byte[] state) { ulong[] longState = new ulong[state.Length / 8]; FromBytesToWords(longState, state); //displayIntermediateValues.displayStateAsBytes(1, "Input of permutation", longState); KeccakPermutationOnWords(longState); //displayIntermediateValues.displayStateAsBytes(1, "State after permutation", longState); FromWordsToBytes(state, longState); } private void KeccakPermutationAfterXor(byte[] state, byte[] data, int dataLengthInBytes) { for (int i = 0; i < dataLengthInBytes; i++) { state[i] ^= data[i]; } KeccakPermutation(state); } private void KeccakPermutationOnWords(ulong[] state) { int i; //displayIntermediateValues.displayStateAs64bitWords(3, "Same, with lanes as 64-bit words", state); for (i = 0; i < 24; i++) { //displayIntermediateValues.displayRoundNumber(3, i); Theta(state); //displayIntermediateValues.displayStateAs64bitWords(3, "After theta", state); Rho(state); //displayIntermediateValues.displayStateAs64bitWords(3, "After rho", state); Pi(state); //displayIntermediateValues.displayStateAs64bitWords(3, "After pi", state); Chi(state); //displayIntermediateValues.displayStateAs64bitWords(3, "After chi", state); Iota(state, i); //displayIntermediateValues.displayStateAs64bitWords(3, "After iota", state); } } ulong[] C = new ulong[5]; private void Theta(ulong[] A) { for (int x = 0; x < 5; x++) { C[x] = 0; for (int y = 0; y < 5; y++) { C[x] ^= A[x + 5 * y]; } } for (int x = 0; x < 5; x++) { ulong dX = ((((C[(x + 1) % 5]) << 1) ^ ((C[(x + 1) % 5]) >> (64 - 1)))) ^ C[(x + 4) % 5]; for (int y = 0; y < 5; y++) { A[x + 5 * y] ^= dX; } } } private void Rho(ulong[] A) { for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { int index = x + 5 * y; A[index] = ((KeccakRhoOffsets[index] != 0) ? (((A[index]) << KeccakRhoOffsets[index]) ^ ((A[index]) >> (64 - KeccakRhoOffsets[index]))) : A[index]); } } } ulong[] tempA = new ulong[25]; private void Pi(ulong[] A) { Array.Copy(A, 0, tempA, 0, tempA.Length); for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { A[y + 5 * ((2 * x + 3 * y) % 5)] = tempA[x + 5 * y]; } } } ulong[] chiC = new ulong[5]; private void Chi(ulong[] A) { for (int y = 0; y < 5; y++) { for (int x = 0; x < 5; x++) { chiC[x] = A[x + 5 * y] ^ ((~A[(((x + 1) % 5) + 5 * y)]) & A[(((x + 2) % 5) + 5 * y)]); } for (int x = 0; x < 5; x++) { A[x + 5 * y] = chiC[x]; } } } private static void Iota(ulong[] A, int indexRound) { A[(((0) % 5) + 5 * ((0) % 5))] ^= KeccakRoundConstants[indexRound]; } private void KeccakAbsorb(byte[] byteState, byte[] data, int dataInBytes) { KeccakPermutationAfterXor(byteState, data, dataInBytes); } private void KeccakExtract1024bits(byte[] byteState, byte[] data) { Array.Copy(byteState, 0, data, 0, 128); } private void KeccakExtract(byte[] byteState, byte[] data, int laneCount) { Array.Copy(byteState, 0, data, 0, laneCount * 8); } } }
31.398524
168
0.442414
3d7f9fc41ebb1362b7ca58ca6ef932196c67c95b
2,965
cs
C#
JJ.TryThingsOut.MonoCross/MonoCross 1.3/DeviceAccess/DeviceAccess.WP/VideoAccess.cs
jjvanzon/JJ.TryOut
15063afd56add73bf197eaee6eb039e39dde0fa8
[ "MIT" ]
null
null
null
JJ.TryThingsOut.MonoCross/MonoCross 1.3/DeviceAccess/DeviceAccess.WP/VideoAccess.cs
jjvanzon/JJ.TryOut
15063afd56add73bf197eaee6eb039e39dde0fa8
[ "MIT" ]
null
null
null
JJ.TryThingsOut.MonoCross/MonoCross 1.3/DeviceAccess/DeviceAccess.WP/VideoAccess.cs
jjvanzon/JJ.TryOut
15063afd56add73bf197eaee6eb039e39dde0fa8
[ "MIT" ]
null
null
null
using System; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; using System.IO.IsolatedStorage; namespace DeviceAccess { public class VideoAccess { // Source and device for capturing video. CaptureSource captureSource; VideoCaptureDevice videoCaptureDevice; // File details for storing the recording. IsolatedStorageFileStream isoVideoFile; FileSink fileSink; // Viewfinder for capturing video. VideoBrush videoRecorderBrush; public void StartRecording(Rectangle viewfinderRectangle, string filePath) { InitializeVideoRecorder(viewfinderRectangle); // Connect fileSink to captureSource. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); // Connect the input and output of fileSink. fileSink.CaptureSource = captureSource; fileSink.IsolatedStorageFileName = filePath; } // Begin recording. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Stopped) { captureSource.Start(); } } public void StopRecording() { if (captureSource != null) { // Stop captureSource if it is running. if (captureSource.VideoCaptureDevice != null && captureSource.State == CaptureState.Started) { captureSource.Stop(); } // Remove the event handlers for capturesource and the shutter button. captureSource.CaptureFailed -= OnCaptureFailed; // Remove the video recording objects. captureSource = null; videoCaptureDevice = null; fileSink = null; videoRecorderBrush = null; } } void InitializeVideoRecorder(Rectangle viewfinderRectangle) { if (captureSource == null) { // Create the VideoRecorder objects. captureSource = new CaptureSource(); fileSink = new FileSink(); videoCaptureDevice = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice(); // Add eventhandlers for captureSource. captureSource.CaptureFailed += new EventHandler<ExceptionRoutedEventArgs>(OnCaptureFailed); // Initialize the camera if it exists on the device. if (videoCaptureDevice != null) { // Create the VideoBrush for the viewfinder. videoRecorderBrush = new VideoBrush(); videoRecorderBrush.SetSource(captureSource); // Display the viewfinder image on the rectangle. viewfinderRectangle.Fill = videoRecorderBrush; // Start video capture and display it on the viewfinder. captureSource.Start(); } else { // A camera is not supported on this device } } } void OnCaptureFailed(object sender, ExceptionRoutedEventArgs e) { } } }
28.238095
99
0.650253
3d84feea1919fc9e7358084e31175b84d8eace07
3,824
cs
C#
Aleph1.Logging/LoggedAttribute.cs
avrahamcool/Aleph1
aaf06536cfe7701214742574e03b1d043277a60b
[ "MIT" ]
4
2018-01-31T22:21:22.000Z
2021-12-09T20:46:38.000Z
Aleph1.Logging/LoggedAttribute.cs
avrahamcool/Aleph1
aaf06536cfe7701214742574e03b1d043277a60b
[ "MIT" ]
69
2018-02-25T19:57:34.000Z
2021-07-08T03:16:56.000Z
Aleph1.Logging/LoggedAttribute.cs
avrahamcool/Aleph1
aaf06536cfe7701214742574e03b1d043277a60b
[ "MIT" ]
2
2018-02-25T19:59:16.000Z
2018-08-16T05:41:45.000Z
using Newtonsoft.Json; using NLog; using PostSharp.Aspects; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Aleph1.Logging { /// <summary>Aspect to handle logging</summary> [Serializable, AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true), LinesOfCodeAvoided(20)] public sealed class LoggedAttribute : OnMethodBoundaryAspect { /// <summary>Default = true, set to False when you don't want the parameters of the function to be logged</summary> public bool LogParameters { get; set; } = true; /// <summary>Default = false, set to true when you want the return value of the function to be logged</summary> public bool LogReturnValue { get; set; } = false; [NonSerialized] private ILogger logger; private string[] ParameterNames { get; set; } private string ClassName { get; set; } private string MethodName { get; set; } /// <summary>Initializing the fixed fields at compile time to improve performance</summary> public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { ClassName = method.ReflectedType.Name; MethodName = method.Name; ParameterNames = method.GetParameters().Select(pi => pi.Name).ToArray(); } /// <summary>Initializing the run time fields</summary> public override void RuntimeInitialize(MethodBase method) { logger = LogManager.GetLogger(ClassName); } /// <summary>Handle the logging of entering a function. depends on LogParameters</summary> /// <param name="args"></param> public override sealed void OnEntry(MethodExecutionArgs args) { args.MethodExecutionTag = Guid.NewGuid(); string message = LogParameters ? $"Entering with parameters: {GetArguments(args)}" : "Entering"; logger.LogAleph1(LogLevel.Trace, message, null, args.MethodExecutionTag, ClassName, MethodName); } /// <summary>Handle the logging of exiting a function. depends on LogReturnValue</summary> /// <param name="args"></param> public override sealed void OnExit(MethodExecutionArgs args) { string message = LogReturnValue ? $"Leaving with result: {GetReturnValue(args)}" : "Leaving"; logger.LogAleph1(LogLevel.Trace, message, null, args.MethodExecutionTag, ClassName, MethodName); } /// <summary>Handle the logging of an error in a function</summary> /// <param name="args"></param> public override sealed void OnException(MethodExecutionArgs args) { logger.LogAleph1(LogLevel.Error, args.Exception.StackTrace, args.Exception, args.MethodExecutionTag, ClassName, MethodName); } private string GetArguments(MethodExecutionArgs args) { if (ParameterNames.Length == 0) return "null"; Dictionary<string, object> o = new Dictionary<string, object>(); for (int i = 0; i < ParameterNames.Length; i++) o.Add(ParameterNames[i], args.Arguments[i]); try { return JsonConvert.SerializeObject(o); } catch (JsonSerializationException e) { return $"[Error in Serializing the arguments: {e.Message}]"; } } private string GetReturnValue(MethodExecutionArgs args) { if (args.ReturnValue == null) return "null"; try { return JsonConvert.SerializeObject(args.ReturnValue); } catch (JsonSerializationException e) { return $"[Error in Serializing the return value: {e.Message} ---ReturnValue.ToString: {args.ReturnValue.ToString()}]"; } } } }
42.488889
171
0.648013
3d8fb077e259a510f4f8c9ae5559b23aabc29f54
2,135
cs
C#
Dorothy/Game/World.cs
IppClub/Dorothy-Xna
e4bddec0b17b2d310f11f1ab68fb4ec7fd06d31d
[ "MIT" ]
1
2017-01-13T09:01:46.000Z
2017-01-13T09:01:46.000Z
Dorothy/Game/World.cs
IppClub/Dorothy-Xna
e4bddec0b17b2d310f11f1ab68fb4ec7fd06d31d
[ "MIT" ]
null
null
null
Dorothy/Game/World.cs
IppClub/Dorothy-Xna
e4bddec0b17b2d310f11f1ab68fb4ec7fd06d31d
[ "MIT" ]
null
null
null
using Dorothy.Core; using Microsoft.Xna.Framework; using Dorothy.Cameras; namespace Dorothy.Game { public class World : DrawComponent { public const float B2FACTOR = 100.0f; private int _velocityIterations = 8; private int _positionIterations = 6; private float _deltaTime; private Box2D.World _world; public int VelocityIterations { set { _velocityIterations = value; } get { return _velocityIterations; } } public int PositionIterations { set { _positionIterations = value; } get { return _positionIterations; } } public float DeltaTime { set { _deltaTime = value; } get { return _deltaTime; } } public bool IsRunning { set { this.Enable = value; } get { return this.Enable; } } public Box2D.World B2World { get { return _world; } } public static float B2Value(float value) { return value / B2FACTOR; } public static Vector2 B2Value(Vector2 value) { return new Vector2(value.X / B2FACTOR, value.Y / B2FACTOR); } public static Vector2 B2Value(ref Vector2 value) { return new Vector2(value.X / B2FACTOR, value.Y / B2FACTOR); } public static float GameValue(float value) { return value * B2FACTOR; } public static Vector2 GameValue(Vector2 value) { return new Vector2(value.X * B2FACTOR, value.Y * B2FACTOR); } public static Vector2 GameValue(ref Vector2 value) { return new Vector2(value.X * B2FACTOR, value.Y * B2FACTOR); } public World(Vector2 gravity) : base(oSceneManager.CurrentScene.Controller) { _world = new Box2D.World(gravity, true); _world.ContactListener = new ContactListener(); _deltaTime = oGame.TargetFrameInterval / 1000.0f; oSceneManager.CurrentScene.Root.Add(this); base.Enable = true; } public override void Update() { _world.Step(_deltaTime, _velocityIterations, _positionIterations); } protected override void GetReady() { base.GetReady(); if (_world.DebugDraw != null) { _world.DrawDebugData(); } } public override void Draw() { } } }
23.722222
70
0.661827
3d92024454604cd7f21614b6c4bcfc05cdf2d497
3,927
cs
C#
src/Features/Core/Portable/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs
jbevain/roslyn
1a4bf536e3b06c09def2f796e56ac988c84362c7
[ "Apache-2.0" ]
null
null
null
src/Features/Core/Portable/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs
jbevain/roslyn
1a4bf536e3b06c09def2f796e56ac988c84362c7
[ "Apache-2.0" ]
null
null
null
src/Features/Core/Portable/UseObjectInitializer/AbstractUseObjectInitializerCodeFixProvider.cs
jbevain/roslyn
1a4bf536e3b06c09def2f796e56ac988c84362c7
[ "Apache-2.0" ]
null
null
null
// Copyright (c) Microsoft. 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.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.UseObjectInitializer { internal abstract class AbstractUseObjectInitializerCodeFixProvider< TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclarator> : CodeFixProvider where TExpressionSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TObjectCreationExpressionSyntax : TExpressionSyntax where TMemberAccessExpressionSyntax : TExpressionSyntax where TAssignmentStatementSyntax : TStatementSyntax where TVariableDeclarator : SyntaxNode { public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.UseObjectInitializerDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Diagnostics.First(), c)), context.Diagnostics); return SpecializedTasks.EmptyTask; } private async Task<Document> FixAsync( Document document, Diagnostic diagnostic, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var objectCreation = (TObjectCreationExpressionSyntax)root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var analyzer = new Analyzer<TExpressionSyntax, TStatementSyntax, TObjectCreationExpressionSyntax, TMemberAccessExpressionSyntax, TAssignmentStatementSyntax, TVariableDeclarator>( syntaxFacts, objectCreation); var matches = analyzer.Analyze(); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var statement = objectCreation.FirstAncestorOrSelf<TStatementSyntax>(); var newStatement = statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)).WithAdditionalAnnotations(Formatter.Annotation); editor.ReplaceNode(statement, newStatement); foreach (var match in matches) { editor.RemoveNode(match.Statement); } var newRoot = editor.GetChangedRoot(); return document.WithSyntaxRoot(newRoot); } protected abstract TObjectCreationExpressionSyntax GetNewObjectCreation( TObjectCreationExpressionSyntax objectCreation, List<Match<TAssignmentStatementSyntax, TMemberAccessExpressionSyntax, TExpressionSyntax>> matches); private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(FeaturesResources.Object_initialization_can_be_simplified, createChangedDocument) { } } } }
44.123596
190
0.724726
3d9262e3c8e14a94ded02008cf65d4f2a7258824
5,010
cs
C#
SDK/Samples/ScheduleAutomaticFormatter/CS/Application.cs
xin1627/RevitSdkSamples
06ba6e054162304ad07f38afb365925ef15a7be9
[ "MIT" ]
1
2021-06-11T07:25:38.000Z
2021-06-11T07:25:38.000Z
SDK/Samples/ScheduleAutomaticFormatter/CS/Application.cs
xin1627/RevitSdkSamples
06ba6e054162304ad07f38afb365925ef15a7be9
[ "MIT" ]
null
null
null
SDK/Samples/ScheduleAutomaticFormatter/CS/Application.cs
xin1627/RevitSdkSamples
06ba6e054162304ad07f38afb365925ef15a7be9
[ "MIT" ]
null
null
null
// // (C) Copyright 2003-2019 by Autodesk, Inc. All rights reserved. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM 'AS IS' AND WITH ALL ITS FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.IO; using Autodesk; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.ApplicationServices; using System.Windows.Media.Imaging; using System.Windows; namespace Revit.SDK.Samples.ScheduleAutomaticFormatter.CS { /// <summary> /// Implements the Revit add-in interface IExternalApplication /// </summary> [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)] public class Application : IExternalApplication { #region IExternalApplication Members /// <summary> /// Implements the OnShutdown event /// </summary> /// <param name="application"></param> /// <returns></returns> public Result OnShutdown(UIControlledApplication application) { return Result.Succeeded; } /// <summary> /// Implements the OnStartup event /// </summary> /// <param name="application"></param> /// <returns></returns> public Result OnStartup(UIControlledApplication application) { CreateScheduleFormatterPanel(application); return Result.Succeeded; } #endregion private void CreateScheduleFormatterPanel(UIControlledApplication application) { RibbonPanel rp = application.CreateRibbonPanel("Schedule Formatter"); PushButtonData pbd = new PushButtonData("ScheduleFormatter", "Format schedule", addAssemblyPath, typeof(Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.ScheduleFormatterCommand).FullName); pbd.LongDescription = "Format the active schedule background columns."; PushButton formatSchedulePB = rp.AddItem(pbd) as PushButton; SetIconsForPushButton(formatSchedulePB, Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.Properties.Resources.ScheduleFormatter); } /// <summary> /// Utility for adding icons to the button. /// </summary> /// <param name="button">The push button.</param> /// <param name="icon">The icon.</param> private static void SetIconsForPushButton(PushButton button, System.Drawing.Icon icon) { button.LargeImage = GetStdIcon(icon); button.Image = GetSmallIcon(icon); } /// <summary> /// Gets the standard sized icon as a BitmapSource. /// </summary> /// <param name="icon">The icon.</param> /// <returns>The BitmapSource.</returns> private static BitmapSource GetStdIcon(System.Drawing.Icon icon) { return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon( icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } /// <summary> /// Gets the small sized icon as a BitmapSource. /// </summary> /// <param name="icon">The icon.</param> /// <returns>The BitmapSource.</returns> private static BitmapSource GetSmallIcon(System.Drawing.Icon icon) { System.Drawing.Icon smallIcon = new System.Drawing.Icon(icon, new System.Drawing.Size(16, 16)); return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon( smallIcon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } /// <summary> /// Path to this assembly. /// </summary> static String addAssemblyPath = typeof(Revit.SDK.Samples.ScheduleAutomaticFormatter.CS.Application).Assembly.Location; } }
39.140625
141
0.645509
3d95b93f169a776f84fd448eb691a34e4cd20da5
2,668
cs
C#
UnifiedStorage.SysIo/DotNetFileSystem.cs
fiveninedigital/UnifiedStorage
d2aaa758737d51cf5d88ad77984d79c79ca47a1b
[ "MS-PL" ]
10
2015-07-07T08:42:12.000Z
2017-10-08T09:23:07.000Z
UnifiedStorage.SysIo/DotNetFileSystem.cs
fiveninedigital/UnifiedStorage
d2aaa758737d51cf5d88ad77984d79c79ca47a1b
[ "MS-PL" ]
3
2015-09-30T12:18:22.000Z
2017-09-21T05:44:04.000Z
UnifiedStorage.SysIo/DotNetFileSystem.cs
fiveninedigital/UnifiedStorage
d2aaa758737d51cf5d88ad77984d79c79ca47a1b
[ "MS-PL" ]
6
2016-03-30T11:47:01.000Z
2021-08-15T15:08:51.000Z
using System.IO; using System.Threading; using System.Threading.Tasks; using UnifiedStorage.Extensions; // ReSharper disable ConvertPropertyToExpressionBody namespace UnifiedStorage.DotNet { /// <summary> /// A <see cref="IFileSystem"/> implementation base class for the classic .NET System.IO API. /// </summary> public abstract class DotNetFileSystem : IFileSystem { /// <summary> /// A folder representing storage which is local to the current device. /// </summary> public abstract IDirectory LocalStorage { get; } /// <summary> /// A folder representing storage which may be synced with other devices for the same user. /// </summary> public abstract IDirectory RoamingStorage { get; } /// <summary> /// Gets the temporary storage directory. /// </summary> /// <value> /// The temporary storage directory. /// </value> public IDirectory TemporaryStorage { get { return new DotNetDirectory(Path.GetTempPath()); } } /// <summary> /// Creates the path object from the given <c>string</c>. /// </summary> /// <param name="path">The path to create.</param> /// <returns>A new instance of a <see cref="IPath"/>.</returns> public IPath CreatePath(string path) { return new DotNetPath(path); } /// <summary> /// Gets a file, given its path. /// </summary> /// <param name="path">The path to a file, as returned from the <see cref="IFile.Path"/> property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A file for the given path.</returns> public async Task<IFile> GetFileFromPathAsync(string path, CancellationToken cancellationToken) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return new DotNetFile(path); } /// <summary> /// Gets a folder, given its path. /// </summary> /// <param name="path">The path to a directory, as returned from the <see cref="IDirectory.Path"/> property.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A folder for the specified path.</returns> public async Task<IDirectory> GetDirectoryFromPathAsync(string path, CancellationToken cancellationToken = new CancellationToken()) { await AwaitExtensions.SwitchOffMainThreadAsync(cancellationToken); return new DotNetDirectory(path); } } }
37.577465
139
0.615817
3d95d89af0fede75a577d7739d5cd8d9003b1229
3,111
cs
C#
src/SJP.Schematic.PostgreSql/Versions/V10/PostgreSqlDatabaseSequenceProvider.cs
sjp/Schematic
62b21a1329c10976e92e9b4e27f06a15aa0fa64e
[ "MIT" ]
4
2019-07-09T00:34:09.000Z
2022-02-16T06:21:06.000Z
src/SJP.Schematic.PostgreSql/Versions/V10/PostgreSqlDatabaseSequenceProvider.cs
sjp/Schematic
62b21a1329c10976e92e9b4e27f06a15aa0fa64e
[ "MIT" ]
503
2017-08-25T00:36:53.000Z
2022-03-24T06:06:17.000Z
src/SJP.Schematic.PostgreSql/Versions/V10/PostgreSqlDatabaseSequenceProvider.cs
sjp/Schematic
62b21a1329c10976e92e9b4e27f06a15aa0fa64e
[ "MIT" ]
2
2020-07-14T19:32:20.000Z
2021-12-31T06:22:22.000Z
using SJP.Schematic.Core; using SJP.Schematic.PostgreSql.Query; using SJP.Schematic.PostgreSql.QueryResult; namespace SJP.Schematic.PostgreSql.Versions.V10 { /// <summary> /// A database sequence provider for PostgreSQL v10 (and higher) databases. /// </summary> /// <seealso cref="IDatabaseSequenceProvider" /> public class PostgreSqlDatabaseSequenceProvider : PostgreSqlDatabaseSequenceProviderBase { /// <summary> /// Initializes a new instance of the <see cref="PostgreSqlDatabaseSequenceProvider"/> class. /// </summary> /// <param name="connection">A database connection factory.</param> /// <param name="identifierDefaults">Database identifier defaults.</param> /// <param name="identifierResolver">An identifier resolver.</param> public PostgreSqlDatabaseSequenceProvider(IDbConnectionFactory connection, IIdentifierDefaults identifierDefaults, IIdentifierResolutionStrategy identifierResolver) : base(connection, identifierDefaults, identifierResolver) { } /// <summary> /// Gets a query that retrieves information on all sequences in the database. /// </summary> /// <value>A SQL query.</value> protected override string SequencesQuery => SequencesQuerySql; private static readonly string SequencesQuerySql = @$" select schemaname as ""{ nameof(GetAllSequenceDefinitionsQueryResult.SchemaName) }"", sequencename as ""{ nameof(GetAllSequenceDefinitionsQueryResult.SequenceName) }"", start_value as ""{ nameof(GetAllSequenceDefinitionsQueryResult.StartValue) }"", min_value as ""{ nameof(GetAllSequenceDefinitionsQueryResult.MinValue) }"", max_value as ""{ nameof(GetAllSequenceDefinitionsQueryResult.MaxValue) }"", increment_by as ""{ nameof(GetAllSequenceDefinitionsQueryResult.Increment) }"", cycle as ""{ nameof(GetAllSequenceDefinitionsQueryResult.Cycle) }"", cache_size as ""{ nameof(GetAllSequenceDefinitionsQueryResult.CacheSize) }"" from pg_catalog.pg_sequences order by schemaname, sequencename"; /// <summary> /// Gets a query that retrieves all relevant information on a sequence. /// </summary> /// <value>A SQL query.</value> protected override string SequenceQuery => SequenceQuerySql; private static readonly string SequenceQuerySql = @$" select start_value as ""{ nameof(GetSequenceDefinitionQueryResult.StartValue) }"", min_value as ""{ nameof(GetSequenceDefinitionQueryResult.MinValue) }"", max_value as ""{ nameof(GetSequenceDefinitionQueryResult.MaxValue) }"", increment_by as ""{ nameof(GetSequenceDefinitionQueryResult.Increment) }"", cycle as ""{ nameof(GetSequenceDefinitionQueryResult.Cycle) }"", cache_size as ""{ nameof(GetSequenceDefinitionQueryResult.CacheSize) }"" from pg_catalog.pg_sequences where schemaname = @{ nameof(GetSequenceDefinitionQuery.SchemaName) } and sequencename = @{ nameof(GetSequenceDefinitionQuery.SequenceName) }"; } }
51
173
0.70974
3d96ec6784e8523ed64ea29d3ab8411da915e4e8
26,035
cs
C#
JUST.net/Transformer.cs
recepaslan/JUST.net
19a2abf9cdb87f7d00024bfee9c2989a986838a7
[ "MIT" ]
null
null
null
JUST.net/Transformer.cs
recepaslan/JUST.net
19a2abf9cdb87f7d00024bfee9c2989a986838a7
[ "MIT" ]
null
null
null
JUST.net/Transformer.cs
recepaslan/JUST.net
19a2abf9cdb87f7d00024bfee9c2989a986838a7
[ "MIT" ]
null
null
null
using JUST.net.Selectables; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Globalization; using System.Linq; namespace JUST { internal class Transformer { protected static object TypedNumber(decimal number) { return number * 10 % 10 == 0 ? (number <= int.MaxValue ? (object)Convert.ToInt32(number) : number) : number; } internal static object GetValue(JToken selectedToken) { object output = null; if (selectedToken != null) { switch (selectedToken.Type) { case JTokenType.Object: output = selectedToken; break; case JTokenType.Array: output = selectedToken.Values<object>().ToArray(); break; case JTokenType.Integer: output = selectedToken.ToObject<long>(); break; case JTokenType.Float: output = selectedToken.ToObject<double>(); break; case JTokenType.String: output = selectedToken.ToString(); break; case JTokenType.Boolean: output = selectedToken.ToObject<bool>(); break; case JTokenType.Date: DateTime value = selectedToken.Value<DateTime>(); output = value.ToString("yyyy-MM-ddTHH:mm:ss.fffK"); break; case JTokenType.Raw: break; case JTokenType.Bytes: output = selectedToken.Value<byte[]>(); break; case JTokenType.Guid: output = selectedToken.Value<Guid>(); break; case JTokenType.TimeSpan: output = selectedToken.Value<TimeSpan>(); break; case JTokenType.Uri: case JTokenType.Undefined: case JTokenType.Constructor: case JTokenType.Property: case JTokenType.Comment: case JTokenType.Null: case JTokenType.None: break; default: break; } } return output; } } internal class Transformer<T> : Transformer where T : ISelectableToken { public static object valueof(string path, JUSTContext context) { var selector = context.Resolve<T>(context.Input); JToken selectedToken = selector.Select(path); return GetValue(selectedToken); } public static bool exists(string path, JUSTContext context) { var selector = context.Resolve<T>(context.Input); JToken selectedToken = selector.Select(path); return selectedToken != null; } public static bool existsandnotempty(string path, JUSTContext context) { var selector = context.Resolve<T>(context.Input); JToken selectedToken = selector.Select(path); return selectedToken != null && selectedToken.ToString().Trim() != string.Empty; } public static object ifcondition(object condition, object value, object trueResult, object falseResult, JUSTContext context) { object output = falseResult; if (condition.ToString().ToLower() == value.ToString().ToLower()) output = trueResult; return output; } #region string functions private static object ConcatArray(object obj1, object obj2) { JArray item = new JArray(); JToken item1 = null, item2 = null; for (int i = 0; i < ((object[])obj1).Length; i++) { if (((object[])obj1)[i] is JValue) { item1 = (JValue)((object[])obj1)[i]; item.Add(item1); } else { item1 = (JObject)((object[])obj1)[i]; item.Add(item1); } } for (int j = 0; obj2 != null && j < ((object[])obj2).Length; j++) { if (((object[])obj2)[j] is JValue) { item2 = (JValue)((object[])obj2)[j]; item1.AddAfterSelf(item2); } else { item2 = (JObject)((object[])obj2)[j]; item.Add(item2); } } return item.ToObject<object[]>(); } public static object concat(object obj1, object obj2, JUSTContext context) { if (obj1 != null) { if (obj1 is string str1) { return str1.Length > 0 ? str1 + obj2?.ToString() : string.Empty + obj2.ToString(); } return ConcatArray(obj1, obj2); } else if (obj2 != null) { if (obj2 is string str2) { return str2.Length > 0 ? obj1?.ToString() + str2 : obj1.ToString() + string.Empty; } return ConcatArray(obj2, obj1); } return null; } public static string substring(string stringRef, int startIndex, int length, JUSTContext context) { try { return stringRef.Substring(startIndex, length); } catch (Exception ex) { ExceptionHelper.HandleException(ex, context.EvaluationMode); } return null; } public static int firstindexof(string stringRef, string searchString, JUSTContext context) { return stringRef.IndexOf(searchString, 0); } public static int lastindexof(string stringRef, string searchString, JUSTContext context) { return stringRef.LastIndexOf(searchString); } public static string concatall(object obj, JUSTContext context) { JToken token = JToken.FromObject(obj); if (obj is string path && path.StartsWith(context.Resolve<T>(token).RootReference)) { return Concatall(JToken.FromObject(valueof(path, context)), context); } else { return Concatall(token, context); } } private static string Concatall(JToken parsedArray, JUSTContext context) { string result = null; if (parsedArray != null) { if (result == null) { result = string.Empty; } foreach (JToken token in parsedArray.Children()) { if (context.IsStrictMode() && token.Type != JTokenType.String) { throw new Exception($"Invalid value in array to concatenate: {token.ToString()}"); } result += token.ToString(); } } return result; } public static string concatallatpath(JArray parsedArray, string path, JUSTContext context) { string result = null; if (parsedArray != null) { result = string.Empty; foreach (JToken token in parsedArray.Children()) { var selector = context.Resolve<T>(token); JToken selectedToken = selector.Select(path); if (context.IsStrictMode() && selectedToken.Type != JTokenType.String) { throw new Exception($"Invalid value in array to concatenate: {selectedToken.ToString()}"); } result += selectedToken.ToString(); } } return result; } #endregion #region math functions public static object add(decimal num1, decimal num2, JUSTContext context) { return TypedNumber(num1 + num2); } public static object subtract(decimal num1, decimal num2, JUSTContext context) { return TypedNumber(num1 - num2); } public static object multiply(decimal num1, decimal num2, JUSTContext context) { return TypedNumber(num1 * num2); } public static object divide(decimal num1, decimal num2, JUSTContext context) { return TypedNumber(num1 / num2); } #endregion #region aggregate functions public static object sum(object obj, JUSTContext context) { JToken token = JToken.FromObject(obj); if (obj is string path && path.StartsWith(context.Resolve<T>(token).RootReference)) { return Sum(JToken.FromObject(valueof(path, context)), context); } else { return Sum(token, context); } } private static object Sum(JToken parsedArray, JUSTContext context) { decimal result = 0; if (parsedArray != null) { foreach (JToken token in parsedArray.Children()) { result += Convert.ToDecimal(token.ToString()); } } return TypedNumber(result); } public static object sumatpath(JArray parsedArray, string path, JUSTContext context) { decimal result = 0; if (parsedArray != null) { foreach (JToken token in parsedArray.Children()) { var selector = context.Resolve<T>(token); JToken selectedToken = selector.Select(path); result += Convert.ToDecimal(selectedToken.ToString()); } } return TypedNumber(result); } public static object average(object obj, JUSTContext context) { JToken token = JToken.FromObject(obj); if (obj is string path && path.StartsWith(context.Resolve<T>(token).RootReference)) { return Average(JToken.FromObject(valueof(path, context)), context); } else { return Average(token, context); } } private static object Average(JToken token, JUSTContext context) { decimal result = 0; JArray parsedArray = token as JArray; if (token != null) { foreach (JToken child in token.Children()) { result += Convert.ToDecimal(child.ToString()); } } return TypedNumber(result / parsedArray.Count); } public static object averageatpath(JArray parsedArray, string path, JUSTContext context) { decimal result = 0; if (parsedArray != null) { foreach (JToken token in parsedArray.Children()) { var selector = context.Resolve<T>(token); JToken selectedToken = selector.Select(path); result += Convert.ToDecimal(selectedToken.ToString()); } } return TypedNumber(result / parsedArray.Count); } public static object max(object obj, JUSTContext context) { JToken token = JToken.FromObject(obj); if (obj is string path && path.StartsWith(context.Resolve<T>(token).RootReference)) { return Max(JToken.FromObject(valueof(path, context)), context); } else { return Max(token, context); } } private static object Max(JToken token, JUSTContext context) { decimal result = 0; if (token != null) { foreach (JToken child in token.Children()) { result = Max(result, child); } } return TypedNumber(result); } private static decimal Max(decimal d1, JToken token) { decimal thisValue = Convert.ToDecimal(token.ToString()); return Math.Max(d1, thisValue); } public static object maxatpath(JArray parsedArray, string path, JUSTContext context) { decimal result = 0; if (parsedArray != null) { foreach (JToken token in parsedArray.Children()) { var selector = context.Resolve<T>(token); JToken selectedToken = selector.Select(path); result = Max(result, selectedToken); } } return TypedNumber(result); } public static object min(object obj, JUSTContext context) { JToken token = JToken.FromObject(obj); if (obj is string path && path.StartsWith(context.Resolve<T>(token).RootReference)) { return Min(JToken.FromObject(valueof(path, context)), context); } else { return Min(token, context); } } private static object Min(JToken token, JUSTContext context) { decimal result = decimal.MaxValue; if (token != null) { foreach (JToken child in token.Children()) { decimal thisValue = Convert.ToDecimal(child.ToString()); result = Math.Min(result, thisValue); } } return TypedNumber(result); } public static object minatpath(JArray parsedArray, string path, JUSTContext context) { decimal result = decimal.MaxValue; if (parsedArray != null) { foreach (JToken token in parsedArray.Children()) { var selector = context.Resolve<T>(token); JToken selectedToken = selector.Select(path); decimal thisValue = Convert.ToDecimal(selectedToken.ToString()); result = Math.Min(result, thisValue); } } return TypedNumber(result); } public static int arraylength(string array, JUSTContext context) { JArray parsedArray = JArray.Parse(array); return parsedArray.Count; } #endregion #region arraylooping public static object currentvalue(JArray array, JToken currentElement) { return GetValue(currentElement); } public static int currentindex(JArray array, JToken currentElement) { return array.IndexOf(currentElement); } public static object lastvalue(JArray array, JToken currentElement) { return GetValue(array.Last); } public static int lastindex(JArray array, JToken currentElement) { return array.Count - 1; } public static object currentvalueatpath(JArray array, JToken currentElement, string path, JUSTContext context) { var selector = context.Resolve<T>(currentElement); JToken selectedToken = selector.Select(path); return GetValue(selectedToken); } public static object currentproperty(JArray array, JToken currentElement, JUSTContext context) { var prop = (currentElement.First as JProperty); if (prop == null && context.IsStrictMode()) { throw new InvalidOperationException("Element is not a property: " + prop.ToString()); } return prop.Name; } public static object lastvalueatpath(JArray array, JToken currentElement, string path, JUSTContext context) { var selector = context.Resolve<T>(array.Last); JToken selectedToken = selector.Select(path); return GetValue(selectedToken); } #endregion #region date functions public static string formatdate(string string1, string string2, JUSTContext context) { try { var date = Convert.ToDateTime(string1); return date.ToString(string2); } catch { return null; } } public static string currentdate(JUSTContext context) { return DateTime.Now.ToString(); } #endregion #region date functions public static string dateformat(string string1, string string2, JUSTContext context) { try { var date = Convert.ToDateTime(string1); return date.ToString(string2); } catch { return null; } } #endregion #region Constants public static string constant_comma(JUSTContext context) { return ","; } public static string constant_hash(JUSTContext context) { return "#"; } #endregion #region Variable parameter functions public static object xconcat(object[] list) { object result = null; for (int i = 0; i < list.Length - 1; i++) { if (list[i] != null) { result = concat(result, list[i], null); } } return result; } public static object xadd(object[] list) { JUSTContext context = list[list.Length - 1] as JUSTContext; decimal add = 0; for (int i = 0; i < list.Length - 1; i++) { if (list[i] != null) add += (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[i], context.EvaluationMode); } return TypedNumber(add); } #endregion #region grouparrayby public static JArray grouparrayby(string path, string groupingElement, string groupedElement, JUSTContext context) { JArray result; var selector = context.Resolve<T>(context.Input); JArray arr = (JArray)selector.Select(path); if (!groupingElement.Contains(":")) { result = Utilities.GroupArray<T>(arr, groupingElement, groupedElement, context); } else { string[] groupingElements = groupingElement.Split(':'); result = Utilities.GroupArrayMultipleProperties<T>(arr, groupingElements, groupedElement, context); } return result; } #endregion #region operators public static bool stringequals(object[] list) { bool result = false; if (list.Length >= 2) { var context = (list.Length > 2) ? (JUSTContext)list[2] : new JUSTContext(); if (ComparisonHelper.Equals(list[0], list[1], context.EvaluationMode)) result = true; } return result; } public static bool stringcontains(object[] list) { bool result = false; if (list.Length >= 2) { var context = (list.Length > 2) ? (JUSTContext)list[2] : new JUSTContext(); result = ComparisonHelper.Contains(list[0], list[1], context.EvaluationMode); } return result; } public static bool mathequals(object[] list) { bool result = false; if (list.Length >= 2) { decimal lshDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[0], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); decimal rhsDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[1], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); result = lshDecimal == rhsDecimal; } return result; } public static bool mathgreaterthan(object[] list) { bool result = false; if (list.Length >= 2) { decimal lshDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[0], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); decimal rhsDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[1], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); result = lshDecimal > rhsDecimal; } return result; } public static bool mathlessthan(object[] list) { bool result = false; if (list.Length >= 2) { decimal lshDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[0], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); decimal rhsDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[1], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); result = lshDecimal < rhsDecimal; } return result; } public static bool mathgreaterthanorequalto(object[] list) { bool result = false; if (list.Length >= 2) { decimal lshDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[0], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); decimal rhsDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[1], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); result = lshDecimal >= rhsDecimal; } return result; } public static bool mathlessthanorequalto(object[] list) { bool result = false; if (list.Length >= 2) { decimal lshDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[0], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); decimal rhsDecimal = (decimal)ReflectionHelper.GetTypedValue(typeof(decimal), list[1], list.Length >= 3 ? ((JUSTContext)list[2]).EvaluationMode : EvaluationMode.Strict); result = lshDecimal <= rhsDecimal; } return result; } #endregion public static object tointeger(object val, JUSTContext context) { return ReflectionHelper.GetTypedValue(typeof(int), val, context.EvaluationMode); } public static object tostring(object val, JUSTContext context) { return ReflectionHelper.GetTypedValue(typeof(string), val, context.EvaluationMode); } public static object toboolean(object val, JUSTContext context) { return ReflectionHelper.GetTypedValue(typeof(bool), val, context.EvaluationMode); } public static decimal todecimal(object val, JUSTContext context) { return decimal.Round((decimal)ReflectionHelper.GetTypedValue(typeof(decimal), val, context.EvaluationMode), context.DefaultDecimalPlaces); } public static decimal round(decimal val, int decimalPlaces, JUSTContext context) { return decimal.Round(val, decimalPlaces, MidpointRounding.AwayFromZero); } public static int length(object val, JUSTContext context) { int result = 0; if (val is string path && path.StartsWith(context.Resolve<T>(null).RootReference)) { result = length(valueof(path, context), context); } else if (val is IEnumerable enumerable) { var enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { result++; } } else { if (context.IsStrictMode()) { throw new ArgumentException($"Argument not elegible for #length: {val}"); } } return result; } } }
33.335467
150
0.502785
3d9921f39835271633e48ba471f67b925e7782ae
2,395
cs
C#
Assets/Scripts/Level/LevelGeneratorController.cs
Elrohil44/StairMaze
667451c3a57ce423728b1f55316e51dda898a042
[ "MIT" ]
null
null
null
Assets/Scripts/Level/LevelGeneratorController.cs
Elrohil44/StairMaze
667451c3a57ce423728b1f55316e51dda898a042
[ "MIT" ]
null
null
null
Assets/Scripts/Level/LevelGeneratorController.cs
Elrohil44/StairMaze
667451c3a57ce423728b1f55316e51dda898a042
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; public class LevelGeneratorController : MonoBehaviour { public GameObject Player; public GameObject LevelPrefab; private List<Level> levels = new List<Level>(); private int currentLevel = 0; private int seed = Settings.seed; void Start() { UpdateLevelDeque(); Player.transform.position = new Vector3(0, 1f, 0); } void Update() { if (Player != null) { int playerLevel = (int)Math.Ceiling(-Player.transform.position.y / this.transform.localScale.y); if (playerLevel > currentLevel) { Debug.Log("Transition from level " + currentLevel.ToString() + " to level " + playerLevel); currentLevel = playerLevel; this.UpdateLevelDeque(); } } } void UpdateLevelDeque() { var expectedLevelNumbers = new List<int>(); if (currentLevel - 1 >= 0) expectedLevelNumbers.Add((currentLevel - 1)); if (currentLevel - 2 >= 0) expectedLevelNumbers.Add((currentLevel - 2)); expectedLevelNumbers.Add(currentLevel); expectedLevelNumbers.Add(currentLevel + 1); expectedLevelNumbers.Add(currentLevel + 2); // todo: remove old entries foreach (Level level in levels) { if (!expectedLevelNumbers.Contains(level.number)) { if (level.gameObject != null) Destroy(level.gameObject); } else { expectedLevelNumbers.Remove(level.number); } } foreach (int levelNo in expectedLevelNumbers) { Level newLevel = new Level(); newLevel.number = levelNo; newLevel.gameObject = Instantiate(LevelPrefab, transform); newLevel.gameObject.transform.localPosition = new Vector3(0, -levelNo, 0); newLevel.gameObject.GetComponent<MazeGenerator>().level = levelNo; newLevel.gameObject.GetComponent<MazeGenerator>().seed = seed; newLevel.gameObject.name = levelNo.ToString(); Debug.Log("Created level " + levelNo); levels.Add(newLevel); } } } struct Level { public GameObject gameObject; public int number; }
31.103896
108
0.589979
3d9a0546bf8eae1f4704747dfe0bb7456b9373de
1,814
cs
C#
Composition/AttributeBasedSample/AttributeBasedSample/AdvancedCalculator/Calculator.cs
okyuanzhui/bb
6697c94a365d6dfdd32e84b29a1d55ff84dee053
[ "MIT" ]
479
2017-06-26T01:37:33.000Z
2022-03-27T13:04:14.000Z
Composition/AttributeBasedSample/AttributeBasedSample/AdvancedCalculator/Calculator.cs
lifejoyforpy/ProfessionalCSharp7
cf083cbb389644c40a0f3ad1dd6d1036c80b80f0
[ "MIT" ]
11
2018-05-11T12:54:59.000Z
2021-04-08T22:14:02.000Z
Composition/AttributeBasedSample/AttributeBasedSample/AdvancedCalculator/Calculator.cs
lifejoyforpy/ProfessionalCSharp7
cf083cbb389644c40a0f3ad1dd6d1036c80b80f0
[ "MIT" ]
266
2017-06-29T19:45:57.000Z
2022-03-29T12:22:19.000Z
using System; using System.Collections.Generic; using System.Composition; namespace Wrox.ProCSharp.Composition { [Export(typeof(ICalculator))] public class Calculator : ICalculator { public IList<IOperation> GetOperations() => new List<IOperation>() { new Operation { Name="+", NumberOperands=2}, new Operation { Name="-", NumberOperands=2}, new Operation { Name="/", NumberOperands=2}, new Operation { Name="*", NumberOperands=2}, new Operation { Name="%", NumberOperands=2}, new Operation { Name="++", NumberOperands=1}, new Operation { Name="--", NumberOperands=1} }; public double Operate(IOperation operation, double[] operands) { double result = 0; switch (operation.Name) { case "+": result = operands[0] + operands[1]; break; case "-": result = operands[0] - operands[1]; break; case "/": result = operands[0] / operands[1]; break; case "*": result = operands[0] * operands[1]; break; case "%": result = operands[0] % operands[1]; break; case "++": result = ++operands[0]; break; case "--": result = --operands[0]; break; default: throw new InvalidOperationException($"invalid operation {operation.Name}"); } return result; } } }
32.981818
95
0.438809
3d9ad21f87eef169b207868ca678cf555df517b7
7,123
cs
C#
WaterPreview/WaterPreview/Controllers/HomeController.cs
Kate605690919/Water-Preview
2472f64fb1bfc01a910545dcc10b967e19de78ef
[ "MIT" ]
null
null
null
WaterPreview/WaterPreview/Controllers/HomeController.cs
Kate605690919/Water-Preview
2472f64fb1bfc01a910545dcc10b967e19de78ef
[ "MIT" ]
null
null
null
WaterPreview/WaterPreview/Controllers/HomeController.cs
Kate605690919/Water-Preview
2472f64fb1bfc01a910545dcc10b967e19de78ef
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using WaterPreview.Base; using WaterPreview.Other; using WaterPreview.Other.Attribute; using WaterPreview.Other.Client; using WaterPreview.Redis; using WaterPreview.Service; using WaterPreview.Service.Interface; using WaterPreview.Service.Service; namespace WaterPreview.Controllers { public class HomeController : Controller { private IAccountService accountService; private IRoleService roleService; private IUserInnerRoleService userInnerRoleService; public HomeController() { accountService = new AccountService(); roleService = new RoleService(); userInnerRoleService = new UserInnerRoleService(); } [AllowAnonymous] public ActionResult Login() { ViewBag.Exception = false; return View(); } [HttpPost] [AllowAnonymous] public JsonResult Login(string userName, string password) { JsonResult result= new JsonResult(); User_t user = accountService.GetAccountByName(userName); if (user.Usr_UId == new Guid() || user.Usr_Password != MD5_Util.MD5Encrypt(password)) { ViewBag.Exception = true; result.Data = false; return result; } password = MD5_Util.MD5Encrypt(password); Response.Headers.Add("username", user.Usr_Name); Response.Headers.Add("useruid", user.Usr_UId.ToString()); //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Value = user.Usr_UId.ToString(); //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Domain = ConfigurationManager.AppSettings["DomainName"]; //Response.Cookies[ConfigurationManager.AppSettings["CookieName"]].Expires = DateTime.Now.AddDays(1); //Response.Cookies["username"].Value = user.Usr_Name; //Response.Cookies["username"].Domain = ConfigurationManager.AppSettings["DomainName"]; //Response.Cookies["username"].Expires = DateTime.Now.AddDays(1); HttpClientCrant client = new HttpClientCrant(); client.Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant(userName,password); UserContext.account = user; //return RedirectToAction("index"); //return View("index"); var userInnerRoles = userInnerRoleService.GetByUid(user.Usr_UId); List<InnerRole_t> roleLists = new List<InnerRole_t>(); foreach (var item in userInnerRoles) { var role = roleService.GetRoles(item.UIr_IrUId); if(role != null) { roleLists.Add(role); } } var names = new List<String>(); foreach (var item in roleLists) { var name = item.Ir_Name; names.Add(name); } //var roles = new List<String>(); RoleHelper.Role personalRole = new RoleHelper.Role(); foreach (var item in names) { switch (item) { case "总查看员": RoleHelper.GetAllPermission(personalRole); break; case "流量计查看员": RoleHelper.GetFlowMeterViewPermission(personalRole); break; case "流量计管理员": RoleHelper.GetClientManagePermission(personalRole); break; case "压力计查看员": RoleHelper.GetPressureMeterViewPermission(personalRole); break; case "压力计管理员": RoleHelper.GetPressureMeterManagePermission(personalRole); break; case "水质计查看员": RoleHelper.GetQualityMeterViewPermission(personalRole); break; case "水质计管理员": RoleHelper.GetQualityMeterManagePermission(personalRole); break; case "区域查看员": RoleHelper.GetAreaViewPermission(personalRole); break; case "区域管理员": RoleHelper.GetAreaManagePermission(personalRole); break; case "客户查看员": RoleHelper.GetClientViewPermission(personalRole); break; case "客户管理员": RoleHelper.GetClientManagePermission(personalRole); break; case "职员查看员": result.Data = RoleHelper.GetStaffViewPermission(personalRole); break; case "职员管理员": RoleHelper.GetStaffManagePermission(personalRole); break; case "职位查看员": RoleHelper.GetRolesViewPermission(personalRole); break; case "职位管理员": RoleHelper.GetRolesManagePermission(personalRole); break; } } result.Data = personalRole; return result; } [Login(IsCheck=true)] [AllowAnonymous] public ActionResult Index() { return View(); } public JsonResult LogOut() { JsonResult result = new JsonResult(); User_t account = UserContext.account; try { //清除token和账号uid对应缓存 DBHelper.SetExpire(ConfigurationManager.AppSettings["tokenByUserUid"] + UserContext.account.Usr_UId); DBHelper.SetExpire("token-" + UserContext.access_token); UserContext.access_token = UserContext.access_token != null ? "" : UserContext.access_token; //清除用户信息上下文 account = account != null && account.Usr_UId != new Guid() ? account : new User_t(); //清除可能的cookie HttpCookie cookiename = Request.Cookies["username"]; if (cookiename != null) { cookiename.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookiename); } HttpCookie cookieuid = Request.Cookies["useruid"]; if (cookieuid != null) { cookieuid.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookieuid); } result.Data = true; } catch { result.Data = false; } return result; } } }
39.137363
135
0.522813
3d9b46a8f30e2daadfeb645a53a0abd815e7405c
4,171
cs
C#
tests/src/CoreMangLib/cti/system/char/chargethashcode.cs
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
10
2015-11-03T16:35:25.000Z
2021-07-31T16:36:29.000Z
tests/src/CoreMangLib/cti/system/char/chargethashcode.cs
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
1
2019-03-05T18:50:09.000Z
2019-03-05T18:50:09.000Z
tests/src/CoreMangLib/cti/system/char/chargethashcode.cs
CyberSys/coreclr-mono
83b2cb83b32faa45b4f790237b5c5e259692294a
[ "MIT" ]
4
2015-10-28T12:26:26.000Z
2021-09-04T11:36:04.000Z
using System; /// <summary> /// Char.GetHashCode() /// Returns the hash code for this instance. /// </summary> public class CharGetHashCode { public static int Main() { CharGetHashCode testObj = new CharGetHashCode(); TestLibrary.TestFramework.BeginTestCase("for method: Char.GetHashCode()"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = "PosTest1: char.MaxValue"; string errorDesc; int expectedValue; int actualValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedValue = (int)char.MaxValue | ((int)char.MaxValue << 16); actualValue = char.MaxValue.GetHashCode(); if (actualValue != expectedValue) { errorDesc = "Hash code of char.MaxValue is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = "PosTest2: char.MinValue"; string errorDesc; int expectedValue; int actualValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { expectedValue = (int)char.MinValue | ((int)char.MinValue << 16); actualValue = char.MinValue.GetHashCode(); if (actualValue != expectedValue) { errorDesc = "Hash code of char.MinValue is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: random character value"; string errorDesc; int expectedValue; int actualValue; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { char ch = TestLibrary.Generator.GetChar(-55); expectedValue = (int)ch | ((int)ch << 16); actualValue = ch.GetHashCode(); if (actualValue != expectedValue) { errorDesc = string.Format("Hash code of \'\\u{0:x}\' is not {1} as expected: Actual({2})", (int)ch, expectedValue, actualValue); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } }
29.58156
144
0.550468
3d9d36965a311acbe6148b1e09637461b08f2804
6,593
cs
C#
src/aspCart.Web/ViewComponents/FilterViewComponent.cs
workingrom/aspCart
c16a1ba7f0518187ef4abd94b74d570cbf27ce01
[ "MIT" ]
null
null
null
src/aspCart.Web/ViewComponents/FilterViewComponent.cs
workingrom/aspCart
c16a1ba7f0518187ef4abd94b74d570cbf27ce01
[ "MIT" ]
null
null
null
src/aspCart.Web/ViewComponents/FilterViewComponent.cs
workingrom/aspCart
c16a1ba7f0518187ef4abd94b74d570cbf27ce01
[ "MIT" ]
null
null
null
using aspCart.Core.Interface.Services.Catalog; using aspCart.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace aspCart.Web.ViewComponents { [ViewComponent(Name = "Filter")] public class FilterViewComponent : ViewComponent { #region Fields private readonly ICategoryService _categoryService; private readonly IManufacturerService _manufacturerService; private readonly IProductService _productService; #endregion #region Constructor public FilterViewComponent( ICategoryService categoryService, IManufacturerService manufacturerService, IProductService productService) { _categoryService = categoryService; _manufacturerService = manufacturerService; _productService = productService; } #endregion #region Methods public IViewComponentResult Invoke(string nameFilter = "", string categoryFilter = "", string manufacturerFilter = "" ) { // // category filter // var categoryFilterViewModel = new List<CategoryFilterViewModel>(); var allCategories = _categoryService.GetAllCategoriesWithoutParent(); foreach(var category in allCategories) { var filterModel = new CategoryFilterViewModel { Name = category.Name, Id = category.Id }; var qty = 0; if(nameFilter.Length > 0) { qty = filterModel.Quantity = _productService.Table() .Include(x => x.Categories).ThenInclude(x => x.Category) .Where(x => x.Name.ToLower().Contains(nameFilter.ToLower())) .Where(x => x.Categories.Any(c => c.Category.SeoUrl.ToLower() == category.SeoUrl.ToLower())) .Where(x => x.Published == true) .AsNoTracking() .Count(); } if(manufacturerFilter.Length > 0) { qty = filterModel.Quantity = _productService.Table() .Include(x => x.Categories).ThenInclude(x => x.Category) .Include(x => x.Manufacturers).ThenInclude(x => x.Manufacturer) .Where(x => x.Manufacturers.Any(m => m.Manufacturer.Name.ToLower() == manufacturerFilter.ToLower())) .Where(x => x.Categories.Any(c => c.Category.SeoUrl.ToLower() == category.SeoUrl.ToLower())) .Where(x => x.Published == true) .AsNoTracking() .Count(); } if (qty > 0) { categoryFilterViewModel.Add(filterModel); } } // // manufacturer filter // var manufacturerFilterViewModel = new List<ManufacturerFilterViewModel>(); var allManufacturer = _manufacturerService.GetAllManufacturers(); foreach(var manufacturer in allManufacturer) { var filterModel = new ManufacturerFilterViewModel { Name = manufacturer.Name, Id = manufacturer.Id }; var qty = 0; qty = filterModel.Quantity = _productService.Table() .Include(x => x.Categories).ThenInclude(x => x.Category) .Include(x => x.Manufacturers).ThenInclude(x => x.Manufacturer) .Where(x => x.Manufacturers.Any(m => m.Manufacturer.Name.ToLower() == manufacturer.Name.ToLower())) .Where(x => x.Categories.Any(c => c.Category.Name.ToLower() == categoryFilter.ToLower())) .Where(x => x.Published == true) .AsNoTracking() .Count(); if (qty > 0) { manufacturerFilterViewModel.Add(filterModel); } } // // price filter // var allProducts = _productService.Table() .Include(x => x.Categories).ThenInclude(x => x.Category) .Include(x => x.Manufacturers).ThenInclude(x => x.Manufacturer) .Where( x=> x.Published == true) .AsNoTracking() .ToList(); bool showPrice = false; if(nameFilter.Length > 0) { allProducts = allProducts .Where(x => x.Name.ToLower().Contains(nameFilter.ToLower())) .ToList(); showPrice = true; } if(manufacturerFilter.Length > 0) { allProducts = allProducts .Where(x => x.Manufacturers.Any(m => m.Manufacturer.Name.ToLower() == manufacturerFilter.ToLower())) .ToList(); showPrice = true; } if (categoryFilter.Length > 0) { allProducts = allProducts .Where(x => x.Categories.Any(m => m.Category.Name.ToLower() == categoryFilter.ToLower())) .ToList(); showPrice = true; } List<int> range = new List<int>(); List<IGrouping<int, decimal>> groupings = new List<IGrouping<int, decimal>>(); List<decimal> allPrices = allProducts.Select(x => x.Price).ToList(); if (showPrice) { range = new List<int> { 0, 100, 250, 500, 750, 1000, 1500, 2000, 3000, 4000, 5000, 10000 }; groupings = allPrices.GroupBy(price => range.FirstOrDefault(r => r >= price)).ToList(); } // // result // var result = new FilterViewModel(); result.CategoryFilterViewModel = categoryFilterViewModel; result.ManufacturerFilterViewModel = manufacturerFilterViewModel; result.PriceGroupings = groupings.OrderBy(x => x.Key); result.PriceRange = range; if (nameFilter.Length > 0) { result.FilterType = "name"; ViewData["name"] = nameFilter; } if (manufacturerFilter.Length > 0) { result.FilterType = "manufacturer"; } if (categoryFilter.Length > 0) { result.FilterType = "category"; } return View(result); } #endregion } }
37.039326
127
0.531321
3d9f6be3dd310469988a0f092affd91d5e849a55
4,466
cs
C#
src/ClusterClientHostedService.cs
gonac/FanoutAPIV2
3690f1b46540d9818c1927502089cf3a951955e4
[ "MIT" ]
1
2021-05-31T16:02:39.000Z
2021-05-31T16:02:39.000Z
src/ClusterClientHostedService.cs
gonac/FanoutAPIV2
3690f1b46540d9818c1927502089cf3a951955e4
[ "MIT" ]
null
null
null
src/ClusterClientHostedService.cs
gonac/FanoutAPIV2
3690f1b46540d9818c1927502089cf3a951955e4
[ "MIT" ]
1
2021-06-02T15:14:31.000Z
2021-06-02T15:14:31.000Z
using System; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Configuration; using Orleans.Runtime; namespace FanoutAPIV2 { public class ClusterClientHostedService : IHostedService { private readonly ILogger<ClusterClientHostedService> _logger; public IClusterClient Client { get; } public ClusterClientHostedService( ILogger<ClusterClientHostedService> logger, ILoggerProvider loggerProvider) { _logger = logger; _logger.LogInformation("creating cluster client..."); var advertisedIp = Environment.GetEnvironmentVariable("ADVERTISEDIP"); var siloAdvertisedIpAddress = advertisedIp == null ? GetLocalIpAddress() : IPAddress.Parse(advertisedIp); var extractedGatewayPort = Environment.GetEnvironmentVariable("GATEWAYPORT") ?? throw new Exception("Gateway port cannot be null"); var siloGatewayPort = int.Parse(extractedGatewayPort); Client = new ClientBuilder() .Configure<ClusterOptions>(clusterOptions => { clusterOptions.ClusterId = "cluster-of-silos"; clusterOptions.ServiceId = "hello-world-service"; }) .UseStaticClustering(new IPEndPoint(siloAdvertisedIpAddress, siloGatewayPort)) .ConfigureLogging(loggingBuilder => loggingBuilder.SetMinimumLevel(LogLevel.Information).AddProvider(loggerProvider)) .Build(); _logger.LogInformation("cluster client created"); } public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("connecting cluster client..."); var attempt = 0; var maxAttempts = 100; var delay = TimeSpan.FromSeconds(1); return Client.Connect(async error => { if (cancellationToken.IsCancellationRequested) { return false; } if (++attempt < maxAttempts) { _logger.LogWarning( error, "Failed to connect to Orleans cluster on attempt {@Attempt} of {@MaxAttempts}.", attempt, maxAttempts); try { await Task.Delay(delay, cancellationToken); } catch (OperationCanceledException) { return false; } return true; } _logger.LogError( error, "Failed to connect to Orleans cluster on attempt {@Attempt} of {@MaxAttempts}.", attempt, maxAttempts); return false; }); } public async Task StopAsync(CancellationToken cancellationToken) { try { await Client.Close(); } catch (OrleansException error) { _logger.LogWarning( error, "Error while gracefully disconnecting from Orleans cluster. Will ignore and continue to shutdown."); } } private static IPAddress GetLocalIpAddress() { var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (var network in networkInterfaces) { if (network.OperationalStatus != OperationalStatus.Up) continue; var properties = network.GetIPProperties(); if (properties.GatewayAddresses.Count == 0) continue; foreach (var address in properties.UnicastAddresses) { if (address.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(address.Address)) { return address.Address; } } } return null; } } }
34.091603
144
0.535826
3d9fe753bec6fc0ed37c7e5e7cb4e81b68a785d3
10,069
cs
C#
external/QuickGraph/Sandwych.QuickGraph.Graphviz/Dot/GraphvizEdge.cs
mikhail-khalizev/max
dd20e7f3a8a0972a4240d240fea0b2e89938983b
[ "Apache-2.0" ]
3
2020-08-04T13:18:57.000Z
2020-12-06T20:22:19.000Z
external/QuickGraph/Sandwych.QuickGraph.Graphviz/Dot/GraphvizEdge.cs
mikhail-khalizev/max
dd20e7f3a8a0972a4240d240fea0b2e89938983b
[ "Apache-2.0" ]
null
null
null
external/QuickGraph/Sandwych.QuickGraph.Graphviz/Dot/GraphvizEdge.cs
mikhail-khalizev/max
dd20e7f3a8a0972a4240d240fea0b2e89938983b
[ "Apache-2.0" ]
null
null
null
namespace QuickGraph.Graphviz.Dot { using System; using System.IO; using System.Collections.Generic; public class GraphvizEdge { private string comment = null; private GraphvizEdgeDirection dir = GraphvizEdgeDirection.Forward; private GraphvizFont font = null; private GraphvizColor fontGraphvizColor = GraphvizColor.Black; private GraphvizEdgeExtremity head = new GraphvizEdgeExtremity(true); private GraphvizArrow headArrow = null; private bool isConstrained = true; private bool isDecorated = false; private GraphvizEdgeLabel label = new GraphvizEdgeLabel(); private GraphvizLayer layer = null; private int minLength = 1; private GraphvizColor strokeGraphvizColor = GraphvizColor.Black; private GraphvizEdgeStyle style = GraphvizEdgeStyle.Unspecified; private GraphvizEdgeExtremity tail = new GraphvizEdgeExtremity(false); private GraphvizArrow tailArrow = null; private string tooltip = null; private string url = null; private double weight = 1; private int length = 1; internal string GenerateDot(Dictionary<string, object> pairs) { bool flag = false; StringWriter writer = new StringWriter(); foreach (var entry in pairs) { if (flag) { writer.Write(", "); } else { flag = true; } if (entry.Value is string) { writer.Write("{0}=\"{1}\"", entry.Key.ToString(), entry.Value.ToString()); continue; } if (entry.Value is GraphvizEdgeDirection) { writer.Write("{0}={1}", entry.Key.ToString(), ((GraphvizEdgeDirection) entry.Value).ToString().ToLower()); continue; } if (entry.Value is GraphvizEdgeStyle) { writer.Write("{0}={1}", entry.Key.ToString(), ((GraphvizEdgeStyle) entry.Value).ToString().ToLower()); continue; } if (entry.Value is GraphvizColor) { GraphvizColor GraphvizColor = (GraphvizColor) entry.Value; writer.Write("{0}=\"#{1}{2}{3}{4}\"", new object[] { entry.Key.ToString(), GraphvizColor.R.ToString("x2").ToUpper(), GraphvizColor.G.ToString("x2").ToUpper(), GraphvizColor.B.ToString("x2").ToUpper(), GraphvizColor.A.ToString("x2").ToUpper() }); continue; } writer.Write(" {0}={1}", entry.Key.ToString(), entry.Value.ToString().ToLower()); } return writer.ToString(); } public string ToDot() { var dic = new Dictionary<string, object>(StringComparer.Ordinal); if (this.Comment != null) { dic["comment"] = this.Comment; } if (this.Dir != GraphvizEdgeDirection.Forward) { dic["dir"] = this.Dir.ToString().ToLower(); } if (this.Font != null) { dic["fontname"] = this.Font.Name; dic["fontsize"] = this.Font.SizeInPoints; } if (!this.FontGraphvizColor.Equals(GraphvizColor.Black)) { dic["fontGraphvizColor"] = this.FontGraphvizColor; } this.Head.AddParameters(dic); if (this.HeadArrow != null) { dic["arrowhead"] = this.HeadArrow.ToDot(); } if (!this.IsConstrained) { dic["constraint"] = this.IsConstrained; } if (this.IsDecorated) { dic["decorate"] = this.IsDecorated; } this.Label.AddParameters(dic); if (this.Layer != null) { dic["layer"] = this.Layer.Name; } if (this.MinLength != 1) { dic["minlen"] = this.MinLength; } if (!this.StrokeGraphvizColor.Equals(GraphvizColor.Black)) { dic["GraphvizColor"] = this.StrokeGraphvizColor; } if (this.Style != GraphvizEdgeStyle.Unspecified) { dic["style"] = this.Style.ToString().ToLower(); } this.Tail.AddParameters(dic); if (this.TailArrow != null) { dic["arrowtail"] = this.TailArrow.ToDot(); } if (this.ToolTip != null) { dic["tooltip"] = this.ToolTip; } if (this.Url != null) { dic["URL"] = this.Url; } if (this.Weight != 1) { dic["weight"] = this.Weight; } if (this.HeadPort != null) dic["headport"] = this.HeadPort; if (this.TailPort != null) dic["tailport"] = this.TailPort; if (this.length != 1) dic["len"] = this.length; return this.GenerateDot(dic); } public override string ToString() { return this.ToDot(); } public string Comment { get { return this.comment; } set { this.comment = value; } } public GraphvizEdgeDirection Dir { get { return this.dir; } set { this.dir = value; } } public GraphvizFont Font { get { return this.font; } set { this.font = value; } } public GraphvizColor FontGraphvizColor { get { return this.fontGraphvizColor; } set { this.fontGraphvizColor = value; } } public GraphvizEdgeExtremity Head { get { return this.head; } set { this.head = value; } } public GraphvizArrow HeadArrow { get { return this.headArrow; } set { this.headArrow = value; } } public bool IsConstrained { get { return this.isConstrained; } set { this.isConstrained = value; } } public bool IsDecorated { get { return this.isDecorated; } set { this.isDecorated = value; } } public GraphvizEdgeLabel Label { get { return this.label; } set { this.label = value; } } public GraphvizLayer Layer { get { return this.layer; } set { this.layer = value; } } public int MinLength { get { return this.minLength; } set { this.minLength = value; } } public GraphvizColor StrokeGraphvizColor { get { return this.strokeGraphvizColor; } set { this.strokeGraphvizColor = value; } } public GraphvizEdgeStyle Style { get { return this.style; } set { this.style = value; } } public GraphvizEdgeExtremity Tail { get { return this.tail; } set { this.tail = value; } } public GraphvizArrow TailArrow { get { return this.tailArrow; } set { this.tailArrow = value; } } public string ToolTip { get { return this.tooltip; } set { this.tooltip = value; } } public string Url { get { return this.url; } set { this.url = value; } } public double Weight { get { return this.weight; } set { this.weight = value; } } public string HeadPort { get; set; } public string TailPort {get;set;} public int Length { get { return this.length; } set { this.length = value; } } } }
26.708223
266
0.394279
3da074ee5a2653a237739271c162af0ddfc31362
7,178
cs
C#
src/Assets.Tools.Script.Helper/GameObjectUtilities.cs
moto2002/kaituo_src
a75fe94ede2ef27ce87047f5b760ab855ab36eec
[ "MIT" ]
1
2018-08-28T12:20:57.000Z
2018-08-28T12:20:57.000Z
src/Assets.Tools.Script.Helper/GameObjectUtilities.cs
moto2002/kaituo_src
a75fe94ede2ef27ce87047f5b760ab855ab36eec
[ "MIT" ]
null
null
null
src/Assets.Tools.Script.Helper/GameObjectUtilities.cs
moto2002/kaituo_src
a75fe94ede2ef27ce87047f5b760ab855ab36eec
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using UnityEngine; namespace Assets.Tools.Script.Helper { public static class GameObjectUtilities { public static Bounds GetBoundsWithChildren(this GameObject obj) { Renderer[] componentsInChildren = obj.GetComponentsInChildren<Renderer>(); if (componentsInChildren.Length == 0) { throw new Exception("no child in this gameobject"); } Vector3 min = componentsInChildren[0].bounds.min; Vector3 max = componentsInChildren[0].bounds.max; for (int i = 1; i < componentsInChildren.Length; i++) { Renderer renderer = componentsInChildren[i]; if (renderer.bounds.min.x < min.x) { min.x = renderer.bounds.min.x; } if (renderer.bounds.min.y < min.y) { min.y = renderer.bounds.min.y; } if (renderer.bounds.min.z < min.z) { min.z = renderer.bounds.min.z; } if (renderer.bounds.max.x > max.x) { max.x = renderer.bounds.max.x; } if (renderer.bounds.max.y > max.y) { max.y = renderer.bounds.max.y; } if (renderer.bounds.max.z > max.z) { max.z = renderer.bounds.max.z; } } Bounds result = new Bounds((min + max) / 2f, new Vector3(Math.Abs(min.x - max.x), Math.Abs(min.y - max.y), Math.Abs(min.z - max.z))); return result; } public static bool IsActive(this GameObject obj) { return obj && obj.activeInHierarchy; } public static GameObject Parent(this GameObject obj) { if (obj == null || obj.transform.parent == null) { return null; } return obj.transform.parent.gameObject; } public static void ClearChildrenImmediate(this GameObject parent) { List<GameObject> list = new List<GameObject>(); foreach (Transform transform in parent.transform) { list.Add(transform.gameObject); } foreach (GameObject current in list) { UnityEngine.Object.DestroyImmediate(current); } } public static void ClearChildren(this GameObject parent) { List<GameObject> list = new List<GameObject>(); foreach (Transform transform in parent.transform) { list.Add(transform.gameObject); } foreach (GameObject current in list) { UnityEngine.Object.Destroy(current); } } public static GameObject AddEmptyGameObject(this GameObject parent) { return new GameObject { transform = { parent = parent.transform, localPosition = Vector3.zero, localScale = Vector3.one, localRotation = Quaternion.identity }, layer = parent.layer }; } public static GameObject AddInstantiate(this GameObject parent, GameObject src) { return parent.AddInstantiate(src, Vector3.zero, Vector3.one, Quaternion.identity, true); } public static GameObject AddInstantiate(this GameObject parent, GameObject src, Vector3 position, Vector3 scale, Quaternion quaternion, bool withParentLayer = true) { GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(src); gameObject.transform.parent = parent.transform; gameObject.transform.localPosition = position; gameObject.transform.localScale = scale; gameObject.transform.localRotation = quaternion; if (withParentLayer) { gameObject.SetLayerWidthChildren(parent.layer); } return gameObject; } public static List<GameObject> GetChildren(this GameObject parent) { List<GameObject> list = new List<GameObject>(); foreach (Transform transform in parent.transform) { list.Add(transform.gameObject); } return list; } public static GameObject GetChildByName(this GameObject parent, string name) { foreach (Transform transform in parent.transform) { if (transform.gameObject.name == name) { return transform.gameObject; } } return null; } public static GameObject GetParentByName(this GameObject child, string name) { if (child.name == name) { return child; } if (child.transform.parent != null) { return child.transform.parent.gameObject.GetParentByName(name); } return null; } public static bool IsChildBy(this GameObject child, GameObject parent) { Transform[] componentsInChildren = parent.GetComponentsInChildren<Transform>(); for (int i = 0; i < componentsInChildren.Length; i++) { Transform transform = componentsInChildren[i]; if (transform.gameObject == child) { return true; } } return false; } public static Transform GetChildByNameRecursion(this Transform parent, string name) { Transform transform = parent.transform.FindChild(name); if (transform == null) { for (int i = 0; i < parent.transform.childCount; i++) { transform = parent.transform.GetChild(i).GetChildByNameRecursion(name); if (transform != null) { return transform; } } return null; } return transform; } public static void SetLayerWidthChildren(this GameObject parent, int layer) { parent.layer = layer; foreach (Transform transform in parent.transform) { transform.gameObject.SetLayerWidthChildren(layer); } } public static void SetLayerToCameraCullingMask(this GameObject obj, Camera camera) { if (camera.cullingMask == 0) { return; } int num = 1 << obj.layer; int cullingMask = camera.cullingMask; if ((num & cullingMask) == 0) { for (int i = 0; i < 100; i++) { if ((1 << i & cullingMask) != 0) { obj.SetLayerWidthChildren(i); break; } } } } public static void ForEachAllChildren(this Transform obj, Func<Transform, bool> doFunc) { obj.TraverseTransform(doFunc); } private static bool TraverseTransform(this Transform obj, Func<Transform, bool> doFunc) { if (!doFunc(obj)) { return false; } for (int i = 0; i < obj.childCount; i++) { Transform child = obj.GetChild(i); if (!child.TraverseTransform(doFunc)) { return false; } } return true; } public static void NormalizationGameObject(GameObject obj) { obj.transform.localPosition = Vector3.zero; obj.transform.localScale = Vector3.one; } public static void NormalizationTransform(Transform transform) { transform.localPosition = Vector3.zero; transform.localScale = Vector3.one; } public static void SetTransformParentAndNormalization(Transform transform, Transform parent) { transform.parent = parent; transform.localPosition = Vector3.zero; transform.localScale = Vector3.one; } public static void SetGameObjectParentAndNormalization(GameObject obj, Transform parent) { obj.transform.parent = parent; obj.transform.localPosition = Vector3.zero; obj.transform.localScale = Vector3.one; } public static void SetTransformProperty(Transform transform, string name, Transform parent, float localPositionX, float localPositionY, float localPositionZ, float localScaleX, float localScaleY, float localScaleZ) { transform.name = name; transform.parent = parent; transform.localPosition = new Vector3(localPositionX, localPositionY, localPositionZ); transform.localScale = new Vector3(localScaleX, localScaleY, localScaleZ); } } }
25.820144
216
0.684731
3da1b3d5da83c15dbff61d37dd263e2cd2d70b2b
5,981
cs
C#
sdk/src/Services/DataExchange/Generated/Model/ResponseDetails.cs
dariolingotti/aws-sdk-net
d911b68e0d86ac2ffd01e0256aeb4de78a70cdb7
[ "Apache-2.0" ]
1,705
2015-01-15T19:41:21.000Z
2022-03-28T15:25:23.000Z
sdk/src/Services/DataExchange/Generated/Model/ResponseDetails.cs
dariolingotti/aws-sdk-net
d911b68e0d86ac2ffd01e0256aeb4de78a70cdb7
[ "Apache-2.0" ]
1,811
2015-01-05T19:40:22.000Z
2022-03-31T19:57:40.000Z
sdk/src/Services/DataExchange/Generated/Model/ResponseDetails.cs
dariolingotti/aws-sdk-net
d911b68e0d86ac2ffd01e0256aeb4de78a70cdb7
[ "Apache-2.0" ]
839
2015-01-17T12:51:09.000Z
2022-03-28T09:59:50.000Z
/* * 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 dataexchange-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DataExchange.Model { /// <summary> /// Details for the response. /// </summary> public partial class ResponseDetails { private ExportAssetsToS3ResponseDetails _exportAssetsToS3; private ExportAssetToSignedUrlResponseDetails _exportAssetToSignedUrl; private ExportRevisionsToS3ResponseDetails _exportRevisionsToS3; private ImportAssetFromApiGatewayApiResponseDetails _importAssetFromApiGatewayApi; private ImportAssetFromSignedUrlResponseDetails _importAssetFromSignedUrl; private ImportAssetsFromRedshiftDataSharesResponseDetails _importAssetsFromRedshiftDataShares; private ImportAssetsFromS3ResponseDetails _importAssetsFromS3; /// <summary> /// Gets and sets the property ExportAssetsToS3. /// <para> /// Details for the export to Amazon S3 response. /// </para> /// </summary> public ExportAssetsToS3ResponseDetails ExportAssetsToS3 { get { return this._exportAssetsToS3; } set { this._exportAssetsToS3 = value; } } // Check to see if ExportAssetsToS3 property is set internal bool IsSetExportAssetsToS3() { return this._exportAssetsToS3 != null; } /// <summary> /// Gets and sets the property ExportAssetToSignedUrl. /// <para> /// Details for the export to signed URL response. /// </para> /// </summary> public ExportAssetToSignedUrlResponseDetails ExportAssetToSignedUrl { get { return this._exportAssetToSignedUrl; } set { this._exportAssetToSignedUrl = value; } } // Check to see if ExportAssetToSignedUrl property is set internal bool IsSetExportAssetToSignedUrl() { return this._exportAssetToSignedUrl != null; } /// <summary> /// Gets and sets the property ExportRevisionsToS3. /// <para> /// Details for the export revisions to Amazon S3 response. /// </para> /// </summary> public ExportRevisionsToS3ResponseDetails ExportRevisionsToS3 { get { return this._exportRevisionsToS3; } set { this._exportRevisionsToS3 = value; } } // Check to see if ExportRevisionsToS3 property is set internal bool IsSetExportRevisionsToS3() { return this._exportRevisionsToS3 != null; } /// <summary> /// Gets and sets the property ImportAssetFromApiGatewayApi. /// <para> /// The response details. /// </para> /// </summary> public ImportAssetFromApiGatewayApiResponseDetails ImportAssetFromApiGatewayApi { get { return this._importAssetFromApiGatewayApi; } set { this._importAssetFromApiGatewayApi = value; } } // Check to see if ImportAssetFromApiGatewayApi property is set internal bool IsSetImportAssetFromApiGatewayApi() { return this._importAssetFromApiGatewayApi != null; } /// <summary> /// Gets and sets the property ImportAssetFromSignedUrl. /// <para> /// Details for the import from signed URL response. /// </para> /// </summary> public ImportAssetFromSignedUrlResponseDetails ImportAssetFromSignedUrl { get { return this._importAssetFromSignedUrl; } set { this._importAssetFromSignedUrl = value; } } // Check to see if ImportAssetFromSignedUrl property is set internal bool IsSetImportAssetFromSignedUrl() { return this._importAssetFromSignedUrl != null; } /// <summary> /// Gets and sets the property ImportAssetsFromRedshiftDataShares. /// <para> /// Details from an import from Amazon Redshift datashare response. /// </para> /// </summary> public ImportAssetsFromRedshiftDataSharesResponseDetails ImportAssetsFromRedshiftDataShares { get { return this._importAssetsFromRedshiftDataShares; } set { this._importAssetsFromRedshiftDataShares = value; } } // Check to see if ImportAssetsFromRedshiftDataShares property is set internal bool IsSetImportAssetsFromRedshiftDataShares() { return this._importAssetsFromRedshiftDataShares != null; } /// <summary> /// Gets and sets the property ImportAssetsFromS3. /// <para> /// Details for the import from Amazon S3 response. /// </para> /// </summary> public ImportAssetsFromS3ResponseDetails ImportAssetsFromS3 { get { return this._importAssetsFromS3; } set { this._importAssetsFromS3 = value; } } // Check to see if ImportAssetsFromS3 property is set internal bool IsSetImportAssetsFromS3() { return this._importAssetsFromS3 != null; } } }
34.976608
110
0.643203
3da4a0f3a78f96618b0b1d051919bb2cf1ce3b91
4,609
cs
C#
src/Gallio/Gallio/Common/Concurrency/TaskResult.cs
soelske/mbunit-v3
8e561d2cc0653d94c511fa9c60d75f27a84d62e7
[ "ECL-2.0", "Apache-2.0" ]
49
2015-03-13T12:14:29.000Z
2021-12-05T23:10:31.000Z
src/Gallio/Gallio/Common/Concurrency/TaskResult.cs
soelske/mbunit-v3
8e561d2cc0653d94c511fa9c60d75f27a84d62e7
[ "ECL-2.0", "Apache-2.0" ]
9
2015-03-17T18:22:35.000Z
2019-07-17T03:05:30.000Z
src/Gallio/Gallio/Common/Concurrency/TaskResult.cs
soelske/mbunit-v3
8e561d2cc0653d94c511fa9c60d75f27a84d62e7
[ "ECL-2.0", "Apache-2.0" ]
39
2015-03-15T11:53:10.000Z
2021-11-09T03:03:13.000Z
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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 Gallio.Common.Concurrency { /// <summary> /// Holds the value or exception produced by a task. /// </summary> [Serializable] public abstract class TaskResult { private readonly Exception exception; internal TaskResult(Exception exception) { this.exception = exception; } /// <summary> /// Returns true if the task ran to completion and returned a value, /// or false if an exception was thrown. /// </summary> public bool HasValue { get { return exception == null; } } /// <summary> /// Gets the value that was returned by the task. /// </summary> /// <exception cref="InvalidOperationException">Thrown if <see cref="HasValue" /> is false.</exception> public object Value { get { if (!HasValue) throw new InvalidOperationException("The value is not available because the task threw an exception."); return GetValueAsObject(); } } /// <summary> /// Gets the exception that was thrown by the task. /// </summary> /// <exception cref="InvalidOperationException">Thrown if <see cref="HasValue" /> is true.</exception> public Exception Exception { get { if (HasValue) throw new InvalidOperationException("The exception is not available because the task returned a value."); return exception; } } /// <inheritdoc /> public override string ToString() { return (exception ?? GetValueAsObject() ?? string.Empty).ToString(); } internal abstract object GetValueAsObject(); } /// <summary> /// Holds the value or exception produced by a task. /// </summary> [Serializable] public sealed class TaskResult<T> : TaskResult { private readonly T value; private TaskResult(T value, Exception exception) : base(exception) { this.value = value; } /// <summary> /// Creates a result object containing the value returned by the task. /// </summary> /// <returns>The new task result.</returns> /// <param name="value">The value.</param> public static TaskResult<T> CreateFromValue(T value) { return new TaskResult<T>(value, null); } /// <summary> /// Creates a result object containing the exception thrown by the task. /// </summary> /// <param name="exception">The exception.</param> /// <returns>The new task result.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="exception"/> is null.</exception> public static TaskResult<T> CreateFromException(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); return new TaskResult<T>(default(T), exception); } /// <summary> /// Gets the value that was returned by the task. /// </summary> /// <exception cref="InvalidOperationException">Thrown if <see cref="TaskResult.HasValue" /> is false.</exception> new public T Value { get { if (!HasValue) throw new InvalidOperationException("The value is not available because the task threw an exception."); return value; } } internal override object GetValueAsObject() { return value; } } }
33.642336
126
0.561727
3da75823f5fd4dadecbc9d4ee6814ba8e2e9b60c
11,350
cs
C#
Assets/XLua/Gen/Minecraft_Assets_AsyncAssetWrap.cs
Jin-Yuhan/MinecraftClone-Unity
f2e266a9c84330ceb83c4e302d8a7559c92a826f
[ "MIT" ]
60
2020-08-14T07:11:03.000Z
2022-03-26T13:47:46.000Z
Assets/XLua/Gen/Minecraft_Assets_AsyncAssetWrap.cs
Jin-Yuhan/MinecraftClone-Unity
f2e266a9c84330ceb83c4e302d8a7559c92a826f
[ "MIT" ]
1
2021-04-19T13:18:23.000Z
2021-05-04T02:29:45.000Z
Assets/XLua/Gen/Minecraft_Assets_AsyncAssetWrap.cs
Jin-Yuhan/MinecraftClone-Unity
f2e266a9c84330ceb83c4e302d8a7559c92a826f
[ "MIT" ]
15
2020-12-29T18:51:34.000Z
2022-03-24T19:20:48.000Z
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class MinecraftAssetsAsyncAssetWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(Minecraft.Assets.AsyncAsset); Utils.BeginObjectRegister(type, L, translator, 0, 3, 5, 0); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Initialize", _m_Initialize); Utils.RegisterFunc(L, Utils.METHOD_IDX, "UpdateLoadingState", _m_UpdateLoadingState); Utils.RegisterFunc(L, Utils.METHOD_IDX, "Unload", _m_Unload); Utils.RegisterFunc(L, Utils.GETTER_IDX, "IsDone", _g_get_IsDone); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Progress", _g_get_Progress); Utils.RegisterFunc(L, Utils.GETTER_IDX, "AssetName", _g_get_AssetName); Utils.RegisterFunc(L, Utils.GETTER_IDX, "AssetBundle", _g_get_AssetBundle); Utils.RegisterFunc(L, Utils.GETTER_IDX, "Asset", _g_get_Asset); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "WaitAll", _m_WaitAll_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { var gen_ret = new Minecraft.Assets.AsyncAsset(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Initialize(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<System.Type>(L, 3)&& translator.Assignable<Minecraft.Assets.IAssetBundle>(L, 4)) { string _name = LuaAPI.lua_tostring(L, 2); System.Type _type = (System.Type)translator.GetObject(L, 3, typeof(System.Type)); Minecraft.Assets.IAssetBundle _assetBundle = (Minecraft.Assets.IAssetBundle)translator.GetObject(L, 4, typeof(Minecraft.Assets.IAssetBundle)); gen_to_be_invoked.Initialize( _name, _type, _assetBundle ); return 0; } if(gen_param_count == 4&& (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING)&& translator.Assignable<UnityEngine.Object>(L, 3)&& translator.Assignable<Minecraft.Assets.IAssetBundle>(L, 4)) { string _name = LuaAPI.lua_tostring(L, 2); UnityEngine.Object _asset = (UnityEngine.Object)translator.GetObject(L, 3, typeof(UnityEngine.Object)); Minecraft.Assets.IAssetBundle _assetBundle = (Minecraft.Assets.IAssetBundle)translator.GetObject(L, 4, typeof(Minecraft.Assets.IAssetBundle)); gen_to_be_invoked.Initialize( _name, _asset, _assetBundle ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset.Initialize!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_UpdateLoadingState(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); { var gen_ret = gen_to_be_invoked.UpdateLoadingState( ); LuaAPI.lua_pushboolean(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_Unload(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); { gen_to_be_invoked.Unload( ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m_WaitAll_xlua_st_(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); int gen_param_count = LuaAPI.lua_gettop(L); if(gen_param_count >= 0&& (LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, 1) || translator.Assignable<Minecraft.Assets.AsyncAsset>(L, 1))) { Minecraft.Assets.AsyncAsset[] _assets = translator.GetParams<Minecraft.Assets.AsyncAsset>(L, 1); var gen_ret = Minecraft.Assets.AsyncAsset.WaitAll( _assets ); translator.PushAny(L, gen_ret); return 1; } if(gen_param_count == 1&& translator.Assignable<System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>>(L, 1)) { System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset> _assets = (System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>)translator.GetObject(L, 1, typeof(System.Collections.Generic.IReadOnlyList<Minecraft.Assets.AsyncAsset>)); var gen_ret = Minecraft.Assets.AsyncAsset.WaitAll( _assets ); translator.PushAny(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to Minecraft.Assets.AsyncAsset.WaitAll!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_IsDone(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushboolean(L, gen_to_be_invoked.IsDone); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Progress(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushnumber(L, gen_to_be_invoked.Progress); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_AssetName(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); LuaAPI.lua_pushstring(L, gen_to_be_invoked.AssetName); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_AssetBundle(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); translator.PushAny(L, gen_to_be_invoked.AssetBundle); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _g_get_Asset(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); Minecraft.Assets.AsyncAsset gen_to_be_invoked = (Minecraft.Assets.AsyncAsset)translator.FastGetCSObj(L, 1); translator.Push(L, gen_to_be_invoked.Asset); } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return 1; } } }
36.970684
277
0.552687
3da8850dd96b88d25b28dc8aa7a2ed1e16148b02
24,064
cs
C#
samples-from-msdn/Change Tracking Sample/ChangeTrackingSample.cs
neeranelli/Dynamics365-Apps-Samples
06e9c84263bac81e7411f95365c5e792aca15122
[ "MIT" ]
72
2019-10-29T09:11:47.000Z
2022-03-27T22:12:50.000Z
samples-from-msdn/Change Tracking Sample/ChangeTrackingSample.cs
neeranelli/Dynamics365-Apps-Samples
06e9c84263bac81e7411f95365c5e792aca15122
[ "MIT" ]
19
2019-11-21T15:13:19.000Z
2022-03-22T06:36:58.000Z
samples-from-msdn/Change Tracking Sample/ChangeTrackingSample.cs
neeranelli/Dynamics365-Apps-Samples
06e9c84263bac81e7411f95365c5e792aca15122
[ "MIT" ]
154
2019-11-05T23:37:49.000Z
2022-03-16T23:32:59.000Z
// ===================================================================== // // This file is part of the Microsoft Dynamics CRM SDK code samples. // // Copyright (C) Microsoft Corporation. All rights reserved. // // This source code is intended only as a supplement to Microsoft // Development Tools and/or on-line documentation. See these other // materials for detailed information regarding Microsoft code samples. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // ===================================================================== //<snippetChangeTrackingSample> using System; using System.ServiceModel; using System.ServiceModel.Description; using System.Diagnostics; using System.Xml.Linq; using System.Linq.Expressions; using System.Linq; using System.IO; using System.Collections.Generic; using System.Xml; using System.Threading; // These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly // found in the SDK\bin folder. using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Microsoft.Xrm.Sdk.Query; using Microsoft.Xrm.Sdk.Discovery; using Microsoft.Xrm.Sdk.Messages; using Microsoft.Xrm.Sdk.Metadata; using Microsoft.Xrm.Sdk.Metadata.Query; // This namespace is found in Microsoft.Crm.Sdk.Proxy.dll assembly // found in the SDK\bin folder. using Microsoft.Crm.Sdk.Messages; namespace Microsoft.Crm.Sdk.Samples { public class ChangeTrackingSample { #region Class Level Members /// <summary> /// Stores the organization service proxy. /// </summary> private OrganizationServiceProxy _serviceProxy; private const String _customBooksEntityName = "sample_book"; System.String ManagedSolutionLocation = @".\\Solution\ChangeTrackingSample_1_0_0_0_managed.zip"; #endregion Class Level Members #region How To Sample Code /// <summary> /// Imports the ChangeTrackingSample solution. /// Creates 10 records in sample_book /// Initial sync and retrieves the 10 records. /// Updates the reords (Adds 10 new records and deletes one record and updates one record). /// Second sync to retrieve the changes since the last sync. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Check CRM version if(CheckCRMVersion()) { // Import the ChangeTrackingSample solution if it is not already installed. ImportChangeTrackingSolution(); // Wait for entity and key index to be active. WaitForEntityAndKeysToBeActive(_serviceProxy, _customBooksEntityName.ToLower()); // Create 10 demo records. CreateRequiredRecords(); //<snippetChangeTrackingSample1> string token; // Initialize page number. int pageNumber = 1; List<Entity> initialrecords = new List<Entity>(); // Retrieve records by using Change Tracking feature. RetrieveEntityChangesRequest request = new RetrieveEntityChangesRequest(); request.EntityName = _customBooksEntityName.ToLower(); request.Columns = new ColumnSet("sample_bookcode", "sample_name", "sample_author"); request.PageInfo = new PagingInfo() { Count = 5000, PageNumber = 1, ReturnTotalRecordCount = false }; // Initial Synchronization. Retrieves all records as well as token value. Console.WriteLine("Initial synchronization....retrieving all records."); while (true) { RetrieveEntityChangesResponse response = (RetrieveEntityChangesResponse)_serviceProxy.Execute(request); initialrecords.AddRange(response.EntityChanges.Changes.Select(x => (x as NewOrUpdatedItem).NewOrUpdatedEntity).ToArray()); initialrecords.ForEach(x => Console.WriteLine("initial record id:{0}", x.Id)); if (!response.EntityChanges.MoreRecords) { // Store token for later query token = response.EntityChanges.DataToken; break; } // Increment the page number to retrieve the next page. request.PageInfo.PageNumber++; // Set the paging cookie to the paging cookie returned from current results. request.PageInfo.PagingCookie = response.EntityChanges.PagingCookie; } //</snippetChangeTrackingSample1> // Display the initial records. // Do you like to view the records in browser? Add code. if (PromptForView()) { ViewEntityListInBrowser(); } // Delay 10 seconds, then create/update/delete records Console.WriteLine("waiting 10 seconds until next operation.."); Thread.Sleep(10000); // Add another 10 records, 1 update, and 1 delete. UpdateRecords(); // Second Synchronization. Basically do the same. // Reset paging pageNumber = 1; request.PageInfo.PageNumber = pageNumber; request.PageInfo.PagingCookie = null; // Assign token request.DataVersion = token; // Instantiate cache. List<Entity> updatedRecords = new List<Entity>(); List<EntityReference> deletedRecords = new List<EntityReference>(); while (true) { RetrieveEntityChangesResponse results = (RetrieveEntityChangesResponse)_serviceProxy.Execute(request); updatedRecords.AddRange(results.EntityChanges.Changes.Where(x => x.Type == ChangeType.NewOrUpdated).Select(x => (x as NewOrUpdatedItem).NewOrUpdatedEntity).ToArray()); deletedRecords.AddRange(results.EntityChanges.Changes.Where(x => x.Type == ChangeType.RemoveOrDeleted).Select(x => (x as RemovedOrDeletedItem).RemovedItem).ToArray()); if (!results.EntityChanges.MoreRecords) break; // Increment the page number to retrieve the next page. request.PageInfo.PageNumber++; // Set the paging cookie to the paging cookie returned from current results. request.PageInfo.PagingCookie = results.EntityChanges.PagingCookie; } // Do synchronizig work here. Console.WriteLine("Retrieving changes since the last sync...."); updatedRecords.ForEach(x => Console.WriteLine("new or updated record id:{0}!", x.Id)); deletedRecords.ForEach(x => Console.WriteLine("record id:{0} deleted!", x.Id)); // Prompt to view the records in the browser. if (PromptForView()) { Console.WriteLine("Retrieving the changes for the sample_book entity....."); ViewEntityListInBrowser(); } // Prompts to delete the ChangeTrackingSample managed solution. DeleteChangeTrackingSampleSolution(promptForDelete); } } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } } /// <summary> /// Checks whether the ChangeTrackingSample solution is already installed. /// If it is not, the ChangeTrackingSample_1_0_0_0_managed.zip file is imported to install /// this solution. /// </summary> public void ImportChangeTrackingSolution() { try { Console.WriteLine("Checking whether the ChangeTrackingSample solution already exists....."); QueryByAttribute queryCheckForSampleSolution = new QueryByAttribute(); queryCheckForSampleSolution.AddAttributeValue("uniquename", "ChangeTrackingSample"); queryCheckForSampleSolution.EntityName = Solution.EntityLogicalName; EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { Console.WriteLine("The {0} solution already exists....", "ChangeTrackingSample"); SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; } else { Console.WriteLine("The ChangeTrackingSample solution does not exist. Importing the solution...."); byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = fileBytes }; _serviceProxy.Execute(impSolReq); Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation); Console.WriteLine("Waiting for the alternate key index to be created......."); Thread.Sleep(50000); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } } /// <summary> /// Checks the current CRM version. /// If it is anything lower than 7.1.0.0, prompt to upgrade. /// </summary> private bool CheckCRMVersion() { RetrieveVersionRequest crmVersionReq = new RetrieveVersionRequest(); RetrieveVersionResponse crmVersionResp = (RetrieveVersionResponse)_serviceProxy.Execute(crmVersionReq); if (String.CompareOrdinal("7.1.0.0", crmVersionResp.Version) < 0) { return true; } else { Console.WriteLine("This sample cannot be run against the current version of CRM."); Console.WriteLine("Upgrade your CRM instance to the latest version to run this sample."); return false; } } /// <summary> /// Alternate keys may not be active immediately after the ChangeTrackingSample /// solution is installed.This method polls the metadata for the sample_book /// entity to delay execution of the rest of the sample until the alternate keys are ready. /// </summary> /// <param name="service">Specifies the service to connect to.</param> /// <param name="entityLogicalName">The entity logical name, i.e. sample_product.</param> private static void WaitForEntityAndKeysToBeActive(IOrganizationService service, string entityLogicalName) { EntityQueryExpression entityQuery = new EntityQueryExpression(); entityQuery.Criteria = new MetadataFilterExpression(LogicalOperator.And) { Conditions = { { new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, entityLogicalName) } } }; entityQuery.Properties = new MetadataPropertiesExpression("Keys"); RetrieveMetadataChangesRequest metadataRequest = new RetrieveMetadataChangesRequest() { Query = entityQuery }; bool allKeysReady = false; do { System.Threading.Thread.Sleep(5000); Console.WriteLine("Check for Entity..."); RetrieveMetadataChangesResponse metadataResponse = (RetrieveMetadataChangesResponse)service.Execute(metadataRequest); if (metadataResponse.EntityMetadata.Count > 0) { EntityKeyMetadata[] keys = metadataResponse.EntityMetadata[0].Keys; allKeysReady = true; if (keys.Length == 0) { Console.WriteLine("No Keys Found!!!"); allKeysReady = false; } else { foreach (var key in keys) { Console.WriteLine(" Key {0} status {1}", key.SchemaName, key.EntityKeyIndexStatus); allKeysReady = allKeysReady && (key.EntityKeyIndexStatus == EntityKeyIndexStatus.Active); } } } } while (!allKeysReady); Console.WriteLine("Waiting 30 seconds for metadata caches to all synchronize..."); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30)); } // Prompt to view the entity. private static bool PromptForView() { Console.WriteLine("\nDo you want to view the sample product entity records? (y/n)"); String answer = Console.ReadLine(); if (answer.StartsWith("y") || answer.StartsWith("Y")) { return true; } else { return false; } } // Displays the sample product entity records in the browser. public void ViewEntityListInBrowser() { try { //Get the view ID QueryByAttribute query = new QueryByAttribute("savedquery"); query.AddAttributeValue("returnedtypecode", "sample_book"); query.AddAttributeValue("name", "Active Sample Books"); query.ColumnSet = new ColumnSet("savedqueryid", "name"); query.AddOrder("name", OrderType.Ascending); RetrieveMultipleRequest req = new RetrieveMultipleRequest() { Query = query }; RetrieveMultipleResponse resp = (RetrieveMultipleResponse)_serviceProxy.Execute(req); SavedQuery activeSampleBooksView = (SavedQuery)resp.EntityCollection[0]; String webServiceURL = _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Address.Uri.AbsoluteUri; String entityInDefaultSolutionUrl = webServiceURL.Replace("XRMServices/2011/Organization.svc", String.Format("main.aspx?etn={0}&pagetype=entitylist&viewid=%7b{1}%7d&viewtype=1039", "sample_book", activeSampleBooksView.SavedQueryId)); // View in IE ProcessStartInfo browserProcess = new ProcessStartInfo("iexplore.exe"); browserProcess.Arguments = entityInDefaultSolutionUrl; Process.Start(browserProcess); } catch (SystemException) { Console.WriteLine("\nThere was a problem opening Internet Explorer."); } } Guid bookIdtoDelete; /// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { Console.WriteLine("Creating required records......"); // Create 10 book records for demo. for (int i = 0; i < 10; i++) { Entity book = new Entity("sample_book"); book["sample_name"] = "Demo Book " + i.ToString(); book["sample_bookcode"] = "BookCode" + i.ToString(); book["sample_author"] = "Author" + i.ToString(); bookIdtoDelete = _serviceProxy.Create(book); } Console.WriteLine("10 records created..."); } /// <summary> /// Update and delete records that this sample requires. /// </summary> public void UpdateRecords() { Console.WriteLine("Adding ten more records...."); // Create another 10 Account records for demo. for (int i = 10; i < 20; i++) { Entity book = new Entity("sample_book"); book["sample_name"] = "Demo Book " + i.ToString(); book["sample_bookcode"] = "BookCode" + i.ToString(); book["sample_author"] = "Author" + i.ToString(); _serviceProxy.Create(book); } // Update a record. Console.WriteLine("Updating an existing record"); Entity updatebook = new Entity(_customBooksEntityName.ToLower(), "sample_bookcode", "BookCode0"); updatebook["sample_name"] = "Demo Book 0 updated"; _serviceProxy.Update(updatebook); // Delete a record. Console.WriteLine("Deleting the {0} record....", bookIdtoDelete); _serviceProxy.Delete(_customBooksEntityName.ToLower(), bookIdtoDelete); } /// <summary> /// Deletes the managed solution that was created for this sample. /// <param name="prompt"> Indicates whether to prompt the user to delete /// the solution created in this sample.</param> /// If you choose "y", the managed solution will be deleted including the /// sample_book entity and all the data in the entity. /// If you choose "n", you must delete the solution manually to return /// your organization to the original state. /// </summary> public void DeleteChangeTrackingSampleSolution(bool prompt) { bool deleteSolution = true; if (prompt) { Console.WriteLine("\nDo you want to delete the ChangeTackingSample solution? (y/n)"); String answer = Console.ReadLine(); deleteSolution = (answer.StartsWith("y") || answer.StartsWith("Y")); } if (deleteSolution) { Console.WriteLine("Deleting the {0} solution....", "ChangeTrackingSample"); QueryExpression queryImportedSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "solutionid", "friendlyname" }), Criteria = new FilterExpression() }; queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, "ChangeTrackingSample"); Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0]; _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId); Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName); } } #endregion How To Sample Code* #region Main /// <summary> /// Standard Main() method used by most SDK samples. /// </summary> /// <param name="args"></param> static public void Main(string[] args) { try { // Obtain the target organization's Web address and client logon // credentials from the user. ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration config = serverConnect.GetServerConfiguration(); ChangeTrackingSample app = new ChangeTrackingSample(); app.Run(config, true); } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp); Console.WriteLine("Code: {0}", ex.Detail.ErrorCode); Console.WriteLine("Message: {0}", ex.Detail.Message); Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } catch (System.TimeoutException ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Message: {0}", ex.Message); Console.WriteLine("Stack Trace: {0}", ex.StackTrace); Console.WriteLine("Inner Fault: {0}", null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message); } catch (System.Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException as FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>; if (fe != null) { Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp); Console.WriteLine("Code: {0}", fe.Detail.ErrorCode); Console.WriteLine("Message: {0}", fe.Detail.Message); Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } } finally { Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } } #endregion Main } } //</snippetChangeTrackingSample>
45.148218
195
0.562832
3da8fd9dcec5ebd2f8bf876f9799c3f23d2879b5
6,807
cs
C#
Assets/VRTK/Scripts/Interactions/GrabAttachMechanics/VRTK_TrackObjectGrabAttach.cs
omaryasser/Wheelchair-Waiter
2cdfa14d04a9613047894289ffdfdc57f57ab1d9
[ "MIT" ]
3
2018-09-23T18:15:54.000Z
2021-02-06T06:46:34.000Z
Assets/VRTK/Scripts/Interactions/GrabAttachMechanics/VRTK_TrackObjectGrabAttach.cs
omaryasser/Wheelchair-Waiter
2cdfa14d04a9613047894289ffdfdc57f57ab1d9
[ "MIT" ]
45
2017-10-25T02:12:49.000Z
2017-12-07T16:25:57.000Z
Technodungeon/Assets/VRTK/Scripts/Interactions/GrabAttachMechanics/VRTK_TrackObjectGrabAttach.cs
Anedumgottil/VR-Mazmorra
c545ae2f1d1fd16fc64fc658e516e0267af0eacd
[ "Apache-2.0" ]
2
2018-09-02T15:01:53.000Z
2018-09-23T15:27:29.000Z
// Track Object Grab Attach|GrabAttachMechanics|50080 namespace VRTK.GrabAttachMechanics { using UnityEngine; /// <summary> /// The Track Object Grab Attach script doesn't attach the object to the controller via a joint, instead it ensures the object tracks the direction of the controller. /// </summary> /// <remarks> /// This works well for items that are on hinged joints or objects that require to interact naturally with other scene rigidbodies. /// </remarks> /// <example> /// `VRTK/Examples/021_Controller_GrabbingObjectsWithJoints` demonstrates this grab attach mechanic on the Chest handle and Fire Extinguisher body. /// </example> [AddComponentMenu("VRTK/Scripts/Interactions/Grab Attach Mechanics/VRTK_TrackObjectGrabAttach")] public class VRTK_TrackObjectGrabAttach : VRTK_BaseGrabAttach { [Header("Track Options", order = 2)] [Tooltip("The maximum distance the grabbing controller is away from the object before it is automatically dropped.")] public float detachDistance = 1f; [Tooltip("The maximum amount of velocity magnitude that can be applied to the object. Lowering this can prevent physics glitches if objects are moving too fast.")] public float velocityLimit = float.PositiveInfinity; [Tooltip("The maximum amount of angular velocity magnitude that can be applied to the object. Lowering this can prevent physics glitches if objects are moving too fast.")] public float angularVelocityLimit = float.PositiveInfinity; protected bool isReleasable = true; /// <summary> /// The StopGrab method ends the grab of the current object and cleans up the state. /// </summary> /// <param name="applyGrabbingObjectVelocity">If true will apply the current velocity of the grabbing object to the grabbed object on release.</param> public override void StopGrab(bool applyGrabbingObjectVelocity) { if (isReleasable) { ReleaseObject(applyGrabbingObjectVelocity); } base.StopGrab(applyGrabbingObjectVelocity); } /// <summary> /// The CreateTrackPoint method sets up the point of grab to track on the grabbed object. /// </summary> /// <param name="controllerPoint">The point on the controller where the grab was initiated.</param> /// <param name="currentGrabbedObject">The object that is currently being grabbed.</param> /// <param name="currentGrabbingObject">The object that is currently doing the grabbing.</param> /// <param name="customTrackPoint">A reference to whether the created track point is an auto generated custom object.</param> /// <returns>The transform of the created track point.</returns> public override Transform CreateTrackPoint(Transform controllerPoint, GameObject currentGrabbedObject, GameObject currentGrabbingObject, ref bool customTrackPoint) { Transform trackPoint = null; if (precisionGrab) { trackPoint = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, currentGrabbedObject.name, "TrackObject", "PrecisionSnap", "AttachPoint")).transform; trackPoint.parent = currentGrabbingObject.transform; SetTrackPointOrientation(ref trackPoint, currentGrabbedObject.transform, controllerPoint); customTrackPoint = true; } else { trackPoint = base.CreateTrackPoint(controllerPoint, currentGrabbedObject, currentGrabbingObject, ref customTrackPoint); } return trackPoint; } /// <summary> /// The ProcessUpdate method is run in every Update method on the interactable object. It is responsible for checking if the tracked object has exceeded it's detach distance. /// </summary> public override void ProcessUpdate() { if (trackPoint && grabbedObjectScript.IsDroppable()) { float distance = Vector3.Distance(trackPoint.position, initialAttachPoint.position); if (distance > detachDistance) { ForceReleaseGrab(); } } } /// <summary> /// The ProcessFixedUpdate method is run in every FixedUpdate method on the interactable object. It applies velocity to the object to ensure it is tracking the grabbing object. /// </summary> public override void ProcessFixedUpdate() { if (!grabbedObject) { return; } float maxDistanceDelta = 10f; Vector3 positionDelta = trackPoint.position - (grabbedSnapHandle != null ? grabbedSnapHandle.position : grabbedObject.transform.position); Quaternion rotationDelta = trackPoint.rotation * Quaternion.Inverse((grabbedSnapHandle != null ? grabbedSnapHandle.rotation : grabbedObject.transform.rotation)); float angle; Vector3 axis; rotationDelta.ToAngleAxis(out angle, out axis); angle = ((angle > 180) ? angle -= 360 : angle); if (angle != 0) { Vector3 angularTarget = angle * axis; Vector3 calculatedAngularVelocity = Vector3.MoveTowards(grabbedObjectRigidBody.angularVelocity, angularTarget, maxDistanceDelta); if (angularVelocityLimit == float.PositiveInfinity || calculatedAngularVelocity.sqrMagnitude < angularVelocityLimit) { grabbedObjectRigidBody.angularVelocity = calculatedAngularVelocity; } } Vector3 velocityTarget = positionDelta / Time.fixedDeltaTime; Vector3 calculatedVelocity = Vector3.MoveTowards(grabbedObjectRigidBody.velocity, velocityTarget, maxDistanceDelta); if (velocityLimit == float.PositiveInfinity || calculatedVelocity.sqrMagnitude < velocityLimit) { grabbedObjectRigidBody.velocity = calculatedVelocity; } } protected override void Initialise() { tracked = true; climbable = false; kinematic = false; FlipSnapHandles(); } protected virtual void SetTrackPointOrientation(ref Transform trackPoint, Transform currentGrabbedObject, Transform controllerPoint) { trackPoint.position = currentGrabbedObject.position; trackPoint.rotation = currentGrabbedObject.rotation; } } }
50.422222
185
0.643161
3da91bdc5f8a4cd883a2ccbbebd114d0a5e7bcda
1,847
cs
C#
Classes/ODataOptions.cs
Killers2/K2host.Data
b43f69be92722b5ef6a0d33cfd9dd20d42bef834
[ "MIT" ]
1
2021-09-12T17:32:29.000Z
2021-09-12T17:32:29.000Z
Classes/ODataOptions.cs
Killers2/K2host.Data
b43f69be92722b5ef6a0d33cfd9dd20d42bef834
[ "MIT" ]
null
null
null
Classes/ODataOptions.cs
Killers2/K2host.Data
b43f69be92722b5ef6a0d33cfd9dd20d42bef834
[ "MIT" ]
null
null
null
/* ' /====================================================\ '| Developed Tony N. Hyde (www.k2host.co.uk) | '| Projected Started: 2019-03-26 | '| Use: General | ' \====================================================/ */ using System; using System.Collections.Generic; using K2host.Data.Enums; using K2host.Data.Interfaces; namespace K2host.Data.Classes { public class ODataOptions : IDataOptions { /// <summary> /// The factories used to build the string queries for the databases. /// </summary> public Dictionary<OConnectionDbType, ISqlFactory> SqlFactories { get; set; } = new(); /// <summary> /// The property converters in the context of the domain. /// </summary> public List<IDataPropertyConverter> PropertyConverters { get; set; } = new(); /// <summary> /// The database connection in the context of the domain. /// </summary> public Dictionary<string, IDataConnection> Connections { get; set; } /// <summary> /// The current primary connection used globally /// </summary> public IDataConnection Primary { get; set; } /// <summary> /// The migration tool using the current primary connection /// </summary> public ODataMigrationTool MigrationTool { get; set; } #region Deconstuctor private bool IsDisposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!IsDisposed) if (disposing) { } IsDisposed = true; } #endregion } }
25.652778
93
0.51164
3dab2d7bb77a3ecb25d94ed7840e0ba4a3f4d9f0
2,142
cs
C#
src/EntityFramework.Core/ChangeTracking/Internal/InternalShadowEntityEntry.cs
craiggwilson/EntityFramework
e172882e1e039b61fa980e4466baa049f8ac94b1
[ "Apache-2.0" ]
null
null
null
src/EntityFramework.Core/ChangeTracking/Internal/InternalShadowEntityEntry.cs
craiggwilson/EntityFramework
e172882e1e039b61fa980e4466baa049f8ac94b1
[ "Apache-2.0" ]
null
null
null
src/EntityFramework.Core/ChangeTracking/Internal/InternalShadowEntityEntry.cs
craiggwilson/EntityFramework
e172882e1e039b61fa980e4466baa049f8ac94b1
[ "Apache-2.0" ]
null
null
null
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics; using JetBrains.Annotations; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Storage; namespace Microsoft.Data.Entity.ChangeTracking.Internal { public class InternalShadowEntityEntry : InternalEntityEntry { private readonly object[] _propertyValues; public override object Entity => null; public InternalShadowEntityEntry( [NotNull] IStateManager stateManager, [NotNull] IEntityType entityType, [NotNull] IEntityEntryMetadataServices metadataServices) : base(stateManager, entityType, metadataServices) { _propertyValues = new object[entityType.ShadowPropertyCount()]; } public InternalShadowEntityEntry( [NotNull] IStateManager stateManager, [NotNull] IEntityType entityType, [NotNull] IEntityEntryMetadataServices metadataServices, [NotNull] IValueReader valueReader) : base(stateManager, entityType, metadataServices) { _propertyValues = new object[valueReader.Count]; var index = 0; foreach (var property in entityType.GetProperties()) { _propertyValues[index++] = metadataServices.ReadValueFromReader(valueReader, property); } } protected override object ReadPropertyValue(IPropertyBase propertyBase) { var property = propertyBase as IProperty; Debug.Assert(property != null && property.IsShadowProperty); return _propertyValues[property.GetShadowIndex()]; } protected override void WritePropertyValue(IPropertyBase propertyBase, object value) { var property = propertyBase as IProperty; Debug.Assert(property != null && property.IsShadowProperty); _propertyValues[property.GetShadowIndex()] = value; } } }
36.305085
111
0.666667
3dab77337ab25b45d1965319f2b9e3d4b93f41b9
1,757
cs
C#
Assets/Scripts/LAN/LetterLAN.cs
DeadSith/Scrabble2d
f5ae645fda2d6da6a90b873e9770dc63c66f5714
[ "Apache-2.0" ]
null
null
null
Assets/Scripts/LAN/LetterLAN.cs
DeadSith/Scrabble2d
f5ae645fda2d6da6a90b873e9770dc63c66f5714
[ "Apache-2.0" ]
null
null
null
Assets/Scripts/LAN/LetterLAN.cs
DeadSith/Scrabble2d
f5ae645fda2d6da6a90b873e9770dc63c66f5714
[ "Apache-2.0" ]
null
null
null
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class LetterLAN : MonoBehaviour, IPointerClickHandler { public Text LetterText; public Text PointsText; public Material StandardMaterial; public Material CheckedMaterial; public bool isChecked = false; private LetterBoxLAN parent; private void Start() { parent = gameObject.transform.parent.GetComponent<LetterBoxLAN>(); } public void ChangeLetter(string letter) { LetterText.text = letter; PointsText.text = LetterBoxH.PointsDictionary[letter].ToString(); PointsText.enabled = false; } //Mark LetterH as checked public void OnPointerClick(PointerEventData eventData) { if (eventData.button == PointerEventData.InputButton.Right && parent.CanChangeLetters) { gameObject.GetComponent<Image>().material = isChecked ? StandardMaterial : CheckedMaterial; isChecked = !isChecked; } } //Hides points, shows letter public void OnMouseExit() { LetterText.enabled = true; PointsText.enabled = false; } //Shows points for current letter public void OnMouseEnter() { LetterText.enabled = false; PointsText.enabled = true; } //Removes stuck letter from field public void Fix() { parent.FreeCoordinates.Add(DragHandler.StartPosition); parent.ChangeBox(1, LetterText.text); var index = parent.FindIndex(this); parent.CurrentLetters[index] = parent.CurrentLetters[parent.CurrentLetters.Count - 1]; parent.CurrentLetters.RemoveAt(parent.CurrentLetters.Count - 1); transform.position = new Vector3(-500, -500); } }
29.283333
103
0.670461
3dac4280912873c4072336a1bd946a3c986c2d81
4,273
cs
C#
tests/src/Interop/PInvoke/SafeHandles/Interface/InterfaceTest.cs
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
159
2020-06-17T01:01:55.000Z
2022-03-28T10:33:37.000Z
tests/src/Interop/PInvoke/SafeHandles/Interface/InterfaceTest.cs
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-06-27T01:16:35.000Z
2022-02-06T20:33:24.000Z
tests/src/Interop/PInvoke/SafeHandles/Interface/InterfaceTest.cs
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-05-21T08:18:20.000Z
2021-06-29T01:13:13.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using SafeHandlesTests; using System.Threading; using TestLibrary; [StructLayout(LayoutKind.Sequential)] public struct StructMAIntf { [MarshalAs(UnmanagedType.Interface)] public SafeFileHandle hnd; } public class SHtoIntfTester { public static int Main() { try { RunTests(); return 100; } catch (Exception e) { Console.WriteLine($"Test Failure: {e}"); return 101; } } [DllImport("PInvoke_SafeHandle_MarshalAs_Interface")] public static extern bool SH_MAIntf([MarshalAs(UnmanagedType.Interface)]SafeFileHandle sh, Int32 shVal, Int32 shfld1Val, Int32 shfld2Val); [DllImport("PInvoke_SafeHandle_MarshalAs_Interface")] public static extern bool SH_MAIntf_Ref([MarshalAs(UnmanagedType.Interface)]ref SafeFileHandle sh, Int32 shVal, Int32 shfld1Val, Int32 shfld2Val); [DllImport("PInvoke_SafeHandle_MarshalAs_Interface")] public static extern bool SHFld_MAIntf(StructMAIntf s, Int32 shndVal, Int32 shfld1Val, Int32 shfld2Val); public static void RunTests() { Console.WriteLine("RunTests started"); //////////////////////////////////////////////////////// SafeFileHandle sh = Helper.NewSFH(); Int32 shVal = Helper.SHInt32(sh); sh.shfld1 = Helper.NewSFH(); //SH field of SFH class Int32 shfld1Val = Helper.SHInt32(sh.shfld1); sh.shfld2 = Helper.NewSFH(); //SFH field of SFH class Int32 shfld2Val = Helper.SHInt32(sh.shfld2); //NOTE: SafeHandle is now ComVisible(false)...QIs for IDispatch or the class interface on a // type with a ComVisible(false) type in its hierarchy are no longer allowed; so calling // the DW ctor with a SH subclass causes an invalidoperationexception to be thrown since // the ctor QIs for IDispatch Console.WriteLine("Testing SH_MAIntf..."); Assert.Throws<InvalidOperationException>(() => SH_MAIntf(sh, shVal, shfld1Val, shfld2Val), "Did not throw InvalidOperationException!"); //////////////////////////////////////////////////////// sh = Helper.NewSFH(); shVal = Helper.SHInt32(sh); sh.shfld1 = Helper.NewSFH(); //SH field of SFH class shfld1Val = Helper.SHInt32(sh.shfld1); sh.shfld2 = Helper.NewSFH(); //SFH field of SFH class shfld2Val = Helper.SHInt32(sh.shfld2); //NOTE: SafeHandle is now ComVisible(false)...QIs for IDispatch or the class interface on a // type with a ComVisible(false) type in its hierarchy are no longer allowed; so calling // the DW ctor with a SH subclass causes an invalidoperationexception to be thrown since // the ctor QIs for IDispatch Console.WriteLine("Testing SH_MAIntf_Ref..."); Assert.Throws<InvalidOperationException>(() => SH_MAIntf_Ref(ref sh, shVal, shfld1Val, shfld2Val), "Did not throw InvalidOperationException!"); //////////////////////////////////////////////////////// StructMAIntf s = new StructMAIntf(); s.hnd = Helper.NewSFH(); Int32 shndVal = Helper.SHInt32(s.hnd); s.hnd.shfld1 = Helper.NewSFH(); //SH field of SFH field of struct shfld1Val = Helper.SHInt32(s.hnd.shfld1); s.hnd.shfld2 = Helper.NewSFH(); //SFH field of SFH field of struct shfld2Val = Helper.SHInt32(s.hnd.shfld2); //NOTE: SafeHandle is now ComVisible(false)...QIs for IDispatch or the class interface on a // type with a ComVisible(false) type in its hierarchy are no longer allowed; so calling // the DW ctor with a SH subclass causes an invalidoperationexception to be thrown since // the ctor QIs for IDispatch Console.WriteLine("Testing SHFld_MAIntf..."); Assert.Throws<InvalidOperationException>(() => SHFld_MAIntf(s, shndVal, shfld1Val, shfld2Val), "Did not throw InvalidOperationException!"); Console.WriteLine("RunTests end"); } }
44.510417
151
0.647788
3dad19b84fd8c8a1a35ff1e1f97b8d01043096e6
2,370
cshtml
C#
Capstone.Bookstore/Views/Home/Category.cshtml
nehadesign/Capstone-ASP-BookStore
77f15aa47d009a294d38347e233c24c0eacbfa6b
[ "Apache-2.0" ]
null
null
null
Capstone.Bookstore/Views/Home/Category.cshtml
nehadesign/Capstone-ASP-BookStore
77f15aa47d009a294d38347e233c24c0eacbfa6b
[ "Apache-2.0" ]
3
2022-03-26T23:53:05.000Z
2022-03-28T01:10:12.000Z
Capstone.Bookstore/Views/Home/Category.cshtml
nehadesign/Capstone-ASP-BookStore
77f15aa47d009a294d38347e233c24c0eacbfa6b
[ "Apache-2.0" ]
1
2022-03-29T01:06:07.000Z
2022-03-29T01:06:07.000Z
@model IEnumerable<Capstone.Bookstore.DAL.Tbl_Product> @{ ViewBag.Title = "Category"; } <h2>Category : @ViewBag.CategoryName </h2> <table class="table"> <tr> <th> Product Name </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> Image </th> <th> @Html.DisplayNameFor(model => model.Price) </th> <th> @Html.DisplayNameFor(model => model.Tbl_Author.AuthorName) </th> <th> Category </th> <th> Add to Cart </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ProductName) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> <img src="@item.ProductImage" alt="@item.ProductName" style="height:150px; width:auto; padding:3px; border:solid 1px #ededed;"/> </td> <td> $ @Html.DisplayFor(modelItem => item.Price) </td> <td> @Html.DisplayFor(modelItem => item.Tbl_Author.AuthorName) </td> <td> @Html.DisplayFor(modelItem => item.Tbl_Category.CategoryName) </td> <td> <p> @if (item.Quantity > 0) { using (Html.BeginForm("AddToCart", "Home", new { productId = item.ProductId, returnAction = "Category" }, FormMethod.Post)) { <button type="submit" class="pull-right"><i class="fa fa-shopping-cart"></i></button> } } else { <p>Not Available</p> } </p> </td> @*<td> @Html.ActionLink("Edit", "Edit", new { id = item.ProductId }) | @Html.ActionLink("Details", "Details", new { id = item.ProductId }) | @Html.ActionLink("Delete", "Delete", new { id = item.ProductId }) </td>*@ </tr> } </table>
27.882353
160
0.411392
3daf1cc91e6854550f394214c500e782419be3c4
3,477
cs
C#
TLM/TLM/TrafficManagerMod.cs
jrthsr700tmax/Cities-Skylines-Traffic-Manager-President-Edition
d862b5ce0205563d32a9f6cf37296fa7c6c39489
[ "MIT" ]
null
null
null
TLM/TLM/TrafficManagerMod.cs
jrthsr700tmax/Cities-Skylines-Traffic-Manager-President-Edition
d862b5ce0205563d32a9f6cf37296fa7c6c39489
[ "MIT" ]
null
null
null
TLM/TLM/TrafficManagerMod.cs
jrthsr700tmax/Cities-Skylines-Traffic-Manager-President-Edition
d862b5ce0205563d32a9f6cf37296fa7c6c39489
[ "MIT" ]
null
null
null
namespace TrafficManager { using System; using System.Reflection; using ColossalFramework.Globalization; using ColossalFramework.UI; using CSUtil.Commons; using ICities; using JetBrains.Annotations; using State; using TrafficManager.UI; using Util; public class TrafficManagerMod : IUserMod { #if LABS public const string BRANCH = "LABS"; #elif DEBUG public const string BRANCH = "DEBUG"; #else public const string BRANCH = "STABLE"; #endif public const uint GAME_VERSION = 184803856u; public const uint GAME_VERSION_A = 1u; public const uint GAME_VERSION_B = 12u; public const uint GAME_VERSION_C = 1u; public const uint GAME_VERSION_BUILD = 2u; public const string VERSION = "11.0-alpha11"; public static readonly string ModName = "TM:PE " + BRANCH + " " + VERSION; public string Name => ModName; public string Description => "Manage your city's traffic"; [UsedImplicitly] public void OnEnabled() { Log.InfoFormat( "TM:PE enabled. Version {0}, Build {1} {2} for game version {3}.{4}.{5}-f{6}", VERSION, Assembly.GetExecutingAssembly().GetName().Version, BRANCH, GAME_VERSION_A, GAME_VERSION_B, GAME_VERSION_C, GAME_VERSION_BUILD); Log.InfoFormat( "Enabled TM:PE has GUID {0}", Assembly.GetExecutingAssembly().ManifestModule.ModuleVersionId); // check for incompatible mods if (UIView.GetAView() != null) { // when TM:PE is enabled in content manager CheckForIncompatibleMods(); } else { // or when game first loads if TM:PE was already enabled LoadingManager.instance.m_introLoaded += CheckForIncompatibleMods; } // Log Mono version Type monoRt = Type.GetType("Mono.Runtime"); if (monoRt != null) { MethodInfo displayName = monoRt.GetMethod( "GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static); if (displayName != null) { Log.InfoFormat("Mono version: {0}", displayName.Invoke(null, null)); } } } [UsedImplicitly] public void OnDisabled() { Log.Info("TM:PE disabled."); LoadingManager.instance.m_introLoaded -= CheckForIncompatibleMods; LocaleManager.eventLocaleChanged -= Translation.HandleGameLocaleChange; Translation.IsListeningToGameLocaleChanged = false; // is this necessary? } [UsedImplicitly] public void OnSettingsUI(UIHelperBase helper) { // Note: This bugs out if done in OnEnabled(), hence doing it here instead. if (!Translation.IsListeningToGameLocaleChanged) { Translation.IsListeningToGameLocaleChanged = true; LocaleManager.eventLocaleChanged += new LocaleManager.LocaleChangedHandler(Translation.HandleGameLocaleChange); } Options.MakeSettings(helper); } private static void CheckForIncompatibleMods() { ModsCompatibilityChecker mcc = new ModsCompatibilityChecker(); mcc.PerformModCheck(); } } }
35.845361
127
0.592177
3dafa5913e60ac45f3e878085305ad0f94004403
3,779
cs
C#
Source/Migrations/Machine.Migrations/DatabaseProviders/SqlServerDatabaseProvider.cs
abombss/machine
9f5e3d3e7c06ff088bc2e4c9af0e0310cd6257b0
[ "MIT" ]
1
2016-05-08T16:10:57.000Z
2016-05-08T16:10:57.000Z
Source/Migrations/Machine.Migrations/DatabaseProviders/SqlServerDatabaseProvider.cs
dtabuenc/machine
e0428b58945a24d71c954ee50557d6ead3aefa9c
[ "MIT" ]
null
null
null
Source/Migrations/Machine.Migrations/DatabaseProviders/SqlServerDatabaseProvider.cs
dtabuenc/machine
e0428b58945a24d71c954ee50557d6ead3aefa9c
[ "MIT" ]
1
2021-07-13T07:20:53.000Z
2021-07-13T07:20:53.000Z
using System; using System.Collections.Generic; using System.Data; using Machine.Migrations.Services; namespace Machine.Migrations.DatabaseProviders { public class SqlServerDatabaseProvider : IDatabaseProvider { #region Logging static readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(SqlServerDatabaseProvider)); #endregion #region Member Data readonly IConnectionProvider _connectionProvider; readonly ITransactionProvider _transactionProvider; readonly IConfiguration _configuration; #endregion #region SqlServerDatabaseProvider() public SqlServerDatabaseProvider(IConnectionProvider connectionProvider, ITransactionProvider transactionProvider, IConfiguration configuration) { _configuration = configuration; _connectionProvider = connectionProvider; _transactionProvider = transactionProvider; } #endregion #region IDatabaseProvider Members public void Open() { _connectionProvider.OpenConnection(); } public object ExecuteScalar(string sql, params object[] objects) { try { IDbCommand command = PrepareCommand(sql, objects); return command.ExecuteScalar(); } catch (Exception ex) { throw new Exception("ExecuteScalar: Error executing " + string.Format(sql, objects), ex); } } public T ExecuteScalar<T>(string sql, params object[] objects) { try { IDbCommand command = PrepareCommand(sql, objects); return (T)command.ExecuteScalar(); } catch (Exception ex) { throw new Exception("ExecuteScalar<>: Error executing " + string.Format(sql, objects), ex); } } public T[] ExecuteScalarArray<T>(string sql, params object[] objects) { try { IDataReader reader = ExecuteReader(sql, objects); List<T> values = new List<T>(); while (reader.Read()) { values.Add((T)reader.GetValue(0)); } reader.Close(); return values.ToArray(); } catch (Exception ex) { throw new Exception("ExecuteScalarArray: Error executing " + string.Format(sql, objects), ex); } } public IDataReader ExecuteReader(string sql, params object[] objects) { try { IDbCommand command = PrepareCommand(sql, objects); return command.ExecuteReader(); } catch (Exception ex) { throw new Exception("ExecuteReader: Error executing " + string.Format(sql, objects), ex); } } public bool ExecuteNonQuery(string sql, params object[] objects) { try { IDbCommand command = PrepareCommand(sql, objects); command.ExecuteNonQuery(); return true; } catch (Exception ex) { throw new Exception("ExecuteNonQuery: Error executing " + string.Format(sql, objects), ex); } } public void Close() { if (this.DatabaseConnection != null) { this.DatabaseConnection.Close(); } } #endregion #region Member Data protected virtual IDbConnection DatabaseConnection { get { return _connectionProvider.CurrentConnection; } } IDbCommand PrepareCommand(string sql, object[] objects) { IDbCommand command = this.DatabaseConnection.CreateCommand(); command.CommandTimeout = _configuration.CommandTimeout; command.CommandText = String.Format(sql, objects); _transactionProvider.Enlist(command); _log.Info(command.CommandText); return command; } #endregion } }
27.992593
119
0.626092
3db15287e701ecba8d13c3630f32f2658083e5a3
226,768
cs
C#
CSharp.lua/LuaSyntaxNodeTransform.cs
Drake53/CSharp.lua
761e89c02f7d26a85a2aa7b86dea3e2187e660a2
[ "Apache-2.0" ]
12
2019-08-09T14:17:34.000Z
2021-08-14T12:14:54.000Z
CSharp.lua/LuaSyntaxNodeTransform.cs
Drake53/CSharp.lua
761e89c02f7d26a85a2aa7b86dea3e2187e660a2
[ "Apache-2.0" ]
1
2019-10-22T17:00:28.000Z
2020-06-02T23:15:54.000Z
CSharp.lua/LuaSyntaxNodeTransform.cs
Drake53/CSharp.lua
761e89c02f7d26a85a2aa7b86dea3e2187e660a2
[ "Apache-2.0" ]
1
2019-10-16T19:13:53.000Z
2019-10-16T19:13:53.000Z
/* Copyright 2017 YANG Huan (sy.yanghuan@gmail.com). 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 CSharpLua.LuaAst; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; using System.Linq; namespace CSharpLua { public sealed partial class LuaSyntaxNodeTransform : CSharpSyntaxVisitor<LuaSyntaxNode> { public const int kStringConstInlineCount = 27; private sealed class MethodInfo { public IMethodSymbol Symbol { get; } public IList<LuaExpressionSyntax> RefOrOutParameters { get; } public List<LuaIdentifierNameSyntax> InliningReturnVars { get; set; } public bool IsInlining => InliningReturnVars != null; public bool HasInlineGoto; public bool HasYield; public MethodInfo(IMethodSymbol symbol) { Symbol = symbol; RefOrOutParameters = Array.Empty<LuaExpressionSyntax>(); } public MethodInfo(IMethodSymbol symbol, IList<LuaExpressionSyntax> refOrOutParameters) { Symbol = symbol; RefOrOutParameters = refOrOutParameters; } } internal sealed class TypeDeclarationInfo { public INamedTypeSymbol TypeSymbol { get; } public LuaTypeDeclarationSyntax TypeDeclaration { get; } public TypeDeclarationInfo(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax luaTypeDeclarationSyntax) { TypeSymbol = typeSymbol; TypeDeclaration = luaTypeDeclarationSyntax; } public bool CheckTypeName(INamedTypeSymbol getNameTypeSymbol, out LuaIdentifierNameSyntax name) { if (getNameTypeSymbol.EQ(TypeSymbol)) { TypeDeclaration.IsClassUsed = true; name = LuaIdentifierNameSyntax.Class; return true; } name = null; return false; } } private readonly LuaSyntaxGenerator generator_; private SemanticModel semanticModel_; private readonly Stack<LuaCompilationUnitSyntax> compilationUnits_ = new(); private readonly Stack<TypeDeclarationInfo> typeDeclarations_ = new(); private readonly Stack<LuaFunctionExpressionSyntax> functions_ = new(); private readonly Stack<MethodInfo> methodInfos_ = new(); private readonly Stack<LuaBlockSyntax> blocks_ = new(); private readonly Stack<LuaIfStatementSyntax> ifStatements_ = new(); private readonly Stack<LuaSwitchAdapterStatementSyntax> switches_ = new(); private int noImportTypeNameCounter_; public bool IsNoImportTypeName => noImportTypeNameCounter_ > 0; private int genericTypeCounter_; public bool IsNoneGenericTypeCounter => genericTypeCounter_ == 0; public void AddGenericTypeCounter() => ++genericTypeCounter_; public void SubGenericTypeCounter() => --genericTypeCounter_; private int metadataTypeNameCounter_; public bool IsMetadataTypeName => metadataTypeNameCounter_ > 0; private static readonly Dictionary<string, string> operatorTokenMap_ = new() { ["!="] = LuaSyntaxNode.Tokens.NotEquals, ["!"] = LuaSyntaxNode.Tokens.Not, ["&&"] = LuaSyntaxNode.Tokens.And, ["||"] = LuaSyntaxNode.Tokens.Or, ["??"] = LuaSyntaxNode.Tokens.Or, ["^"] = LuaSyntaxNode.Tokens.BitXor, }; public LuaSyntaxNodeTransform(LuaSyntaxGenerator generator, SemanticModel semanticModel) { generator_ = generator; semanticModel_ = semanticModel; } private XmlMetaProvider XmlMetaProvider { get { return generator_.XmlMetaProvider; } } private static string GetOperatorToken(SyntaxToken operatorToken) { string token = operatorToken.ValueText; return GetOperatorToken(token); } private static string GetOperatorToken(string token) { return operatorTokenMap_.GetOrDefault(token, token); } private bool IsLuaClassic => generator_.Setting.IsClassic; private bool IsLuaNewest => !IsLuaClassic; private bool IsPreventDebug => generator_.Setting.IsPreventDebugObject; private LuaCompilationUnitSyntax CurCompilationUnit { get { return compilationUnits_.Peek(); } } private LuaTypeDeclarationSyntax CurType { get { return typeDeclarations_.Peek().TypeDeclaration; } } private INamedTypeSymbol CurTypeSymbol { get { return typeDeclarations_.Peek().TypeSymbol; } } internal TypeDeclarationInfo CurTypeDeclaration { get { return typeDeclarations_.Count > 0 ? typeDeclarations_.Peek() : null; } } private LuaFunctionExpressionSyntax CurFunction { get { return functions_.Peek(); } } private LuaFunctionExpressionSyntax CurFunctionOrNull { get { return functions_.Count > 0 ? functions_.Peek() : null; } } private MethodInfo CurMethodInfoOrNull { get { return methodInfos_.Count > 0 ? methodInfos_.Peek() : null; } } private void PushFunction(LuaFunctionExpressionSyntax function) { functions_.Push(function); ++localMappingCounter_; PushBlock(function.Body); } private void PopFunction() { PopBlock(); var function = functions_.Pop(); --localMappingCounter_; if (localMappingCounter_ == 0) { localReservedNames_.Clear(); } functionUpValues_.Remove(function); Contract.Assert(function.TempCount == 0); } public void PushBlock(LuaBlockSyntax block) { blocks_.Push(block); } public void PopBlock() { var block = blocks_.Pop(); if (block.TempCount > 0) { Contract.Assert(CurFunction.TempCount >= block.TempCount); CurFunction.TempCount -= block.TempCount; } } private LuaBlockSyntax CurBlock { get { return blocks_.Peek(); } } private LuaBlockSyntax CurBlockOrNull { get { return blocks_.Count > 0 ? blocks_.Peek() : null; } } private LuaIdentifierNameSyntax GetTempIdentifier() { int index = CurFunction.TempCount++; string name = LuaSyntaxNode.TempIdentifiers.GetOrDefault(index); if (name == null) { throw new CompilationErrorException($"Your code is startling,{LuaSyntaxNode.TempIdentifiers.Length} temporary variables is not enough"); } ++CurBlock.TempCount; return name; } private void ReleaseTempIdentifiers(int prevTempCount) { int count = CurFunction.TempCount - prevTempCount; PopTempCount(count); } private void PopTempCount(int count) { Contract.Assert(CurBlock.TempCount >= count && CurFunction.TempCount >= count); CurBlock.TempCount -= count; CurFunction.TempCount -= count; } private void AddReleaseTempIdentifier(LuaIdentifierNameSyntax tempName) { CurBlock.ReleaseCount++; } private void ReleaseTempIdentifiers() { if (CurBlock.ReleaseCount > 0) { PopTempCount(CurBlock.ReleaseCount); CurBlock.ReleaseCount = 0; } } public LuaCompilationUnitSyntax VisitCompilationUnit(CompilationUnitSyntax node, bool isSingleFile = false) { LuaCompilationUnitSyntax compilationUnit = new LuaCompilationUnitSyntax(node.SyntaxTree.FilePath, !isSingleFile); compilationUnits_.Push(compilationUnit); var statements = VisitTriviaAndNode(node, node.Members, false); foreach (var statement in statements) { if (statement is LuaTypeDeclarationSyntax typeDeclaration) { var ns = new LuaNamespaceDeclarationSyntax(LuaIdentifierNameSyntax.Empty); ns.AddStatement(typeDeclaration); compilationUnit.AddStatement(ns); } else { compilationUnit.AddStatement(statement); } } var attributes = BuildAttributes(node.AttributeLists); generator_.WithAssemblyAttributes(attributes); compilationUnits_.Pop(); return compilationUnit; } public override LuaSyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); bool isContained = node.Parent.IsKind(SyntaxKind.NamespaceDeclaration); string name = generator_.GetNamespaceDefineName(symbol, node); LuaNamespaceDeclarationSyntax namespaceDeclaration = new LuaNamespaceDeclarationSyntax(name, isContained); var statements = VisitTriviaAndNode(node, node.Members); namespaceDeclaration.AddStatements(statements); return namespaceDeclaration; } private void BuildTypeMembers(LuaTypeDeclarationSyntax typeDeclaration, TypeDeclarationSyntax node) { foreach (var nestedTypeDeclaration in node.Members.Where(i => i.Kind().IsTypeDeclaration())) { var luaNestedTypeDeclaration = nestedTypeDeclaration.Accept<LuaTypeDeclarationSyntax>(this); typeDeclaration.AddNestedTypeDeclaration(luaNestedTypeDeclaration); } foreach (var member in node.Members.Where(i => !i.Kind().IsTypeDeclaration())) { member.Accept(this); } } private void CheckBaseTypeGenericKind(ref bool hasExtendSelf, INamedTypeSymbol typeSymbol, BaseTypeSyntax baseType) { if (!hasExtendSelf) { if (baseType.IsKind(SyntaxKind.SimpleBaseType)) { var baseNode = (SimpleBaseTypeSyntax)baseType; if (baseNode.Type.IsKind(SyntaxKind.GenericName)) { var baseGenericNameNode = (GenericNameSyntax)baseNode.Type; var baseTypeSymbol = (INamedTypeSymbol)semanticModel_.GetTypeInfo(baseGenericNameNode).Type; hasExtendSelf = Utility.IsExtendSelf(typeSymbol, baseTypeSymbol); } } } } private LuaSpecialGenericType CheckSpecialGenericArgument(INamedTypeSymbol typeSymbol) { var interfaceType = typeSymbol.AllInterfaces.FirstOrDefault(i => i.IsGenericIEnumerableType()); if (interfaceType != null) { bool isBaseImplementation = typeSymbol.BaseType != null && typeSymbol.BaseType.AllInterfaces.Any(i => i.IsGenericIEnumerableType()); if (!isBaseImplementation) { var argumentType = interfaceType.TypeArguments.First(); bool isLazy = argumentType.Kind != SymbolKind.TypeParameter && argumentType.IsFromCode(); var typeName = isLazy ? GetTypeNameWithoutImport(argumentType) : GetTypeName(argumentType); return new LuaSpecialGenericType { Name = LuaIdentifierNameSyntax.GenericT, Value = typeName, IsLazy = isLazy }; } } return null; } private List<LuaIdentifierNameSyntax> GetBaseCopyFields(BaseTypeSyntax baseType) { if (baseType != null) { var fields = new List<LuaIdentifierNameSyntax>(); var semanticModel = generator_.GetSemanticModel(baseType.SyntaxTree); var baseTypeSymbol = semanticModel.GetTypeInfo(baseType.Type).Type; if (baseTypeSymbol.TypeKind == TypeKind.Class && baseTypeSymbol.SpecialType != SpecialType.System_Object) { if (baseTypeSymbol.IsMemberExists("Finalize", true)) { fields.Add(LuaIdentifierNameSyntax.__GC); } if (baseTypeSymbol.Is(generator_.SystemExceptionTypeSymbol)) { fields.Add(LuaIdentifierNameSyntax.__ToString); } } return fields; } return null; } private bool IsBaseTypeIgnore(ITypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Object) { return true; } if (symbol.ContainingNamespace.IsRuntimeCompilerServices()) { return true; } return false; } private void BuildBaseTypes(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, IEnumerable<BaseTypeSyntax> types, bool isPartial) { bool hasExtendSelf = false; var baseTypes = new List<LuaExpressionSyntax>(); foreach (var baseType in types) { if (isPartial) { semanticModel_ = generator_.GetSemanticModel(baseType.SyntaxTree); } var baseTypeSymbol = semanticModel_.GetTypeInfo(baseType.Type).Type; if (!IsBaseTypeIgnore(baseTypeSymbol)) { var baseTypeName = BuildInheritTypeName(baseTypeSymbol); baseTypes.Add(baseTypeName); CheckBaseTypeGenericKind(ref hasExtendSelf, typeSymbol, baseType); } } if (baseTypes.Count > 0) { if (typeSymbol.IsRecordType()) { baseTypes.Add(GetRecordInterfaceTypeName(typeSymbol)); } var genericArgument = CheckSpecialGenericArgument(typeSymbol); var baseCopyFields = GetBaseCopyFields(types.FirstOrDefault()); typeDeclaration.AddBaseTypes(baseTypes, genericArgument, baseCopyFields); if (hasExtendSelf && !generator_.IsExplicitStaticCtorExists(typeSymbol)) { typeDeclaration.IsForceStaticCtor = true; } } } private void BuildTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, typeDeclaration)); var comments = BuildDocumentationComment(node); typeDeclaration.AddDocument(comments); var attributes = BuildAttributes(node.AttributeLists); BuildTypeParameters(typeSymbol, node, typeDeclaration); if (node.BaseList != null) { BuildBaseTypes(typeSymbol, typeDeclaration, node.BaseList.Types, false); } CheckRecordParameterCtor(typeSymbol, node, typeDeclaration); BuildTypeMembers(typeDeclaration, node); CheckTypeDeclaration(typeSymbol, typeDeclaration, attributes, node); typeDeclarations_.Pop(); CurCompilationUnit.AddTypeDeclarationCount(); } private void CheckTypeDeclaration(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, List<LuaExpressionSyntax> attributes, BaseTypeDeclarationSyntax node) { if (typeDeclaration.IsNoneCtors) { var baseTypeSymbol = typeSymbol.BaseType; if (baseTypeSymbol != null) { var isNeedCallBase = typeDeclaration.IsInitStatementExists ? generator_.IsBaseExplicitCtorExists(baseTypeSymbol) : generator_.HasStaticCtor(baseTypeSymbol); if (isNeedCallBase) { var baseCtorInvoke = BuildCallBaseConstructor(typeSymbol); if (baseCtorInvoke != null) { var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.AddStatement(baseCtorInvoke); typeDeclaration.AddCtor(function, false); } } } } else if (typeSymbol.IsValueType && !typeSymbol.IsCombineImplicitlyCtor()) { var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); typeDeclaration.AddCtor(function, true); } if (typeSymbol.IsRecordType()) { if (typeSymbol.BaseType is {SpecialType: SpecialType.System_Object}) { typeDeclaration.AddBaseTypes(LuaIdentifierNameSyntax.RecordType.ArrayOf(GetRecordInterfaceTypeName(typeSymbol)), null, null); } BuildRecordMembers(typeSymbol, typeDeclaration); } if (typeDeclaration.IsIgnoreExport) { generator_.AddIgnoreExportType(typeSymbol); } if (IsCurTypeExportMetadataAll || attributes.Count > 0 || typeDeclaration.IsExportMetadata) { var data = new LuaTableExpression { IsSingleLine = true }; data.Add(typeSymbol.GetMetaDataAttributeFlags()); data.AddRange(typeDeclaration.TypeParameterExpressions); data.AddRange(attributes); typeDeclaration.AddClassMetaData(data); } } private void CheckRecordParameterCtor(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { if (typeSymbol.IsRecordType()) { var recordDeclaration = (RecordDeclarationSyntax)node; if (recordDeclaration.ParameterList != null) { BuildRecordParameterCtor(typeSymbol, typeDeclaration, recordDeclaration); } } } private void BuildRecordParameterCtor(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration, RecordDeclarationSyntax recordDeclaration) { var parameterList = recordDeclaration.ParameterList.Accept<LuaParameterListSyntax>(this); var function = new LuaConstructorAdapterExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.AddParameters(parameterList.Parameters); function.AddStatements(parameterList.Parameters.Select(i => LuaIdentifierNameSyntax.This.MemberAccess(i).Assignment(i).ToStatementSyntax())); typeDeclaration.AddCtor(function, false); var ctor = typeSymbol.InstanceConstructors.First(); int index = 0; foreach (var p in ctor.Parameters) { var expression = GetFieldValueExpression(p.Type, null, out bool isLiteral, out _); if (expression != null) { typeDeclaration.AddField(parameterList.Parameters[index], expression, p.Type.IsImmutable() && isLiteral, false, false, true, null, false); } ++index; } } private void BuildRecordMembers(INamedTypeSymbol typeSymbol, LuaTypeDeclarationSyntax typeDeclaration) { var properties = typeSymbol.GetMembers().OfType<IPropertySymbol>().Skip(1); var expressions = new List<LuaExpressionSyntax> { typeSymbol.Name.ToStringLiteral() }; expressions.AddRange(properties.Select(i => GetMemberName(i).ToStringLiteral())); var function = new LuaFunctionExpressionSyntax(); function.AddStatement(new LuaReturnStatementSyntax(expressions)); typeDeclaration.AddMethod(LuaIdentifierNameSyntax.RecordMembers, function, false); } private INamedTypeSymbol VisitTypeDeclaration(INamedTypeSymbol typeSymbol, TypeDeclarationSyntax node, LuaTypeDeclarationSyntax typeDeclaration) { if (node.Modifiers.IsPartial()) { if (typeSymbol.DeclaringSyntaxReferences.Length > 1) { generator_.AddPartialTypeDeclaration(typeSymbol, node, typeDeclaration, CurCompilationUnit); typeDeclaration.IsPartialMark = true; } else { BuildTypeDeclaration(typeSymbol, node, typeDeclaration); } } else { BuildTypeDeclaration(typeSymbol, node, typeDeclaration); } return typeSymbol; } internal void AcceptPartialType(PartialTypeDeclaration major, IEnumerable<PartialTypeDeclaration> typeDeclarations) { compilationUnits_.Push(major.CompilationUnit); typeDeclarations_.Push(new TypeDeclarationInfo(major.Symbol, major.TypeDeclaration)); List<LuaExpressionSyntax> attributes = new List<LuaExpressionSyntax>(); foreach (var typeDeclaration in typeDeclarations) { semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree); var document = BuildDocumentationComment(typeDeclaration.Node); major.TypeDeclaration.AddDocument(document); var expressions = BuildAttributes(typeDeclaration.Node.AttributeLists); attributes.AddRange(expressions); } BuildTypeParameters(major.Symbol, major.Node, major.TypeDeclaration); List<BaseTypeSyntax> baseTypes = new List<BaseTypeSyntax>(); HashSet<ITypeSymbol> baseSymbols = new HashSet<ITypeSymbol>(); foreach (var typeDeclaration in typeDeclarations) { if (typeDeclaration.Node.BaseList != null) { foreach (var baseTypeSyntax in typeDeclaration.Node.BaseList.Types) { var semanticModel = generator_.GetSemanticModel(baseTypeSyntax.SyntaxTree); var baseTypeSymbol = semanticModel.GetTypeInfo(baseTypeSyntax.Type).Type; if (baseSymbols.Add(baseTypeSymbol)) { baseTypes.Add(baseTypeSyntax); } } } } if (baseTypes.Count > 0) { if (baseTypes.Count > 1) { var baseTypeIndex = baseTypes.FindIndex(generator_.IsBaseType); if (baseTypeIndex > 0) { var baseType = baseTypes[baseTypeIndex]; baseTypes.RemoveAt(baseTypeIndex); baseTypes.Insert(0, baseType); } } BuildBaseTypes(major.Symbol, major.TypeDeclaration, baseTypes, true); } foreach (var typeDeclaration in typeDeclarations) { semanticModel_ = generator_.GetSemanticModel(typeDeclaration.Node.SyntaxTree); BuildTypeMembers(major.TypeDeclaration, typeDeclaration.Node); } CheckTypeDeclaration(major.Symbol, major.TypeDeclaration, attributes, major.Node); typeDeclarations_.Pop(); compilationUnits_.Pop(); major.TypeDeclaration.IsPartialMark = false; major.CompilationUnit.AddTypeDeclarationCount(); } private void GetTypeDeclarationName(BaseTypeDeclarationSyntax typeDeclaration, out LuaIdentifierNameSyntax name, out INamedTypeSymbol typeSymbol) { typeSymbol = semanticModel_.GetDeclaredSymbol(typeDeclaration); name = generator_.GetTypeDeclarationName(typeSymbol); } public override LuaSyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaClassDeclarationSyntax classDeclaration = new LuaClassDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, classDeclaration); return classDeclaration; } public override LuaSyntaxNode VisitStructDeclaration(StructDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaStructDeclarationSyntax structDeclaration = new LuaStructDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, structDeclaration); return structDeclaration; } public override LuaSyntaxNode VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); var interfaceDeclaration = new LuaInterfaceDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, interfaceDeclaration); return interfaceDeclaration; } private void VisitEnumDeclaration(INamedTypeSymbol typeSymbol, EnumDeclarationSyntax node, LuaEnumDeclarationSyntax enumDeclaration) { typeDeclarations_.Push(new TypeDeclarationInfo(typeSymbol, enumDeclaration)); var document = BuildDocumentationComment(node); enumDeclaration.AddDocument(document); var attributes = BuildAttributes(node.AttributeLists); foreach (var member in node.Members) { var statement = member.Accept<LuaKeyValueTableItemSyntax>(this); enumDeclaration.Add(statement); } CheckTypeDeclaration(typeSymbol, enumDeclaration, attributes, node); typeDeclarations_.Pop(); generator_.AddEnumDeclaration(typeSymbol, enumDeclaration); } public override LuaSyntaxNode VisitEnumDeclaration(EnumDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaEnumDeclarationSyntax enumDeclaration = new LuaEnumDeclarationSyntax(typeSymbol.ToString(), name, CurCompilationUnit); VisitEnumDeclaration(typeSymbol, node, enumDeclaration); return enumDeclaration; } public override LuaSyntaxNode VisitRecordDeclaration(RecordDeclarationSyntax node) { GetTypeDeclarationName(node, out var name, out var typeSymbol); LuaClassDeclarationSyntax classDeclaration = new LuaClassDeclarationSyntax(name); VisitTypeDeclaration(typeSymbol, node, classDeclaration); return classDeclaration; } public override LuaSyntaxNode VisitDelegateDeclaration(DelegateDeclarationSyntax node) { return LuaStatementSyntax.Empty; } private void VisitYield(IMethodSymbol symbol, LuaFunctionExpressionSyntax function) { var returnTypeSymbol = (INamedTypeSymbol)symbol.ReturnType; string name = LuaSyntaxNode.Tokens.Yield + returnTypeSymbol.Name; var invokeExpression = LuaIdentifierNameSyntax.System.MemberAccess(name).Invocation(); var wrapFunction = new LuaFunctionExpressionSyntax(); if (symbol.IsAsync) { wrapFunction.AddParameter(LuaIdentifierNameSyntax.Async); } var parameters = function.ParameterList.Parameters; wrapFunction.ParameterList.Parameters.AddRange(parameters); wrapFunction.AddStatements(function.Body.Statements); invokeExpression.AddArgument(wrapFunction); if (returnTypeSymbol.IsGenericType) { var typeName = returnTypeSymbol.TypeArguments.First(); var expression = GetTypeName(typeName); invokeExpression.AddArgument(expression); } else { invokeExpression.AddArgument(LuaIdentifierNameSyntax.Object); } invokeExpression.ArgumentList.Arguments.AddRange(parameters); var returnStatement = new LuaReturnStatementSyntax(invokeExpression); function.Body.Statements.Clear(); function.AddStatement(returnStatement); } private void VisitAsync(bool returnsVoid, LuaFunctionExpressionSyntax function) { var invokeExpression = LuaIdentifierNameSyntax.System.MemberAccess(LuaIdentifierNameSyntax.Async).Invocation(); var wrapFunction = new LuaFunctionExpressionSyntax(); var parameters = function.ParameterList.Parameters; wrapFunction.AddParameter(LuaIdentifierNameSyntax.Async); wrapFunction.ParameterList.Parameters.AddRange(parameters); wrapFunction.AddStatements(function.Body.Statements); invokeExpression.AddArgument(wrapFunction); invokeExpression.AddArgument(returnsVoid ? LuaIdentifierNameSyntax.True : LuaIdentifierNameSyntax.Nil); invokeExpression.ArgumentList.Arguments.AddRange(parameters); function.Body.Statements.Clear(); if (returnsVoid) { function.AddStatement(invokeExpression); } else { function.AddStatement(new LuaReturnStatementSyntax(invokeExpression)); } } private sealed class MethodDeclarationResult { public IMethodSymbol Symbol; public LuaFunctionExpressionSyntax Function; public bool IsPrivate; public LuaIdentifierNameSyntax Name; public LuaDocumentStatement Document; public List<LuaExpressionSyntax> Attributes; public bool IsIgnore => Document is {HasIgnoreAttribute: true}; public bool IsMetadata => (Document is {HasMetadataAttribute: true}); } private void AddMethodMetaData(MethodDeclarationResult result, bool isMoreThanLocalVariables = false) { var table = new LuaTableExpression { IsSingleLine = true }; table.Add(new LuaStringLiteralExpressionSyntax(result.Symbol.Name)); table.Add(result.Symbol.GetMetaDataAttributeFlags()); if (isMoreThanLocalVariables) { table.Add(LuaIdentifierNameSyntax.MoreManyLocalVarTempTable.MemberAccess(result.Name)); } else { table.Add(result.Name); } var parameters = result.Symbol.Parameters.Select(i => GetTypeNameOfMetadata(i.Type)).ToList(); if (!result.Symbol.ReturnsVoid) { parameters.Add(GetTypeNameOfMetadata(result.Symbol.ReturnType)); } if (result.Symbol.IsGenericMethod) { var function = new LuaFunctionExpressionSyntax(); function.AddParameters(result.Symbol.TypeParameters.Select(i => (LuaIdentifierNameSyntax)i.Name)); function.AddStatement(new LuaReturnStatementSyntax(parameters)); table.Add(function); } else { table.AddRange(parameters); } table.AddRange(result.Attributes); CurType.AddMethodMetaData(table); } private MethodDeclarationResult BuildMethodDeclaration( CSharpSyntaxNode node, SyntaxList<AttributeListSyntax> attributeLists, ParameterListSyntax parameterList, TypeParameterListSyntax typeParameterList, BlockSyntax body, ArrowExpressionClauseSyntax expressionBody) { IMethodSymbol symbol = (IMethodSymbol)semanticModel_.GetDeclaredSymbol(node); var refOrOutParameters = new List<LuaExpressionSyntax>(); MethodInfo methodInfo = new MethodInfo(symbol, refOrOutParameters); methodInfos_.Push(methodInfo); var methodName = symbol.MethodKind == MethodKind.LocalFunction ? GetLocalMethodName(symbol, node) : GetMemberName(symbol); LuaFunctionExpressionSyntax function = new LuaFunctionExpressionSyntax(); PushFunction(function); var document = BuildDocumentationComment(node); bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; if (!symbol.IsStatic && symbol.MethodKind != MethodKind.LocalFunction) { function.AddParameter(LuaIdentifierNameSyntax.This); if (isPrivate) { if (generator_.IsForcePublicSymbol(symbol) || generator_.IsMonoBehaviourSpecialMethod(symbol)) { isPrivate = false; } } } else if (symbol.IsMainEntryPoint()) { isPrivate = false; generator_.SetMainEntryPoint(symbol, node); } else if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } var attributes = BuildAttributes(attributeLists); foreach (var parameterNode in parameterList.Parameters) { var parameter = parameterNode.Accept<LuaIdentifierNameSyntax>(this); function.AddParameter(parameter); if (parameterNode.Modifiers.IsOutOrRef()) { refOrOutParameters.Add(parameter); } else if (parameterNode.Modifiers.IsParams() && symbol.HasParamsAttribute()) { function.ParameterList.Parameters[^1] = LuaSyntaxNode.Tokens.Params; } } if (typeParameterList != null) { var typeParameters = typeParameterList.Accept<LuaParameterListSyntax>(this); function.AddParameters(typeParameters.Parameters); } if (body != null) { var block = body.Accept<LuaBlockSyntax>(this); function.AddStatements(block.Statements); } else { var expression = expressionBody.AcceptExpression(this); if (symbol.ReturnsVoid) { function.AddStatement(expression); } else { var returnStatement = new LuaReturnStatementSyntax(expression); returnStatement.Expressions.AddRange(refOrOutParameters); function.AddStatement(returnStatement); } } if (methodInfo.HasYield) { VisitYield(symbol, function); } else if (symbol.IsAsync) { VisitAsync(symbol.ReturnsVoid, function); } else { if (symbol.ReturnsVoid && refOrOutParameters.Count > 0) { function.AddStatement(new LuaReturnStatementSyntax(refOrOutParameters)); } } PopFunction(); methodInfos_.Pop(); return new MethodDeclarationResult { Symbol = symbol, Name = methodName, Function = function, IsPrivate = isPrivate, Document = document, Attributes = attributes, }; } private bool IsCurTypeExportMetadataAll { get { return generator_.Setting.IsExportMetadata || CurType.IsExportMetadataAll; } } private bool IsCurTypeSerializable { get { return IsCurTypeExportMetadataAll || CurTypeSymbol.IsSerializable; } } private static bool IsExportMethodDeclaration(BaseMethodDeclarationSyntax node) { return (node.Body != null || node.ExpressionBody != null) && !node.HasCSharpLuaAttribute(LuaDocumentStatement.AttributeFlags.Ignore); } public override LuaSyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node) { if (IsExportMethodDeclaration(node)) { var result = BuildMethodDeclaration(node, node.AttributeLists, node.ParameterList, node.TypeParameterList, node.Body, node.ExpressionBody); bool isMoreThanLocalVariables = IsMoreThanLocalVariables(result.Symbol); CurType.AddMethod(result.Name, result.Function, result.IsPrivate, result.Document, isMoreThanLocalVariables, result.Symbol.IsInterfaceDefaultMethod()); if (IsCurTypeExportMetadataAll || result.Attributes.Count > 0 || result.IsMetadata) { AddMethodMetaData(result, isMoreThanLocalVariables); } return result.Function; } return base.VisitMethodDeclaration(node); } private LuaExpressionSyntax BuildEnumNoConstantDefaultValue(ITypeSymbol typeSymbol) { var typeName = GetTypeName(typeSymbol); var field = typeSymbol.GetMembers().OfType<IFieldSymbol>().FirstOrDefault(i => i.ConstantValue.Equals(0)); if (field != null) { return typeName.MemberAccess(field.Name); } return typeName.Invocation(LuaNumberLiteralExpressionSyntax.Zero); } private LuaExpressionSyntax GetPredefinedValueTypeDefaultValue(ITypeSymbol typeSymbol) { switch (typeSymbol.SpecialType) { case SpecialType.None: { if (typeSymbol.TypeKind == TypeKind.Enum) { if (!generator_.IsConstantEnum(typeSymbol)) { return BuildEnumNoConstantDefaultValue(typeSymbol); } return LuaNumberLiteralExpressionSyntax.Zero; } if (typeSymbol.IsTimeSpanType()) { return BuildDefaultValue(LuaIdentifierNameSyntax.TimeSpan); } return null; } case SpecialType.System_Boolean: { return new LuaIdentifierLiteralExpressionSyntax(LuaIdentifierNameSyntax.False); } case SpecialType.System_Char: { return new LuaCharacterLiteralExpression(default); } case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: { return LuaNumberLiteralExpressionSyntax.Zero; } case SpecialType.System_Single: case SpecialType.System_Double: { return LuaNumberLiteralExpressionSyntax.ZeroFloat; } case SpecialType.System_DateTime: { return BuildDefaultValue(LuaIdentifierNameSyntax.DateTime); } default: return null; } } private static LuaInvocationExpressionSyntax BuildDefaultValue(LuaExpressionSyntax typeExpression) { return new(LuaIdentifierNameSyntax.SystemDefault, typeExpression); } private void AddFieldMetaData(IFieldSymbol symbol, LuaIdentifierNameSyntax fieldName, List<LuaExpressionSyntax> attributes) { var data = new LuaTableExpression { IsSingleLine = true }; data.Add(new LuaStringLiteralExpressionSyntax(symbol.Name)); data.Add(symbol.GetMetaDataAttributeFlags()); data.Add(GetTypeNameOfMetadata(symbol.Type)); if (generator_.IsNeedRefactorName(symbol)) { data.Add(new LuaStringLiteralExpressionSyntax(fieldName)); } data.AddRange(attributes); CurType.AddFieldMetaData(data); } private void VisitBaseFieldDeclarationSyntax(BaseFieldDeclarationSyntax node) { if (!node.Modifiers.IsConst()) { bool isStatic = node.Modifiers.IsStatic(); bool isPrivate = node.Modifiers.IsPrivate(); bool isReadOnly = node.Modifiers.IsReadOnly(); var attributes = BuildAttributes(node.AttributeLists); var type = node.Declaration.Type; ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol; bool isImmutable = typeSymbol.IsImmutable(); foreach (var variable in node.Declaration.Variables) { var variableSymbol = semanticModel_.GetDeclaredSymbol(variable); if (variableSymbol.IsAbstract) { continue; } if (node.IsKind(SyntaxKind.EventFieldDeclaration)) { var eventSymbol = (IEventSymbol)variableSymbol; if (!IsEventField(eventSymbol)) { var eventName = GetMemberName(eventSymbol); var innerName = AddInnerName(eventSymbol); LuaExpressionSyntax valueExpression = GetFieldValueExpression(typeSymbol, variable.Initializer?.Value, out bool valueIsLiteral, out var statements); LuaExpressionSyntax typeExpression = null; if (isStatic) { typeExpression = GetTypeName(eventSymbol.ContainingType); } var (add, remove) = CurType.AddEvent(eventName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements); if (attributes.Count > 0 || variableSymbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(variableSymbol, new PropertyMethodResult(add), new PropertyMethodResult(remove), null, attributes); } continue; } } if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) { isPrivate = false; } var fieldName = GetMemberName(variableSymbol); AddField(fieldName, typeSymbol, variable.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, attributes); if (IsCurTypeSerializable || attributes.Count > 0 || variableSymbol.HasMetadataAttribute()) { if (variableSymbol.Kind == SymbolKind.Field) { AddFieldMetaData((IFieldSymbol)variableSymbol, fieldName, attributes); } else { AddPropertyOrEventMetaData(variableSymbol, null, null, fieldName, attributes); } } } } else { bool isPrivate = node.Modifiers.IsPrivate(); var type = node.Declaration.Type; ITypeSymbol typeSymbol = (ITypeSymbol)semanticModel_.GetSymbolInfo(type).Symbol; if (typeSymbol.SpecialType == SpecialType.System_String) { foreach (var variable in node.Declaration.Variables) { var constValue = semanticModel_.GetConstantValue(variable.Initializer.Value); Contract.Assert(constValue.HasValue); string v = (string)constValue.Value; if (v is {Length: > kStringConstInlineCount}) { var variableSymbol = semanticModel_.GetDeclaredSymbol(variable); if (isPrivate && generator_.IsForcePublicSymbol(variableSymbol)) { isPrivate = false; } var attributes = BuildAttributes(node.AttributeLists); var fieldName = GetMemberName(variableSymbol); bool isMoreThanLocalVariables = IsMoreThanLocalVariables(variableSymbol); AddField(fieldName, typeSymbol, variable.Initializer.Value, true, true, isPrivate, true, attributes, isMoreThanLocalVariables); } } } } } public override LuaSyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node) { VisitBaseFieldDeclarationSyntax(node); return base.VisitFieldDeclaration(node); } private LuaExpressionSyntax GetFieldValueExpression(ITypeSymbol typeSymbol, ExpressionSyntax expression, out bool valueIsLiteral, out List<LuaStatementSyntax> statements) { LuaExpressionSyntax valueExpression = null; valueIsLiteral = false; statements = null; if (expression != null && !expression.IsKind(SyntaxKind.NullLiteralExpression)) { var function = new LuaFunctionExpressionSyntax(); PushFunction(function); valueExpression = VisitExpression(expression); PopFunction(); if (function.Body.Statements.Count > 0) { statements = function.Body.Statements; } LuaExpressionSyntax v = valueExpression; if (valueExpression is LuaPrefixUnaryExpressionSyntax prefixUnaryExpression) { v = prefixUnaryExpression.Operand; } valueIsLiteral = v is LuaLiteralExpressionSyntax; } if (valueExpression == null) { if (typeSymbol.IsMaybeValueType() && !typeSymbol.IsNullableType()) { var defaultValue = GetPredefinedValueTypeDefaultValue(typeSymbol); if (defaultValue != null) { valueExpression = defaultValue; valueIsLiteral = defaultValue is LuaLiteralExpressionSyntax; } else { valueExpression = GetDefaultValueExpression(typeSymbol); } } } return valueExpression; } private void AddField(LuaIdentifierNameSyntax name, ITypeSymbol typeSymbol, ExpressionSyntax expression, bool isImmutable, bool isStatic, bool isPrivate, bool isReadOnly, List<LuaExpressionSyntax> attributes, bool isMoreThanLocalVariables = false) { var valueExpression = GetFieldValueExpression(typeSymbol, expression, out bool valueIsLiteral, out var statements); CurType.AddField(name, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, isReadOnly, statements, isMoreThanLocalVariables); } private sealed class PropertyMethodResult { public LuaPropertyOrEventIdentifierNameSyntax Name { get; } public List<LuaExpressionSyntax> Attributes { get; } public PropertyMethodResult(LuaPropertyOrEventIdentifierNameSyntax name, List<LuaExpressionSyntax> attributes = null) { Name = name; Attributes = attributes; } } private void AddPropertyOrEventMetaData(ISymbol symbol, PropertyMethodResult get, PropertyMethodResult set, LuaIdentifierNameSyntax name, List<LuaExpressionSyntax> attributes) { bool isProperty = symbol.Kind == SymbolKind.Property; PropertyMethodKind kind; if (get != null) { kind = set != null ? PropertyMethodKind.Both : PropertyMethodKind.GetOnly; } else { kind = set != null ? PropertyMethodKind.SetOnly : PropertyMethodKind.Field; } var data = new LuaTableExpression { IsSingleLine = true }; data.Add(new LuaStringLiteralExpressionSyntax(symbol.Name)); data.Add(symbol.GetMetaDataAttributeFlags(kind)); var type = isProperty ? ((IPropertySymbol)symbol).Type : ((IEventSymbol)symbol).Type; data.Add(GetTypeNameOfMetadata(type)); if (kind == PropertyMethodKind.Field) { if (generator_.IsNeedRefactorName(symbol)) { data.Add(new LuaStringLiteralExpressionSyntax(name)); } } else { if (get != null) { if (get.Attributes.IsNullOrEmpty()) { data.Add(get.Name); } else { var getTable = new LuaTableExpression(); getTable.Add(get.Name); getTable.AddRange(get.Attributes); data.Add(getTable); } } if (set != null) { if (set.Attributes.IsNullOrEmpty()) { data.Add(set.Name); } else { var setTable = new LuaTableExpression(); setTable.Add(set.Name); setTable.AddRange(set.Attributes); data.Add(setTable); } } } data.AddRange(attributes); if (isProperty) { CurType.AddPropertyMetaData(data); } else { CurType.AddEventMetaData(data); } } public override LuaSyntaxNode VisitPropertyDeclaration(PropertyDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { bool isStatic = symbol.IsStatic; bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; bool hasGet = false; bool hasSet = false; if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } var propertyName = GetMemberName(symbol); var attributes = BuildAttributes(node.AttributeLists); PropertyMethodResult getMethod = null; PropertyMethodResult setMethod = null; if (node.AccessorList != null) { foreach (var accessor in node.AccessorList.Accessors) { if (accessor.Body != null || accessor.ExpressionBody != null) { var accessorSymbol = semanticModel_.GetDeclaredSymbol(accessor); var methodInfo = new MethodInfo(accessorSymbol); methodInfos_.Push(methodInfo); bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); var functionExpression = new LuaFunctionExpressionSyntax(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } PushFunction(functionExpression); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); functionExpression.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); if (isGet) { functionExpression.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); } else { if (bodyExpression != LuaExpressionSyntax.EmptyExpression) { functionExpression.AddStatement(bodyExpression); } } } if (methodInfo.HasYield) { VisitYield(accessorSymbol, functionExpression); } PopFunction(); methodInfos_.Pop(); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName); CurType.AddMethod(name, functionExpression, isPrivate, null, IsMoreThanLocalVariables(accessorSymbol)); var methodAttributes = BuildAttributes(accessor.AttributeLists); if (isGet) { Contract.Assert(!hasGet); hasGet = true; getMethod = new PropertyMethodResult(name, methodAttributes); } else { Contract.Assert(!hasSet); functionExpression.AddParameter(LuaIdentifierNameSyntax.Value); name.IsGetOrAdd = false; hasSet = true; setMethod = new PropertyMethodResult(name, methodAttributes); } } } } else { Contract.Assert(!hasGet); methodInfos_.Push(new MethodInfo(symbol.GetMethod)); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, propertyName); var functionExpression = new LuaFunctionExpressionSyntax(); PushFunction(functionExpression); var expression = node.ExpressionBody.AcceptExpression(this); PopFunction(); methodInfos_.Pop(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } var returnStatement = new LuaReturnStatementSyntax(expression); functionExpression.AddStatement(returnStatement); CurType.AddMethod(name, functionExpression, isPrivate); hasGet = true; getMethod = new PropertyMethodResult(name); } if (!hasGet && !hasSet) { ITypeSymbol typeSymbol = symbol.Type; bool isImmutable = typeSymbol.IsImmutable(); bool isField = IsPropertyField(semanticModel_.GetDeclaredSymbol(node)); if (isField) { bool isReadOnly = IsReadOnlyProperty(node); AddField(propertyName, typeSymbol, node.Initializer?.Value, isImmutable, isStatic, isPrivate, isReadOnly, attributes); } else { var innerName = AddInnerName(symbol); var valueExpression = GetFieldValueExpression(typeSymbol, node.Initializer?.Value, out bool valueIsLiteral, out var statements); LuaExpressionSyntax typeExpression = null; if (isStatic) { typeExpression = GetTypeName(symbol.ContainingType); } bool isGetOnly = symbol.SetMethod == null; var (getName, setName) = CurType.AddProperty(propertyName, innerName, valueExpression, isImmutable && valueIsLiteral, isStatic, isPrivate, typeExpression, statements, isGetOnly); getMethod = new PropertyMethodResult(getName); setMethod = isGetOnly ? null : new PropertyMethodResult(setName); } } if (IsCurTypeSerializable || attributes.Count > 0 || symbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(symbol, getMethod, setMethod, propertyName, attributes); } } return base.VisitPropertyDeclaration(node); } private bool IsReadOnlyProperty(PropertyDeclarationSyntax node) { return node.AccessorList.Accessors.Count == 1 && node.AccessorList.Accessors[0].Body == null; } public override LuaSyntaxNode VisitEventDeclaration(EventDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { var attributes = BuildAttributes(node.AttributeLists); bool isStatic = symbol.IsStatic; bool isPrivate = symbol.IsPrivate() && symbol.ExplicitInterfaceImplementations.IsEmpty; var eventName = GetMemberName(symbol); PropertyMethodResult addMethod = null; PropertyMethodResult removeMethod = null; foreach (var accessor in node.AccessorList.Accessors) { var methodAttributes = BuildAttributes(accessor.AttributeLists); var functionExpression = new LuaFunctionExpressionSyntax(); if (!isStatic) { functionExpression.AddParameter(LuaIdentifierNameSyntax.This); } functionExpression.AddParameter(LuaIdentifierNameSyntax.Value); PushFunction(functionExpression); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); functionExpression.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); functionExpression.AddStatement(bodyExpression); } PopFunction(); var name = new LuaPropertyOrEventIdentifierNameSyntax(false, eventName); CurType.AddMethod(name, functionExpression, isPrivate); if (accessor.IsKind(SyntaxKind.RemoveAccessorDeclaration)) { name.IsGetOrAdd = false; removeMethod = new PropertyMethodResult(name, methodAttributes); } else { addMethod = new PropertyMethodResult(name, methodAttributes); } } if (attributes.Count > 0 || symbol.HasMetadataAttribute()) { AddPropertyOrEventMetaData(symbol, addMethod, removeMethod, null, attributes); } } return base.VisitEventDeclaration(node); } public override LuaSyntaxNode VisitEventFieldDeclaration(EventFieldDeclarationSyntax node) { VisitBaseFieldDeclarationSyntax(node); return base.VisitEventFieldDeclaration(node); } public override LuaSyntaxNode VisitEnumMemberDeclaration(EnumMemberDeclarationSyntax node) { IFieldSymbol symbol = semanticModel_.GetDeclaredSymbol(node); Contract.Assert(symbol.HasConstantValue); var attributes = BuildAttributes(node.AttributeLists); LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; AddFieldMetaData(symbol, identifier, attributes); var value = new LuaIdentifierLiteralExpressionSyntax(symbol.ConstantValue.ToString()); return new LuaKeyValueTableItemSyntax(identifier, value); } public override LuaSyntaxNode VisitIndexerDeclaration(IndexerDeclarationSyntax node) { var symbol = semanticModel_.GetDeclaredSymbol(node); if (!symbol.IsAbstract) { bool isPrivate = symbol.IsPrivate(); var indexName = GetMemberName(symbol); var parameterList = node.ParameterList.Accept<LuaParameterListSyntax>(this); void Fill(Action<LuaFunctionExpressionSyntax, LuaPropertyOrEventIdentifierNameSyntax> action) { var function = new LuaFunctionExpressionSyntax(); function.AddParameter(LuaIdentifierNameSyntax.This); function.ParameterList.Parameters.AddRange(parameterList.Parameters); var name = new LuaPropertyOrEventIdentifierNameSyntax(true, indexName); PushFunction(function); action(function, name); PopFunction(); CurType.AddMethod(name, function, isPrivate); } if (node.AccessorList != null) { foreach (var accessor in node.AccessorList.Accessors) { Fill((function, name) => { bool isGet = accessor.IsKind(SyntaxKind.GetAccessorDeclaration); if (accessor.Body != null) { var block = accessor.Body.Accept<LuaBlockSyntax>(this); function.AddStatements(block.Statements); } else { var bodyExpression = accessor.ExpressionBody.AcceptExpression(this); if (isGet) { function.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); } else { function.AddStatement(bodyExpression); } } if (!isGet) { function.AddParameter(LuaIdentifierNameSyntax.Value); name.IsGetOrAdd = false; } }); } } else { Fill((function, name) => { var bodyExpression = node.ExpressionBody.AcceptExpression(this); function.AddStatement(new LuaReturnStatementSyntax(bodyExpression)); }); } } return base.VisitIndexerDeclaration(node); } public override LuaSyntaxNode VisitBracketedParameterList(BracketedParameterListSyntax node) { return BuildParameterList(node.Parameters); } public override LuaSyntaxNode VisitParameterList(ParameterListSyntax node) { return BuildParameterList(node.Parameters); } private LuaSyntaxNode BuildParameterList(SeparatedSyntaxList<ParameterSyntax> parameters) { var parameterList = new LuaParameterListSyntax(); foreach (var parameter in parameters) { var newNode = parameter.Accept<LuaIdentifierNameSyntax>(this); parameterList.Parameters.Add(newNode); } return parameterList; } public override LuaSyntaxNode VisitParameter(ParameterSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); return identifier; } private sealed class BlockCommonNode : IComparable<BlockCommonNode> { public SyntaxTrivia SyntaxTrivia { get; } public CSharpSyntaxNode SyntaxNode { get; } public FileLinePositionSpan LineSpan { get; } public BlockCommonNode(SyntaxTrivia syntaxTrivia) { SyntaxTrivia = syntaxTrivia; LineSpan = syntaxTrivia.SyntaxTree.GetLineSpan(syntaxTrivia.Span); } public BlockCommonNode(CSharpSyntaxNode statement) { SyntaxNode = statement; LineSpan = statement.SyntaxTree.GetLineSpan(statement.Span); } public int CompareTo(BlockCommonNode other) { return LineSpan.StartLinePosition.CompareTo(other.LineSpan.StartLinePosition); } public bool Contains(BlockCommonNode other) { var otherLineSpan = other.LineSpan; return otherLineSpan.StartLinePosition > LineSpan.StartLinePosition && otherLineSpan.EndLinePosition < LineSpan.EndLinePosition; } public LuaBlankLinesStatement CheckBlankLine(ref int lastLine) { LuaBlankLinesStatement statement = null; if (lastLine != -1) { if (SyntaxTrivia != null && SyntaxTrivia.Kind() == SyntaxKind.DisabledTextTrivia) { ++lastLine; } int count = LineSpan.StartLinePosition.Line - lastLine - 1; if (count > 0) { statement = new LuaBlankLinesStatement(count); } } lastLine = LineSpan.EndLinePosition.Line; return statement; } public LuaSyntaxNode Visit(LuaSyntaxNodeTransform transfor) { const int kCommentCharCount = 2; if (SyntaxNode != null) { try { var node = SyntaxNode.Accept(transfor); return node ?? throw new InvalidOperationException(); } catch (CompilationErrorException e) { throw e.With(SyntaxNode); } catch (BugErrorException) { throw; } catch (Exception e) { if (e.InnerException is CompilationErrorException ex) { throw ex.With(SyntaxNode); } throw new BugErrorException(SyntaxNode, e); } } string content = SyntaxTrivia.ToString(); switch (SyntaxTrivia.Kind()) { case SyntaxKind.SingleLineCommentTrivia: { string commentContent = content[kCommentCharCount..]; return new LuaShortCommentStatement(commentContent); } case SyntaxKind.MultiLineCommentTrivia: { string commentContent = content[kCommentCharCount..^kCommentCharCount]; commentContent = commentContent.ReplaceNewline(); if (CheckInsertLuaCodeTemplate(commentContent, out var codeStatement)) { return codeStatement; } return new LuaLongCommentStatement(commentContent); } case SyntaxKind.SingleLineDocumentationCommentTrivia: case SyntaxKind.DisabledTextTrivia: { return LuaStatementSyntax.Empty; } case SyntaxKind.RegionDirectiveTrivia: case SyntaxKind.EndRegionDirectiveTrivia: { return new LuaShortCommentStatement(content); } default: throw new InvalidOperationException(); } } private bool CheckInsertLuaCodeTemplate(string commentContent, out LuaStatementSyntax statement) { statement = null; char openBracket = LuaSyntaxNode.Tokens.OpenBracket[0]; int index = commentContent.IndexOf(openBracket); if (index != -1) { char equals = LuaSyntaxNode.Tokens.Equals[0]; int count = 0; ++index; while (commentContent[index] == equals) { ++index; ++count; } if (commentContent[index] == openBracket) { string closeToken = LuaSyntaxNode.Tokens.CloseBracket + new string(equals, count) + LuaSyntaxNode.Tokens.CloseBracket; int begin = index + 1; int end = commentContent.IndexOf(closeToken, begin, StringComparison.Ordinal); if (end != -1) { string codeString = commentContent[begin..end]; string[] lines = codeString.Split('\n'); var codeLines = new LuaStatementListSyntax(); int indent = -1; foreach (string line in lines) { if (!string.IsNullOrWhiteSpace(line)) { if (indent == -1) { indent = line.IndexOf(i => !char.IsWhiteSpace(i)); } int space = line.IndexOf(i => !char.IsWhiteSpace(i)); string code = space >= indent && indent != -1 ? line[indent..] : line; codeLines.Statements.Add((LuaIdentifierNameSyntax)code); } } statement = codeLines; return true; } } } return false; } } private IEnumerable<LuaStatementSyntax> VisitTriviaAndNode(SyntaxNode rootNode, IEnumerable<CSharpSyntaxNode> nodes, bool isCheckBlank = true) { var syntaxTrivias = rootNode.DescendantTrivia().Where(i => i.IsExportSyntaxTrivia(rootNode)); var syntaxTriviaNodes = syntaxTrivias.Select(i => new BlockCommonNode(i)); List<BlockCommonNode> list = nodes.Select(i => new BlockCommonNode(i)).ToList(); bool hasComments = false; foreach (var comment in syntaxTriviaNodes) { bool isContains = list.Any(i => i.Contains(comment)); if (!isContains) { list.Add(comment); hasComments = true; } } if (hasComments) { list.Sort(); } int lastLine = -1; foreach (var common in list) { if (isCheckBlank) { var black = common.CheckBlankLine(ref lastLine); if (black != null) { yield return black; } } yield return (LuaStatementSyntax)common.Visit(this); } } public override LuaSyntaxNode VisitBlock(BlockSyntax node) { LuaBlockStatementSyntax block = new LuaBlockStatementSyntax(); PushBlock(block); var statements = VisitTriviaAndNode(node, node.Statements); block.Statements.AddRange(statements); var indexes = block.UsingDeclarations; if (indexes != null) { block.UsingDeclarations = null; ApplyUsingDeclarations(block, indexes, node); } PopBlock(); return block; } private LuaReturnStatementSyntax BuildLoopControlReturnStatement(LuaExpressionSyntax expression) { var returnStatement = new LuaReturnStatementSyntax(LuaIdentifierLiteralExpressionSyntax.True); if (expression != null) { returnStatement.Expressions.Add(expression); } return returnStatement; } private LuaStatementSyntax InternalVisitReturnStatement(LuaExpressionSyntax expression, ReturnStatementSyntax node = null) { if (CurFunction is LuaCheckLoopControlExpressionSyntax check) { check.HasReturn = true; return BuildLoopControlReturnStatement(expression); } if (CurBlock.HasUsingDeclarations) { return BuildLoopControlReturnStatement(expression); } LuaStatementSyntax result; var curMethodInfo = CurMethodInfoOrNull; if (curMethodInfo != null && curMethodInfo.RefOrOutParameters.Count > 0) { if (curMethodInfo.IsInlining) { var multipleAssignment = new LuaMultipleAssignmentExpressionSyntax(); multipleAssignment.Lefts.AddRange(curMethodInfo.InliningReturnVars); if (expression != null) { multipleAssignment.Rights.Add(expression); } multipleAssignment.Rights.AddRange(curMethodInfo.RefOrOutParameters); result = multipleAssignment; } else { var returnStatement = new LuaReturnStatementSyntax(); if (expression != null) { returnStatement.Expressions.Add(expression); } returnStatement.Expressions.AddRange(curMethodInfo.RefOrOutParameters); result = returnStatement; } } else { if (curMethodInfo?.IsInlining == true) { Contract.Assert(curMethodInfo.InliningReturnVars.Count == 1); var assignment = curMethodInfo.InliningReturnVars.First().Assignment(expression); if (node != null && !IsLastStatement(node)) { var statements = new LuaStatementListSyntax(); statements.Statements.Add(assignment); statements.Statements.Add(new LuaGotoStatement(LuaIdentifierNameSyntax.InlineReturnLabel)); result = statements; curMethodInfo.HasInlineGoto = true; } else { result = assignment; } } else { result = new LuaReturnStatementSyntax(expression); } } return result; } public override LuaSyntaxNode VisitReturnStatement(ReturnStatementSyntax node) { var expression = node.Expression != null ? VisitExpression(node.Expression) : null; var result = InternalVisitReturnStatement(expression, node); if (node.Parent.IsKind(SyntaxKind.Block) && node.Parent.Parent is MemberDeclarationSyntax) { var block = (BlockSyntax)node.Parent; if (block.Statements.Last() != node) { var blockStatement = new LuaBlockStatementSyntax(); blockStatement.Statements.Add(result); result = blockStatement; } else if (expression == null) { result = LuaStatementSyntax.Empty; } } return result; } public override LuaSyntaxNode VisitExpressionStatement(ExpressionStatementSyntax node) { var expression = node.Expression.AcceptExpression(this); ReleaseTempIdentifiers(); if (expression != LuaExpressionSyntax.EmptyExpression) { if (expression is LuaLiteralExpressionSyntax) { return new LuaShortCommentExpressionStatement(expression); } return new LuaExpressionStatementSyntax(expression); } return LuaStatementSyntax.Empty; } private LuaExpressionSyntax BuildCommonAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, ExpressionSyntax rightNode, ExpressionSyntax parent) { bool isPreventDebugConcatenation = IsPreventDebug && operatorToken == LuaSyntaxNode.Tokens.Concatenation; if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { LuaExpressionSyntax expression = null; var getter = propertyAdapter.GetCloneOfGet(); LuaExpressionSyntax leftExpression = getter; if (isPreventDebugConcatenation) { leftExpression = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, leftExpression); } if (parent != null) { expression = GetUserDefinedOperatorExpression(parent, leftExpression, right); } expression ??= leftExpression.Binary(operatorToken, right); propertyAdapter.ArgumentList.AddArgument(expression); return propertyAdapter; } else { LuaExpressionSyntax expression = null; LuaExpressionSyntax leftExpression = left; if (isPreventDebugConcatenation) { leftExpression = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, leftExpression); } if (parent != null) { expression = GetUserDefinedOperatorExpression(parent, leftExpression, right); } if (expression == null) { bool isRightParenthesized = rightNode is BinaryExpressionSyntax || rightNode.IsKind(SyntaxKind.ConditionalExpression); if (isRightParenthesized) { right = right.Parenthesized(); } expression = leftExpression.Binary(operatorToken, right); } return left.Assignment(expression); } } private LuaExpressionSyntax BuildCommonAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string operatorToken, ExpressionSyntax parent) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); return BuildCommonAssignmentExpression(left, right, operatorToken, rightNode, parent); } private LuaExpressionSyntax BuildDelegateBinaryExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isPlus) { if (IsPreventDebug) { var methodName = isPlus ? LuaIdentifierNameSyntax.DelegateCombine : LuaIdentifierNameSyntax.DelegateRemove; return new LuaInvocationExpressionSyntax(methodName, left, right); } var operatorToken = isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; return left.Binary(operatorToken, right); } private LuaExpressionSyntax BuildDelegateAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isPlus) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { if (propertyAdapter.IsProperty) { propertyAdapter.ArgumentList.AddArgument(BuildDelegateBinaryExpression(propertyAdapter.GetCloneOfGet(), right, isPlus)); return propertyAdapter; } propertyAdapter.IsGetOrAdd = isPlus; propertyAdapter.ArgumentList.AddArgument(right); return propertyAdapter; } return left.Assignment(BuildDelegateBinaryExpression(left, right, isPlus)); } private LuaExpressionSyntax BuildBinaryInvokeAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, LuaExpressionSyntax methodName) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var invocation = new LuaInvocationExpressionSyntax(methodName, propertyAdapter.GetCloneOfGet(), right); propertyAdapter.ArgumentList.AddArgument(invocation); return propertyAdapter; } else { var invocation = new LuaInvocationExpressionSyntax(methodName, left, right); return left.Assignment(invocation); } } private LuaExpressionSyntax BuildBinaryInvokeAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, LuaExpressionSyntax methodName) { var left = leftNode.AcceptExpression(this); var right = rightNode.AcceptExpression(this); return BuildBinaryInvokeAssignmentExpression(left, right, methodName); } private LuaExpressionSyntax BuildLuaSimpleAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { propertyAdapter.IsGetOrAdd = false; propertyAdapter.ArgumentList.AddArgument(right); return propertyAdapter; } return left.Assignment(right); } private List<LuaExpressionSyntax> BuildNumberNullableIdentifiers(ref LuaExpressionSyntax left, ref LuaExpressionSyntax right, bool isLeftNullable, bool isRightNullable) { var identifiers = new List<LuaExpressionSyntax>(); if (isLeftNullable) { if (isRightNullable) { left = BuildNullableExpressionIdentifier(left, identifiers); right = BuildNullableExpressionIdentifier(right, identifiers); } else { left = BuildNullableExpressionIdentifier(left, identifiers); } } else { right = BuildNullableExpressionIdentifier(right, identifiers); } return identifiers; } private static void TransformIdentifiersForCompareExpression(List<LuaExpressionSyntax> identifiers) { for (int i = 0; i < identifiers.Count; ++i) { var identifier = identifiers[i]; identifiers[i] = identifier.NotEquals(LuaIdentifierNameSyntax.Nil); } } private static void CheckNumberNullableCompareExpression(string operatorToken, List<LuaExpressionSyntax> identifiers) { switch (operatorToken) { case ">": case ">=": case "<": case "<=": { TransformIdentifiersForCompareExpression(identifiers); break; } } } private LuaExpressionSyntax BuildNumberNullableExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, bool isLeftNullable, bool isRightNullable, LuaIdentifierNameSyntax method) { if (left.IsNil() || right.IsNil()) { return LuaIdentifierLiteralExpressionSyntax.Nil; } var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullable, isRightNullable); LuaExpressionSyntax expression; if (method != null) { expression = new LuaInvocationExpressionSyntax(method, left, right); } else { expression = left.Binary(operatorToken, right); CheckNumberNullableCompareExpression(operatorToken, identifiers); } return identifiers.Aggregate((x, y) => x.And(y)).And(expression); } private LuaExpressionSyntax BuildNumberNullableAssignment(LuaExpressionSyntax left, LuaExpressionSyntax right, string operatorToken, bool isLeftNullable, bool isRightNullable, LuaIdentifierNameSyntax method) { if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { Contract.Assert(propertyAdapter.IsProperty); propertyAdapter.ArgumentList.AddArgument(BuildNumberNullableExpression(propertyAdapter.GetCloneOfGet(), right, operatorToken, isLeftNullable, isRightNullable, method)); return propertyAdapter; } return left.Assignment(BuildNumberNullableExpression(left, right, operatorToken, isLeftNullable, isRightNullable, method)); } private bool IsNullableType(ExpressionSyntax leftNode, ExpressionSyntax rightNode, out bool isLeftNullable, out bool isRightNullable) { var leftType = semanticModel_.GetTypeInfo(leftNode).Type; var rightType = semanticModel_.GetTypeInfo(rightNode).Type; isLeftNullable = leftType != null && leftType.IsNullableType(); isRightNullable = rightType != null && rightType.IsNullableType(); return isLeftNullable || isRightNullable; } private bool IsNullableType(ExpressionSyntax leftNode, ExpressionSyntax rightNode) => IsNullableType(leftNode, rightNode, out _, out _); private bool IsNullableAssignmentExpression(ExpressionSyntax left, ExpressionSyntax right, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (IsNullableType(left, right, out bool isLeftNullable, out bool isRightNullable)) { var leftExpression = left.AcceptExpression(this); var rightExpression = right.AcceptExpression(this); result = BuildNumberNullableAssignment(leftExpression, rightExpression, operatorToken, isLeftNullable, isRightNullable, method); return true; } result = null; return false; } private bool IsNumberNullableAssignmentExpression(INamedTypeSymbol containingType, ExpressionSyntax left, ExpressionSyntax right, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (containingType.IsNumberType(false)) { if (IsNullableAssignmentExpression(left, right, operatorToken, out result, method)) { return true; } } result = null; return false; } private LuaExpressionSyntax BuildNumberAssignmentExpression(ExpressionSyntax node, ExpressionSyntax leftNode, ExpressionSyntax rightNode, SyntaxKind kind) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol symbol) { var containingType = symbol.ContainingType; if (containingType != null) { switch (kind) { case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: { if (containingType.IsStringType()) { var left = leftNode.AcceptExpression(this); var right = WrapStringConcatExpression(rightNode); return BuildCommonAssignmentExpression(left, right, LuaSyntaxNode.Tokens.Concatenation, rightNode, null); } bool isPlus = kind == SyntaxKind.AddAssignmentExpression; if (containingType.IsDelegateType() || symbol.MethodKind is MethodKind.EventAdd or MethodKind.EventRemove) { var left = leftNode.AcceptExpression(this); var right = rightNode.AcceptExpression(this); return BuildDelegateAssignmentExpression(left, right, isPlus); } if (IsPreventDebug) { if (IsNumberNullableAssignmentExpression(containingType, leftNode, rightNode, isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } } break; } case SyntaxKind.MultiplyAssignmentExpression: { if (IsNumberNullableAssignmentExpression(containingType, leftNode, rightNode, LuaSyntaxNode.Tokens.Multiply, out var result)) { return result; } break; } case SyntaxKind.DivideAssignmentExpression: { if (IsPreventDebug && containingType.IsDoubleOrFloatType(false)) { if (IsNullableAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.Div, out var result)) { return result; } } if (containingType.IsIntegerType(false)) { if (IsNullableType(leftNode, rightNode)) { if (IsLuaClassic || IsPreventDebug) { bool success = IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, LuaIdentifierNameSyntax.IntegerDiv); Contract.Assert(success); return result; } } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, LuaIdentifierNameSyntax.IntegerDiv); } break; } case SyntaxKind.ModuloAssignmentExpression: { if (containingType.IsNumberType(false)) { if (IsLuaClassic) { var method = containingType.IsIntegerType(false) ? LuaIdentifierNameSyntax.Mod : LuaIdentifierNameSyntax.ModFloat; if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, method)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, method); } else { if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, LuaIdentifierNameSyntax.Mod)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, LuaIdentifierNameSyntax.Mod); } } break; } case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: { if (containingType.IsIntegerType(false)) { bool isLeftShift = kind == SyntaxKind.LeftShiftAssignmentExpression; if (IsLuaClassic) { var method = isLeftShift ? LuaIdentifierNameSyntax.ShiftLeft : LuaIdentifierNameSyntax.ShiftRight; if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, method)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, method); } else if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, isLeftShift ? LuaSyntaxNode.Tokens.ShiftLeft : LuaSyntaxNode.Tokens.ShiftRight, out var result)) { return result; } } break; } } } } return null; } private LuaExpressionSyntax BuildLuaAssignmentExpression(AssignmentExpressionSyntax node, ExpressionSyntax leftNode, ExpressionSyntax rightNode, SyntaxKind kind) { LuaExpressionSyntax resultExpression = null; switch (kind) { case SyntaxKind.SimpleAssignmentExpression: { var left = leftNode.AcceptExpression(this); var right = VisitExpression(rightNode); if (leftNode.Kind().IsTupleDeclaration()) { if (!rightNode.IsKind(SyntaxKind.TupleExpression)) { right = BuildDeconstructExpression(rightNode, right); } } else if (leftNode.IsKind(SyntaxKind.IdentifierName) && left == LuaIdentifierNameSyntax.Placeholder) { var local = new LuaLocalVariableDeclaratorSyntax(LuaIdentifierNameSyntax.Placeholder, right); CurBlock.AddStatement(local); return LuaExpressionSyntax.EmptyExpression; } else if (leftNode.IsKind(SyntaxKind.ThisExpression)) { return left.MemberAccess(LuaIdentifierNameSyntax.CopyThis, true).Invocation(right); } return BuildLuaSimpleAssignmentExpression(left, right); } case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: resultExpression = BuildNumberAssignmentExpression(node, leftNode, rightNode, kind); break; case SyntaxKind.AndAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.And, LuaIdentifierNameSyntax.BitAnd, node); break; } case SyntaxKind.ExclusiveOrAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.NotEquals, LuaIdentifierNameSyntax.BitXor, node); break; } case SyntaxKind.OrAssignmentExpression: { resultExpression = BuildBitAssignmentExpression(leftNode, rightNode, LuaSyntaxNode.Tokens.Or, LuaIdentifierNameSyntax.BitOr, node); break; } case SyntaxKind.CoalesceAssignmentExpression: { var left = leftNode.AcceptExpression(this); var right = VisitExpression(rightNode); var ifStatement = new LuaIfStatementSyntax(left.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(left.Assignment(right)); CurBlock.AddStatement(ifStatement); return LuaExpressionSyntax.EmptyExpression; } } if (resultExpression != null) { return resultExpression; } string operatorToken = GetOperatorToken(node.OperatorToken.ValueText[..^1]); return BuildCommonAssignmentExpression(leftNode, rightNode, operatorToken, node); } private LuaIdentifierNameSyntax BuildBoolXorOfNullAssignmentExpression(LuaExpressionSyntax left, LuaExpressionSyntax right, bool isLeftNullable, bool isRightNullable) { var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullable, isRightNullable); LuaExpressionSyntax condition = identifiers.Count == 1 ? identifiers.First().NotEquals(LuaIdentifierNameSyntax.Nil) : left.NotEquals(LuaIdentifierNameSyntax.Nil).And(right.NotEquals(LuaIdentifierNameSyntax.Nil)); var ifStatement = new LuaIfStatementSyntax(condition); ifStatement.Body.AddStatement(temp.Assignment(left.NotEquals(right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildBoolXorOfNullAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, bool isLeftNullable, bool isRightNullable) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); LuaExpressionSyntax result; if (right.IsNil()) { result = new LuaConstLiteralExpression(LuaIdentifierLiteralExpressionSyntax.Nil, rightNode.ToString()); } else if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { result = BuildBoolXorOfNullAssignmentExpression(propertyAdapter.GetCloneOfGet(), right, isLeftNullable, isRightNullable); } else { result = BuildBoolXorOfNullAssignmentExpression(left, right, isLeftNullable, isRightNullable); } return BuildLuaSimpleAssignmentExpression(left, result); } private LuaExpressionSyntax BuildLeftNullableBoolLogicAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string boolOperatorToken) { var left = VisitExpression(leftNode); var right = VisitExpression(rightNode); var temp = GetTempIdentifier(); LuaExpressionSyntax identifier; CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); if (left is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var getter = propertyAdapter.GetCloneOfGet(); identifier = BuildNullableExpressionIdentifier(getter, new List<LuaExpressionSyntax>()); } else { identifier = BuildNullableExpressionIdentifier(left, new List<LuaExpressionSyntax>()); } var ifStatement = new LuaIfStatementSyntax(identifier.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(right.Binary(boolOperatorToken, identifier))); ifStatement.Else = new LuaElseClauseSyntax(); ifStatement.Else.Body.AddStatement(temp.Assignment(identifier.Binary(boolOperatorToken, right))); CurBlock.AddStatement(ifStatement); return BuildLuaSimpleAssignmentExpression(left, temp); } private LuaExpressionSyntax BuildBitAssignmentExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode, string boolOperatorToken, LuaIdentifierNameSyntax methodName, ExpressionSyntax parent) { if (semanticModel_.GetSymbolInfo(parent).Symbol is IMethodSymbol symbol) { var containingType = symbol.ContainingType; if (containingType != null) { if (containingType.IsBoolType(false)) { switch (parent.Kind()) { case SyntaxKind.ExclusiveOrAssignmentExpression: { if (IsNullableType(leftNode, rightNode, out bool isLeftNullable, out bool isRightNullable)) { return BuildBoolXorOfNullAssignmentExpression(leftNode, rightNode, isLeftNullable, isRightNullable); } break; } case SyntaxKind.AndAssignmentExpression: case SyntaxKind.OrAssignmentExpression: { if (IsNullableType(leftNode, rightNode, out bool isLeftNullable, out _) && isLeftNullable) { return BuildLeftNullableBoolLogicAssignmentExpression(leftNode, rightNode, boolOperatorToken); } break; } } return BuildCommonAssignmentExpression(leftNode, rightNode, boolOperatorToken, null); } if (containingType.IsIntegerType(false) || containingType.TypeKind == TypeKind.Enum) { if (IsLuaClassic) { if (IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, methodName)) { return result; } return BuildBinaryInvokeAssignmentExpression(leftNode, rightNode, methodName); } else if (IsPreventDebug && IsNullableAssignmentExpression(leftNode, rightNode, null, out var result, methodName)) { return result; } } } } return null; } private LuaExpressionSyntax InternalVisitAssignmentExpression(AssignmentExpressionSyntax node) { List<LuaExpressionSyntax> assignments = new List<LuaExpressionSyntax>(); while (true) { var leftExpression = node.Left; var rightExpression = node.Right; var kind = node.Kind(); if (rightExpression is AssignmentExpressionSyntax assignmentRight) { assignments.Add(BuildLuaAssignmentExpression(node, leftExpression, assignmentRight.Left, kind)); node = assignmentRight; } else { assignments.Add(BuildLuaAssignmentExpression(node, leftExpression, rightExpression, kind)); break; } } if (assignments.Count == 1) { return assignments.First(); } assignments.Reverse(); LuaLineMultipleExpressionSyntax multipleAssignment = new LuaLineMultipleExpressionSyntax(); multipleAssignment.Assignments.AddRange(assignments); return multipleAssignment; } private bool IsInlineAssignment(AssignmentExpressionSyntax node) { bool isInlineAssignment = false; SyntaxKind kind = node.Parent.Kind(); switch (kind) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ForStatement: break; case SyntaxKind.ArrowExpressionClause: { var symbol = semanticModel_.GetDeclaredSymbol(node.Parent.Parent); switch (symbol.Kind) { case SymbolKind.Method: var method = (IMethodSymbol)symbol; if (!method.ReturnsVoid) { isInlineAssignment = true; } break; case SymbolKind.Property: { var property = (IPropertySymbol)symbol; if (!property.GetMethod.ReturnsVoid) { isInlineAssignment = true; } break; } } break; } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: { var method = CurMethodInfoOrNull.Symbol; if (!method.ReturnsVoid) { isInlineAssignment = true; } break; } default: isInlineAssignment = true; break; } return isInlineAssignment; } public override LuaSyntaxNode VisitAssignmentExpression(AssignmentExpressionSyntax node) { var assignment = InternalVisitAssignmentExpression(node); if (IsInlineAssignment(node)) { CurBlock.Statements.Add(assignment); if (assignment is LuaLineMultipleExpressionSyntax lineMultipleExpression) { assignment = lineMultipleExpression.Assignments.Last(); } if (assignment is LuaAssignmentExpressionSyntax assignmentExpression) { assignment = assignmentExpression.Left; } else { assignment = node.Left.AcceptExpression(this); } } return assignment; } private sealed class RefOrOutArgument { public LuaExpressionSyntax Expression { get; } public bool IsDeclaration { get; } public bool IsSpecial { get; } public RefOrOutArgument(LuaExpressionSyntax expression) { Expression = expression; } public RefOrOutArgument(LuaExpressionSyntax expression, ArgumentSyntax argument) { Expression = expression; IsSpecial = IsInSpecialBinaryExpression(argument); IsDeclaration = (argument.Expression.IsKind(SyntaxKind.DeclarationExpression) && !IsSpecial) || expression == LuaIdentifierNameSyntax.Placeholder; } private static bool IsInSpecialBinaryExpression(ArgumentSyntax argument) { if (argument.Expression.IsKind(SyntaxKind.DeclarationExpression)) { var invocationExpression = (InvocationExpressionSyntax)argument.Parent.Parent; var parent = invocationExpression.Parent; if (parent.IsKind(SyntaxKind.LogicalAndExpression) || parent.IsKind(SyntaxKind.LogicalOrExpression)) { var binaryExpression = (BinaryExpressionSyntax)parent; if (binaryExpression.Right == invocationExpression) { return true; } } } return false; } } private LuaExpressionSyntax BuildInvokeRefOrOut(CSharpSyntaxNode node, LuaExpressionSyntax invocation, IEnumerable<RefOrOutArgument> refOrOutArguments) { var locals = new LuaLocalVariablesSyntax(); var multipleAssignment = new LuaMultipleAssignmentExpressionSyntax(); var propertyStatements = new LuaStatementListSyntax(); void FillRefOrOutArguments() { foreach (var refOrOutArgument in refOrOutArguments) { // fn(out arr[0]) if (refOrOutArgument.Expression is LuaPropertyAdapterExpressionSyntax propertyAdapter) { var propertyTemp = GetTempIdentifier(); locals.Variables.Add(propertyTemp); multipleAssignment.Lefts.Add(propertyTemp); var setPropertyAdapter = propertyAdapter.GetClone(); setPropertyAdapter.IsGetOrAdd = false; setPropertyAdapter.ArgumentList.AddArgument(propertyTemp); propertyStatements.Statements.Add(setPropertyAdapter); } else { if (refOrOutArgument.IsDeclaration) { locals.Variables.Add((LuaIdentifierNameSyntax)refOrOutArgument.Expression); } else if (refOrOutArgument.IsSpecial) { CurFunction.Body.AddHeadVariable((LuaIdentifierNameSyntax)refOrOutArgument.Expression); } multipleAssignment.Lefts.Add(refOrOutArgument.Expression); } } } switch (node.Parent.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ConstructorDeclaration: { var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (!symbol.ReturnsVoid || node.IsKind(SyntaxKind.ObjectCreationExpression)) { var temp = node.Parent.IsKind(SyntaxKind.ExpressionStatement) ? LuaIdentifierNameSyntax.Placeholder : GetTempIdentifier(); locals.Variables.Add(temp); multipleAssignment.Lefts.Add(temp); } FillRefOrOutArguments(); multipleAssignment.Rights.Add(invocation); if (locals.Variables.Count > 0) { CurBlock.Statements.Add(locals); if (locals.Variables.SequenceEqual(multipleAssignment.Lefts)) { locals.Initializer = new LuaEqualsValueClauseListSyntax(multipleAssignment.Rights); if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(propertyStatements); } return LuaExpressionSyntax.EmptyExpression; } } if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(multipleAssignment); CurBlock.Statements.Add(propertyStatements); return LuaExpressionSyntax.EmptyExpression; } return multipleAssignment; } default: { bool isReturnsVoid = false; if (node.Parent.IsKind(SyntaxKind.ArrowExpressionClause)) { isReturnsVoid = CurMethodInfoOrNull?.Symbol.ReturnsVoid == true; } var temp = !isReturnsVoid ? GetTempIdentifier() : LuaIdentifierNameSyntax.Placeholder; locals.Variables.Add(temp); multipleAssignment.Lefts.Add(temp); FillRefOrOutArguments(); multipleAssignment.Rights.Add(invocation); CurBlock.Statements.Add(locals); if (locals.Variables.SequenceEqual(multipleAssignment.Lefts)) { locals.Initializer = new LuaEqualsValueClauseListSyntax(multipleAssignment.Rights); } else { CurBlock.Statements.Add(multipleAssignment); } if (propertyStatements.Statements.Count > 0) { CurBlock.Statements.Add(propertyStatements); } return !isReturnsVoid ? temp : LuaExpressionSyntax.EmptyExpression; } } } private bool IsEnumToStringInvocationExpression(IMethodSymbol symbol, InvocationExpressionSyntax node, out LuaExpressionSyntax result) { result = null; if (symbol.Name == "ToString") { if (symbol.ContainingType.SpecialType == SpecialType.System_Enum) { var memberAccessExpression = (MemberAccessExpressionSyntax)node.Expression; var target = memberAccessExpression.Expression.AcceptExpression(this); var enumTypeSymbol = semanticModel_.GetTypeInfo(memberAccessExpression.Expression).Type; result = BuildEnumToStringExpression(enumTypeSymbol, false, target, memberAccessExpression.Expression); return true; } else if (symbol.ContainingType.IsEnumType(out var enumTypeSymbol, out bool isNullable)) { var memberAccessExpression = (MemberAccessExpressionSyntax)node.Expression; var target = memberAccessExpression.Expression.AcceptExpression(this); result = BuildEnumToStringExpression(enumTypeSymbol, isNullable, target, memberAccessExpression.Expression); return true; } } return false; } private List<Func<LuaExpressionSyntax>> FillCodeTemplateInvocationArguments(IMethodSymbol symbol, ArgumentListSyntax argumentList, List<Func<LuaExpressionSyntax>> argumentExpressions) { argumentExpressions ??= new List<Func<LuaExpressionSyntax>>(); foreach (var argument in argumentList.Arguments) { if (argument.NameColon != null) { string name = argument.NameColon.Name.Identifier.ValueText; int index = symbol.Parameters.IndexOf(i => i.Name == name); if (index == -1) { throw new InvalidOperationException(); } argumentExpressions.AddAt(index, () => VisitExpression(argument.Expression)); } else { argumentExpressions.Add(() => VisitExpression(argument.Expression)); } } for (int i = 0; i < argumentExpressions.Count; ++i) { argumentExpressions[i] ??= () => GetDefaultParameterValue(symbol.Parameters[i], argumentList.Parent, true); } if (symbol.Parameters.Length > argumentList.Arguments.Count) { argumentExpressions.AddRange(symbol.Parameters.Skip(argumentList.Arguments.Count).Where(i => !i.IsParams).Select(i => { Func<LuaExpressionSyntax> func = () => GetDefaultParameterValue(i, argumentList.Parent, true); return func; })); } return argumentExpressions; } private LuaExpressionSyntax CheckCodeTemplateInvocationExpression(IMethodSymbol symbol, InvocationExpressionSyntax node) { var kind = node.Expression.Kind(); if (kind is SyntaxKind.SimpleMemberAccessExpression or SyntaxKind.MemberBindingExpression or SyntaxKind.IdentifierName) { if (IsEnumToStringInvocationExpression(symbol, node, out var result)) { return result; } string codeTemplate = XmlMetaProvider.GetMethodCodeTemplate(symbol); if (codeTemplate != null) { var argumentExpressions = new List<Func<LuaExpressionSyntax>>(); var memberAccessExpression = node.Expression as MemberAccessExpressionSyntax; if (symbol.IsExtensionMethod) { if (symbol.ReducedFrom != null) { if (memberAccessExpression != null) { argumentExpressions.Add(() => memberAccessExpression.Expression.AcceptExpression(this)); } else { Contract.Assert(kind == SyntaxKind.MemberBindingExpression); argumentExpressions.Add(() => conditionalTemps_.Peek()); } } if (symbol.ContainingType.IsSystemLinqEnumerable()) { CurCompilationUnit.ImportLinq(); } } #if false else if (!symbol.IsStatic) { if (memberAccessExpression != null) { argumentExpressions.Add(() => memberAccessExpression.Expression.AcceptExpression(this)); } else { Contract.Assert(kind == SyntaxKind.MemberBindingExpression); argumentExpressions.Add(() => conditionalTemps_.Peek()); } } #endif FillCodeTemplateInvocationArguments(symbol, node.ArgumentList, argumentExpressions); var invocationExpression = InternalBuildCodeTemplateExpression( codeTemplate, memberAccessExpression?.Expression, argumentExpressions, symbol.TypeArguments, kind == SyntaxKind.MemberBindingExpression ? conditionalTemps_.Peek() : null); var refOrOuts = node.ArgumentList.Arguments.Where(i => i.RefKindKeyword.IsOutOrRef()); if (refOrOuts.Any()) { var refOrOutArguments = refOrOuts.Select(i => { var argument = i.AcceptExpression(this); return new RefOrOutArgument(argument, i); }); return BuildInvokeRefOrOut(node, invocationExpression, refOrOutArguments); } return invocationExpression; } } return null; } private List<LuaExpressionSyntax> BuildInvocationArguments(IMethodSymbol symbol, InvocationExpressionSyntax node, out List<RefOrOutArgument> refOrOutArguments) { refOrOutArguments = new List<RefOrOutArgument>(); List<LuaExpressionSyntax> arguments; if (symbol != null) { arguments = BuildArgumentList(symbol, symbol.Parameters, node.ArgumentList, refOrOutArguments); bool ignoreGeneric = generator_.XmlMetaProvider.IsMethodIgnoreGeneric(symbol); if (!ignoreGeneric) { if (symbol.MethodKind == MethodKind.DelegateInvoke) { foreach (var typeArgument in symbol.ContainingType.TypeArguments) { if (typeArgument.TypeKind == TypeKind.TypeParameter) { LuaExpressionSyntax typeName = GetTypeName(typeArgument); arguments.Add(typeName); } } } else { foreach (var typeArgument in symbol.TypeArguments) { LuaExpressionSyntax typeName = GetTypeName(typeArgument); arguments.Add(typeName); } } } TryRemoveNilArgumentsAtTail(symbol, arguments); } else { arguments = new List<LuaExpressionSyntax>(); foreach (var argument in node.ArgumentList.Arguments) { if (argument.NameColon != null) { throw new CompilationErrorException(argument, "named argument is not support at dynamic"); } FillInvocationArgument(arguments, argument, ImmutableArray<IParameterSymbol>.Empty, refOrOutArguments); } } return arguments; } private LuaInvocationExpressionSyntax CheckInvocationExpression(IMethodSymbol symbol, LuaExpressionSyntax expression) { LuaInvocationExpressionSyntax invocation; if (symbol is {IsExtensionMethod: true}) { if (expression is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Name is LuaInternalMethodExpressionSyntax) { invocation = new LuaInvocationExpressionSyntax(memberAccess.Name); invocation.AddArgument(memberAccess.Expression); } else if (symbol.ReducedFrom != null) { invocation = BuildExtensionMethodInvocation(symbol.ReducedFrom, memberAccess.Expression); } else { invocation = new LuaInvocationExpressionSyntax(expression); } } else { invocation = new LuaInvocationExpressionSyntax(expression); /*if (symbol.ReducedFrom != null && symbol.HasAttribute<NativeLuaMemberAttribute>(out _)) { // invocation.AddArgument(((node.Expression as MemberAccessExpressionSyntax).Expression as IdentifierNameSyntax).Identifier.ValueText); // TODO: replace hacky solution that makes incorrect assumptions var thisArgument = new LuaMemberAccessExpressionSyntax( LuaIdentifierNameSyntax.This, ((node.Expression as MemberAccessExpressionSyntax).Expression as IdentifierNameSyntax).Identifier.ValueText); invocation.AddArgument(thisArgument); }*/ } } else { if (expression is LuaMemberAccessExpressionSyntax memberAccess) { if (memberAccess.Name is LuaInternalMethodExpressionSyntax) { invocation = new LuaInvocationExpressionSyntax(memberAccess.Name); invocation.AddArgument(memberAccess.Expression); } else { invocation = new LuaInvocationExpressionSyntax(memberAccess); if (IsPreventDebug && symbol is {IsStatic: false}) { var containingType = symbol.ContainingType; if (containingType.IsBasicType()) { var typeName = GetTypeName(containingType); invocation = typeName.MemberAccess(memberAccess.Name).Invocation(memberAccess.Expression); } else if (containingType.SpecialType == SpecialType.System_Object || containingType.IsBasicTypInterface()) { var methodMemberAccess = LuaIdentifierNameSyntax.System.MemberAccess(new LuaCodeTemplateExpressionSyntax(symbol.ContainingType.Name, memberAccess.Name)); invocation = methodMemberAccess.Invocation(memberAccess.Expression); } } } } else { invocation = new LuaInvocationExpressionSyntax(expression); if (expression is LuaInternalMethodExpressionSyntax) { if (!symbol.IsStatic) { invocation.AddArgument(LuaIdentifierNameSyntax.This); } } } } return invocation; } public override LuaSyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { var constExpression = GetConstExpression(node); if (constExpression != null) { return constExpression; } var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (symbol != null) { if (symbol.ReturnsVoid) { if (generator_.IsConditionalAttributeIgnore(symbol) || symbol.IsEmptyPartialMethod()) { return LuaExpressionSyntax.EmptyExpression; } } var codeTemplateExpression = CheckCodeTemplateInvocationExpression(symbol, node); if (codeTemplateExpression != null) { return codeTemplateExpression; } } var arguments = BuildInvocationArguments(symbol, node, out var refOrOutArguments); var expression = node.Expression.AcceptExpression(this); var invocation = CheckInvocationExpression(symbol, expression); invocation.AddArguments(arguments); LuaExpressionSyntax resultExpression = invocation; if (symbol != null && symbol.HasAggressiveInliningAttribute()) { if (InliningInvocationExpression(node, symbol, invocation, out var inlineExpression)) { resultExpression = inlineExpression; } } if (refOrOutArguments.Count > 0) { resultExpression = BuildInvokeRefOrOut(node, resultExpression, refOrOutArguments); } return resultExpression; } private LuaInvocationExpressionSyntax BuildExtensionMethodInvocation(IMethodSymbol reducedFrom, LuaExpressionSyntax expression) { var typeName = GetTypeName(reducedFrom.ContainingType); var methodName = GetMemberName(reducedFrom); return typeName.MemberAccess(methodName).Invocation(expression); } private LuaExpressionSyntax GetDefaultParameterValue(IParameterSymbol parameter, SyntaxNode node, bool isCheckCallerAttribute) { Contract.Assert(parameter.HasExplicitDefaultValue); LuaExpressionSyntax defaultValue = isCheckCallerAttribute ? CheckCallerAttribute(parameter, node) : null; if (defaultValue == null) { if (parameter.ExplicitDefaultValue == null && parameter.Type.IsValueType) { defaultValue = GetDefaultValueExpression(parameter.Type); } else { defaultValue = GetLiteralExpression(parameter.ExplicitDefaultValue); } } Contract.Assert(defaultValue != null); return defaultValue; } private void CheckInvocationDefaultArguments( ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, List<LuaExpressionSyntax> arguments, List<(NameColonSyntax Name, ExpressionSyntax Expression)> argumentNodeInfos, SyntaxNode node, bool isCheckCallerAttribute) { if (parameters.Length > arguments.Count) { var optionalParameters = parameters.Skip(arguments.Count); foreach (IParameterSymbol parameter in optionalParameters) { if (parameter.IsParams) { var arrayType = (IArrayTypeSymbol)parameter.Type; var elementType = GetTypeName(arrayType.ElementType); arguments.Add(LuaIdentifierNameSyntax.EmptyArray.Invocation(elementType)); } else { LuaExpressionSyntax defaultValue = GetDefaultParameterValue(parameter, node, isCheckCallerAttribute); arguments.Add(defaultValue); } } } else if (!parameters.IsEmpty) { IParameterSymbol last = parameters.Last(); if (last.IsParams && generator_.IsFromLuaModule(symbol) && !symbol.HasParamsAttribute()) { if (parameters.Length == arguments.Count) { var paramsArgument = argumentNodeInfos.Last(); if (paramsArgument.Name != null) { string name = paramsArgument.Name.Name.Identifier.ValueText; if (name != last.Name) { paramsArgument = argumentNodeInfos.First(i => i.Name != null && i.Name.Name.Identifier.ValueText == last.Name); } } var paramsType = semanticModel_.GetTypeInfo(paramsArgument.Expression).Type; bool isLastParamsArrayType = paramsType is {TypeKind: TypeKind.Array}; if (!isLastParamsArrayType) { var arrayTypeSymbol = (IArrayTypeSymbol)last.Type; var array = BuildArray(arrayTypeSymbol.ElementType, arguments.Last()); arguments[^1] = array; } } else { int otherParameterCount = parameters.Length - 1; var arrayTypeSymbol = (IArrayTypeSymbol)last.Type; var paramsArguments = arguments.Skip(otherParameterCount).ToArray(); var array = BuildArray(arrayTypeSymbol.ElementType, paramsArguments); arguments.RemoveRange(otherParameterCount, arguments.Count - otherParameterCount); arguments.Add(array); } } } for (int i = 0; i < arguments.Count; ++i) { if (arguments[i] == null) { LuaExpressionSyntax defaultValue = GetDefaultParameterValue(parameters[i], node, isCheckCallerAttribute); arguments[i] = defaultValue; } } } private void CheckInvocationDefaultArguments(ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, List<LuaExpressionSyntax> arguments, BaseArgumentListSyntax node) { var argumentNodeInfos = node.Arguments.Select(i => (i.NameColon, i.Expression)).ToList(); CheckInvocationDefaultArguments(symbol, parameters, arguments, argumentNodeInfos, node.Parent, true); } private void CheckPrevIsInvokeStatement(ExpressionSyntax node) { SyntaxNode current = node; while (true) { var parent = current.Parent; if (parent == null) { return; } switch (parent.Kind()) { case SyntaxKind.Argument: case SyntaxKind.LocalDeclarationStatement: case SyntaxKind.CastExpression: { return; } default: { if (parent is AssignmentExpressionSyntax assignment && assignment.Right == current) { return; } break; } } if (parent.IsKind(SyntaxKind.ExpressionStatement)) { break; } current = parent; } var curBlock = CurBlockOrNull; if (curBlock != null) { var statement = curBlock.Statements.FindLast(i => i is not LuaBlankLinesStatement && i is not LuaCommentStatement); if (statement != null) { statement.ForceSemicolon = true; } } } private LuaExpressionSyntax BuildMemberAccessTargetExpression(ExpressionSyntax targetExpression) { var expression = targetExpression.AcceptExpression(this); SyntaxKind kind = targetExpression.Kind(); if ((kind is >= SyntaxKind.NumericLiteralExpression and <= SyntaxKind.NullLiteralExpression) || (expression is LuaLiteralExpressionSyntax)) { CheckPrevIsInvokeStatement(targetExpression); expression = expression.Parenthesized(); } return expression; } private LuaExpressionSyntax BuildMemberAccessExpression(ISymbol symbol, ExpressionSyntax node) { bool isExtensionMethod = symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsExtensionMethod; if (isExtensionMethod) { return node.AcceptExpression(this); } return BuildMemberAccessTargetExpression(node); } private LuaExpressionSyntax CheckMemberAccessCodeTemplate(ISymbol symbol, MemberAccessExpressionSyntax node) { switch (symbol.Kind) { case SymbolKind.Field: { IFieldSymbol fieldSymbol = (IFieldSymbol)symbol; if (fieldSymbol.ContainingType.IsTupleType) { int elementIndex = fieldSymbol.GetTupleElementIndex(); var targetExpression = node.Expression.AcceptExpression(this); return new LuaTableIndexAccessExpressionSyntax(targetExpression, elementIndex); } string codeTemplate = XmlMetaProvider.GetFieldCodeTemplate(fieldSymbol); if (codeTemplate != null) { return BuildCodeTemplateExpression(codeTemplate, node.Expression); } if (fieldSymbol.HasConstantValue) { if (!fieldSymbol.IsStringConstNotInline()) { return GetConstLiteralExpression(fieldSymbol); } } if (XmlMetaProvider.IsFieldForceProperty(fieldSymbol)) { var expression = node.Expression.AcceptExpression(this); var propertyIdentifierName = new LuaPropertyOrEventIdentifierNameSyntax(true, GetMemberName(symbol)); return new LuaPropertyAdapterExpressionSyntax(expression, propertyIdentifierName, !fieldSymbol.IsStatic); } break; } case SymbolKind.Property: { var propertySymbol = (IPropertySymbol)symbol; bool isGet = node.IsGetExpressionNode(); string codeTemplate = XmlMetaProvider.GetPropertyCodeTemplate(propertySymbol, isGet); if (codeTemplate != null) { var result = BuildCodeTemplateExpression(codeTemplate, node.Expression); if (codeTemplate[0] == '#' && node.Parent.Parent.IsKind(SyntaxKind.InvocationExpression)) { result = result.Parenthesized(); } return result; } break; } } return null; } private LuaExpressionSyntax InternalVisitMemberAccessExpression(ISymbol symbol, MemberAccessExpressionSyntax node) { var codeTemplateExpression = CheckMemberAccessCodeTemplate(symbol, node); if (codeTemplateExpression != null) { return codeTemplateExpression; } if (node.Expression.IsKind(SyntaxKind.ThisExpression)) { var nameExpression = node.Name.AcceptExpression(this); if (symbol.Kind == SymbolKind.Method) { if (IsDelegateExpression((IMethodSymbol)symbol, node, nameExpression, LuaIdentifierNameSyntax.This, out var delegateExpression)) { return delegateExpression; } } return nameExpression; } if (node.Expression.IsKind(SyntaxKind.BaseExpression)) { var baseExpression = node.Expression.AcceptExpression(this); var nameExpression = node.Name.AcceptExpression(this); if (symbol.Kind is SymbolKind.Property or SymbolKind.Event) { switch (nameExpression) { case LuaPropertyAdapterExpressionSyntax propertyMethod: { if (baseExpression != LuaIdentifierNameSyntax.This) { propertyMethod.ArgumentList.AddArgument(LuaIdentifierNameSyntax.This); propertyMethod.Update(baseExpression, false); } else { propertyMethod.Update(baseExpression, true); } return propertyMethod; } case LuaMemberAccessExpressionSyntax memberAccess when memberAccess.Expression == LuaIdentifierNameSyntax.This: return nameExpression; default: return baseExpression.MemberAccess(nameExpression); } } if (baseExpression == LuaIdentifierNameSyntax.This) { return baseExpression.MemberAccess(nameExpression, symbol.Kind == SymbolKind.Method); } return new LuaInternalMethodExpressionSyntax(baseExpression.MemberAccess(nameExpression)); } if (symbol.IsStatic && node.Expression.IsKind(SyntaxKind.IdentifierName) && CurTypeSymbol.IsContainsInternalSymbol(symbol)) { bool isOnlyName = false; switch (symbol.Kind) { case SymbolKind.Method: { isOnlyName = true; break; } case SymbolKind.Property: case SymbolKind.Event: { if (!generator_.IsPropertyFieldOrEventField(symbol)) { isOnlyName = true; } break; } case SymbolKind.Field: { if (symbol.IsPrivate()) { isOnlyName = true; } break; } } if (isOnlyName) { return node.Name.AcceptExpression(this); } } var name = node.Name.AcceptExpression(this); if (generator_.IsInlineSymbol(symbol) && symbol.Kind == SymbolKind.Property) { return name; } var expression = BuildMemberAccessExpression(symbol, node.Expression); return symbol.Kind switch { SymbolKind.Property or SymbolKind.Event => BuildFieldOrPropertyMemberAccessExpression(expression, name, symbol.IsStatic), SymbolKind.Method when IsDelegateExpression((IMethodSymbol)symbol, node, name, expression, out var delegateExpression) => delegateExpression, _ => expression.MemberAccess(name, !symbol.IsStatic && symbol.Kind == SymbolKind.Method) }; } private bool IsDelegateExpression(IMethodSymbol symbol, MemberAccessExpressionSyntax node, LuaExpressionSyntax name, LuaExpressionSyntax expression, out LuaExpressionSyntax delegateExpression) { if (!node.Parent.IsKind(SyntaxKind.InvocationExpression)) { if (!IsInternalMember(symbol)) { if (symbol.IsExtensionMethod) { var typeName = GetTypeName(symbol.ContainingType); name = typeName.MemberAccess(name); } else { name = expression.MemberAccess(name); } } delegateExpression = BuildDelegateNameExpression(symbol, expression, name, node); return true; } if (IsDelegateInvoke(symbol, node.Name)) { delegateExpression = expression; return true; } delegateExpression = null; return false; } private static bool IsDelegateInvoke(ISymbol symbol, SimpleNameSyntax name) { return symbol.ContainingType.IsDelegateType() && name.Identifier.ValueText == "Invoke"; } public override LuaSyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { ISymbol symbol = semanticModel_.GetSymbolInfo(node).Symbol; if (symbol == null) { // dynamic var expressSymbol = semanticModel_.GetSymbolInfo(node.Expression).Symbol; var expression = node.Expression.AcceptExpression(this); bool isObjectColon = node.Parent.IsKind(SyntaxKind.InvocationExpression) && (expressSymbol is not {Kind: SymbolKind.NamedType}); LuaIdentifierNameSyntax name = node.Name.Identifier.ValueText; return expression.MemberAccess(name, isObjectColon); } if (symbol.Kind == SymbolKind.NamedType) { var expressionSymbol = semanticModel_.GetSymbolInfo(node.Expression).Symbol; if (expressionSymbol.Kind is SymbolKind.Namespace or SymbolKind.NamedType) { return node.Name.Accept(this); } } return InternalVisitMemberAccessExpression(symbol, node); } private LuaExpressionSyntax BuildStaticFieldName(ISymbol symbol, bool isReadOnly, IdentifierNameSyntax node) { Contract.Assert(symbol.IsStatic); LuaIdentifierNameSyntax name = GetMemberName(symbol); bool isPrivate = symbol.IsPrivate(); if (isPrivate && generator_.IsForcePublicSymbol(symbol)) { isPrivate = false; } if (!isPrivate) { if (isReadOnly) { if (node.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression)) { AssignmentExpressionSyntax assignmentExpression = (AssignmentExpressionSyntax)node.Parent; if (assignmentExpression.Left == node) { CurType.AddStaticReadOnlyAssignmentName(name); } } if (CheckUsingStaticNameSyntax(symbol, node, name, out var newExpression)) { return newExpression; } } else { if (IsInternalNode(node)) { if (CurFunctionOrNull is LuaConstructorAdapterExpressionSyntax {IsStatic: true}) { return LuaIdentifierNameSyntax.This.MemberAccess(name); } var typeName = GetTypeName(symbol.ContainingType); return typeName.MemberAccess(name); } if (CheckUsingStaticNameSyntax(symbol, node, name, out var newExpression)) { return newExpression; } } } else { if (!CurTypeSymbol.IsContainsInternalSymbol(symbol)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } var typeName = GetTypeName(symbol.ContainingType); return typeName.MemberAccess(name); } } return name; } private bool IsInternalNode(NameSyntax node) { var parentNode = node.Parent; switch (parentNode.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: { MemberAccessExpressionSyntax parent = (MemberAccessExpressionSyntax)parentNode; if (parent.Expression.IsKind(SyntaxKind.ThisExpression)) { return true; } if (parent.Expression == node) { return true; } return false; } case SyntaxKind.MemberBindingExpression: case SyntaxKind.NameColon: case SyntaxKind.NameEquals: { return false; } case SyntaxKind.SimpleAssignmentExpression: { AssignmentExpressionSyntax parent = (AssignmentExpressionSyntax)parentNode; if (parent.Right != node) { switch (parent.Parent.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.WithInitializerExpression: return false; } } break; } } return true; } private bool IsEventAddOrRemoveIdentifierName(IdentifierNameSyntax node) { SyntaxNode current = node; while (true) { var parent = current.Parent; if (parent == null) { break; } var kind = parent.Kind(); if (kind is SyntaxKind.AddAssignmentExpression or SyntaxKind.SubtractAssignmentExpression) { var assignment = (AssignmentExpressionSyntax)parent; return assignment.Left == current; } if (kind == SyntaxKind.SimpleMemberAccessExpression) { var memberAccessExpression = (MemberAccessExpressionSyntax)parent; if (memberAccessExpression.Name != current) { break; } } else { break; } current = parent; } return false; } private LuaExpressionSyntax VisitPropertyOrEventIdentifierName(IdentifierNameSyntax node, ISymbol symbol, bool isProperty, out bool isField) { bool isReadOnly; if (isProperty) { var propertySymbol = (IPropertySymbol)symbol; isField = IsPropertyField(propertySymbol); isReadOnly = propertySymbol.IsReadOnly; } else { var eventSymbol = (IEventSymbol)symbol; isField = IsEventField(eventSymbol); isReadOnly = false; if (!isField) { if (!IsEventAddOrRemoveIdentifierName(node)) { isField = true; } } } if (isField) { if (symbol.IsStatic) { return BuildStaticFieldName(symbol, isReadOnly, node); } LuaIdentifierNameSyntax fieldName = GetMemberName(symbol); if (IsInternalNode(node)) { return LuaIdentifierNameSyntax.This.MemberAccess(fieldName); } return fieldName; } if (isProperty) { var propertySymbol = (IPropertySymbol)symbol; if (IsWantInline(propertySymbol)) { if (InliningPropertyGetExpression(node, propertySymbol.GetMethod, out var inlineExpression)) { return inlineExpression; } } } var name = GetMemberName(symbol); var identifierName = new LuaPropertyOrEventIdentifierNameSyntax(isProperty, name); if (symbol.IsStatic) { var identifierExpression = new LuaPropertyAdapterExpressionSyntax(identifierName); if (CheckUsingStaticNameSyntax(symbol, node, identifierExpression, out var newExpression)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } return newExpression; } if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); var usingStaticType = GetTypeName(symbol.ContainingType); return usingStaticType.MemberAccess(identifierName); } return identifierExpression; } if (IsInternalMember(symbol)) { var propertyAdapter = new LuaPropertyAdapterExpressionSyntax(identifierName); propertyAdapter.ArgumentList.AddArgument(LuaIdentifierNameSyntax.This); return propertyAdapter; } if (IsInternalNode(node)) { return new LuaPropertyAdapterExpressionSyntax(LuaIdentifierNameSyntax.This, identifierName, true); } if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); } return new LuaPropertyAdapterExpressionSyntax(identifierName); } private static bool IsParentDelegateName(NameSyntax node) { var kind = node.Parent.Kind(); return kind switch { SyntaxKind.SimpleMemberAccessExpression or SyntaxKind.InvocationExpression or SyntaxKind.MemberBindingExpression => false, _ => true }; } private sealed class GenericPlaceholder { public ITypeSymbol Symbol { get; } private readonly int index_; public int TypeParameterIndex => index_ + 1; public bool IsTypeParameter => index_ != -1; public bool IsSwapped { get; private set; } public GenericPlaceholder(ITypeSymbol symbol, int index = -1) { Symbol = symbol; index_ = index; } public LuaExpressionSyntax Build(LuaSyntaxNodeTransform transform) { return IsTypeParameter ? TypeParameterIndex.ToString() : transform.GetTypeName(Symbol); } public static void Swap(List<GenericPlaceholder> placeholders, int x, int y) { var itemX = placeholders[x]; var itemY = placeholders[y]; placeholders[x] = itemY; placeholders[y] = itemX; itemX.IsSwapped = true; itemY.IsSwapped = true; } public static bool IsEnable(List<GenericPlaceholder> placeholders) { int index = 0; foreach (var placeholder in placeholders) { if (!placeholder.IsTypeParameter) { return true; } if (placeholder.index_ != index) { return true; } ++index; } return false; } } private sealed class TypeParameterPlaceholder { public ITypeSymbol Symbol; public int ParameterIndex; } private IMethodSymbol GetDelegateTargetMethodSymbol(CSharpSyntaxNode node) { var parent = node.Parent; switch (parent.Kind()) { case SyntaxKind.Argument: { var argument = (ArgumentSyntax)parent; var symbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(argument.Parent.Parent).Symbol; var parameter = GetParameterSymbol(symbol.OriginalDefinition, argument); var type = (INamedTypeSymbol)parameter.Type; return type.DelegateInvokeMethod; } case SyntaxKind.EqualsValueClause: { var variableDeclaration = (VariableDeclarationSyntax)parent.Parent.Parent; var type = (INamedTypeSymbol)semanticModel_.GetTypeInfo(variableDeclaration.Type).Type; return type.DelegateInvokeMethod; } case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: { var assignment = (AssignmentExpressionSyntax)parent; var type = (INamedTypeSymbol)semanticModel_.GetTypeInfo(assignment.Left).Type; return type.DelegateInvokeMethod; } case SyntaxKind.ReturnStatement: { var type = (INamedTypeSymbol)CurMethodInfoOrNull.Symbol.ReturnType; return type.DelegateInvokeMethod; } default: throw new InvalidProgramException(); } } private void CheckDelegateBind(IMethodSymbol symbol, CSharpSyntaxNode node, ref LuaExpressionSyntax nameExpression) { const int kReturnParameterIndex = int.MaxValue; if (symbol.IsGenericMethod) { var originalDefinition = symbol.OriginalDefinition; if (!originalDefinition.EQ(symbol)) { var targetMethodSymbol = GetDelegateTargetMethodSymbol(node); var targetTypeParameters = new List<TypeParameterPlaceholder>(); foreach (var typeArgument in targetMethodSymbol.ContainingType.TypeArguments) { if (typeArgument.TypeKind == TypeKind.TypeParameter) { int parameterIndex = targetMethodSymbol.Parameters.IndexOf(i => i.Type.IsTypeParameterExists(typeArgument)); if (parameterIndex == -1) { Contract.Assert(targetMethodSymbol.ReturnType != null && targetMethodSymbol.ReturnType.IsTypeParameterExists(typeArgument)); parameterIndex = kReturnParameterIndex; } targetTypeParameters.Add(new TypeParameterPlaceholder { Symbol = typeArgument, ParameterIndex = parameterIndex, }); } } int j = 0; var originalTypeParameters = new List<TypeParameterPlaceholder>(); foreach (var originalTypeArgument in originalDefinition.TypeArguments) { Contract.Assert(originalTypeArgument.TypeKind == TypeKind.TypeParameter); int parameterIndex = originalDefinition.Parameters.IndexOf(i => i.Type.IsTypeParameterExists(originalTypeArgument)); if (parameterIndex != -1) { originalTypeParameters.Add(new TypeParameterPlaceholder { Symbol = originalTypeArgument, ParameterIndex = parameterIndex, }); } else { if (originalDefinition.ReturnType != null && originalDefinition.ReturnType.IsTypeParameterExists(originalTypeArgument)) { originalTypeParameters.Add(new TypeParameterPlaceholder { Symbol = originalTypeArgument, ParameterIndex = kReturnParameterIndex, }); } else { var typeArgument = symbol.TypeArguments[j]; Contract.Assert(typeArgument.TypeKind != TypeKind.TypeParameter); originalTypeParameters.Add(new TypeParameterPlaceholder { Symbol = typeArgument, ParameterIndex = -1, }); } } ++j; } var placeholders = new List<GenericPlaceholder>(); foreach (var originalTypeParameter in originalTypeParameters) { int parameterIndex = originalTypeParameter.ParameterIndex; if (parameterIndex != -1) { int index = targetTypeParameters.FindIndex(i => i.ParameterIndex == parameterIndex); if (index != -1) { placeholders.Add(new GenericPlaceholder(originalTypeParameter.Symbol, index)); } else { ITypeSymbol parameterType; if (parameterIndex == kReturnParameterIndex) { Contract.Assert(targetMethodSymbol.ReturnType != null); parameterType = targetMethodSymbol.ReturnType; } else { var parameter = targetMethodSymbol.Parameters[parameterIndex]; parameterType = parameter.Type; } placeholders.Add(new GenericPlaceholder(parameterType)); } } else { placeholders.Add(new GenericPlaceholder(originalTypeParameter.Symbol)); } } if (GenericPlaceholder.IsEnable(placeholders)) { if (placeholders.TrueForAll(i => !i.IsTypeParameter)) { if (placeholders.Count <= 3) { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + placeholders.Count; var invocationExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); invocationExpression.AddArguments(placeholders.Select(i => i.Build(this))); nameExpression = invocationExpression; return; } } else if (symbol.Parameters.Length == 2) { switch (placeholders.Count) { case 2 when placeholders[0].TypeParameterIndex == 2 && placeholders[1].TypeParameterIndex == 1: { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + "2_1"; nameExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); return; } case 1 when placeholders.First().TypeParameterIndex == 2: { string bindMethodName = LuaIdentifierNameSyntax.DelegateBind.ValueText + "0_2"; nameExpression = new LuaInvocationExpressionSyntax(bindMethodName, nameExpression); return; } } } var invocation = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.DelegateBind, nameExpression, symbol.Parameters.Length.ToString()); invocation.AddArguments(placeholders.Select(i => i.Build(this))); nameExpression = invocation; } } } } private LuaExpressionSyntax BuildDelegateNameExpression(IMethodSymbol symbol, LuaExpressionSyntax target, LuaExpressionSyntax name, CSharpSyntaxNode node) { var nameExpression = symbol.IsStatic ? name : new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.DelegateMake, target, name); CheckDelegateBind(symbol, node, ref nameExpression); return nameExpression; } private LuaExpressionSyntax BuildDelegateNameExpression(IMethodSymbol symbol, LuaExpressionSyntax name, CSharpSyntaxNode node) { return BuildDelegateNameExpression(symbol, LuaIdentifierNameSyntax.This, name, node); } private LuaExpressionSyntax GetMethodNameExpression(IMethodSymbol symbol, NameSyntax node, bool isFromIdentifier) { LuaIdentifierNameSyntax methodName = GetMemberName(symbol); if (symbol.IsStatic) { if (CheckUsingStaticNameSyntax(symbol, node, methodName, out var outExpression)) { if (symbol.IsPrivate()) { generator_.AddForcePublicSymbol(symbol); } if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, outExpression, node); } return outExpression; } if (IsInternalMember(symbol)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, methodName, node); } return new LuaInternalMethodExpressionSyntax(methodName); } if (CurTypeSymbol.IsContainsInternalSymbol(symbol) && IsMoreThanLocalVariables(symbol)) { return LuaIdentifierNameSyntax.MoreManyLocalVarTempTable.MemberAccess(methodName); } if (isFromIdentifier && IsMaxUpValues(symbol, out bool isNeedImport)) { var name = LuaIdentifierNameSyntax.MoreManyLocalVarTempTable.MemberAccess(methodName); if (isNeedImport) { CurType.AddMaxUpvalue(name, methodName); } return name; } return methodName; } if (IsInternalMember(symbol)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, methodName, node); } return new LuaInternalMethodExpressionSyntax(methodName); } if (IsInternalNode(node)) { if (IsParentDelegateName(node)) { return BuildDelegateNameExpression(symbol, LuaIdentifierNameSyntax.This.MemberAccess(methodName), node); } return LuaIdentifierNameSyntax.This.MemberAccess(methodName, true); } if (symbol.IsPrivate() && !CurTypeSymbol.IsContainsInternalSymbol(symbol)) { generator_.AddForcePublicSymbol(symbol); } return methodName; } private LuaExpressionSyntax GetFieldNameExpression(IFieldSymbol symbol, IdentifierNameSyntax node) { if (symbol.IsStatic) { if (symbol.HasConstantValue) { if (symbol.Type.SpecialType == SpecialType.System_String) { if (((string)symbol.ConstantValue).Length <= kStringConstInlineCount) { return GetConstLiteralExpression(symbol); } } else { return GetConstLiteralExpression(symbol); } } return BuildStaticFieldName(symbol, symbol.IsReadOnly, node); } if (IsInternalNode(node)) { return LuaIdentifierNameSyntax.This.MemberAccess(GetMemberName(symbol)); } return GetMemberName(symbol); } public override LuaSyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { LuaIdentifierNameSyntax GetSampleName(ISymbol nodeSymbol) { LuaIdentifierNameSyntax nameIdentifier = nodeSymbol.Name; CheckLocalSymbolName(nodeSymbol, ref nameIdentifier); return nameIdentifier; } SymbolInfo symbolInfo = semanticModel_.GetSymbolInfo(node); ISymbol symbol = symbolInfo.Symbol; if (symbol == null) { // dynamic return (LuaIdentifierNameSyntax)node.Identifier.ValueText; } LuaExpressionSyntax identifier; switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (ILocalSymbol)symbol; if (localSymbol.IsConst) { if (localSymbol.Type.SpecialType == SpecialType.System_String) { if (((string)localSymbol.ConstantValue).Length <= kStringConstInlineCount) { return GetConstLiteralExpression(localSymbol); } } else { return GetConstLiteralExpression(localSymbol); } } identifier = GetSampleName(symbol); CheckValueTypeClone(localSymbol.Type, node, ref identifier); break; } case SymbolKind.Parameter: { var parameterSymbol = (IParameterSymbol)symbol; identifier = GetSampleName(symbol); CheckValueTypeClone(parameterSymbol.Type, node, ref identifier); break; } case SymbolKind.RangeVariable: { identifier = GetRangeIdentifierName(node); break; } case SymbolKind.TypeParameter: case SymbolKind.Label: { identifier = symbol.Name; break; } case SymbolKind.NamedType: { identifier = GetTypeName(symbol); break; } case SymbolKind.Field: { var fieldSymbol = (IFieldSymbol)symbol; var codeTemplate = fieldSymbol.GetCodeTemplateFromAttribute(); if (codeTemplate != null) { identifier = BuildCodeTemplateExpression(codeTemplate, fieldSymbol.IsStatic ? null : LuaIdentifierNameSyntax.This); break; } identifier = GetFieldNameExpression(fieldSymbol, node); CheckValueTypeClone(fieldSymbol.Type, node, ref identifier); break; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; identifier = methodSymbol.MethodKind == MethodKind.LocalFunction ? GetLocalMethodName(methodSymbol, node) : GetMethodNameExpression(methodSymbol, node, true); break; } case SymbolKind.Property: { var propertyField = (IPropertySymbol)symbol; identifier = VisitPropertyOrEventIdentifierName(node, propertyField, true, out bool isField); if (isField) { CheckValueTypeClone(propertyField.Type, node, ref identifier, true); } break; } case SymbolKind.Event: { identifier = VisitPropertyOrEventIdentifierName(node, symbol, false, out _); break; } case SymbolKind.Discard: { identifier = LuaIdentifierNameSyntax.Placeholder; break; } default: { throw new NotSupportedException(); } } return identifier; } public override LuaSyntaxNode VisitQualifiedName(QualifiedNameSyntax node) { return node.Right.Accept(this); } private void FillInvocationArgument(List<LuaExpressionSyntax> arguments, ArgumentSyntax node, ImmutableArray<IParameterSymbol> parameters, List<RefOrOutArgument> refOrOutArguments) { var expression = node.Expression.AcceptExpression(this); Contract.Assert(expression != null); if (node.RefKindKeyword.IsKind(SyntaxKind.RefKeyword)) { refOrOutArguments.Add(new RefOrOutArgument(expression)); } else if (node.RefKindKeyword.IsKind(SyntaxKind.OutKeyword)) { refOrOutArguments.Add(new RefOrOutArgument(expression, node)); expression = LuaIdentifierNameSyntax.Nil; } else { CheckConversion(node.Expression, ref expression); } if (node.NameColon != null) { string name = node.NameColon.Name.Identifier.ValueText; int index = parameters.IndexOf(i => i.Name == name); if (index == -1) { throw new InvalidOperationException(); } arguments.AddAt(index, expression); } else { arguments.Add(expression); } } private List<LuaExpressionSyntax> BuildArgumentList(ISymbol symbol, ImmutableArray<IParameterSymbol> parameters, BaseArgumentListSyntax node, List<RefOrOutArgument> refOrOutArguments = null) { Contract.Assert(node != null); List<LuaExpressionSyntax> arguments = new List<LuaExpressionSyntax>(); foreach (var argument in node.Arguments) { FillInvocationArgument(arguments, argument, parameters, refOrOutArguments); } CheckInvocationDefaultArguments(symbol, parameters, arguments, node); return arguments; } private LuaArgumentListSyntax BuildArgumentList(SeparatedSyntaxList<ArgumentSyntax> arguments) { var argumentList = new LuaArgumentListSyntax(); foreach (var argument in arguments) { var newNode = argument.AcceptExpression(this); argumentList.Arguments.Add(newNode); } return argumentList; } public override LuaSyntaxNode VisitArgumentList(ArgumentListSyntax node) { return BuildArgumentList(node.Arguments); } public override LuaSyntaxNode VisitArgument(ArgumentSyntax node) { Contract.Assert(node.NameColon == null); return node.Expression.AcceptExpression(this); } private bool IsExtremelyZero(LiteralExpressionSyntax node, string value) { object v = semanticModel_.GetConstantValue(node).Value; var isFloatZero = (v is float and 0 or double and 0); return isFloatZero && value.Length > 5; } private LuaExpressionSyntax InternalVisitLiteralExpression(LiteralExpressionSyntax node) { switch (node.Kind()) { case SyntaxKind.NumericLiteralExpression: { bool hasTransform = false; string value = node.Token.Text; value = value.Replace("_", ""); if (value.StartsWith("0b") || value.StartsWith("0B")) { value = node.Token.ValueText; hasTransform = true; } else { int len = value.Length; int removeCount = 0; switch (value[len - 1]) { case 'f': case 'F': case 'd': case 'D': { if (!value.StartsWith("0x") && !value.StartsWith("0X")) { if (IsExtremelyZero(node, value)) { value = LuaNumberLiteralExpressionSyntax.ZeroFloat.Text; hasTransform = true; } else { removeCount = 1; } } break; } case 'L': case 'l': { removeCount = 1; if (len > 2) { if (value[len - 2] == 'U' || value[len - 2] == 'u') { removeCount = 2; } } break; } case 'u': case 'U': case 'm': case 'M': { removeCount = 1; break; } } if (removeCount > 0) { value = value.Remove(len - removeCount); } } if (hasTransform) { return new LuaConstLiteralExpression(value, node.Token.Text); } return new LuaIdentifierLiteralExpressionSyntax(value); } case SyntaxKind.StringLiteralExpression: { return BuildStringLiteralTokenExpression(node.Token); } case SyntaxKind.CharacterLiteralExpression: { return new LuaCharacterLiteralExpression((char)node.Token.Value); } case SyntaxKind.NullLiteralExpression: { return LuaIdentifierLiteralExpressionSyntax.Nil; } case SyntaxKind.DefaultLiteralExpression: { var type = semanticModel_.GetTypeInfo(node).Type; return GetDefaultValueExpression(type); } default: { return new LuaIdentifierLiteralExpressionSyntax(node.Token.ValueText); } } } public override LuaSyntaxNode VisitLiteralExpression(LiteralExpressionSyntax node) { return InternalVisitLiteralExpression(node); } public override LuaSyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { var declaration = node.Declaration.Accept<LuaVariableDeclarationSyntax>(this); if (node.UsingKeyword.IsKeyword()) { var block = CurBlock; block.UsingDeclarations ??= new List<int>(); block.UsingDeclarations.Add(block.Statements.Count); } return new LuaLocalDeclarationStatementSyntax(declaration); } private bool IsValueTypeVariableDeclarationWithoutAssignment(VariableDeclaratorSyntax variable) { var body = FindParentMethodBody(variable); if (body != null) { int index = body.Statements.IndexOf((StatementSyntax)variable.Parent.Parent); foreach (var i in body.Statements.Skip(index + 1)) { if (i.IsKind(SyntaxKind.ExpressionStatement)) { var expressionStatement = (ExpressionStatementSyntax)i; if (expressionStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression)) { var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; if (assignment.Left.IsKind(SyntaxKind.IdentifierName)) { var identifierName = (IdentifierNameSyntax)assignment.Left; if (identifierName.Identifier.ValueText == variable.Identifier.ValueText) { return false; } } else if (assignment.Left.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccessExpression = (MemberAccessExpressionSyntax)assignment.Left; if (memberAccessExpression.Expression.IsKind(SyntaxKind.IdentifierName)) { var identifierName = (IdentifierNameSyntax)memberAccessExpression.Expression; if (identifierName.Identifier.ValueText == variable.Identifier.ValueText) { return true; } } } } } } } return false; } public override LuaSyntaxNode VisitVariableDeclaration(VariableDeclarationSyntax node) { ITypeSymbol typeSymbol = null; var variableListDeclaration = new LuaVariableListDeclarationSyntax(); foreach (var variable in node.Variables) { bool isRefIgnore = false; if (variable.Initializer != null && variable.Initializer.Value.IsKind(SyntaxKind.RefExpression)) { var value = (RefExpressionSyntax)variable.Initializer.Value; var refExpression = value.AcceptExpression(this); if (value.Expression.IsKind(SyntaxKind.InvocationExpression)) { var invocationExpression = (LuaInvocationExpressionSyntax)refExpression; AddRefInvocationVariableMapping((InvocationExpressionSyntax)value.Expression, invocationExpression, variable); } else { AddLocalVariableMapping(new LuaSymbolNameSyntax(refExpression), variable); isRefIgnore = true; } } if (!isRefIgnore) { bool isConst = false; if (node.Parent is LocalDeclarationStatementSyntax {IsConst: true}) { isConst = true; if (variable.Initializer.Value is LiteralExpressionSyntax value) { var token = value.Token; if (token.Value is string str) { if (str.Length > kStringConstInlineCount) { isConst = false; } } } } if (!isConst) { var variableDeclarator = variable.Accept<LuaVariableDeclaratorSyntax>(this); if (variableDeclarator.Initializer == null) { typeSymbol ??= semanticModel_.GetTypeInfo(node.Type).Type; if (typeSymbol.IsCustomValueType() && IsValueTypeVariableDeclarationWithoutAssignment(variable)) { var typeExpression = GetTypeName(typeSymbol); variableDeclarator.Initializer = new LuaEqualsValueClauseSyntax(BuildDefaultValue(typeExpression)); } } variableListDeclaration.Variables.Add(variableDeclarator); } } } bool isMultiNil = variableListDeclaration.Variables.Count > 0 && variableListDeclaration.Variables.All(i => i.Initializer == null); if (isMultiNil) { LuaLocalVariablesSyntax declarationStatement = new LuaLocalVariablesSyntax(); foreach (var variable in variableListDeclaration.Variables) { declarationStatement.Variables.Add(variable.Identifier); } return declarationStatement; } return variableListDeclaration; } public override LuaSyntaxNode VisitVariableDeclarator(VariableDeclaratorSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); var variableDeclarator = new LuaVariableDeclaratorSyntax(identifier); if (node.Initializer != null) { variableDeclarator.Initializer = node.Initializer.Accept<LuaEqualsValueClauseSyntax>(this); } return variableDeclarator; } public override LuaSyntaxNode VisitEqualsValueClause(EqualsValueClauseSyntax node) { var expression = VisitExpression(node.Value); return new LuaEqualsValueClauseSyntax(expression); } public override LuaSyntaxNode VisitPredefinedType(PredefinedTypeSyntax node) { ISymbol symbol = semanticModel_.GetSymbolInfo(node).Symbol; return GetTypeShortName(symbol); } private void WriteStatementOrBlock(StatementSyntax statement, LuaBlockSyntax block) { if (statement.IsKind(SyntaxKind.Block)) { var blockNode = statement.Accept<LuaBlockSyntax>(this); block.Statements.AddRange(blockNode.Statements); } else { PushBlock(block); var statementNode = statement.Accept<LuaStatementSyntax>(this); block.Statements.Add(statementNode); PopBlock(); } } #region if else switch public override LuaSyntaxNode VisitIfStatement(IfStatementSyntax node) { var condition = VisitExpression(node.Condition); LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(condition); WriteStatementOrBlock(node.Statement, ifStatement.Body); ifStatements_.Push(ifStatement); node.Else?.Accept(this); ifStatements_.Pop(); return ifStatement; } public override LuaSyntaxNode VisitElseClause(ElseClauseSyntax node) { if (node.Statement.IsKind(SyntaxKind.IfStatement)) { var ifStatement = (IfStatementSyntax)node.Statement; LuaBlockSyntax conditionBody = new LuaBlockSyntax(); PushBlock(conditionBody); var condition = VisitExpression(ifStatement.Condition); PopBlock(); if (conditionBody.Statements.Count == 0) { var elseIfStatement = new LuaElseIfStatementSyntax(condition); WriteStatementOrBlock(ifStatement.Statement, elseIfStatement.Body); ifStatements_.Peek().ElseIfStatements.Add(elseIfStatement); ifStatement.Else?.Accept(this); return elseIfStatement; } else { var elseClause = new LuaElseClauseSyntax(); elseClause.Body.Statements.AddRange(conditionBody.Statements); var elseIfStatement = new LuaIfStatementSyntax(condition); WriteStatementOrBlock(ifStatement.Statement, elseIfStatement.Body); elseClause.Body.AddStatement(elseIfStatement); ifStatements_.Peek().Else = elseClause; ifStatements_.Push(elseIfStatement); ifStatement.Else?.Accept(this); ifStatements_.Pop(); return elseClause; } } { LuaElseClauseSyntax elseClause = new LuaElseClauseSyntax(); WriteStatementOrBlock(node.Statement, elseClause.Body); ifStatements_.Peek().Else = elseClause; return elseClause; } } public override LuaSyntaxNode VisitSwitchStatement(SwitchStatementSyntax node) { var temp = GetTempIdentifier(); var switchStatement = new LuaSwitchAdapterStatementSyntax(temp); switches_.Push(switchStatement); var expression = node.Expression.AcceptExpression(this); switchStatement.Fill(expression, node.Sections.Select(i => i.Accept<LuaStatementSyntax>(this))); switches_.Pop(); return switchStatement; } private void FillSwitchSectionStatements(LuaBlockSyntax block, SwitchSectionSyntax node) { if (node.Statements.Count == 1 && node.Statements.First().IsKind(SyntaxKind.Block)) { var luaBlock = node.Statements.First().Accept<LuaBlockSyntax>(this); block.Statements.AddRange(luaBlock.Statements); } else { PushBlock(block); var statements = VisitTriviaAndNode(node, node.Statements); block.AddStatements(statements); PopBlock(); } } public override LuaSyntaxNode VisitSwitchSection(SwitchSectionSyntax node) { bool isDefault = node.Labels.Any(i => i.Kind() == SyntaxKind.DefaultSwitchLabel); if (isDefault) { var block = new LuaBlockSyntax(); FillSwitchSectionStatements(block, node); return block; } var expressions = node.Labels.Select(i => i.AcceptExpression(this)); var condition = expressions.Aggregate((x, y) => x.Or(y)); var ifStatement = new LuaIfStatementSyntax(condition); FillSwitchSectionStatements(ifStatement.Body, node); return ifStatement; } public override LuaSyntaxNode VisitCaseSwitchLabel(CaseSwitchLabelSyntax node) { var left = switches_.Peek().Temp; var right = node.Value.AcceptExpression(this); return left.EqualsEquals(right); } private LuaExpressionSyntax BuildSwitchLabelWhenClause(LuaExpressionSyntax expression, WhenClauseSyntax whenClause) { if (whenClause != null) { var whenExpression = whenClause.AcceptExpression(this); return expression != null ? expression.And(whenExpression) : whenExpression; } return expression; } private LuaExpressionSyntax BuildDeclarationPattern(DeclarationPatternSyntax declarationPattern, LuaIdentifierNameSyntax left, ExpressionSyntax expressionType, WhenClauseSyntax whenClause) { if (!declarationPattern.Designation.IsKind(SyntaxKind.DiscardDesignation)) { AddLocalVariableMapping(left, declarationPattern.Designation); } var isExpression = BuildIsPatternExpression(expressionType, declarationPattern.Type, left); if (isExpression == LuaIdentifierLiteralExpressionSyntax.True) { return whenClause != null ? whenClause.AcceptExpression(this) : LuaIdentifierLiteralExpressionSyntax.True; } return BuildSwitchLabelWhenClause(isExpression, whenClause); } public override LuaSyntaxNode VisitCasePatternSwitchLabel(CasePatternSwitchLabelSyntax node) { var left = switches_.Peek().Temp; switch (node.Pattern.Kind()) { case SyntaxKind.DeclarationPattern: { var switchStatement = (SwitchStatementSyntax)FindParent(node, SyntaxKind.SwitchStatement); var declarationPattern = (DeclarationPatternSyntax)node.Pattern; return BuildDeclarationPattern(declarationPattern, left, switchStatement.Expression, node.WhenClause); } case SyntaxKind.VarPattern: { var varPattern = (VarPatternSyntax)node.Pattern; AddLocalVariableMapping(left, varPattern.Designation); return BuildSwitchLabelWhenClause(null, node.WhenClause); } default: { var patternExpression = node.Pattern.AcceptExpression(this); var expression = left.EqualsEquals(patternExpression); return BuildSwitchLabelWhenClause(expression, node.WhenClause); } } } public override LuaSyntaxNode VisitWhenClause(WhenClauseSyntax node) { return node.Condition.AcceptExpression(this); } public override LuaSyntaxNode VisitConstantPattern(ConstantPatternSyntax node) { return node.Expression.AcceptExpression(this); } private void FillSwitchPatternSyntax(ref LuaIfStatementSyntax ifStatement, LuaExpressionSyntax condition, WhenClauseSyntax whenClause, LuaIdentifierNameSyntax assignmentLeft, ExpressionSyntax assignmentRight) { if (condition == null && whenClause == null) { condition = LuaIdentifierLiteralExpressionSyntax.True; } else { condition = BuildSwitchLabelWhenClause(condition, whenClause); } if (ifStatement == null) { ifStatement = new LuaIfStatementSyntax(condition); PushBlock(ifStatement.Body); var rightExpression = assignmentRight.AcceptExpression(this); PopBlock(); ifStatement.Body.AddStatement(assignmentLeft.Assignment(rightExpression)); } else { var elseIfStatement = new LuaElseIfStatementSyntax(condition); PushBlock(elseIfStatement.Body); var rightExpression = assignmentRight.AcceptExpression(this); PopBlock(); elseIfStatement.Body.AddStatement(assignmentLeft.Assignment(rightExpression)); ifStatement.ElseIfStatements.Add(elseIfStatement); } } private void CheckSwitchDeconstruct(ref LuaLocalVariablesSyntax deconstruct, LuaIdentifierNameSyntax identifier, ExpressionSyntax type, int count) { if (deconstruct == null) { var typeSymbol = semanticModel_.GetTypeInfo(type).Type; var deconstructInvocation = BuildDeconstructExpression(typeSymbol, identifier, type); deconstruct = new LuaLocalVariablesSyntax(); for (int i = 0; i < count; ++i) { deconstruct.Variables.Add(GetTempIdentifier()); } deconstruct.Initializer = new LuaEqualsValueClauseListSyntax(); deconstruct.Initializer.Values.Add(deconstructInvocation); } } public LuaExpressionSyntax BuildPropertyPatternNameExpression(LuaIdentifierNameSyntax governingIdentifier, IdentifierNameSyntax nameIdentifier) { var symbol = semanticModel_.GetSymbolInfo(nameIdentifier).Symbol; if (symbol.Kind == SymbolKind.Field) { var name = GetMemberName(symbol); return governingIdentifier.MemberAccess(name); } else { var propertySymbol = (IPropertySymbol)symbol; var codeTemplate = XmlMetaProvider.GetPropertyCodeTemplate(propertySymbol, true); if (codeTemplate != null) { return InternalBuildCodeTemplateExpression(codeTemplate, null, null, null, governingIdentifier); } var name = nameIdentifier.AcceptExpression(this); return governingIdentifier.MemberAccess(name, name is LuaPropertyAdapterExpressionSyntax); } } private LuaExpressionSyntax BuildRecursivePatternExpression(RecursivePatternSyntax recursivePattern, LuaIdentifierNameSyntax governingIdentifier, LuaLocalVariablesSyntax deconstruct, ExpressionSyntax governingExpression) { var subpatterns = recursivePattern.PropertyPatternClause?.Subpatterns ?? recursivePattern.PositionalPatternClause.Subpatterns; var subpatternExpressions = new List<LuaExpressionSyntax>(); int subpatternIndex = 0; foreach (var subpattern in subpatterns) { var expression = subpattern.Pattern.AcceptExpression(this); if (subpattern.NameColon != null) { LuaExpressionSyntax left; if (governingIdentifier != null) { left = BuildPropertyPatternNameExpression(governingIdentifier, subpattern.NameColon.Name); } else { var fieldSymbol = (IFieldSymbol)semanticModel_.GetSymbolInfo(subpattern.NameColon.Name).Symbol; Contract.Assert(fieldSymbol.ContainingType.IsTupleType); left = deconstruct.Variables[subpatternIndex]; } subpatternExpressions.Add(left.EqualsEquals(expression)); } else if (!subpattern.Pattern.IsKind(SyntaxKind.DiscardPattern)) { CheckSwitchDeconstruct(ref deconstruct, governingIdentifier, recursivePattern.Type ?? governingExpression, subpatterns.Count); var variable = deconstruct.Variables[subpatternIndex]; subpatternExpressions.Add(variable.EqualsEquals(expression)); } } ++subpatternIndex; var condition = subpatternExpressions.Count > 0 ? subpatternExpressions.Aggregate((x, y) => x.And(y)) : governingIdentifier.NotEquals(LuaIdentifierNameSyntax.Nil); if (recursivePattern.Type != null) { var isExpression = BuildIsPatternExpression(governingExpression, recursivePattern.Type, governingIdentifier); if (isExpression != LuaIdentifierLiteralExpressionSyntax.True) { condition = isExpression.And(condition); } } return condition; } public override LuaSyntaxNode VisitSwitchExpression(SwitchExpressionSyntax node) { const string kNewSwitchExpressionException = "System.SwitchExpressionException()"; var result = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(result)); LuaIdentifierNameSyntax governingIdentifier; LuaLocalVariablesSyntax deconstruct = null; var governingExpression = node.GoverningExpression.AcceptExpression(this); if (node.GoverningExpression.IsKind(SyntaxKind.TupleExpression)) { governingIdentifier = null; var invocation = (LuaInvocationExpressionSyntax)governingExpression; deconstruct = new LuaLocalVariablesSyntax(); for (int i = 0; i < invocation.ArgumentList.Arguments.Count; ++i) { deconstruct.Variables.Add(GetTempIdentifier()); } deconstruct.Initializer = new LuaEqualsValueClauseListSyntax(); deconstruct.Initializer.Values.AddRange(invocation.ArgumentList.Arguments); } else { governingIdentifier = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(governingIdentifier, governingExpression)); } LuaIfStatementSyntax ifStatement = null; foreach (var arm in node.Arms) { switch (arm.Pattern.Kind()) { case SyntaxKind.ConstantPattern: { var patternExpression = arm.Pattern.AcceptExpression(this); var condition = governingIdentifier.EqualsEquals(patternExpression); FillSwitchPatternSyntax(ref ifStatement, condition, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.RecursivePattern: { var recursivePattern = (RecursivePatternSyntax)arm.Pattern; if (recursivePattern.Designation != null) { AddLocalVariableMapping(governingIdentifier, recursivePattern.Designation); } var condition = BuildRecursivePatternExpression(recursivePattern, governingIdentifier, deconstruct, node.GoverningExpression); FillSwitchPatternSyntax(ref ifStatement, condition, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.DeclarationPattern: { var declarationPattern = (DeclarationPatternSyntax)arm.Pattern; var condition = BuildDeclarationPattern(declarationPattern, governingIdentifier, node.GoverningExpression, arm.WhenClause); FillSwitchPatternSyntax(ref ifStatement, condition, null, result, arm.Expression); break; } case SyntaxKind.VarPattern: { var varPatternSyntax = (VarPatternSyntax)arm.Pattern; var parenthesizedVariable = (ParenthesizedVariableDesignationSyntax)varPatternSyntax.Designation; int variableIndex = 0; foreach (var variable in parenthesizedVariable.Variables) { if (!variable.IsKind(SyntaxKind.DiscardDesignation)) { CheckSwitchDeconstruct(ref deconstruct, governingIdentifier, node.GoverningExpression, parenthesizedVariable.Variables.Count); var variableName = deconstruct.Variables[variableIndex]; AddLocalVariableMapping(variableName, variable); } ++variableIndex; } FillSwitchPatternSyntax(ref ifStatement, null, arm.WhenClause, result, arm.Expression); break; } case SyntaxKind.DiscardPattern: { var elseClause = new LuaElseClauseSyntax(); PushBlock(elseClause.Body); var rightExpression = arm.Expression.AcceptExpression(this); PopBlock(); elseClause.Body.AddStatement(result.Assignment(rightExpression)); ifStatement.Else = elseClause; break; } default: { throw new NotImplementedException(); } } } if (ifStatement.Else == null) { var elseClause = new LuaElseClauseSyntax(); elseClause.Body.AddStatement(LuaIdentifierNameSyntax.Throw.Invocation(kNewSwitchExpressionException)); ifStatement.Else = elseClause; } if (deconstruct != null) { CurBlock.AddStatement(deconstruct); } CurBlock.AddStatement(ifStatement); return result; } #endregion private bool IsParentTryStatement(SyntaxNode node) { bool isTry = false; FindParent(node, i => { var kind = i.Kind(); switch (kind) { case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.SwitchStatement: return true; case SyntaxKind.TryStatement: case SyntaxKind.UsingStatement: isTry = true; return true; } return false; }); return isTry; } private bool CheckBreakLastBlockStatement(BreakStatementSyntax node) { if (IsLuaClassic) { switch (node.Parent.Kind()) { case SyntaxKind.Block: { var block = (BlockSyntax)node.Parent; return block.Statements.Last() != node; } case SyntaxKind.SwitchSection: { var switchSection = (SwitchSectionSyntax)node.Parent; return switchSection.Statements.Last() != node; } } } return false; } public override LuaSyntaxNode VisitBreakStatement(BreakStatementSyntax node) { if (IsParentTryStatement(node)) { var check = (LuaCheckLoopControlExpressionSyntax)CurFunction; check.HasBreak = true; return new LuaReturnStatementSyntax(LuaIdentifierLiteralExpressionSyntax.False); } if (CheckBreakLastBlockStatement(node)) { var blockStatement = new LuaBlockStatementSyntax(); blockStatement.Statements.Add(LuaBreakStatementSyntax.Instance); return blockStatement; } return LuaBreakStatementSyntax.Instance; } private LuaExpressionSyntax BuildEnumToStringExpression(ITypeSymbol typeInfo, bool isNullable, LuaExpressionSyntax original, ExpressionSyntax node) { if (original is LuaLiteralExpressionSyntax) { var symbol = semanticModel_.GetSymbolInfo(node).Symbol; return new LuaConstLiteralExpression(new LuaStringLiteralExpressionSyntax(symbol!.Name), typeInfo.ToString()); } AddExportEnum(typeInfo); var typeName = GetTypeShortName(typeInfo); if (IsPreventDebug || isNullable) { return LuaIdentifierNameSyntax.System.MemberAccess(LuaIdentifierNameSyntax.EnumToString).Invocation(original, typeName); } return original.MemberAccess(LuaIdentifierNameSyntax.EnumToString, true).Invocation(typeName); } private LuaExpressionSyntax WrapStringConcatExpression(ExpressionSyntax expression) { ITypeSymbol typeInfo = semanticModel_.GetTypeInfo(expression).Type; var original = expression.AcceptExpression(this); if (typeInfo.IsStringType()) { if (IsPreventDebug && !expression.IsKind(SyntaxKind.AddExpression) && !expression.IsKind(SyntaxKind.StringLiteralExpression)) { return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, original); } return original; } switch (typeInfo.SpecialType) { case SpecialType.System_Char: { var constValue = semanticModel_.GetConstantValue(expression); if (constValue.HasValue) { string text = SyntaxFactory.Literal((char)constValue.Value).Text; return new LuaIdentifierLiteralExpressionSyntax(text); } return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.StringChar, original); } case >= SpecialType.System_Boolean and <= SpecialType.System_Double when IsPreventDebug && typeInfo.SpecialType == SpecialType.System_Boolean: return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.SystemToString, original); case >= SpecialType.System_Boolean and <= SpecialType.System_Double: return original; } if (typeInfo.IsEnumType(out var enumTypeSymbol, out bool isNullable)) { return BuildEnumToStringExpression(enumTypeSymbol, isNullable, original, expression); } if (typeInfo.IsValueType) { return original.MemberAccess(LuaIdentifierNameSyntax.ToStr, true).Invocation(); } return LuaIdentifierNameSyntax.SystemToString.Invocation(original); } private LuaExpressionSyntax BuildStringConcatExpression(BinaryExpressionSyntax node) { return BuildStringConcatExpression(node.Left, node.Right); } private LuaExpressionSyntax BuildStringConcatExpression(ExpressionSyntax leftNode, ExpressionSyntax rightNode) { var left = WrapStringConcatExpression(leftNode); var right = WrapStringConcatExpression(rightNode); return left.Binary(LuaSyntaxNode.Tokens.Concatenation, right); } private LuaExpressionSyntax BuildBinaryInvokeExpression(BinaryExpressionSyntax node, LuaExpressionSyntax name) { var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); return new LuaInvocationExpressionSyntax(name, left, right); } private LuaBinaryExpressionSyntax BuildBinaryExpression(BinaryExpressionSyntax node, string operatorToken) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); return left.Binary(operatorToken, right); } private bool IsNullableType(BinaryExpressionSyntax node, out bool isLeftNullable, out bool isRightNullable) { var leftType = semanticModel_.GetTypeInfo(node.Left).Type; var rightType = semanticModel_.GetTypeInfo(node.Right).Type; isLeftNullable = leftType != null && leftType.IsNullableType(); isRightNullable = rightType != null && rightType.IsNullableType(); return isLeftNullable || isRightNullable; } private bool IsNullableType(BinaryExpressionSyntax node) => IsNullableType(node, out _, out _); private LuaExpressionSyntax BuildBoolXorOfNullExpression(BinaryExpressionSyntax node, bool isLeftNullable, bool isRightNullable) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); if (left.IsNil() || right.IsNil()) { return new LuaConstLiteralExpression(LuaIdentifierLiteralExpressionSyntax.Nil, node.ToString()); } var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifiers = BuildNumberNullableIdentifiers(ref left, ref right, isLeftNullable, isRightNullable); LuaExpressionSyntax condition = identifiers.Count == 1 ? identifiers.First().NotEquals(LuaIdentifierNameSyntax.Nil) : left.NotEquals(LuaIdentifierNameSyntax.Nil).And(right.NotEquals(LuaIdentifierNameSyntax.Nil)); var ifStatement = new LuaIfStatementSyntax(condition); ifStatement.Body.AddStatement(temp.Assignment(left.NotEquals(right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildLeftNullableBoolLogicExpression(BinaryExpressionSyntax node, string boolOperatorToken) { var left = VisitExpression(node.Left); var right = VisitExpression(node.Right); var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifier = BuildNullableExpressionIdentifier(left, new List<LuaExpressionSyntax>()); var ifStatement = new LuaIfStatementSyntax(identifier.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(right.Binary(boolOperatorToken, identifier))); ifStatement.Else = new LuaElseClauseSyntax(); ifStatement.Else.Body.AddStatement(temp.Assignment(identifier.Binary(boolOperatorToken, right))); CurBlock.AddStatement(ifStatement); return temp; } private LuaExpressionSyntax BuildBitExpression(BinaryExpressionSyntax node, string boolOperatorToken, LuaIdentifierNameSyntax bitMethodName) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol methodSymbol) { var containingType = methodSymbol.ContainingType; if (containingType != null) { if (containingType.IsBoolType(false)) { switch (node.Kind()) { case SyntaxKind.ExclusiveOrExpression: { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { return BuildBoolXorOfNullExpression(node, isLeftNullable, isRightNullable); } break; } case SyntaxKind.BitwiseOrExpression: case SyntaxKind.BitwiseAndExpression: { if (IsNullableType(node, out bool isLeftNullable, out _) && isLeftNullable) { return BuildLeftNullableBoolLogicExpression(node, boolOperatorToken); } break; } } return BuildBinaryExpression(node, boolOperatorToken); } if (containingType.IsIntegerType(false) || containingType.TypeKind == TypeKind.Enum) { if (IsLuaClassic) { if (IsNullableBinaryExpression(node, null, out var result, bitMethodName)) { return result; } return BuildBinaryInvokeExpression(node, bitMethodName); } else if (IsPreventDebug && IsNullableBinaryExpression(node, null, out var result, bitMethodName)) { return result; } } } } return null; } private LuaExpressionSyntax BuildLogicOrBinaryExpression(BinaryExpressionSyntax node) { var left = VisitExpression(node.Left); LuaBlockSyntax rightBody = new LuaBlockSyntax(); PushBlock(rightBody); var right = VisitExpression(node.Right); if (rightBody.Statements.Count == 0) { PopBlock(); return left.Or(right); } var temp = GetTempIdentifier(); PopBlock(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp)); LuaIfStatementSyntax leftIfStatement = new LuaIfStatementSyntax(left); CurBlock.Statements.Add(leftIfStatement); leftIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); leftIfStatement.Else = new LuaElseClauseSyntax(); leftIfStatement.Else.Body.Statements.AddRange(rightBody.Statements); LuaIfStatementSyntax rightIfStatement = new LuaIfStatementSyntax(right); leftIfStatement.Else.Body.AddStatement(rightIfStatement); rightIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); return temp; } private LuaExpressionSyntax BuildLogicAndBinaryExpression(BinaryExpressionSyntax node) { var left = VisitExpression(node.Left); LuaBlockSyntax rightBody = new LuaBlockSyntax(); PushBlock(rightBody); var right = VisitExpression(node.Right); if (rightBody.Statements.Count == 0) { PopBlock(); return left.And(right); } var temp = GetTempIdentifier(); PopBlock(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp)); LuaIfStatementSyntax leftIfStatement = new LuaIfStatementSyntax(left); CurBlock.Statements.Add(leftIfStatement); leftIfStatement.Body.Statements.AddRange(rightBody.Statements); LuaIfStatementSyntax rightIfStatement = new LuaIfStatementSyntax(right); leftIfStatement.Body.AddStatement(rightIfStatement); rightIfStatement.Body.AddStatement(temp.Assignment(LuaIdentifierNameSyntax.True)); return temp; } private bool IsNullableBinaryExpression(BinaryExpressionSyntax node, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); result = BuildNumberNullableExpression(left, right, operatorToken, isLeftNullable, isRightNullable, method); return true; } result = null; return false; } private bool IsNumberNullableBinaryExpression(INamedTypeSymbol containingType, BinaryExpressionSyntax node, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { if (containingType.IsNumberType(false)) { if (IsNullableBinaryExpression(node, operatorToken, out result, method)) { return true; } } result = null; return false; } private LuaExpressionSyntax BuildNumberBinaryExpression(BinaryExpressionSyntax node, SyntaxKind kind) { if (semanticModel_.GetSymbolInfo(node).Symbol is IMethodSymbol methodSymbol) { var containingType = methodSymbol.ContainingType; if (containingType != null) { if (kind == SyntaxKind.AddExpression && containingType.IsStringType()) { return BuildStringConcatExpression(node); } if (IsPreventDebug) { switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: { bool isPlus = node.IsKind(SyntaxKind.AddExpression); if (containingType.IsDelegateType()) { return BuildBinaryInvokeExpression(node, isPlus ? LuaIdentifierNameSyntax.DelegateCombine : LuaIdentifierNameSyntax.DelegateRemove); } if (IsNumberNullableBinaryExpression(containingType, node, isPlus ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } break; } case SyntaxKind.MultiplyExpression: { if (IsNumberNullableBinaryExpression(containingType, node, LuaSyntaxNode.Tokens.Multiply, out var result)) { return result; } break; } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: { var operatorToken = GetOperatorToken(node.OperatorToken); if (IsNumberNullableBinaryExpression(containingType, node, operatorToken, out var result)) { return result.Or(LuaIdentifierNameSyntax.False); } break; } } } switch (kind) { case SyntaxKind.DivideExpression: { if (IsPreventDebug && containingType.IsDoubleOrFloatType(false)) { if (IsNullableBinaryExpression(node, LuaSyntaxNode.Tokens.Div, out var result)) { return result; } } if (containingType.IsIntegerType(false)) { if (IsNullableType(node)) { if (IsLuaClassic || IsPreventDebug) { bool success = IsNullableBinaryExpression(node, null, out var result, LuaIdentifierNameSyntax.IntegerDiv); Contract.Assert(success); return result; } } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.IntegerDiv); } break; } case SyntaxKind.ModuloExpression: { if (containingType.IsNumberType(false)) { if (IsLuaClassic) { var method = containingType.IsIntegerType(false) ? LuaIdentifierNameSyntax.Mod : LuaIdentifierNameSyntax.ModFloat; if (IsNullableBinaryExpression(node, null, out var result, method)) { return result; } return BuildBinaryInvokeExpression(node, method); } else { if (IsPreventDebug && IsNullableBinaryExpression(node, null, out var result, LuaIdentifierNameSyntax.Mod)) { return result; } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.Mod); } } break; } case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: { if (containingType.IsIntegerType(false)) { bool isLeftShift = kind == SyntaxKind.LeftShiftExpression; string operatorToken = isLeftShift ? LuaSyntaxNode.Tokens.ShiftLeft : LuaSyntaxNode.Tokens.ShiftRight; if (IsLuaClassic) { var method = isLeftShift ? LuaIdentifierNameSyntax.ShiftLeft : LuaIdentifierNameSyntax.ShiftRight; if (IsNullableBinaryExpression(node, operatorToken, out var result, method)) { return result; } return BuildBinaryInvokeExpression(node, method); } else if (IsPreventDebug && IsNullableBinaryExpression(node, operatorToken, out var result)) { return result; } } break; } } } } return null; } public override LuaSyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { LuaExpressionSyntax resultExpression = GetConstExpression(node); if (resultExpression != null) { return resultExpression; } var kind = node.Kind(); switch (kind) { case SyntaxKind.AddExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: resultExpression = BuildNumberBinaryExpression(node, kind); break; case SyntaxKind.BitwiseOrExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.Or, LuaIdentifierNameSyntax.BitOr); break; } case SyntaxKind.BitwiseAndExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.And, LuaIdentifierNameSyntax.BitAnd); break; } case SyntaxKind.ExclusiveOrExpression: { resultExpression = BuildBitExpression(node, LuaSyntaxNode.Tokens.NotEquals, LuaIdentifierNameSyntax.BitXor); break; } case SyntaxKind.IsExpression: { var rightType = semanticModel_.GetTypeInfo(node.Right).Type; if (rightType.IsNullableType(out var nullElementType)) { var left = node.Left.AcceptExpression(this); var right = GetTypeName(nullElementType); return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Is, left, right); } var leftType = semanticModel_.GetTypeInfo(node.Left).Type; if (leftType.Is(rightType)) { if (leftType.IsValueType) { return LuaIdentifierLiteralExpressionSyntax.True; } return node.Left.AcceptExpression(this).NotEquals(LuaIdentifierNameSyntax.Nil); } var constValue = semanticModel_.GetConstantValue(node.Right); if (constValue.HasValue) { var leftExpression = node.Left.AcceptExpression(this); return BuildIsConstantExpression(leftExpression, node.Right, constValue); } return BuildBinaryInvokeExpression(node, LuaIdentifierNameSyntax.Is); } case SyntaxKind.AsExpression: { if (node.Left.IsKind(SyntaxKind.NullLiteralExpression)) { return LuaIdentifierLiteralExpressionSyntax.Nil; } var leftType = semanticModel_.GetTypeInfo(node.Left).Type; var rightType = semanticModel_.GetTypeInfo(node.Right).Type; if (leftType.Is(rightType)) { return node.Left.Accept(this); } var left = node.Left.AcceptExpression(this); var right = node.Right.AcceptExpression(this); if (rightType.IsNullableType()) { right = ((LuaInvocationExpressionSyntax)right).Arguments.First(); } return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.As, left, right); } case SyntaxKind.LogicalOrExpression: { return BuildLogicOrBinaryExpression(node); } case SyntaxKind.LogicalAndExpression: { return BuildLogicAndBinaryExpression(node); } case SyntaxKind.CoalesceExpression: { var left = node.Left.AcceptExpression(this); var temp = GetTempIdentifier(); var block = new LuaBlockSyntax(); PushBlock(block); var right = node.Right.AcceptExpression(this); PopBlock(); if (block.Statements.Count == 0) { var typeSymbol = semanticModel_.GetTypeInfo(node.Left).Type; bool isBool = typeSymbol != null && typeSymbol.IsBoolType(); if (!isBool) { AddReleaseTempIdentifier(temp); return left.Binary(GetOperatorToken(node.OperatorToken), right); } } CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp, left)); var ifStatement = new LuaIfStatementSyntax(temp.EqualsEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatements(block.Statements); ifStatement.Body.AddStatement(temp.Assignment(right)); CurBlock.AddStatement(ifStatement); return temp; } } if (resultExpression != null) { return resultExpression; } if (IsUserDefinedOperator(node, out var methodSymbol)) { if (IsNullableTypeUserDefinedOperator(node, methodSymbol, out var result)) { return result; } return GetUserDefinedOperatorExpression(methodSymbol, node.Left, node.Right); } string operatorToken = GetOperatorToken(node.OperatorToken); return BuildBinaryExpression(node, operatorToken); } private bool IsNullableTypeUserDefinedOperator(BinaryExpressionSyntax node, IMethodSymbol methodSymbol, out LuaExpressionSyntax result) { if (IsNullableType(node, out bool isLeftNullable, out bool isRightNullable)) { var arguments = new List<Func<LuaExpressionSyntax>>(); var identifiers = new List<LuaExpressionSyntax>(); if (isLeftNullable) { if (isRightNullable) { arguments.Add(() => BuildNullableExpressionIdentifier(node.Left, identifiers)); arguments.Add(() => BuildNullableExpressionIdentifier(node.Right, identifiers)); } else { arguments.Add(() => BuildNullableExpressionIdentifier(node.Left, identifiers)); arguments.Add(() => VisitExpression(node.Right)); } } else { arguments.Add(() => VisitExpression(node.Left)); arguments.Add(() => BuildNullableExpressionIdentifier(node.Right, identifiers)); } var operatorExpression = GetUserDefinedOperatorExpression(methodSymbol, arguments); switch (node.Kind()) { case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: { var prevIdentifiers = identifiers.ToList(); TransformIdentifiersForCompareExpression(identifiers); var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var ifStatement = new LuaIfStatementSyntax(identifiers.Aggregate((x, y) => x.And(y))); ifStatement.Body.AddStatement(temp.Assignment(operatorExpression)); ifStatement.Else = new LuaElseClauseSyntax(); LuaExpressionSyntax right; if (node.IsKind(SyntaxKind.EqualsExpression)) { if (identifiers.Count == 1) { right = LuaIdentifierLiteralExpressionSyntax.False; } else { Contract.Assert(identifiers.Count == 2); right = prevIdentifiers.First().EqualsEquals(prevIdentifiers.Last()); } } else { if (identifiers.Count == 1) { right = LuaIdentifierLiteralExpressionSyntax.True; } else { Contract.Assert(identifiers.Count == 2); right = prevIdentifiers.First().NotEquals(prevIdentifiers.Last()); } } ifStatement.Else.Body.AddStatement(temp.Assignment(right)); CurBlock.AddStatement(ifStatement); result = temp; return true; } case SyntaxKind.LessThanExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: { TransformIdentifiersForCompareExpression(identifiers); break; } } result = identifiers.Aggregate((x, y) => x.And(y)).And(operatorExpression); return true; } result = null; return false; } private LuaExpressionSyntax BuildNullableExpressionIdentifier(ExpressionSyntax node, List<LuaExpressionSyntax> identifiers) { var expression = node.AcceptExpression(this); return BuildNullableExpressionIdentifier(expression, identifiers); } private LuaIdentifierNameSyntax BuildNullableExpressionIdentifier(LuaExpressionSyntax expression, List<LuaExpressionSyntax> identifiers) { if (expression is LuaIdentifierNameSyntax identifierName) { identifiers.Add(identifierName); return identifierName; } var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp, expression)); identifiers.Add(temp); return temp; } private bool IsSingleLineUnary(ExpressionSyntax node) { switch (node.Parent.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ForStatement: { return true; } case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: { var method = CurMethodInfoOrNull.Symbol; if (method.ReturnsVoid) { return true; } break; } } return false; } private void CheckIncrementExpression(ExpressionSyntax operand, ref LuaExpressionSyntax expression, bool isAddOrAssignment) { var symbol = semanticModel_.GetTypeInfo(operand).Type; if (!symbol.IsNumberType()) { var method = symbol.GetMembers("op_Implicit").OfType<IMethodSymbol>(); var methodSymbol = method.FirstOrDefault(i => isAddOrAssignment ? i.ReturnType.IsIntegerType() : i.ReturnType.EQ(symbol)); if (methodSymbol != null) { expression = BuildConversionExpression(methodSymbol, expression); } } } private LuaSyntaxNode BuildPrefixUnaryExpression(bool isSingleLine, string operatorToken, LuaExpressionSyntax operand, PrefixUnaryExpressionSyntax node, bool isLocalVar = false) { var left = operand; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); if (isSingleLine) { return operand.Assignment(binary); } if (isLocalVar) { CurBlock.Statements.Add(operand.Assignment(binary)); return operand; } var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, binary)); CurBlock.Statements.Add(operand.Assignment(temp)); return temp; } private LuaSyntaxNode BuildPropertyPrefixUnaryExpression(bool isSingleLine, string operatorToken, LuaPropertyAdapterExpressionSyntax get, LuaPropertyAdapterExpressionSyntax set, PrefixUnaryExpressionSyntax node) { set.IsGetOrAdd = false; LuaExpressionSyntax left = get; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); if (isSingleLine) { set.ArgumentList.AddArgument(binary); return set; } var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, binary)); set.ArgumentList.AddArgument(temp); CurBlock.Statements.Add(set); return temp; } private LuaMemberAccessExpressionSyntax GetTempUnaryExpression(LuaMemberAccessExpressionSyntax memberAccess, out LuaLocalVariableDeclaratorSyntax localTemp) { var temp = GetTempIdentifier(); localTemp = new LuaLocalVariableDeclaratorSyntax(temp, memberAccess.Expression); return temp.MemberAccess(memberAccess.Name, memberAccess.IsObjectColon); } private LuaPropertyAdapterExpressionSyntax GetTempPropertyUnaryExpression(LuaPropertyAdapterExpressionSyntax propertyAdapter, out LuaLocalVariableDeclaratorSyntax localTemp) { var temp = GetTempIdentifier(); localTemp = new LuaLocalVariableDeclaratorSyntax(temp, propertyAdapter.Expression); var result = new LuaPropertyAdapterExpressionSyntax(temp, propertyAdapter.Name, propertyAdapter.IsObjectColon); result.ArgumentList.AddArguments(propertyAdapter.ArgumentList.Arguments); return result; } private bool IsNullablePrefixUnaryExpression(PrefixUnaryExpressionSyntax node, LuaExpressionSyntax operand, string operatorToken, out LuaExpressionSyntax result, LuaIdentifierNameSyntax method = null) { var type = semanticModel_.GetTypeInfo(node.Operand).Type; if (type.IsNullableType()) { var identifier = BuildNullableExpressionIdentifier(operand, new List<LuaExpressionSyntax>()); result = operatorToken != null ? identifier.And(new LuaPrefixUnaryExpressionSyntax(identifier, operatorToken)) : identifier.And(new LuaInvocationExpressionSyntax(method, identifier)); return true; } result = null; return false; } public override LuaSyntaxNode VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) { SyntaxKind kind = node.Kind(); if (kind == SyntaxKind.IndexExpression) { var expression = VisitExpression(node.Operand); var v = semanticModel_.GetConstantValue(node.Operand); if (v.HasValue && (int)v.Value > 0) { return new LuaPrefixUnaryExpressionSyntax(expression, LuaSyntaxNode.Tokens.Sub); } return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Index, expression, LuaIdentifierNameSyntax.True); } if (IsUserDefinedOperator(node, out var methodSymbol)) { var type = semanticModel_.GetTypeInfo(node.Operand).Type; if (type != null && type.IsNullableType()) { var arguments = new List<Func<LuaExpressionSyntax>>(); var identifiers = new List<LuaExpressionSyntax>(); arguments.Add(() => BuildNullableExpressionIdentifier(node.Operand, identifiers)); var operatorExpression = GetUserDefinedOperatorExpression(methodSymbol, arguments); return identifiers.First().And(operatorExpression); } return GetUserDefinedOperatorExpression(methodSymbol, node.Operand); } var operand = VisitExpression(node.Operand); switch (kind) { case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: { bool isSingleLine = IsSingleLineUnary(node); string operatorToken = kind == SyntaxKind.PreIncrementExpression ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; switch (operand) { case LuaMemberAccessExpressionSyntax memberAccess: { if (memberAccess.Expression != LuaIdentifierNameSyntax.This) { memberAccess = GetTempUnaryExpression(memberAccess, out var localTemp); CurBlock.Statements.Add(localTemp); } return BuildPrefixUnaryExpression(isSingleLine, operatorToken, memberAccess, node); } case LuaPropertyAdapterExpressionSyntax propertyAdapter when propertyAdapter.Expression != null: { var getAdapter = GetTempPropertyUnaryExpression(propertyAdapter, out var localTemp); CurBlock.Statements.Add(localTemp); return BuildPropertyPrefixUnaryExpression(isSingleLine, operatorToken, getAdapter, getAdapter.GetClone(), node); } case LuaPropertyAdapterExpressionSyntax propertyAdapter: return BuildPropertyPrefixUnaryExpression(isSingleLine, operatorToken, propertyAdapter, propertyAdapter.GetClone(), node); } bool isLocalVar = false; if (!isSingleLine) { SymbolKind symbolKind = semanticModel_.GetSymbolInfo(node.Operand).Symbol.Kind; if (symbolKind is SymbolKind.Parameter or SymbolKind.Local) { isLocalVar = true; } } return BuildPrefixUnaryExpression(isSingleLine, operatorToken, operand, node, isLocalVar); } case SyntaxKind.PointerIndirectionExpression: { var identifier = new LuaPropertyOrEventIdentifierNameSyntax(true, LuaIdentifierNameSyntax.Empty); return new LuaPropertyAdapterExpressionSyntax(operand, identifier, true); } case SyntaxKind.BitwiseNotExpression: { if (IsLuaClassic) { if (IsNullablePrefixUnaryExpression(node, operand, null, out var result, LuaIdentifierNameSyntax.BitNot)) { return result; } return LuaIdentifierNameSyntax.BitNot.Invocation(operand); } else if (IsPreventDebug && IsNullablePrefixUnaryExpression(node, operand, LuaSyntaxNode.Tokens.BitNot, out var result)) { return result; } break; } case SyntaxKind.UnaryPlusExpression: { return operand; } case SyntaxKind.UnaryMinusExpression: { if (operand is LuaLiteralExpressionSyntax {Text: "0"}) { return operand; } if (IsPreventDebug && IsNullablePrefixUnaryExpression(node, operand, LuaSyntaxNode.Tokens.Sub, out var result)) { return result; } break; } case SyntaxKind.LogicalNotExpression: { var symbol = semanticModel_.GetTypeInfo(node.Operand).Type; if (symbol != null && symbol.IsNullableType() && symbol.IsBoolType()) { var temp = GetTempIdentifier(); CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); var identifier = BuildNullableExpressionIdentifier(operand, new List<LuaExpressionSyntax>()); var ifStatement = new LuaIfStatementSyntax(identifier.NotEquals(LuaIdentifierNameSyntax.Nil)); ifStatement.Body.AddStatement(temp.Assignment(new LuaPrefixUnaryExpressionSyntax(identifier, LuaSyntaxNode.Tokens.Not))); CurBlock.AddStatement(ifStatement); return temp; } break; } } var unaryExpression = new LuaPrefixUnaryExpressionSyntax(operand, GetOperatorToken(node.OperatorToken)); return unaryExpression; } private LuaSyntaxNode BuildPostfixUnaryExpression(bool isSingleLine, string operatorToken, LuaExpressionSyntax operand, PostfixUnaryExpressionSyntax node) { if (isSingleLine) { var left = operand; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); return operand.Assignment(binary); } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, operand)); LuaExpressionSyntax left = temp; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); CurBlock.Statements.Add(operand.Assignment(binary)); return temp; } } private LuaSyntaxNode BuildPropertyPostfixUnaryExpression(bool isSingleLine, string operatorToken, LuaPropertyAdapterExpressionSyntax get, LuaPropertyAdapterExpressionSyntax set, PostfixUnaryExpressionSyntax node) { set.IsGetOrAdd = false; if (isSingleLine) { LuaExpressionSyntax left = get; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); set.ArgumentList.AddArgument(binary); return set; } else { var temp = GetTempIdentifier(); CurBlock.Statements.Add(new LuaLocalVariableDeclaratorSyntax(temp, get)); LuaExpressionSyntax left = temp; CheckIncrementExpression(node.Operand, ref left, true); LuaExpressionSyntax binary = left.Binary(operatorToken, LuaIdentifierNameSyntax.One); CheckIncrementExpression(node.Operand, ref binary, false); set.ArgumentList.AddArgument(binary); CurBlock.AddStatement(set); return temp; } } public override LuaSyntaxNode VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) { var operand = node.Operand.AcceptExpression(this); SyntaxKind kind = node.Kind(); if (kind == SyntaxKind.SuppressNullableWarningExpression) { return operand; } Contract.Assert(kind is SyntaxKind.PostIncrementExpression or SyntaxKind.PostDecrementExpression); bool isSingleLine = IsSingleLineUnary(node); string operatorToken = kind == SyntaxKind.PostIncrementExpression ? LuaSyntaxNode.Tokens.Plus : LuaSyntaxNode.Tokens.Sub; switch (operand) { case LuaMemberAccessExpressionSyntax memberAccess: { if (memberAccess.Expression != LuaIdentifierNameSyntax.This) { memberAccess = GetTempUnaryExpression(memberAccess, out var localTemp); CurBlock.Statements.Add(localTemp); } return BuildPostfixUnaryExpression(isSingleLine, operatorToken, memberAccess, node); } case LuaPropertyAdapterExpressionSyntax propertyAdapter when propertyAdapter.Expression != null: { var getAdapter = GetTempPropertyUnaryExpression(propertyAdapter, out var localTemp); CurBlock.Statements.Add(localTemp); return BuildPropertyPostfixUnaryExpression(isSingleLine, operatorToken, getAdapter, getAdapter.GetClone(), node); } case LuaPropertyAdapterExpressionSyntax propertyAdapter: return BuildPropertyPostfixUnaryExpression(isSingleLine, operatorToken, propertyAdapter, propertyAdapter.GetClone(), node); default: return BuildPostfixUnaryExpression(isSingleLine, operatorToken, operand, node); } } public override LuaSyntaxNode VisitContinueStatement(ContinueStatementSyntax node) { bool isWithinTry = IsParentTryStatement(node); if (isWithinTry) { var check = (LuaCheckLoopControlExpressionSyntax)CurFunction; check.HasContinue = true; } return new LuaContinueAdapterStatementSyntax(isWithinTry); } private static bool IsLastBreakStatement(LuaStatementSyntax lastStatement) { if (lastStatement == LuaBreakStatementSyntax.Instance) { return true; } switch (lastStatement) { case LuaContinueAdapterStatementSyntax: case LuaLabeledStatement labeledStatement when IsLastBreakStatement(labeledStatement.Statement): return true; default: return false; } } private void VisitLoopBody(StatementSyntax bodyStatement, LuaBlockSyntax block) { bool hasContinue = IsContinueExists(bodyStatement); if (hasContinue) { // http://lua-users.org/wiki/ContinueProposal var continueIdentifier = LuaIdentifierNameSyntax.Continue; block.Statements.Add(new LuaLocalVariableDeclaratorSyntax(continueIdentifier)); LuaRepeatStatementSyntax repeatStatement = new LuaRepeatStatementSyntax(LuaIdentifierNameSyntax.One); WriteStatementOrBlock(bodyStatement, repeatStatement.Body); var lastStatement = repeatStatement.Body.Statements.Last(); bool isLastFinal = lastStatement is LuaBaseReturnStatementSyntax || IsLastBreakStatement(lastStatement); if (!isLastFinal) { repeatStatement.Body.Statements.Add(continueIdentifier.Assignment(LuaIdentifierNameSyntax.True)); } block.Statements.Add(repeatStatement); LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(new LuaPrefixUnaryExpressionSyntax(continueIdentifier, LuaSyntaxNode.Tokens.Not)); ifStatement.Body.Statements.Add(LuaBreakStatementSyntax.Instance); block.Statements.Add(ifStatement); } else { WriteStatementOrBlock(bodyStatement, block); } } private void CheckForeachCast(LuaIdentifierNameSyntax identifier, ForEachStatementSyntax node, LuaForInStatementSyntax forInStatement, bool isAsync) { var sourceType = semanticModel_.GetTypeInfo(node.Expression).Type; var targetType = semanticModel_.GetTypeInfo(node.Type).Type; bool hasCast = false; var elementType = !isAsync ? sourceType.GetIEnumerableElementType() : sourceType.GetIAsyncEnumerableElementType(); if (elementType != null) { if (!elementType.EQ(targetType) && !elementType.Is(targetType)) { hasCast = true; } } else { if (targetType.SpecialType != SpecialType.System_Object) { hasCast = true; } } if (hasCast) { var cast = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Cast, GetTypeName(targetType), identifier); forInStatement.Body.AddStatement(identifier.Assignment(cast)); } } public override LuaSyntaxNode VisitForEachStatement(ForEachStatementSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; CheckLocalVariableName(ref identifier, node); var expression = node.Expression.AcceptExpression(this); bool isAsync = node.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword); var forInStatement = new LuaForInStatementSyntax(identifier, expression, isAsync); CheckForeachCast(identifier, node, forInStatement, isAsync); VisitLoopBody(node.Statement, forInStatement.Body); return forInStatement; } public override LuaSyntaxNode VisitForEachVariableStatement(ForEachVariableStatementSyntax node) { var temp = GetTempIdentifier(); var expression = node.Expression.AcceptExpression(this); var forInStatement = new LuaForInStatementSyntax(temp, expression); var left = node.Variable.AcceptExpression(this); var sourceType = semanticModel_.GetTypeInfo(node.Expression).Type; var elementType = sourceType.GetIEnumerableElementType(); var right = BuildDeconstructExpression(elementType, temp, node.Expression); forInStatement.Body.AddStatement(left.Assignment(right)); VisitLoopBody(node.Statement, forInStatement.Body); return forInStatement; } private LuaWhileStatementSyntax BuildWhileStatement(ExpressionSyntax nodeCondition, StatementSyntax nodeStatement) { LuaBlockSyntax conditionBody = new LuaBlockSyntax(); PushBlock(conditionBody); var condition = nodeCondition != null ? VisitExpression(nodeCondition) : LuaIdentifierNameSyntax.True; PopBlock(); LuaWhileStatementSyntax whileStatement; if (conditionBody.Statements.Count == 0) { whileStatement = new LuaWhileStatementSyntax(condition); } else { whileStatement = new LuaWhileStatementSyntax(LuaIdentifierNameSyntax.True); if (condition is LuaBinaryExpressionSyntax) { condition = condition.Parenthesized(); } LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(new LuaPrefixUnaryExpressionSyntax(condition, LuaSyntaxNode.Tokens.Not)); ifStatement.Body.AddStatement(LuaBreakStatementSyntax.Instance); whileStatement.Body.Statements.AddRange(conditionBody.Statements); whileStatement.Body.Statements.Add(ifStatement); } VisitLoopBody(nodeStatement, whileStatement.Body); return whileStatement; } public override LuaSyntaxNode VisitWhileStatement(WhileStatementSyntax node) { return BuildWhileStatement(node.Condition, node.Statement); } public override LuaSyntaxNode VisitForStatement(ForStatementSyntax node) { var numericalForStatement = GetNumericalForStatement(node); if (numericalForStatement != null) { return numericalForStatement; } LuaBlockSyntax forBlock = new LuaBlockStatementSyntax(); PushBlock(forBlock); if (node.Declaration != null) { forBlock.AddStatement(node.Declaration.Accept<LuaVariableDeclarationSyntax>(this)); } var initializers = node.Initializers.Select(i => i.AcceptExpression(this)); forBlock.AddStatements(initializers); var whileStatement = BuildWhileStatement(node.Condition, node.Statement); PushBlock(whileStatement.Body); var incrementors = node.Incrementors.Select(i => i.AcceptExpression(this)); whileStatement.Body.AddStatements(incrementors); PopBlock(); forBlock.Statements.Add(whileStatement); PopBlock(); return forBlock; } public override LuaSyntaxNode VisitDoStatement(DoStatementSyntax node) { LuaBlockSyntax body = new LuaBlockSyntax(); PushBlock(body); VisitLoopBody(node.Statement, body); var condition = VisitExpression(node.Condition); if (condition is LuaBinaryExpressionSyntax) { condition = condition.Parenthesized(); } var newCondition = new LuaPrefixUnaryExpressionSyntax(condition, LuaSyntaxNode.Tokens.Not); PopBlock(); return new LuaRepeatStatementSyntax(newCondition, body); } public override LuaSyntaxNode VisitYieldStatement(YieldStatementSyntax node) { var curMethod = CurMethodInfoOrNull; curMethod.HasYield = true; if (node.IsKind(SyntaxKind.YieldBreakStatement)) { return new LuaReturnStatementSyntax(); } string yieldToken = node.YieldKeyword.ValueText; var expression = node.Expression.AcceptExpression(this); LuaExpressionSyntax targetMethod = curMethod.Symbol.IsAsync ? LuaIdentifierNameSyntax.Async.MemberAccess(yieldToken, true) : LuaIdentifierNameSyntax.System.MemberAccess(yieldToken); return new LuaExpressionStatementSyntax(targetMethod.Invocation(expression)); } public override LuaSyntaxNode VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { var expression = node.Expression.AcceptExpression(this); if (expression is LuaIdentifierNameSyntax or LuaMemberAccessExpressionSyntax) { return expression; } CheckPrevIsInvokeStatement(node); return expression.Parenthesized(); } /// <summary> /// http://lua-users.org/wiki/TernaryOperator /// </summary> public override LuaSyntaxNode VisitConditionalExpression(ConditionalExpressionSyntax node) { bool mayBeNullOrFalse = MayBeNullOrFalse(node.WhenTrue); if (mayBeNullOrFalse) { var temp = GetTempIdentifier(); var condition = VisitExpression(node.Condition); LuaIfStatementSyntax ifStatement = new LuaIfStatementSyntax(condition); PushBlock(ifStatement.Body); var whenTrue = VisitExpression(node.WhenTrue); PopBlock(); ifStatement.Body.AddStatement(temp.Assignment(whenTrue)); LuaElseClauseSyntax elseClause = new LuaElseClauseSyntax(); PushBlock(elseClause.Body); var whenFalse = VisitExpression(node.WhenFalse); PopBlock(); elseClause.Body.AddStatement(temp.Assignment(whenFalse)); ifStatement.Else = elseClause; CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(temp)); CurBlock.AddStatement(ifStatement); return temp; } else { LuaExpressionSyntax Accept(ExpressionSyntax expressionNode) { var expression = VisitExpression(expressionNode); return expression is LuaBinaryExpressionSyntax ? expression.Parenthesized() : expression; } var condition = Accept(node.Condition); var whenTrue = Accept(node.WhenTrue); var whenFalse = Accept(node.WhenFalse); return condition.And(whenTrue).Or(whenFalse); } } public override LuaSyntaxNode VisitGotoStatement(GotoStatementSyntax node) { if (node.CaseOrDefaultKeyword.IsKind(SyntaxKind.CaseKeyword)) { const string kCaseLabel = "caseLabel"; var switchStatement = switches_.Peek(); int caseIndex = GetCaseLabelIndex(node); var labelIdentifier = switchStatement.CaseLabels.GetOrDefault(caseIndex); if (labelIdentifier == null) { string uniqueName = GetUniqueIdentifier(kCaseLabel + caseIndex, node); labelIdentifier = uniqueName; switchStatement.CaseLabels.Add(caseIndex, labelIdentifier); } return new LuaGotoCaseAdapterStatement(labelIdentifier); } if (node.CaseOrDefaultKeyword.IsKind(SyntaxKind.DefaultKeyword)) { const string kDefaultLabel = "defaultLabel"; var switchStatement = switches_.Peek(); switchStatement.DefaultLabel ??= GetUniqueIdentifier(kDefaultLabel, node); return new LuaGotoCaseAdapterStatement(switchStatement.DefaultLabel); } var identifier = node.Expression.Accept<LuaIdentifierNameSyntax>(this); return new LuaGotoStatement(identifier); } public override LuaSyntaxNode VisitLabeledStatement(LabeledStatementSyntax node) { LuaIdentifierNameSyntax identifier = node.Identifier.ValueText; var statement = node.Statement.Accept<LuaStatementSyntax>(this); return new LuaLabeledStatement(identifier, statement); } public override LuaSyntaxNode VisitEmptyStatement(EmptyStatementSyntax node) { return LuaStatementSyntax.Empty; } private LuaExpressionSyntax BuildEnumCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { if (targetType.TypeKind == TypeKind.Enum) { LuaExpressionSyntax result = null; var targetEnumUnderlyingType = ((INamedTypeSymbol)targetType).EnumUnderlyingType; if (originalType.TypeKind == TypeKind.Enum || originalType.IsCastIntegerType()) { var originalIntegerType = originalType.TypeKind == TypeKind.Enum ? ((INamedTypeSymbol)originalType).EnumUnderlyingType : originalType; result = targetEnumUnderlyingType.IsNumberTypeAssignableFrom(originalIntegerType) ? expression : GetCastToNumberExpression(expression, targetEnumUnderlyingType, false); } else if (originalType.IsDoubleOrFloatType(false)) { result = GetCastToNumberExpression(expression, targetEnumUnderlyingType, true); } if (result != null) { if (!generator_.IsConstantEnum(targetType) && !originalType.EQ(targetType)) { result = GetTypeName(targetType).Invocation(expression); } return result; } } else if (originalType.TypeKind == TypeKind.Enum) { var originalEnumUnderlyingType = ((INamedTypeSymbol)originalType).EnumUnderlyingType; if (targetType.IsCastIntegerType()) { if (!generator_.IsConstantEnum(originalType)) { return GetEnumNoConstantToNumberExpression(expression, targetType); } if (targetType.IsNumberTypeAssignableFrom(originalEnumUnderlyingType)) { return expression; } return GetCastToNumberExpression(expression, targetType, false); } if (targetType.IsDoubleOrFloatType(false)) { return expression; } } return null; } private LuaExpressionSyntax BuildNumberCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { if (targetType.IsCastIntegerType()) { if (originalType.IsCastIntegerType()) { if (targetType.IsNumberTypeAssignableFrom(originalType)) { return expression; } return GetCastToNumberExpression(expression, targetType, false); } if (originalType.IsDoubleOrFloatType(false)) { return GetCastToNumberExpression(expression, targetType, true); } } else if (originalType.IsCastIntegerType()) { if (targetType.IsDoubleOrFloatType(false)) { return expression; } } else if (targetType.SpecialType == SpecialType.System_Single && originalType.SpecialType == SpecialType.System_Double) { return GetCastToNumberExpression(expression, targetType, true); } return null; } private LuaExpressionSyntax BuildEnumAndNumberCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { return BuildEnumCastExpression(expression, originalType, targetType) ?? BuildNumberCastExpression(expression, originalType, targetType); } private LuaExpressionSyntax BuildNullableCastExpression(LuaExpressionSyntax expression, ITypeSymbol originalType, ITypeSymbol targetType) { var targetNullableElementType = targetType.NullableElementType(); var originalNullableElementType = originalType.NullableElementType(); if (targetNullableElementType != null) { if (originalNullableElementType != null) { bool isIdentifier = false; LuaIdentifierNameSyntax identifier; if (expression is LuaIdentifierNameSyntax identifierName) { identifier = identifierName; isIdentifier = true; } else { identifier = GetTempIdentifier(); } var castExpression = BuildEnumAndNumberCastExpression(identifier, originalNullableElementType, targetNullableElementType); if (castExpression != null) { if (castExpression == identifier) { return expression; } if (!isIdentifier) { CurBlock.AddStatement(new LuaLocalVariableDeclaratorSyntax(identifier, expression)); } return identifier.And(castExpression); } } else { return BuildEnumAndNumberCastExpression(expression, originalType, targetNullableElementType); } } else if (originalNullableElementType != null) { var explicitMethod = (IMethodSymbol)originalType.GetMembers("op_Explicit").First(); expression = BuildConversionExpression(explicitMethod, expression); return BuildEnumAndNumberCastExpression(expression, originalNullableElementType, targetType); } return null; } public override LuaSyntaxNode VisitCastExpression(CastExpressionSyntax node) { var constExpression = GetConstExpression(node); if (constExpression != null) { return constExpression; } var targetType = semanticModel_.GetTypeInfo(node.Type).Type; Contract.Assert(targetType != null); var expression = node.Expression.AcceptExpression(this); if (targetType.SpecialType == SpecialType.System_Object || targetType.Kind == SymbolKind.DynamicType) { return expression; } var originalType = semanticModel_.GetTypeInfo(node.Expression).Type; if (originalType == null) { Contract.Assert(targetType.IsDelegateType()); return expression; } if (originalType.Is(targetType)) { return expression; } var result = BuildEnumAndNumberCastExpression(expression, originalType, targetType); if (result != null) { return result; } result = BuildNullableCastExpression(expression, originalType, targetType); if (result != null) { return result; } var explicitSymbol = (IMethodSymbol)semanticModel_.GetSymbolInfo(node).Symbol; if (explicitSymbol != null) { return BuildConversionExpression(explicitSymbol, expression); } return BuildCastExpression(targetType, expression); } private LuaExpressionSyntax BuildCastExpression(ITypeSymbol type, LuaExpressionSyntax expression) { var typeExpression = GetTypeName(type.IsNullableType() ? type.NullableElementType() : type); var invocation = new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.Cast, typeExpression, expression); if (type.IsNullableType()) { invocation.AddArgument(LuaIdentifierNameSyntax.True); } return invocation; } private LuaExpressionSyntax GetEnumNoConstantToNumberExpression(LuaExpressionSyntax expression, ITypeSymbol targetType) { string methodName = "System.Convert.To" + targetType.Name; return new LuaInvocationExpressionSyntax(methodName, expression); } private LuaExpressionSyntax GetCastToNumberExpression(LuaExpressionSyntax expression, ITypeSymbol targetType, bool isFromFloat) { if (expression is LuaParenthesizedExpressionSyntax parenthesizedExpression) { expression = parenthesizedExpression.Expression; } string name = (isFromFloat ? "To" : "to") + (targetType.SpecialType == SpecialType.System_Char ? "UInt16" : targetType.Name); var invocation = LuaIdentifierNameSyntax.System.MemberAccess(name).Invocation(expression); if (IsCurChecked) { invocation.AddArgument(LuaIdentifierNameSyntax.True); } return invocation; } public override LuaSyntaxNode VisitCheckedStatement(CheckedStatementSyntax node) { bool isChecked = node.Keyword.Kind() == SyntaxKind.CheckedKeyword; PushChecked(isChecked); var statements = new LuaStatementListSyntax(); statements.Statements.Add(new LuaShortCommentStatement(" " + node.Keyword.ValueText)); var block = node.Block.Accept<LuaStatementSyntax>(this); statements.Statements.Add(block); PopChecked(); return statements; } public override LuaSyntaxNode VisitCheckedExpression(CheckedExpressionSyntax node) { bool isChecked = node.Keyword.Kind() == SyntaxKind.CheckedKeyword; PushChecked(isChecked); var expression = node.Expression.Accept(this); PopChecked(); return expression; } public override LuaSyntaxNode VisitNullableType(NullableTypeSyntax node) { var elementType = node.ElementType.AcceptExpression(this); return new LuaInvocationExpressionSyntax(LuaIdentifierNameSyntax.NullableType, elementType); } } }
43.904743
253
0.675646
3db2c85521d9d5e78af3c4e5bfc3780108d33cdb
16,206
cs
C#
Win10_1909/winlogon.exe/12e65dd8-887f-41ef-91bf-8d816c42c2e7_1.0.cs
ohio813/WindowsRpcClients
2907d5555ed5d4073a2dea11e46fbc4e7f0eb18c
[ "Unlicense" ]
223
2019-10-31T21:00:47.000Z
2022-03-15T01:21:38.000Z
Win10_1909/winlogon.exe/12e65dd8-887f-41ef-91bf-8d816c42c2e7_1.0.cs
ohio813/WindowsRpcClients
2907d5555ed5d4073a2dea11e46fbc4e7f0eb18c
[ "Unlicense" ]
null
null
null
Win10_1909/winlogon.exe/12e65dd8-887f-41ef-91bf-8d816c42c2e7_1.0.cs
ohio813/WindowsRpcClients
2907d5555ed5d4073a2dea11e46fbc4e7f0eb18c
[ "Unlicense" ]
51
2019-11-01T01:11:32.000Z
2021-12-21T06:18:03.000Z
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Source Executable: c:\windows\system32\winlogon.exe // Interface ID: 12e65dd8-887f-41ef-91bf-8d816c42c2e7 // Interface Version: 1.0 namespace rpc_12e65dd8_887f_41ef_91bf_8d816c42c2e7_1_0 { #region Marshal Helpers internal class _Marshal_Helper : NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer { public void Write_0(Struct_0 p0) { WriteStruct<Struct_0>(p0); } public void Write_1(Struct_1 p0) { WriteStruct<Struct_1>(p0); } public void Write_2(Struct_2 p0) { WriteStruct<Struct_2>(p0); } public void Write_3(sbyte[] p0, long p1, long p2) { WriteConformantVaryingArray<sbyte>(p0, p1, p2); } public void Write_4(sbyte[] p0, long p1) { WriteConformantArray<sbyte>(p0, p1); } public void Write_5(sbyte[] p0, long p1) { WriteConformantArray<sbyte>(p0, p1); } public void Write_6(sbyte[] p0, long p1) { WriteConformantArray<sbyte>(p0, p1); } public void Write_7(char[] p0, long p1) { WriteConformantArray<char>(p0, p1); } public void Write_8(sbyte[] p0, long p1) { WriteConformantArray<sbyte>(p0, p1); } } internal class _Unmarshal_Helper : NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer { public _Unmarshal_Helper(NtApiDotNet.Win32.Rpc.RpcClientResponse r) : base(r.NdrBuffer, r.Handles, r.DataRepresentation) { } public _Unmarshal_Helper(byte[] ba) : base(ba) { } public Struct_0 Read_0() { return ReadStruct<Struct_0>(); } public Struct_1 Read_1() { return ReadStruct<Struct_1>(); } public Struct_2 Read_2() { return ReadStruct<Struct_2>(); } public sbyte[] Read_3() { return ReadConformantVaryingArray<sbyte>(); } public sbyte[] Read_4() { return ReadConformantArray<sbyte>(); } public sbyte[] Read_5() { return ReadConformantArray<sbyte>(); } public sbyte[] Read_6() { return ReadConformantArray<sbyte>(); } public char[] Read_7() { return ReadConformantArray<char>(); } public sbyte[] Read_8() { return ReadConformantArray<sbyte>(); } } #endregion #region Complex Types public struct Struct_0 : NtApiDotNet.Ndr.Marshal.INdrStructure { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteEnum16(Member0); m.WriteEmbeddedPointer<Struct_1>(Member8, new System.Action<Struct_1>(m.Write_1)); m.WriteEmbeddedPointer<string>(Member10, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member18, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member20, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member28, new System.Action<string>(m.WriteTerminatedString)); m.WriteUInt3264(Member30); m.WriteInt16(Member38); m.WriteInt16(Member3A); m.WriteEnum16(Member3C); m.WriteUInt3264(Member40); m.WriteUInt3264(Member48); m.WriteInt32(Member50); m.WriteEmbeddedPointer<sbyte[], long, long>(Member58, new System.Action<sbyte[], long, long>(m.Write_3), Member50, Member50); m.WriteInt32(Member60); m.WriteInt32(Member64); } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Member0 = u.ReadEnum16(); Member8 = u.ReadEmbeddedPointer<Struct_1>(new System.Func<Struct_1>(u.Read_1), false); Member10 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member18 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member20 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member28 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member30 = u.ReadUInt3264(); Member38 = u.ReadInt16(); Member3A = u.ReadInt16(); Member3C = u.ReadEnum16(); Member40 = u.ReadUInt3264(); Member48 = u.ReadUInt3264(); Member50 = u.ReadInt32(); Member58 = u.ReadEmbeddedPointer<sbyte[]>(new System.Func<sbyte[]>(u.Read_3), false); Member60 = u.ReadInt32(); Member64 = u.ReadInt32(); } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 4; } public NtApiDotNet.Ndr.Marshal.NdrEnum16 Member0; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<Struct_1> Member8; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member10; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member18; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member20; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member28; public NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member30; public short Member38; public short Member3A; public NtApiDotNet.Ndr.Marshal.NdrEnum16 Member3C; public NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member40; public NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member48; public int Member50; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<sbyte[]> Member58; public int Member60; public int Member64; public static Struct_0 CreateDefault() { return new Struct_0(); } public Struct_0( NtApiDotNet.Ndr.Marshal.NdrEnum16 Member0, System.Nullable<Struct_1> Member8, string Member10, string Member18, string Member20, string Member28, NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member30, short Member38, short Member3A, NtApiDotNet.Ndr.Marshal.NdrEnum16 Member3C, NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member40, NtApiDotNet.Ndr.Marshal.NdrUInt3264 Member48, int Member50, sbyte[] Member58, int Member60, int Member64) { this.Member0 = Member0; this.Member8 = Member8; this.Member10 = Member10; this.Member18 = Member18; this.Member20 = Member20; this.Member28 = Member28; this.Member30 = Member30; this.Member38 = Member38; this.Member3A = Member3A; this.Member3C = Member3C; this.Member40 = Member40; this.Member48 = Member48; this.Member50 = Member50; this.Member58 = Member58; this.Member60 = Member60; this.Member64 = Member64; } } public struct Struct_1 : NtApiDotNet.Ndr.Marshal.INdrStructure { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteInt32(Member0); } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Member0 = u.ReadInt32(); } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 4; } public int Member0; public static Struct_1 CreateDefault() { return new Struct_1(); } public Struct_1(int Member0) { this.Member0 = Member0; } } public struct Struct_2 : NtApiDotNet.Ndr.Marshal.INdrStructure { void NtApiDotNet.Ndr.Marshal.INdrStructure.Marshal(NtApiDotNet.Ndr.Marshal.NdrMarshalBuffer m) { Marshal(((_Marshal_Helper)(m))); } private void Marshal(_Marshal_Helper m) { m.WriteEmbeddedPointer<string>(Member0, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member8, new System.Action<string>(m.WriteTerminatedString)); m.WriteInt32(Member10); m.WriteEmbeddedPointer<string>(Member18, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member20, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<sbyte[], long>(Member28, new System.Action<sbyte[], long>(m.Write_4), Member30); m.WriteInt32(Member30); m.WriteEmbeddedPointer<System.Guid>(Member38, new System.Action<System.Guid>(m.WriteGuid)); m.WriteEmbeddedPointer<string>(Member40, new System.Action<string>(m.WriteTerminatedString)); m.WriteEmbeddedPointer<string>(Member48, new System.Action<string>(m.WriteTerminatedString)); } void NtApiDotNet.Ndr.Marshal.INdrStructure.Unmarshal(NtApiDotNet.Ndr.Marshal.NdrUnmarshalBuffer u) { Unmarshal(((_Unmarshal_Helper)(u))); } private void Unmarshal(_Unmarshal_Helper u) { Member0 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member8 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member10 = u.ReadInt32(); Member18 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member20 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member28 = u.ReadEmbeddedPointer<sbyte[]>(new System.Func<sbyte[]>(u.Read_4), false); Member30 = u.ReadInt32(); Member38 = u.ReadEmbeddedPointer<System.Guid>(new System.Func<System.Guid>(u.ReadGuid), false); Member40 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); Member48 = u.ReadEmbeddedPointer<string>(new System.Func<string>(u.ReadConformantVaryingString), false); } int NtApiDotNet.Ndr.Marshal.INdrStructure.GetAlignment() { return 4; } public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member0; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member8; public int Member10; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member18; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member20; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<sbyte[]> Member28; public int Member30; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<System.Guid> Member38; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member40; public NtApiDotNet.Ndr.Marshal.NdrEmbeddedPointer<string> Member48; public static Struct_2 CreateDefault() { return new Struct_2(); } public Struct_2(string Member0, string Member8, int Member10, string Member18, string Member20, sbyte[] Member28, int Member30, System.Nullable<System.Guid> Member38, string Member40, string Member48) { this.Member0 = Member0; this.Member8 = Member8; this.Member10 = Member10; this.Member18 = Member18; this.Member20 = Member20; this.Member28 = Member28; this.Member30 = Member30; this.Member38 = Member38; this.Member40 = Member40; this.Member48 = Member48; } } #endregion #region Client Implementation public sealed class Client : NtApiDotNet.Win32.Rpc.RpcClientBase { public Client() : base("12e65dd8-887f-41ef-91bf-8d816c42c2e7", 1, 0) { } private _Unmarshal_Helper SendReceive(int p, _Marshal_Helper m) { return new _Unmarshal_Helper(SendReceive(p, m.DataRepresentation, m.ToArray(), m.Handles)); } // async public int WlSecureDesktoprPromptingRequest(int p0, Struct_0 p1, Struct_2 p2, int p3, int p4, sbyte[] p5, int p6, int p7, int p8, out sbyte[] p9, out int p10, out int p11, out int p12, ref int p13) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteInt32(p0); m.Write_0(p1); m.Write_2(p2); m.WriteInt32(p3); m.WriteInt32(p4); m.WriteReferent(p5, new System.Action<sbyte[], long>(m.Write_5), p6); m.WriteInt32(p6); m.WriteInt32(p7); m.WriteInt32(p8); m.WriteInt32(p13); _Unmarshal_Helper u = SendReceive(0, m); p9 = u.ReadReferent<sbyte[]>(new System.Func<sbyte[]>(u.Read_6), false); p10 = u.ReadInt32(); p11 = u.ReadInt32(); p12 = u.ReadInt32(); p13 = u.ReadInt32(); return u.ReadInt32(); } // async public int WlSecureDesktoprConfirmationRequest(string p0, int p1, int p2, int p3, out char[] p4, out int p5, out sbyte[] p6, out int p7) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteReferent(p0, new System.Action<string>(m.WriteTerminatedString)); m.WriteInt32(p1); m.WriteInt32(p2); m.WriteInt32(p3); _Unmarshal_Helper u = SendReceive(1, m); p4 = u.ReadReferent<char[]>(new System.Func<char[]>(u.Read_7), false); p5 = u.ReadInt32(); p6 = u.ReadReferent<sbyte[]>(new System.Func<sbyte[]>(u.Read_8), false); p7 = u.ReadInt32(); return u.ReadInt32(); } // async public int WlSecureDesktoprCredmanBackupRequest(string p0, int p1) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteReferent(p0, new System.Action<string>(m.WriteTerminatedString)); m.WriteInt32(p1); _Unmarshal_Helper u = SendReceive(2, m); return u.ReadInt32(); } // async public int WlSecureDesktoprCredmanRestoreRequest(string p0, int p1) { _Marshal_Helper m = new _Marshal_Helper(); m.WriteReferent(p0, new System.Action<string>(m.WriteTerminatedString)); m.WriteInt32(p1); _Unmarshal_Helper u = SendReceive(3, m); return u.ReadInt32(); } public int WlSecureDesktoprSimulateSAS() { _Marshal_Helper m = new _Marshal_Helper(); _Unmarshal_Helper u = SendReceive(4, m); return u.ReadInt32(); } } #endregion }
41.13198
208
0.594595
3db350e6baa7282ac641239919e5ddc1c2c52f1a
1,264
cs
C#
src/Splunk.ModularInputs/Splunk/ModularInputs/DataType.cs
ccDev-Labs/splunk-sdk-csharp-pcl
02f4959588f8a05a6f09df6e8181dbc32f9ca8a2
[ "Apache-2.0" ]
58
2015-02-13T17:50:23.000Z
2021-12-18T06:54:57.000Z
src/Splunk.ModularInputs/Splunk/ModularInputs/DataType.cs
ccDev-Labs/splunk-sdk-csharp-pcl
02f4959588f8a05a6f09df6e8181dbc32f9ca8a2
[ "Apache-2.0" ]
55
2015-02-03T23:45:12.000Z
2021-12-18T07:27:18.000Z
src/Splunk.ModularInputs/Splunk/ModularInputs/DataType.cs
ccDev-Labs/splunk-sdk-csharp-pcl
02f4959588f8a05a6f09df6e8181dbc32f9ca8a2
[ "Apache-2.0" ]
46
2015-03-13T17:37:59.000Z
2022-03-27T09:43:57.000Z
/* * Copyright 2014 Splunk, Inc. * * 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 Splunk.ModularInputs { using System.Xml.Serialization; /// <summary> /// Enumeration of the valid values for the Endpoint Argument data type. /// </summary> public enum DataType { /// <summary> /// A Boolean value: <c>true</c> or <c>false</c> /// </summary> [XmlEnum(Name = "boolean")] Boolean, /// <summary> /// A numeric value: regexp = [0-9\.]+ /// </summary> [XmlEnum(Name = "number")] Number, /// <summary> /// A string: virtually everything else /// </summary> [XmlEnum(Name = "string")] String } }
28.088889
76
0.612342
3db481446ba44ff12b06c977058ba7d8eb33a326
2,807
cs
C#
TokenTools.Microsoft/MicrosoftAccessToken.cs
mlafleur/TokenTool
45af2a9b115a81421b08009eadf9d6c585fbafa9
[ "MIT" ]
1
2018-03-08T17:50:13.000Z
2018-03-08T17:50:13.000Z
TokenTools.Microsoft/MicrosoftAccessToken.cs
mlafleur/TokenTool
45af2a9b115a81421b08009eadf9d6c585fbafa9
[ "MIT" ]
null
null
null
TokenTools.Microsoft/MicrosoftAccessToken.cs
mlafleur/TokenTool
45af2a9b115a81421b08009eadf9d6c585fbafa9
[ "MIT" ]
null
null
null
using JWT.Builder; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; using TokenTools.Core; namespace TokenTools.Microsoft { /// <summary> /// A Microsoft v2 Endpoint Access Token. /// Based on the JSON Web Token spec with OpenID Connect Token and Azure AD v2 Endpoint Extentions /// </summary> public class MicrosoftAccessToken : MicrosoftToken { /// <summary> /// Identifies the application that is using the token to access a resource. /// The application can act as itself or on behalf of a user. /// The application ID typically represents an application object, but it can also represent a service principal object in Azure AD. /// </summary> [JsonProperty(PropertyName = "appid")] public string ApplicationId { get; set; } /// <summary> /// Indicates how the client was authenticated. For a public client, the value is 0. If client ID and client secret are used, the value is 1. /// </summary> [JsonProperty(PropertyName = "appidacr")] public string ApplicationIdAcr { get; set; } [JsonProperty(PropertyName = "deviceid")] public string DeviceId { get; set; } /// <summary> /// IP Address of the device that requested the token /// </summary> [JsonProperty(PropertyName = "idaddr")] public string IpAddress { get; set; } /// <summary> /// Indicates the impersonation permissions granted to the client application. The default permission is user_impersonation. The owner of the secured resource can register additional values in Azure AD. /// </summary> [JsonProperty(PropertyName = "scp")] public string Scopes { get; set; } /// <summary> /// Provides a human readable value that identifies the subject of the token. This value is not guaranteed to be unique within a tenant and is designed to be used only for display purposes. /// </summary> [JsonProperty(PropertyName = "unique_name")] public string UniqueName { get; set; } /// <summary> /// Stores the user name of the user principal. /// </summary> [JsonProperty(PropertyName = "upn")] public string UserPrincipalName { get; set; } /// <summary> /// Parse a JWT "access_token" into a new MicrosoftAccessToken object /// </summary> public new static MicrosoftAccessToken Parse(string access_token) { string json = new JwtBuilder().Decode(access_token); var raw = JObject.Parse(json); var typed = JObject.Parse(json).ToObject<MicrosoftAccessToken>(); return typed; } } }
38.986111
210
0.639829
3db7219c6327bca986270c2d80e5e4c58f53b245
3,097
cshtml
C#
NewLife.CubeNC/Areas/Admin/Views/Log/_List_Data.cshtml
yangchongyuan/NewLife.Cube
430286b562685e688b4d82c2b309b4555c377815
[ "MIT" ]
481
2018-05-19T22:38:46.000Z
2022-03-29T07:37:13.000Z
NewLife.CubeNC/Areas/Admin/Views/Log/_List_Data.cshtml
yangchongyuan/NewLife.Cube
430286b562685e688b4d82c2b309b4555c377815
[ "MIT" ]
41
2018-08-01T01:42:38.000Z
2022-01-09T11:42:05.000Z
NewLife.CubeNC/Areas/Admin/Views/Log/_List_Data.cshtml
yangchongyuan/NewLife.Cube
430286b562685e688b4d82c2b309b4555c377815
[ "MIT" ]
129
2018-05-20T04:14:45.000Z
2022-03-07T01:03:38.000Z
@model IList<XCode.Membership.Log> @using NewLife; @using NewLife.Web; @using XCode; @using XCode.Configuration; @{ var fact = ViewBag.Factory as IEntityFactory; var page = ViewBag.Page as Pager; var set = ViewBag.PageSetting as PageSetting; } <table class="table table-bordered table-hover table-striped table-condensed"> <thead> <tr> @if (set.EnableSelect) { <th class="text-center" style="width:10px;"><input type="checkbox" id="chkAll" title="全选" /></th> } <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("Category"))">类别</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("Action"))">操作</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("Success"))">成功</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("Remark"))">详细信息</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("LinkID"))">链接</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("UserName"))">用户名</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("CreateIP"))">IP地址</a></th> <th class="text-center"><a href="@Html.Raw(page.GetSortUrl("CreateAddress"))">物理地址</a></th> <th class="text-center" style="min-width:134px;"><a href="@Html.Raw(page.GetSortUrl("CreateTime"))">时间</a></th> <th class="text-center">附近</th> @if (this.Has(PermissionFlags.Detail)) { <th class="text-center">操作</th> } </tr> </thead> <tbody> @foreach (var entity in Model) { <tr> @if (set.EnableSelect) { <td class="text-center"><input type="checkbox" name="keys" value="@entity.ID" /></td> } <td class="text-center">@entity.Category</td> <td class="text-center">@entity.Action</td> <td class="text-center"> @await Html.PartialAsync("_Icon_Boolean", entity.Success) </td> <td style="max-width:600px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;" title="@entity.Remark">@entity.Remark</td> <td class="text-right">@entity.LinkID.ToString("n0")</td> <td>@entity.UserName</td> <td>@entity.CreateIP</td> <td>@entity.CreateIP.IPToAddress()</td> <td class="text-center" style="max-width:150px">@entity.CreateTime.ToFullString("")</td> <td class="text-center"> <a href="?act=near&id=@entity.ID&range=10" title="前后10行日志">附近</a> </td> @if (this.Has(PermissionFlags.Detail)) { <td class="text-center" style="width: 90px;"> @await Html.PartialAsync("_List_Data_Action", (Object)entity) </td> } </tr> } </tbody> </table>
47.646154
147
0.529868
3db753ebd6ce480d8c5add1257cfaea146b58516
27,744
cs
C#
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs
belav/roslyn
01124c8bbeacb560271261e97c10317114836299
[ "MIT" ]
null
null
null
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs
belav/roslyn
01124c8bbeacb560271261e97c10317114836299
[ "MIT" ]
null
null
null
src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/AsyncLazy`1.cs
belav/roslyn
01124c8bbeacb560271261e97c10317114836299
[ "MIT" ]
null
null
null
// 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; namespace Roslyn.Utilities { internal static class AsyncLazy { public static AsyncLazy<T> Create<T>( Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult ) => new(asynchronousComputeFunction, cacheResult); } /// <summary> /// Represents a value that can be retrieved synchronously or asynchronously by many clients. /// The value will be computed on-demand the moment the first client asks for it. While being /// computed, more clients can request the value. As long as there are outstanding clients the /// underlying computation will proceed. If all outstanding clients cancel their request then /// the underlying value computation will be cancelled as well. /// /// Creators of an <see cref="AsyncLazy{T}" /> can specify whether the result of the computation is /// cached for future requests or not. Choosing to not cache means the computation functions are kept /// alive, whereas caching means the value (but not functions) are kept alive once complete. /// </summary> internal sealed class AsyncLazy<T> : ValueSource<T> { /// <summary> /// The underlying function that starts an asynchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it. Otherwise, /// it is kept around in case the value needs to be computed again. /// </summary> private Func<CancellationToken, Task<T>>? _asynchronousComputeFunction; /// <summary> /// The underlying function that starts a synchronous computation of the resulting value. /// Null'ed out once we've computed the result and we've been asked to cache it, or if we /// didn't get any synchronous function given to us in the first place. /// </summary> private Func<CancellationToken, T>? _synchronousComputeFunction; /// <summary> /// Whether or not we should keep the value around once we've computed it. /// </summary> private readonly bool _cacheResult; /// <summary> /// The Task that holds the cached result. /// </summary> private Task<T>? _cachedResult; /// <summary> /// Mutex used to protect reading and writing to all mutable objects and fields. Traces /// indicate that there's negligible contention on this lock, hence we can save some memory /// by using a single lock for all AsyncLazy instances. Only trivial and non-reentrant work /// should be done while holding the lock. /// </summary> private static readonly NonReentrantLock s_gate = new(useThisInstanceForSynchronization: true); /// <summary> /// The hash set of all currently outstanding asynchronous requests. Null if there are no requests, /// and will never be empty. /// </summary> private HashSet<Request>? _requests; /// <summary> /// If an asynchronous request is active, the CancellationTokenSource that allows for /// cancelling the underlying computation. /// </summary> private CancellationTokenSource? _asynchronousComputationCancellationSource; /// <summary> /// Whether a computation is active or queued on any thread, whether synchronous or /// asynchronous. /// </summary> private bool _computationActive; /// <summary> /// Creates an AsyncLazy that always returns the value, analogous to <see cref="Task.FromResult{T}" />. /// </summary> public AsyncLazy(T value) { _cacheResult = true; _cachedResult = Task.FromResult(value); } public AsyncLazy( Func<CancellationToken, Task<T>> asynchronousComputeFunction, bool cacheResult ) : this( asynchronousComputeFunction, synchronousComputeFunction: null, cacheResult: cacheResult ) { } /// <summary> /// Creates an AsyncLazy that supports both asynchronous computation and inline synchronous /// computation. /// </summary> /// <param name="asynchronousComputeFunction">A function called to start the asynchronous /// computation. This function should be cheap and non-blocking.</param> /// <param name="synchronousComputeFunction">A function to do the work synchronously, which /// is allowed to block. This function should not be implemented by a simple Wait on the /// asynchronous value. If that's all you are doing, just don't pass a synchronous function /// in the first place.</param> /// <param name="cacheResult">Whether the result should be cached once the computation is /// complete.</param> public AsyncLazy( Func<CancellationToken, Task<T>> asynchronousComputeFunction, Func<CancellationToken, T>? synchronousComputeFunction, bool cacheResult ) { Contract.ThrowIfNull(asynchronousComputeFunction); _asynchronousComputeFunction = asynchronousComputeFunction; _synchronousComputeFunction = synchronousComputeFunction; _cacheResult = cacheResult; } #region Lock Wrapper for Invariant Checking /// <summary> /// Takes the lock for this object and if acquired validates the invariants of this class. /// </summary> private WaitThatValidatesInvariants TakeLock(CancellationToken cancellationToken) { s_gate.Wait(cancellationToken); AssertInvariants_NoLock(); return new WaitThatValidatesInvariants(this); } private struct WaitThatValidatesInvariants : IDisposable { private readonly AsyncLazy<T> _asyncLazy; public WaitThatValidatesInvariants(AsyncLazy<T> asyncLazy) => _asyncLazy = asyncLazy; public void Dispose() { _asyncLazy.AssertInvariants_NoLock(); s_gate.Release(); } } private void AssertInvariants_NoLock() { // Invariant #1: thou shalt never have an asynchronous computation running without it // being considered a computation Contract.ThrowIfTrue( _asynchronousComputationCancellationSource != null && !_computationActive ); // Invariant #2: thou shalt never waste memory holding onto empty HashSets Contract.ThrowIfTrue(_requests != null && _requests.Count == 0); // Invariant #3: thou shalt never have an request if there is not // something trying to compute it Contract.ThrowIfTrue(_requests != null && !_computationActive); // Invariant #4: thou shalt never have a cached value and any computation function Contract.ThrowIfTrue( _cachedResult != null && (_synchronousComputeFunction != null || _asynchronousComputeFunction != null) ); // Invariant #5: thou shalt never have a synchronous computation function but not an // asynchronous one Contract.ThrowIfTrue( _asynchronousComputeFunction == null && _synchronousComputeFunction != null ); } #endregion public override bool TryGetValue([MaybeNullWhen(false)] out T result) { // No need to lock here since this is only a fast check to // see if the result is already computed. if (_cachedResult != null) { result = _cachedResult.Result; return true; } result = default; return false; } public override T GetValue(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // If the value is already available, return it immediately if (TryGetValue(out var value)) { return value; } Request? request = null; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult.Result; } // If there is an existing computation active, we'll just create another request if (_computationActive) { request = CreateNewRequest_NoLock(); } else if (_synchronousComputeFunction == null) { // A synchronous request, but we have no synchronous function. Start off the async work request = CreateNewRequest_NoLock(); newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } else { // We will do the computation here _computationActive = true; } } // If we simply created a new asynchronous request, so wait for it. Yes, we're blocking the thread // but we don't want multiple threads attempting to compute the same thing. if (request != null) { request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); // Since we already registered for cancellation, it's possible that the registration has // cancelled this new computation if we were the only requester. if (newAsynchronousComputation != null) { StartAsynchronousComputation( newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken ); } // The reason we have synchronous codepaths in AsyncLazy is to support the synchronous requests for syntax trees // that we may get from the compiler. Thus, it's entirely possible that this will be requested by the compiler or // an analyzer on the background thread when another part of the IDE is requesting the same tree asynchronously. // In that case we block the synchronous request on the asynchronous request, since that's better than alternatives. return request.Task.WaitAndGetResult_CanCallOnBackground(cancellationToken); } else { Contract.ThrowIfNull(_synchronousComputeFunction); T result; // We are the active computation, so let's go ahead and compute. try { result = _synchronousComputeFunction(cancellationToken); } catch (OperationCanceledException) { // This cancelled for some reason. We don't care why, but // it means anybody else waiting for this result isn't going to get it // from us. using (TakeLock(CancellationToken.None)) { _computationActive = false; if (_requests != null) { // There's a possible improvement here: there might be another synchronous caller who // also wants the value. We might consider stealing their thread rather than punting // to the thread pool. newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } if (newAsynchronousComputation != null) { StartAsynchronousComputation( newAsynchronousComputation.Value, requestToCompleteSynchronously: null, callerCancellationToken: cancellationToken ); } throw; } catch (Exception ex) { // We faulted for some unknown reason. We should simply fault everything. CompleteWithTask(Task.FromException<T>(ex), CancellationToken.None); throw; } // We have a value, so complete CompleteWithTask(Task.FromResult(result), CancellationToken.None); // Optimization: if they did cancel and the computation never observed it, let's throw so we don't keep // processing a value somebody never wanted cancellationToken.ThrowIfCancellationRequested(); return result; } } private Request CreateNewRequest_NoLock() { if (_requests == null) { _requests = new HashSet<Request>(); } var request = new Request(); _requests.Add(request); return request; } public override Task<T> GetValueAsync(CancellationToken cancellationToken) { // Optimization: if we're already cancelled, do not pass go if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<T>(cancellationToken); } // Avoid taking the lock if a cached value is available var cachedResult = _cachedResult; if (cachedResult != null) { return cachedResult; } Request request; AsynchronousComputationToStart? newAsynchronousComputation = null; using (TakeLock(cancellationToken)) { // If cached, get immediately if (_cachedResult != null) { return _cachedResult; } request = CreateNewRequest_NoLock(); // If we have either synchronous or asynchronous work current in flight, we don't need to do anything. // Otherwise, we shall start an asynchronous computation for this if (!_computationActive) { newAsynchronousComputation = RegisterAsynchronousComputation_NoLock(); } } // We now have the request counted for, register for cancellation. It is critical this is // done outside the lock, as our registration may immediately fire and we want to avoid the // reentrancy request.RegisterForCancellation(OnAsynchronousRequestCancelled, cancellationToken); if (newAsynchronousComputation != null) { StartAsynchronousComputation( newAsynchronousComputation.Value, requestToCompleteSynchronously: request, callerCancellationToken: cancellationToken ); } return request.Task; } private AsynchronousComputationToStart RegisterAsynchronousComputation_NoLock() { Contract.ThrowIfTrue(_computationActive); Contract.ThrowIfNull(_asynchronousComputeFunction); _asynchronousComputationCancellationSource = new CancellationTokenSource(); _computationActive = true; return new AsynchronousComputationToStart( _asynchronousComputeFunction, _asynchronousComputationCancellationSource ); } private struct AsynchronousComputationToStart { public readonly Func<CancellationToken, Task<T>> AsynchronousComputeFunction; public readonly CancellationTokenSource CancellationTokenSource; public AsynchronousComputationToStart( Func<CancellationToken, Task<T>> asynchronousComputeFunction, CancellationTokenSource cancellationTokenSource ) { AsynchronousComputeFunction = asynchronousComputeFunction; CancellationTokenSource = cancellationTokenSource; } } private void StartAsynchronousComputation( AsynchronousComputationToStart computationToStart, Request? requestToCompleteSynchronously, CancellationToken callerCancellationToken ) { var cancellationToken = computationToStart.CancellationTokenSource.Token; // DO NOT ACCESS ANY FIELDS OR STATE BEYOND THIS POINT. Since this function // runs unsynchronized, it's possible that during this function this request // might be cancelled, and then a whole additional request might start and // complete inline, and cache the result. By grabbing state before we check // the cancellation token, we can be assured that we are only operating on // a state that was complete. try { cancellationToken.ThrowIfCancellationRequested(); var task = computationToStart.AsynchronousComputeFunction(cancellationToken); // As an optimization, if the task is already completed, mark the // request as being completed as well. // // Note: we want to do this before we do the .ContinueWith below. That way, // when the async call to CompleteWithTask runs, it sees that we've already // completed and can bail immediately. if (requestToCompleteSynchronously != null && task.IsCompleted) { using (TakeLock(CancellationToken.None)) { task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } requestToCompleteSynchronously.CompleteFromTask(task); } // We avoid creating a full closure just to pass the token along // Also, use TaskContinuationOptions.ExecuteSynchronously so that we inline // the continuation if asynchronousComputeFunction completes synchronously task.ContinueWith( (t, s) => CompleteWithTask(t, ((CancellationTokenSource)s!).Token), computationToStart.CancellationTokenSource, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default ); } catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken) { // The underlying computation cancelled with the correct token, but we must ourselves ensure that the caller // on our stack gets an OperationCanceledException thrown with the right token callerCancellationToken.ThrowIfCancellationRequested(); // We can only be here if the computation was cancelled, which means all requests for the value // must have been cancelled. Therefore, the ThrowIfCancellationRequested above must have thrown // because that token from the requester was cancelled. throw ExceptionUtilities.Unreachable; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } private void CompleteWithTask(Task<T> task, CancellationToken cancellationToken) { IEnumerable<Request> requestsToComplete; using (TakeLock(cancellationToken)) { // If the underlying computation was cancelled, then all state was already updated in OnAsynchronousRequestCancelled // and there is no new work to do here. We *must* use the local one since this completion may be running far after // the background computation was cancelled and a new one might have already been enqueued. We must do this // check here under the lock to ensure proper synchronization with OnAsynchronousRequestCancelled. cancellationToken.ThrowIfCancellationRequested(); // The computation is complete, so get all requests to complete and null out the list. We'll create another one // later if it's needed requestsToComplete = _requests ?? (IEnumerable<Request>)Array.Empty<Request>(); _requests = null; // The computations are done _asynchronousComputationCancellationSource = null; _computationActive = false; task = GetCachedValueAndCacheThisValueIfNoneCached_NoLock(task); } // Complete the requests outside the lock. It's not necessary to do this (none of this is touching any shared state) // but there's no reason to hold the lock so we could reduce any theoretical lock contention. foreach (var requestToComplete in requestsToComplete) { requestToComplete.CompleteFromTask(task); } } [SuppressMessage( "Style", "VSTHRD200:Use \"Async\" suffix for async methods", Justification = "This is a Task wrapper, not an asynchronous method." )] private Task<T> GetCachedValueAndCacheThisValueIfNoneCached_NoLock(Task<T> task) { if (_cachedResult != null) { return _cachedResult; } else { if (_cacheResult && task.Status == TaskStatus.RanToCompletion) { // Hold onto the completed task. We can get rid of the computation functions for good _cachedResult = task; _asynchronousComputeFunction = null; _synchronousComputeFunction = null; } return task; } } private void OnAsynchronousRequestCancelled(object? state) { var request = (Request)state!; CancellationTokenSource? cancellationTokenSource = null; using (TakeLock(CancellationToken.None)) { // Now try to remove it. It's possible that requests may already be null. You could // imagine that cancellation was requested, but before we could acquire the lock // here the computation completed and the entire CompleteWithTask synchronized // block ran. In that case, the requests collection may already be null, or it // (even scarier!) may have been replaced with another collection because another // computation has started. if (_requests != null) { if (_requests.Remove(request)) { if (_requests.Count == 0) { _requests = null; if (_asynchronousComputationCancellationSource != null) { cancellationTokenSource = _asynchronousComputationCancellationSource; _asynchronousComputationCancellationSource = null; _computationActive = false; } } } } } request.Cancel(); cancellationTokenSource?.Cancel(); } /// <remarks> /// This inherits from <see cref="TaskCompletionSource{TResult}"/> to avoid allocating two objects when we can just use one. /// The public surface area of <see cref="TaskCompletionSource{TResult}"/> should probably be avoided in favor of the public /// methods on this class for correct behavior. /// </remarks> private sealed class Request : TaskCompletionSource<T> { /// <summary> /// The <see cref="CancellationToken"/> associated with this request. This field will be initialized before /// any cancellation is observed from the token. /// </summary> private CancellationToken _cancellationToken; private CancellationTokenRegistration _cancellationTokenRegistration; // We want to always run continuations asynchronously. Running them synchronously could result in deadlocks: // if we're looping through a bunch of Requests and completing them one by one, and the continuation for the // first Request was then blocking waiting for a later Request, we would hang. It also could cause performance // issues. If the first request then consumes a lot of CPU time, we're not letting other Requests complete that // could use another CPU core at the same time. public Request() : base(TaskCreationOptions.RunContinuationsAsynchronously) { } public void RegisterForCancellation( Action<object?> callback, CancellationToken cancellationToken ) { _cancellationToken = cancellationToken; _cancellationTokenRegistration = cancellationToken.Register(callback, this); } public void CompleteFromTask(Task<T> task) { // As an optimization, we'll cancel the request even we did get a value for it. // That way things abort sooner. if (task.IsCanceled || _cancellationToken.IsCancellationRequested) { Cancel(); } else if (task.IsFaulted) { // TrySetException wraps its argument in an AggregateException, so we pass the inner exceptions from // the antecedent to avoid wrapping in two layers of AggregateException. RoslynDebug.AssertNotNull(task.Exception); if (task.Exception.InnerExceptions.Count > 0) this.TrySetException(task.Exception.InnerExceptions); else this.TrySetException(task.Exception); } else { this.TrySetResult(task.Result); } _cancellationTokenRegistration.Dispose(); } public void Cancel() => this.TrySetCanceled(_cancellationToken); } } }
43.968304
132
0.58719
3db7a28e27ba2e10de331399dbe5a65d0f81c5e8
1,473
cs
C#
Assets/Scripts/DeliveryTargtSpawner.cs
thibaudio/ld47
cac7656e8b5b29c0ce12619d5794aca9c6f2f338
[ "CC0-1.0" ]
null
null
null
Assets/Scripts/DeliveryTargtSpawner.cs
thibaudio/ld47
cac7656e8b5b29c0ce12619d5794aca9c6f2f338
[ "CC0-1.0" ]
null
null
null
Assets/Scripts/DeliveryTargtSpawner.cs
thibaudio/ld47
cac7656e8b5b29c0ce12619d5794aca9c6f2f338
[ "CC0-1.0" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DeliveryTargtSpawner : MonoBehaviour { public GameEvent TargetSpawn; public float WarningTime; public GameObject TargetPrefab; public Transform OrbitTarget; public float DelayMin; public float DelayMax; public float MinY; public float MaxY; private float _cd = 0; private bool _warned = false; private int _targetToSpawn = 0; private ObjectPool _pool; private void Awake() { _pool = new ObjectPool(transform, TargetPrefab, 5); } public void OnPackageCollected() { _targetToSpawn++; } private void Update() { if(_cd <= 0) { if (_targetToSpawn > 0) { _cd = Random.Range(DelayMin, DelayMax); _warned = false; } else return; } _cd -= Time.deltaTime; if (_cd <= WarningTime && !_warned) { TargetSpawn.Raise(); _warned = true; } if (_cd <= 0) { GameObject go = _pool.Get(); Vector3 position = transform.position; position.y += Random.Range(MinY, MaxY); go.transform.position = transform.position; go.transform.rotation = transform.rotation; go.GetComponent<Orbit>().Target = OrbitTarget; _targetToSpawn--; } } }
21.661765
59
0.564155
3db9256940dd02e2f938c3157dd769ae690e8d5a
30,767
cs
C#
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/FormMain.Designer.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
1
2021-02-22T14:40:43.000Z
2021-02-22T14:40:43.000Z
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/FormMain.Designer.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
null
null
null
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/FormMain.Designer.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
1
2021-02-22T14:40:57.000Z
2021-02-22T14:40:57.000Z
namespace SqlOptimizerBenchmark { partial class FormMain { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.btnNew = new System.Windows.Forms.ToolStripButton(); this.btnSave = new System.Windows.Forms.ToolStripButton(); this.btnOpen = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.btnNavigateBack = new System.Windows.Forms.ToolStripButton(); this.btnNavigateForward = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.btnActivateAll = new System.Windows.Forms.ToolStripButton(); this.btnDeactivateAll = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.btnLaunchTest = new System.Windows.Forms.ToolStripButton(); this.btnStop = new System.Windows.Forms.ToolStripButton(); this.btnInterrupt = new System.Windows.Forms.ToolStripButton(); this.splitContainer = new System.Windows.Forms.SplitContainer(); this.benchmarkTreeView = new SqlOptimizerBenchmark.Controls.BenchmarkTreeView.BenchmarkTreeView(); this.benchmarkObjectEditor = new SqlOptimizerBenchmark.Controls.BenchmarkObjectControls.BenchmarkObjectEditor(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.benchmarkToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnNew = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnOpen = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnSave = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.mbtnExit = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnNavigateBack = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnNavigateForward = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.mbtnActivateAll = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnDeactivateAll = new System.Windows.Forms.ToolStripMenuItem(); this.testingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnLaunchTest = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnStop = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnInterrupt = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.mbtnExportTestingScript = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnExportToFileSystem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mbtnAbout = new System.Windows.Forms.ToolStripMenuItem(); this.btnTest = new System.Windows.Forms.ToolStripMenuItem(); this.tESTSQLScannerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tESTSQLFormatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.Panel2.SuspendLayout(); this.splitContainer.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.btnNew, this.btnSave, this.btnOpen, this.toolStripSeparator1, this.btnNavigateBack, this.btnNavigateForward, this.toolStripSeparator2, this.btnActivateAll, this.btnDeactivateAll, this.toolStripSeparator3, this.btnLaunchTest, this.btnStop, this.btnInterrupt}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1137, 25); this.toolStrip1.TabIndex = 3; this.toolStrip1.Text = "toolStrip1"; // // btnNew // this.btnNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNew.Image = global::SqlOptimizerBenchmark.Properties.Resources.New_16; this.btnNew.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNew.Name = "btnNew"; this.btnNew.Size = new System.Drawing.Size(23, 22); this.btnNew.Text = "New benchmark"; this.btnNew.Click += new System.EventHandler(this.btnNew_Click); // // btnSave // this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnSave.Image = global::SqlOptimizerBenchmark.Properties.Resources.Save_16; this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(23, 22); this.btnSave.Text = "toolStripButton1"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnOpen // this.btnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnOpen.Image = global::SqlOptimizerBenchmark.Properties.Resources.Open_16; this.btnOpen.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnOpen.Name = "btnOpen"; this.btnOpen.Size = new System.Drawing.Size(23, 22); this.btnOpen.Text = "toolStripButton2"; this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // btnNavigateBack // this.btnNavigateBack.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNavigateBack.Image = global::SqlOptimizerBenchmark.Properties.Resources.Left_16; this.btnNavigateBack.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNavigateBack.Name = "btnNavigateBack"; this.btnNavigateBack.Size = new System.Drawing.Size(23, 22); this.btnNavigateBack.Text = "Navigate backward"; this.btnNavigateBack.Click += new System.EventHandler(this.btnNavigateBack_Click); // // btnNavigateForward // this.btnNavigateForward.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnNavigateForward.Image = global::SqlOptimizerBenchmark.Properties.Resources.Right_16; this.btnNavigateForward.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnNavigateForward.Name = "btnNavigateForward"; this.btnNavigateForward.Size = new System.Drawing.Size(23, 22); this.btnNavigateForward.Text = "Navigate forward"; this.btnNavigateForward.Click += new System.EventHandler(this.btnNavigateForward_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // btnActivateAll // this.btnActivateAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnActivateAll.Image = global::SqlOptimizerBenchmark.Properties.Resources.CheckAll_16; this.btnActivateAll.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnActivateAll.Name = "btnActivateAll"; this.btnActivateAll.Size = new System.Drawing.Size(23, 22); this.btnActivateAll.Text = "Activate all tests"; this.btnActivateAll.Click += new System.EventHandler(this.btnActivateAll_Click); // // btnDeactivateAll // this.btnDeactivateAll.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.btnDeactivateAll.Image = global::SqlOptimizerBenchmark.Properties.Resources.UncheckAll_16; this.btnDeactivateAll.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnDeactivateAll.Name = "btnDeactivateAll"; this.btnDeactivateAll.Size = new System.Drawing.Size(23, 22); this.btnDeactivateAll.Text = "Deactivate all tests"; this.btnDeactivateAll.Click += new System.EventHandler(this.btnDeactivateAll_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // btnLaunchTest // this.btnLaunchTest.Image = global::SqlOptimizerBenchmark.Properties.Resources.Play_16; this.btnLaunchTest.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnLaunchTest.Name = "btnLaunchTest"; this.btnLaunchTest.Size = new System.Drawing.Size(78, 22); this.btnLaunchTest.Text = "Launch ..."; this.btnLaunchTest.Click += new System.EventHandler(this.btnLaunchTest_Click); // // btnStop // this.btnStop.Image = global::SqlOptimizerBenchmark.Properties.Resources.StopRed_16; this.btnStop.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnStop.Name = "btnStop"; this.btnStop.Size = new System.Drawing.Size(51, 22); this.btnStop.Text = "Stop"; this.btnStop.ToolTipText = "Breaks the executing of the tests and runs the clean-up scripts."; this.btnStop.Click += new System.EventHandler(this.btnStop_Click); // // btnInterrupt // this.btnInterrupt.Image = global::SqlOptimizerBenchmark.Properties.Resources.InterruptRed; this.btnInterrupt.ImageTransparentColor = System.Drawing.Color.Magenta; this.btnInterrupt.Name = "btnInterrupt"; this.btnInterrupt.Size = new System.Drawing.Size(73, 22); this.btnInterrupt.Text = "Interrupt"; this.btnInterrupt.ToolTipText = "Breaks the executing of the test, does not run any clean-up scripts."; this.btnInterrupt.Click += new System.EventHandler(this.btnInterrupt_Click); // // splitContainer // this.splitContainer.DataBindings.Add(new System.Windows.Forms.Binding("SplitterDistance", global::SqlOptimizerBenchmark.Properties.Settings.Default, "MainSplitterDistance", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer.Location = new System.Drawing.Point(0, 49); this.splitContainer.Name = "splitContainer"; // // splitContainer.Panel1 // this.splitContainer.Panel1.Controls.Add(this.benchmarkTreeView); // // splitContainer.Panel2 // this.splitContainer.Panel2.Controls.Add(this.benchmarkObjectEditor); this.splitContainer.Size = new System.Drawing.Size(1137, 557); this.splitContainer.SplitterDistance = global::SqlOptimizerBenchmark.Properties.Settings.Default.MainSplitterDistance; this.splitContainer.TabIndex = 2; // // benchmarkTreeView // this.benchmarkTreeView.Dock = System.Windows.Forms.DockStyle.Fill; this.benchmarkTreeView.Location = new System.Drawing.Point(0, 0); this.benchmarkTreeView.Name = "benchmarkTreeView"; this.benchmarkTreeView.Size = new System.Drawing.Size(280, 557); this.benchmarkTreeView.TabIndex = 1; this.benchmarkTreeView.SelectionChanged += new System.EventHandler(this.benchmarkTreeView_SelectionChanged); // // benchmarkObjectEditor // this.benchmarkObjectEditor.Benchmark = null; this.benchmarkObjectEditor.Dock = System.Windows.Forms.DockStyle.Fill; this.benchmarkObjectEditor.Location = new System.Drawing.Point(0, 0); this.benchmarkObjectEditor.Name = "benchmarkObjectEditor"; this.benchmarkObjectEditor.Size = new System.Drawing.Size(853, 557); this.benchmarkObjectEditor.TabIndex = 0; this.benchmarkObjectEditor.NavigateBenchmarkObject += new SqlOptimizerBenchmark.Controls.BenchmarkObjectEventHandler(this.benchmarkObjectEditor_NavigateBenchmarkObject); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.benchmarkToolStripMenuItem, this.toolsToolStripMenuItem, this.testingToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1137, 24); this.menuStrip1.TabIndex = 4; this.menuStrip1.Text = "menuStrip1"; // // benchmarkToolStripMenuItem // this.benchmarkToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mbtnNew, this.mbtnOpen, this.mbtnSave, this.mbtnSaveAs, this.toolStripMenuItem1, this.mbtnExit}); this.benchmarkToolStripMenuItem.Name = "benchmarkToolStripMenuItem"; this.benchmarkToolStripMenuItem.Size = new System.Drawing.Size(79, 20); this.benchmarkToolStripMenuItem.Text = "Benchmark"; // // mbtnNew // this.mbtnNew.Image = global::SqlOptimizerBenchmark.Properties.Resources.New_16; this.mbtnNew.Name = "mbtnNew"; this.mbtnNew.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.mbtnNew.Size = new System.Drawing.Size(158, 22); this.mbtnNew.Text = "New"; this.mbtnNew.Click += new System.EventHandler(this.mbtnNew_Click); // // mbtnOpen // this.mbtnOpen.Image = global::SqlOptimizerBenchmark.Properties.Resources.Open_16; this.mbtnOpen.Name = "mbtnOpen"; this.mbtnOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.mbtnOpen.Size = new System.Drawing.Size(158, 22); this.mbtnOpen.Text = "Open ..."; this.mbtnOpen.Click += new System.EventHandler(this.mbtnOpen_Click); // // mbtnSave // this.mbtnSave.Image = global::SqlOptimizerBenchmark.Properties.Resources.Save_16; this.mbtnSave.Name = "mbtnSave"; this.mbtnSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.mbtnSave.Size = new System.Drawing.Size(158, 22); this.mbtnSave.Text = "Save"; this.mbtnSave.Click += new System.EventHandler(this.mbtnSave_Click); // // mbtnSaveAs // this.mbtnSaveAs.Name = "mbtnSaveAs"; this.mbtnSaveAs.ShortcutKeys = System.Windows.Forms.Keys.F12; this.mbtnSaveAs.Size = new System.Drawing.Size(158, 22); this.mbtnSaveAs.Text = "Save as ..."; this.mbtnSaveAs.Click += new System.EventHandler(this.mbtnSaveAs_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(155, 6); // // mbtnExit // this.mbtnExit.Name = "mbtnExit"; this.mbtnExit.Size = new System.Drawing.Size(158, 22); this.mbtnExit.Text = "Exit"; this.mbtnExit.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mbtnNavigateBack, this.mbtnNavigateForward, this.toolStripMenuItem2, this.mbtnActivateAll, this.mbtnDeactivateAll}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(47, 20); this.toolsToolStripMenuItem.Text = "Tools"; // // mbtnNavigateBack // this.mbtnNavigateBack.Image = global::SqlOptimizerBenchmark.Properties.Resources.Left_16; this.mbtnNavigateBack.Name = "mbtnNavigateBack"; this.mbtnNavigateBack.Size = new System.Drawing.Size(175, 22); this.mbtnNavigateBack.Text = "Navigate backward"; this.mbtnNavigateBack.Click += new System.EventHandler(this.mbtnNavigateBack_Click); // // mbtnNavigateForward // this.mbtnNavigateForward.Image = global::SqlOptimizerBenchmark.Properties.Resources.Right_16; this.mbtnNavigateForward.Name = "mbtnNavigateForward"; this.mbtnNavigateForward.Size = new System.Drawing.Size(175, 22); this.mbtnNavigateForward.Text = "Navigate forward"; this.mbtnNavigateForward.Click += new System.EventHandler(this.mbtnNavigateForward_Click); // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(172, 6); // // mbtnActivateAll // this.mbtnActivateAll.Image = global::SqlOptimizerBenchmark.Properties.Resources.CheckAll_16; this.mbtnActivateAll.Name = "mbtnActivateAll"; this.mbtnActivateAll.Size = new System.Drawing.Size(175, 22); this.mbtnActivateAll.Text = "Activate all tests"; this.mbtnActivateAll.Click += new System.EventHandler(this.mbtnActivateAll_Click); // // mbtnDeactivateAll // this.mbtnDeactivateAll.Image = global::SqlOptimizerBenchmark.Properties.Resources.UncheckAll_16; this.mbtnDeactivateAll.Name = "mbtnDeactivateAll"; this.mbtnDeactivateAll.Size = new System.Drawing.Size(175, 22); this.mbtnDeactivateAll.Text = "Deactivate all tests"; this.mbtnDeactivateAll.Click += new System.EventHandler(this.mbtnDeactivateAll_Click); // // testingToolStripMenuItem // this.testingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mbtnLaunchTest, this.mbtnStop, this.mbtnInterrupt, this.toolStripMenuItem3, this.mbtnExportTestingScript, this.mbtnExportToFileSystem}); this.testingToolStripMenuItem.Name = "testingToolStripMenuItem"; this.testingToolStripMenuItem.Size = new System.Drawing.Size(57, 20); this.testingToolStripMenuItem.Text = "Testing"; // // mbtnLaunchTest // this.mbtnLaunchTest.Image = global::SqlOptimizerBenchmark.Properties.Resources.Play_16; this.mbtnLaunchTest.Name = "mbtnLaunchTest"; this.mbtnLaunchTest.Size = new System.Drawing.Size(180, 22); this.mbtnLaunchTest.Text = "Launch ..."; this.mbtnLaunchTest.Click += new System.EventHandler(this.mbtnLaunchTest_Click); // // mbtnStop // this.mbtnStop.Image = global::SqlOptimizerBenchmark.Properties.Resources.StopRed_16; this.mbtnStop.Name = "mbtnStop"; this.mbtnStop.Size = new System.Drawing.Size(180, 22); this.mbtnStop.Text = "Stop"; this.mbtnStop.Click += new System.EventHandler(this.mbtnStop_Click); // // mbtnInterrupt // this.mbtnInterrupt.Image = global::SqlOptimizerBenchmark.Properties.Resources.InterruptRed; this.mbtnInterrupt.Name = "mbtnInterrupt"; this.mbtnInterrupt.Size = new System.Drawing.Size(180, 22); this.mbtnInterrupt.Text = "Interrupt"; this.mbtnInterrupt.Click += new System.EventHandler(this.mbtnInterrupt_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(177, 6); // // mbtnExportTestingScript // this.mbtnExportTestingScript.Image = global::SqlOptimizerBenchmark.Properties.Resources.ExportToSql_16; this.mbtnExportTestingScript.Name = "mbtnExportTestingScript"; this.mbtnExportTestingScript.Size = new System.Drawing.Size(180, 22); this.mbtnExportTestingScript.Text = "Export testing script"; this.mbtnExportTestingScript.Click += new System.EventHandler(this.mbtnExportTestingScript_Click); // // mbtnExportToFileSystem // this.mbtnExportToFileSystem.Image = global::SqlOptimizerBenchmark.Properties.Resources.ExportToFileSystem_16; this.mbtnExportToFileSystem.Name = "mbtnExportToFileSystem"; this.mbtnExportToFileSystem.Size = new System.Drawing.Size(180, 22); this.mbtnExportToFileSystem.Text = "Export to file system"; this.mbtnExportToFileSystem.Click += new System.EventHandler(this.exportToFileSystemToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mbtnAbout, this.btnTest, this.tESTSQLScannerToolStripMenuItem, this.tESTSQLFormatToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // mbtnAbout // this.mbtnAbout.Name = "mbtnAbout"; this.mbtnAbout.Size = new System.Drawing.Size(180, 22); this.mbtnAbout.Text = "About ..."; this.mbtnAbout.Click += new System.EventHandler(this.mbtnAbout_Click); // // btnTest // this.btnTest.Name = "btnTest"; this.btnTest.Size = new System.Drawing.Size(180, 22); this.btnTest.Text = "TEST Debug"; this.btnTest.Visible = false; this.btnTest.Click += new System.EventHandler(this.btnTest_Click); // // tESTSQLScannerToolStripMenuItem // this.tESTSQLScannerToolStripMenuItem.Name = "tESTSQLScannerToolStripMenuItem"; this.tESTSQLScannerToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.tESTSQLScannerToolStripMenuItem.Text = "TEST SQL Scanner"; this.tESTSQLScannerToolStripMenuItem.Click += new System.EventHandler(this.tESTSQLScannerToolStripMenuItem_Click); // // tESTSQLFormatToolStripMenuItem // this.tESTSQLFormatToolStripMenuItem.Name = "tESTSQLFormatToolStripMenuItem"; this.tESTSQLFormatToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.tESTSQLFormatToolStripMenuItem.Text = "TEST SQL Format"; this.tESTSQLFormatToolStripMenuItem.Click += new System.EventHandler(this.tESTSQLFormatToolStripMenuItem_Click); // // FormMain // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.ClientSize = new System.Drawing.Size(1137, 606); this.Controls.Add(this.splitContainer); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.MainMenuStrip = this.menuStrip1; this.Name = "FormMain"; this.Text = "SQL Optimizer Benchmark"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormMain_FormClosing); this.Load += new System.EventHandler(this.FormMain_Load); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Controls.BenchmarkTreeView.BenchmarkTreeView benchmarkTreeView; private System.Windows.Forms.SplitContainer splitContainer; private Controls.BenchmarkObjectControls.BenchmarkObjectEditor benchmarkObjectEditor; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton btnNavigateBack; private System.Windows.Forms.ToolStripButton btnNavigateForward; private System.Windows.Forms.ToolStripButton btnSave; private System.Windows.Forms.ToolStripButton btnOpen; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton btnActivateAll; private System.Windows.Forms.ToolStripButton btnDeactivateAll; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripButton btnStop; private System.Windows.Forms.ToolStripButton btnNew; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem benchmarkToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mbtnNew; private System.Windows.Forms.ToolStripMenuItem mbtnOpen; private System.Windows.Forms.ToolStripMenuItem mbtnSave; private System.Windows.Forms.ToolStripMenuItem mbtnSaveAs; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem mbtnExit; private System.Windows.Forms.ToolStripMenuItem testingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mbtnLaunchTest; private System.Windows.Forms.ToolStripMenuItem mbtnStop; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mbtnAbout; private System.Windows.Forms.ToolStripButton btnLaunchTest; private System.Windows.Forms.ToolStripButton btnInterrupt; private System.Windows.Forms.ToolStripMenuItem mbtnInterrupt; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mbtnNavigateBack; private System.Windows.Forms.ToolStripMenuItem mbtnNavigateForward; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2; private System.Windows.Forms.ToolStripMenuItem mbtnActivateAll; private System.Windows.Forms.ToolStripMenuItem mbtnDeactivateAll; private System.Windows.Forms.ToolStripMenuItem mbtnExportTestingScript; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem mbtnExportToFileSystem; private System.Windows.Forms.ToolStripMenuItem btnTest; private System.Windows.Forms.ToolStripMenuItem tESTSQLScannerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tESTSQLFormatToolStripMenuItem; } }
55.838475
253
0.649202
3dbe0603dcb6131e22b4e66a8c4777e1101d78d5
58,047
cs
C#
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/ServiceServiceGrpc.cs
skuruppu/google-cloud-dotnet
3594fb9cc98ff092018045dc6174237af34a4d60
[ "Apache-2.0" ]
1
2020-04-06T17:54:26.000Z
2020-04-06T17:54:26.000Z
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/ServiceServiceGrpc.cs
ArulMozhiVaradan/google-cloud-dotnet
831ca867cf72c4cad125bb88128d0dd3a8ade783
[ "Apache-2.0" ]
1
2020-01-10T17:09:28.000Z
2020-01-10T17:09:28.000Z
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3/ServiceServiceGrpc.cs
ArulMozhiVaradan/google-cloud-dotnet
831ca867cf72c4cad125bb88128d0dd3a8ade783
[ "Apache-2.0" ]
1
2021-03-27T09:22:11.000Z
2021-03-27T09:22:11.000Z
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/service_service.proto // </auto-generated> // Original file comments: // Copyright 2019 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 // // 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. // // #pragma warning disable 0414, 1591 #region Designer generated code using grpc = global::Grpc.Core; namespace Google.Cloud.Monitoring.V3 { /// <summary> /// The Stackdriver Monitoring Service-Oriented Monitoring API has endpoints for /// managing and querying aspects of a workspace's services. These include the /// `Service`'s monitored resources, its Service-Level Objectives, and a taxonomy /// of categorized Health Metrics. /// </summary> public static partial class ServiceMonitoringService { static readonly string __ServiceName = "google.monitoring.v3.ServiceMonitoringService"; static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceRequest> __Marshaller_google_monitoring_v3_CreateServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.Service> __Marshaller_google_monitoring_v3_Service = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.Service.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceRequest> __Marshaller_google_monitoring_v3_GetServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesRequest> __Marshaller_google_monitoring_v3_ListServicesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServicesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Marshaller_google_monitoring_v3_ListServicesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServicesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest> __Marshaller_google_monitoring_v3_UpdateServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest> __Marshaller_google_monitoring_v3_DeleteServiceRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteServiceRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_google_protobuf_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Marshaller_google_monitoring_v3_ServiceLevelObjective = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ServiceLevelObjective.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest> __Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_CreateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "CreateService", __Marshaller_google_monitoring_v3_CreateServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_GetService = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "GetService", __Marshaller_google_monitoring_v3_GetServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse> __Method_ListServices = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>( grpc::MethodType.Unary, __ServiceName, "ListServices", __Marshaller_google_monitoring_v3_ListServicesRequest, __Marshaller_google_monitoring_v3_ListServicesResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service> __Method_UpdateService = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>( grpc::MethodType.Unary, __ServiceName, "UpdateService", __Marshaller_google_monitoring_v3_UpdateServiceRequest, __Marshaller_google_monitoring_v3_Service); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteService = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteService", __Marshaller_google_monitoring_v3_DeleteServiceRequest, __Marshaller_google_protobuf_Empty); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_CreateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "CreateServiceLevelObjective", __Marshaller_google_monitoring_v3_CreateServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_GetServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "GetServiceLevelObjective", __Marshaller_google_monitoring_v3_GetServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> __Method_ListServiceLevelObjectives = new grpc::Method<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>( grpc::MethodType.Unary, __ServiceName, "ListServiceLevelObjectives", __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesRequest, __Marshaller_google_monitoring_v3_ListServiceLevelObjectivesResponse); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> __Method_UpdateServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>( grpc::MethodType.Unary, __ServiceName, "UpdateServiceLevelObjective", __Marshaller_google_monitoring_v3_UpdateServiceLevelObjectiveRequest, __Marshaller_google_monitoring_v3_ServiceLevelObjective); static readonly grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteServiceLevelObjective = new grpc::Method<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteServiceLevelObjective", __Marshaller_google_monitoring_v3_DeleteServiceLevelObjectiveRequest, __Marshaller_google_protobuf_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.ServiceServiceReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of ServiceMonitoringService</summary> [grpc::BindServiceMethod(typeof(ServiceMonitoringService), "BindService")] public abstract partial class ServiceMonitoringServiceBase { /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.Service> UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for ServiceMonitoringService</summary> public partial class ServiceMonitoringServiceClient : grpc::ClientBase<ServiceMonitoringServiceClient> { /// <summary>Creates a new client for ServiceMonitoringService</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ServiceMonitoringServiceClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for ServiceMonitoringService that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ServiceMonitoringServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ServiceMonitoringServiceClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ServiceMonitoringServiceClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service CreateService(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateService, null, options, request); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> CreateServiceAsync(global::Google.Cloud.Monitoring.V3.CreateServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateService, null, options, request); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service GetService(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetService, null, options, request); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get the named `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> GetServiceAsync(global::Google.Cloud.Monitoring.V3.GetServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetService, null, options, request); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServices(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServicesResponse ListServices(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListServices, null, options, request); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServicesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List `Service`s for this workspace. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServicesResponse> ListServicesAsync(global::Google.Cloud.Monitoring.V3.ListServicesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListServices, null, options, request); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.Service UpdateService(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateService, null, options, request); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.Service> UpdateServiceAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateService, null, options, request); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteService(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteService(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteService, null, options, request); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Soft delete this `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteService, null, options, request); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective CreateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateServiceLevelObjective, null, options, request); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return CreateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Create a `ServiceLevelObjective` for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> CreateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateServiceLevelObjective, null, options, request); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective GetServiceLevelObjective(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetServiceLevelObjective, null, options, request); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return GetServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Get a `ServiceLevelObjective` by name. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> GetServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetServiceLevelObjective, null, options, request); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServiceLevelObjectives(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse ListServiceLevelObjectives(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListServiceLevelObjectives, null, options, request); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return ListServiceLevelObjectivesAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// List the `ServiceLevelObjective`s for the given `Service`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse> ListServiceLevelObjectivesAsync(global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListServiceLevelObjectives, null, options, request); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Monitoring.V3.ServiceLevelObjective UpdateServiceLevelObjective(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return UpdateServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Update the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Monitoring.V3.ServiceLevelObjective> UpdateServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateServiceLevelObjective, null, options, request); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceLevelObjective(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteServiceLevelObjective(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken)) { return DeleteServiceLevelObjectiveAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Delete the given `ServiceLevelObjective`. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteServiceLevelObjectiveAsync(global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteServiceLevelObjective, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override ServiceMonitoringServiceClient NewInstance(ClientBaseConfiguration configuration) { return new ServiceMonitoringServiceClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(ServiceMonitoringServiceBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateService, serviceImpl.CreateService) .AddMethod(__Method_GetService, serviceImpl.GetService) .AddMethod(__Method_ListServices, serviceImpl.ListServices) .AddMethod(__Method_UpdateService, serviceImpl.UpdateService) .AddMethod(__Method_DeleteService, serviceImpl.DeleteService) .AddMethod(__Method_CreateServiceLevelObjective, serviceImpl.CreateServiceLevelObjective) .AddMethod(__Method_GetServiceLevelObjective, serviceImpl.GetServiceLevelObjective) .AddMethod(__Method_ListServiceLevelObjectives, serviceImpl.ListServiceLevelObjectives) .AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl.UpdateServiceLevelObjective) .AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl.DeleteServiceLevelObjective).Build(); } /// <summary>Register service method with a service binder with or without implementation. Useful when customizing the service binding logic. /// Note: this method is part of an experimental API that can change or be removed without any prior notice.</summary> /// <param name="serviceBinder">Service methods will be bound by calling <c>AddMethod</c> on this object.</param> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static void BindService(grpc::ServiceBinderBase serviceBinder, ServiceMonitoringServiceBase serviceImpl) { serviceBinder.AddMethod(__Method_CreateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.CreateService)); serviceBinder.AddMethod(__Method_GetService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.GetService)); serviceBinder.AddMethod(__Method_ListServices, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServicesRequest, global::Google.Cloud.Monitoring.V3.ListServicesResponse>(serviceImpl.ListServices)); serviceBinder.AddMethod(__Method_UpdateService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceRequest, global::Google.Cloud.Monitoring.V3.Service>(serviceImpl.UpdateService)); serviceBinder.AddMethod(__Method_DeleteService, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteService)); serviceBinder.AddMethod(__Method_CreateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.CreateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.CreateServiceLevelObjective)); serviceBinder.AddMethod(__Method_GetServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.GetServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.GetServiceLevelObjective)); serviceBinder.AddMethod(__Method_ListServiceLevelObjectives, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesRequest, global::Google.Cloud.Monitoring.V3.ListServiceLevelObjectivesResponse>(serviceImpl.ListServiceLevelObjectives)); serviceBinder.AddMethod(__Method_UpdateServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.UpdateServiceLevelObjectiveRequest, global::Google.Cloud.Monitoring.V3.ServiceLevelObjective>(serviceImpl.UpdateServiceLevelObjective)); serviceBinder.AddMethod(__Method_DeleteServiceLevelObjective, serviceImpl == null ? null : new grpc::UnaryServerMethod<global::Google.Cloud.Monitoring.V3.DeleteServiceLevelObjectiveRequest, global::Google.Protobuf.WellKnownTypes.Empty>(serviceImpl.DeleteServiceLevelObjective)); } } } #endregion
77.087649
411
0.73804
3dbe4135a5f74950012382a1ac8bcfb888eea112
1,434
cs
C#
src/Platformus.Core.Backend/Areas/Backend/ViewModels/Roles/CreateOrEdit/CreateOrEditViewModelFactory.cs
Platformus/Platformus
c28a171829f211854da82f3ad7c3862cc0a3e018
[ "Apache-2.0" ]
510
2015-09-04T13:13:28.000Z
2022-03-30T17:33:36.000Z
src/Platformus.Core.Backend/Areas/Backend/ViewModels/Roles/CreateOrEdit/CreateOrEditViewModelFactory.cs
Platformus/Platformus
c28a171829f211854da82f3ad7c3862cc0a3e018
[ "Apache-2.0" ]
221
2016-03-19T19:41:26.000Z
2022-03-22T21:34:45.000Z
src/Platformus.Core.Backend/Areas/Backend/ViewModels/Roles/CreateOrEdit/CreateOrEditViewModelFactory.cs
Platformus/Platformus
c28a171829f211854da82f3ad7c3862cc0a3e018
[ "Apache-2.0" ]
152
2015-09-04T13:13:31.000Z
2022-03-26T13:51:16.000Z
// Copyright © 2020 Dmitry Sikorsky. 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 System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Platformus.Core.Backend.ViewModels.Shared; using Platformus.Core.Data.Entities; using Platformus.Core.Filters; namespace Platformus.Core.Backend.ViewModels.Roles { public static class CreateOrEditViewModelFactory { public static async Task<CreateOrEditViewModel> CreateAsync(HttpContext httpContext, Role role) { if (role == null) return new CreateOrEditViewModel() { RolePermissions = await GetRolePermissionsAsync(httpContext) }; return new CreateOrEditViewModel() { Id = role.Id, Code = role.Code, Name = role.Name, Position = role.Position, RolePermissions = await GetRolePermissionsAsync(httpContext, role) }; } public static async Task<IEnumerable<RolePermissionViewModel>> GetRolePermissionsAsync(HttpContext httpContext, Role role = null) { return (await httpContext.GetStorage().GetRepository<int, Permission, PermissionFilter>().GetAllAsync()).Select( p => RolePermissionViewModelFactory.Create(p, role != null && role.RolePermissions.Any(rp => rp.PermissionId == p.Id)) ); } } }
34.97561
133
0.714784
3dc1059437cc64f88e52c15dcf65f540426d82d5
13,738
cs
C#
Merkur.win/login.Designer.cs
ronaldozb/Merkur2.0
990e3787d138a617684461ade19ddfd347888f5f
[ "MIT" ]
null
null
null
Merkur.win/login.Designer.cs
ronaldozb/Merkur2.0
990e3787d138a617684461ade19ddfd347888f5f
[ "MIT" ]
1
2020-02-23T15:05:40.000Z
2020-02-23T15:05:40.000Z
Merkur.win/login.Designer.cs
ronaldozb/Merkur2.0
990e3787d138a617684461ade19ddfd347888f5f
[ "MIT" ]
null
null
null
namespace Merkur.win { partial class Frmlogin { /// <summary> /// Variable del diseñador necesaria. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Limpiar los recursos que se estén usando. /// </summary> /// <param name="disposing">true si los recursos administrados se deben desechar; false en caso contrario.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Código generado por el Diseñador de Windows Forms /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido de este método con el editor de código. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Frmlogin)); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.label2 = new System.Windows.Forms.Label(); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(46))))); this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(364, 31); this.panel1.TabIndex = 9; this.panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panel1_MouseDown); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Arial", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.SystemColors.ButtonHighlight; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(89, 29); this.label1.TabIndex = 0; this.label1.Text = "LOGIN"; // // panel2 // this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(46))))); this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(0, 510); this.panel2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(364, 18); this.panel2.TabIndex = 10; this.panel2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panel2_MouseDown); // // textBox2 // this.textBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(15)))), ((int)(((byte)(15))))); this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox2.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox2.ForeColor = System.Drawing.Color.DimGray; this.textBox2.Location = new System.Drawing.Point(45, 421); this.textBox2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(277, 25); this.textBox2.TabIndex = 2; this.textBox2.Text = "CONTRASEÑA"; this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged); this.textBox2.Enter += new System.EventHandler(this.textBox2_Enter); this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox2_KeyPress); this.textBox2.Leave += new System.EventHandler(this.textBox2_Leave); // // textBox1 // this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(15)))), ((int)(((byte)(15)))), ((int)(((byte)(15))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.Font = new System.Drawing.Font("Century Gothic", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.ForeColor = System.Drawing.Color.DimGray; this.textBox1.Location = new System.Drawing.Point(45, 389); this.textBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(277, 25); this.textBox1.TabIndex = 1; this.textBox1.Text = "USUARIO"; this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter); this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress); this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave); // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Times New Roman", 21.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.White; this.label3.Location = new System.Drawing.Point(95, 50); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(189, 42); this.label3.TabIndex = 0; this.label3.Tag = ""; this.label3.Text = "MERKUR"; // // pictureBox2 // this.pictureBox2.BackColor = System.Drawing.Color.Transparent; this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(34, 50); this.pictureBox2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(56, 42); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox2.TabIndex = 14; this.pictureBox2.TabStop = false; this.pictureBox2.Tag = ""; // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Transparent; this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage"))); this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(45, 100); this.pictureBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(228, 191); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 15; this.pictureBox1.TabStop = false; this.pictureBox1.Tag = ""; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Century Gothic", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.LightGray; this.label2.Location = new System.Drawing.Point(42, 347); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(283, 21); this.label2.TabIndex = 0; this.label2.Tag = ""; this.label2.Text = "Usuario o Contraseña Incorrecta"; this.label2.Visible = false; // // button2 // this.button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.Font = new System.Drawing.Font("Century Gothic", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.ForeColor = System.Drawing.Color.LightGray; this.button2.Location = new System.Drawing.Point(175, 453); this.button2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(119, 28); this.button2.TabIndex = 4; this.button2.Text = "CANCELAR"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // button1 // this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(40)))), ((int)(((byte)(40))))); this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Font = new System.Drawing.Font("Century Gothic", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button1.ForeColor = System.Drawing.Color.LightGray; this.button1.Location = new System.Drawing.Point(45, 453); this.button1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(116, 28); this.button1.TabIndex = 3; this.button1.Text = "ACCEDER"; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // Frmlogin // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(22)))), ((int)(((byte)(22)))), ((int)(((byte)(26))))); this.ClientSize = new System.Drawing.Size(364, 528); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label3); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.panel2); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.Name = "Frmlogin"; this.Opacity = 0.9D; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Formlogin"; this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Frmlogin_MouseDown); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button1; } }
55.172691
163
0.604819
3dc15871024cc88325cd229f0c7a71c96471f99b
3,790
cs
C#
Drivers/Pages/Admin/AssociativyManageGraphPartDriver.cs
Lombiq/Associativy-Administration
130fe5bf5f4c5c40f15a726f599f6aeb2c36a28b
[ "BSD-2-Clause" ]
2
2019-05-26T23:06:13.000Z
2019-09-29T20:39:20.000Z
Drivers/Pages/Admin/AssociativyManageGraphPartDriver.cs
Lombiq/Associativy-Administration
130fe5bf5f4c5c40f15a726f599f6aeb2c36a28b
[ "BSD-2-Clause" ]
null
null
null
Drivers/Pages/Admin/AssociativyManageGraphPartDriver.cs
Lombiq/Associativy-Administration
130fe5bf5f4c5c40f15a726f599f6aeb2c36a28b
[ "BSD-2-Clause" ]
null
null
null
using System.Collections.Generic; using Associativy.Administration.Models; using Associativy.Administration.Models.Pages.Admin; using Associativy.Administration.Services; using Associativy.Models; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.ContentManagement.MetaData.Models; namespace Associativy.Administration.Drivers.Pages.Admin { public class AssociativyManageGraphPartDriver : ContentPartDriver<AssociativyManageGraphPart> { private readonly IGraphSettingsService _settingsService; private readonly IContentManager _contentManager; protected override string Prefix { get { return "Associativy.Administration.AssociativyManageGraphPart"; } } public AssociativyManageGraphPartDriver( IGraphSettingsService settingsService, IContentManager contentManager) { _settingsService = settingsService; _contentManager = contentManager; } protected override DriverResult Display(AssociativyManageGraphPart part, string displayType, dynamic shapeHelper) { return Editor(part, shapeHelper); } protected override DriverResult Editor(AssociativyManageGraphPart part, dynamic shapeHelper) { SetupLazyLoaders(part); return Combined( ContentShape("Pages_AssociativyManageGraph_GraphInfo", () => shapeHelper.DisplayTemplate( TemplateName: "Pages/Admin/ManageGraph.GraphInfo", Model: part, Prefix: Prefix)), ContentShape("Pages_AssociativyManageGraph_AdminSettings", () => shapeHelper.DisplayTemplate( TemplateName: "Pages/Admin/ManageGraph.AdminSettings", Model: part, Prefix: Prefix)), ContentShape("Pages_AssociativyManageGraph_ImportExport", () => shapeHelper.DisplayTemplate( TemplateName: "Pages/Admin/ManageGraph.ImportExport", Model: part, Prefix: Prefix)) ); } protected override DriverResult Editor(AssociativyManageGraphPart part, IUpdateModel updater, dynamic shapeHelper) { SetupLazyLoaders(part); updater.TryUpdateModel(part, Prefix, null, null); _settingsService.Set(part.GraphDescriptor.Name, part.GraphSettings); return Editor(part, shapeHelper); } private void SetupLazyLoaders(AssociativyManageGraphPart part) { part.SettingsField.Loader(() => _settingsService.GetNotNull<GraphSettings>(part.GraphDescriptor.Name)); part.ImplicitlyCreatableContentTypesField.Loader(() => { var implicitlyCreatableTypes = new List<ContentTypeDefinition>(); foreach (var type in part.GraphDescriptor.ContentTypes) { // This seems to be the only way to check the existence of an aspect var item = _contentManager.New(type); if (item.As<IImplicitlyCreatableAssociativyNodeAspect>() != null) { implicitlyCreatableTypes.Add(item.TypeDefinition); } } return implicitlyCreatableTypes; }); } } }
41.648352
123
0.577045
3dc2f53edb0923028baa07e7609f2fe4562cfc3f
5,642
cs
C#
src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
9,402
2019-11-25T23:26:24.000Z
2022-03-31T23:19:41.000Z
src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
37,522
2019-11-25T23:30:32.000Z
2022-03-31T23:58:30.000Z
src/libraries/System.Text.Encoding.Extensions/tests/Fallback.cs
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
3,629
2019-11-25T23:29:16.000Z
2022-03-31T21:52:28.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Xunit; using System; using System.Text; namespace EncodingTests { public static class Fallback { private static readonly string s_asciiInputStringWithFallback = "\u00abX\u00bb"; // DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING DOUBLE ANGLE QUOTATION MARK (U+00BB). private static readonly string s_asciiInputStringWinNoFallback = "abc"; [Fact] public static void TestEncoderReplacementFallback() { Encoding asciiEncoding = Encoding.GetEncoding("us-ascii", new EncoderReplacementFallback("(unknown)"), new DecoderReplacementFallback("")); byte[] encodedBytes = new byte[asciiEncoding.GetByteCount(s_asciiInputStringWithFallback)]; int numberOfEncodedBytes = asciiEncoding.GetBytes(s_asciiInputStringWithFallback, 0, s_asciiInputStringWithFallback.Length, encodedBytes, 0); Assert.Equal( encodedBytes, new byte[] {0x28, 0x75, 0x6E, 0x6B, 0x6E, 0x6F, 0x77, 0x6E, 0x29, 0x58, 0x28, 0x75, 0x6E, 0x6B, 0x6E, 0x6F, 0x77, 0x6E, 0x29 }); string decodedString = asciiEncoding.GetString(encodedBytes); Assert.Equal("(unknown)X(unknown)", decodedString); // Test when the fallback will not occur encodedBytes = new byte[asciiEncoding.GetByteCount(s_asciiInputStringWinNoFallback)]; numberOfEncodedBytes = asciiEncoding.GetBytes(s_asciiInputStringWinNoFallback, 0, s_asciiInputStringWinNoFallback.Length, encodedBytes, 0); Assert.Equal(encodedBytes, new byte[] { (byte)'a', (byte)'b', (byte)'c' }); decodedString = asciiEncoding.GetString(encodedBytes); Assert.Equal(decodedString, s_asciiInputStringWinNoFallback); } [Fact] public static void TestDecoderReplacementFallback() { Encoding asciiEncoding = Encoding.GetEncoding("us-ascii", new EncoderReplacementFallback("(unknown)"), new DecoderReplacementFallback("Error")); Assert.Equal("ErrorxError", asciiEncoding.GetString(new byte [] { 0xAA, (byte)'x', 0xAB })); } [Fact] public static void TestEncoderExceptionFallback() { Encoding asciiEncoding = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback()); Assert.Throws<EncoderFallbackException>(() => asciiEncoding.GetByteCount(s_asciiInputStringWithFallback)); } [Fact] public static void TestDecoderExceptionFallback() { Encoding asciiEncoding = Encoding.GetEncoding("us-ascii", new EncoderExceptionFallback(), new DecoderExceptionFallback()); Assert.Throws<DecoderFallbackException>(() => asciiEncoding.GetString(new byte [] { 0xAA, (byte)'x', 0xAB })); } [Fact] public static void TestCustomFallback() { Encoding asciiEncoding = Encoding.GetEncoding("us-ascii", new EncoderCustomFallback(), new DecoderReplacementFallback("")); byte[] encodedBytes = new byte[asciiEncoding.GetByteCount(s_asciiInputStringWithFallback)]; int numberOfEncodedBytes = asciiEncoding.GetBytes(s_asciiInputStringWithFallback, 0, s_asciiInputStringWithFallback.Length, encodedBytes, 0); Assert.Equal( encodedBytes, new byte[] {(byte) 'a', 0x58, (byte) 'b'}); string decodedString = asciiEncoding.GetString(encodedBytes); Assert.Equal("aXb", decodedString); } } // a simple fallback class which fallback using the character sequence 'a', 'b', 'c',...etc. internal sealed class EncoderCustomFallback : EncoderFallback { public EncoderCustomFallback() { } public string DefaultString { get { return " "; } } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderCustomFallbackBuffer(); } public override int MaxCharCount { get { return 1; } } public override bool Equals(object value) { return value is EncoderCustomFallback; } public override int GetHashCode() { return "EncoderCustomFallback".GetHashCode(); } } internal sealed class EncoderCustomFallbackBuffer : EncoderFallbackBuffer { private int _nextChar; private bool _fallback; public EncoderCustomFallbackBuffer() { _fallback = false; _nextChar = (int)'a' - 1; } public override bool Fallback(char charUnknown, int index) { _fallback = true; return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { _fallback = true; return true; } public override char GetNextChar() { if (!_fallback) return (char)0; _fallback = false; return (char)++_nextChar; } public override bool MovePrevious() { return --_nextChar >= (int)'a' - 1; } public override int Remaining { get { return 0; } } public override void Reset() { _fallback = false; _nextChar = (int)'a' - 1; } } }
35.2625
200
0.619638
3dc3444192bdeb01a3de54d90ebf732f567a60b5
2,032
cs
C#
src/Framework/Framework/Compilation/Javascript/Ast/JsArrowFunctionExpression.cs
cafstep/dotvvm
892aaf281a55fcf5bf13ba3978df0013debc5af6
[ "Apache-2.0" ]
641
2015-06-13T06:24:47.000Z
2022-03-18T20:06:06.000Z
src/Framework/Framework/Compilation/Javascript/Ast/JsArrowFunctionExpression.cs
cafstep/dotvvm
892aaf281a55fcf5bf13ba3978df0013debc5af6
[ "Apache-2.0" ]
879
2015-06-13T16:10:46.000Z
2022-03-28T14:42:37.000Z
src/Framework/Framework/Compilation/Javascript/Ast/JsArrowFunctionExpression.cs
cafstep/dotvvm
892aaf281a55fcf5bf13ba3978df0013debc5af6
[ "Apache-2.0" ]
128
2015-07-14T15:00:59.000Z
2022-03-02T17:39:24.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DotVVM.Framework.Utils; namespace DotVVM.Framework.Compilation.Javascript.Ast { public class JsArrowFunctionExpression: JsBaseFunctionExpression { public JsExpression? ExpressionBody { get { if (Block.Body.Count == 1 && Block.Body.Single() is JsReturnStatement { Expression: var exprBody }) return exprBody; else return null; } set { Block = value.NotNull().Return().AsBlock(); } } public JsArrowFunctionExpression(IEnumerable<JsIdentifier> parameters, JsBlockStatement bodyBlock, bool isAsync = false) { foreach (var p in parameters) AddChild(p, ParametersRole); AddChild(bodyBlock, BlockRole); IsAsync = isAsync; } public JsArrowFunctionExpression(IEnumerable<JsIdentifier> parameters, JsExpression expressionBody, bool isAsync = false) : this(parameters, expressionBody.Return().AsBlock(), isAsync) { } public override void AcceptVisitor(IJsNodeVisitor visitor) => visitor.VisitArrowFunctionExpression(this); public static JsExpression CreateIIFE(JsExpression expression, IEnumerable<(string name, JsExpression initExpression)>? parameters = null, bool isAsync = false) => CreateIIFE(expression.Return().AsBlock(), parameters, isAsync); public static JsExpression CreateIIFE(JsBlockStatement block, IEnumerable<(string name, JsExpression initExpression)>? parameters = null, bool isAsync = false) { if (parameters == null) parameters = Enumerable.Empty<(string, JsExpression)>(); return new JsArrowFunctionExpression( parameters.Select(p => new JsIdentifier(p.name)), block, isAsync ).Invoke(parameters.Select(p => p.initExpression)); } } }
40.64
171
0.640748
3dc34978bb212715a4a4fba439dbb4879494f797
8,746
cs
C#
Utilities.ORM/ORM/Manager/QueryProvider/BaseClasses/ParameterBase.cs
selfgrowth/Craig-s-Utility-Library
07ac7772b7250f52a4ca65381889ed42b2a2bc29
[ "MIT" ]
1
2019-01-10T13:15:32.000Z
2019-01-10T13:15:32.000Z
Utilities.ORM/ORM/Manager/QueryProvider/BaseClasses/ParameterBase.cs
sealong/Craig-s-Utility-Library
07ac7772b7250f52a4ca65381889ed42b2a2bc29
[ "MIT" ]
null
null
null
Utilities.ORM/ORM/Manager/QueryProvider/BaseClasses/ParameterBase.cs
sealong/Craig-s-Utility-Library
07ac7772b7250f52a4ca65381889ed42b2a2bc29
[ "MIT" ]
1
2021-07-13T11:43:35.000Z
2021-07-13T11:43:35.000Z
/* Copyright (c) 2014 <a href="http://www.gutgames.com">James Craig</a> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ using System; using System.Data; using System.Data.Common; using Utilities.DataTypes; using Utilities.DataTypes.Comparison; using Utilities.ORM.Manager.QueryProvider.Interfaces; namespace Utilities.ORM.Manager.QueryProvider.BaseClasses { /// <summary> /// Parameter base class /// </summary> /// <typeparam name="DataType">Data type of the parameter</typeparam> public abstract class ParameterBase<DataType> : IParameter<DataType> { /// <summary> /// Constructor /// </summary> /// <param name="ID">ID of the parameter</param> /// <param name="Value">Value of the parameter</param> /// <param name="Direction">Direction of the parameter</param> /// <param name="ParameterStarter"> /// What the database expects as the parameter starting string ("@" for SQL Server, ":" for /// Oracle, etc.) /// </param> protected ParameterBase(string ID, DataType Value, ParameterDirection Direction = ParameterDirection.Input, string ParameterStarter = "@") : this(ID, Value == null ? typeof(DataType).To(DbType.Int32) : Value.GetType().To(DbType.Int32), Value, Direction, ParameterStarter) { } /// <summary> /// Constructor /// </summary> /// <param name="ID">ID of the parameter</param> /// <param name="Type">Database type</param> /// <param name="Value">Value of the parameter</param> /// <param name="Direction">Direction of the parameter</param> /// <param name="ParameterStarter"> /// What the database expects as the parameter starting string ("@" for SQL Server, ":" for /// Oracle, etc.) /// </param> protected ParameterBase(string ID, SqlDbType Type, object Value = null, ParameterDirection Direction = ParameterDirection.Input, string ParameterStarter = "@") : this(ID, Type.To(DbType.Int32), Value, Direction, ParameterStarter) { } /// <summary> /// Constructor /// </summary> /// <param name="ID">ID of the parameter</param> /// <param name="Type">Database type</param> /// <param name="Value">Value of the parameter</param> /// <param name="Direction">Direction of the parameter</param> /// <param name="ParameterStarter"> /// What the database expects as the parameter starting string ("@" for SQL Server, ":" for /// Oracle, etc.) /// </param> protected ParameterBase(string ID, DbType Type, object Value = null, ParameterDirection Direction = ParameterDirection.Input, string ParameterStarter = "@") { this.ID = ID; this.Value = (DataType)Value; this.DatabaseType = Type; this.Direction = Direction; this.BatchID = ID; this.ParameterStarter = ParameterStarter; } /// <summary> /// Database type /// </summary> public virtual DbType DatabaseType { get; set; } /// <summary> /// Direction of the parameter /// </summary> public virtual ParameterDirection Direction { get; set; } /// <summary> /// The Name that the parameter goes by /// </summary> public virtual string ID { get; set; } /// <summary> /// Gets the internal value. /// </summary> /// <value>The internal value.</value> public object InternalValue { get { return Value; } } /// <summary> /// Starting string of the parameter /// </summary> public string ParameterStarter { get; set; } /// <summary> /// Parameter value /// </summary> public virtual DataType Value { get; set; } /// <summary> /// Batch ID /// </summary> protected virtual string BatchID { get; set; } /// <summary> /// != operator /// </summary> /// <param name="first">First item</param> /// <param name="second">Second item</param> /// <returns>returns true if they are not equal, false otherwise</returns> public static bool operator !=(ParameterBase<DataType> first, ParameterBase<DataType> second) { return !(first == second); } /// <summary> /// The == operator /// </summary> /// <param name="first">First item</param> /// <param name="second">Second item</param> /// <returns>true if the first and second item are the same, false otherwise</returns> public static bool operator ==(ParameterBase<DataType> first, ParameterBase<DataType> second) { if (Object.ReferenceEquals(first, second)) return true; if ((object)first == null || (object)second == null) return false; return first.GetHashCode() == second.GetHashCode(); } /// <summary> /// Adds this parameter to the SQLHelper /// </summary> /// <param name="Helper">SQLHelper</param> public abstract void AddParameter(DbCommand Helper); /// <summary> /// Finds itself in the string command and adds the value /// </summary> /// <param name="Command">Command to add to</param> /// <returns>The resulting string</returns> public string AddParameter(string Command) { if (string.IsNullOrEmpty(Command)) return ""; string StringValue = Value == null ? "NULL" : Value.ToString(); return Command.Replace(ParameterStarter + ID, typeof(DataType) == typeof(string) ? "'" + StringValue + "'" : StringValue); } /// <summary> /// Creates a copy of the parameter /// </summary> /// <param name="Suffix">Suffix to add to the parameter (for batching purposes)</param> /// <returns>A copy of the parameter</returns> public abstract IParameter CreateCopy(string Suffix); /// <summary> /// Determines if the objects are equal /// </summary> /// <param name="obj">Object to compare to</param> /// <returns>True if they are equal, false otherwise</returns> public override bool Equals(object obj) { var OtherParameter = obj as ParameterBase<DataType>; return (OtherParameter != null && OtherParameter.DatabaseType == DatabaseType && OtherParameter.Direction == Direction && OtherParameter.ID == ID && new GenericEqualityComparer<DataType>().Equals(OtherParameter.Value, Value)); } /// <summary> /// Gets the hash code for the object /// </summary> /// <returns>The hash code</returns> public override int GetHashCode() { unchecked { return (ID.GetHashCode() * 23 + (new GenericEqualityComparer<DataType>().Equals(Value, default(DataType)) ? 0 : Value.GetHashCode())) * 23 + DatabaseType.GetHashCode(); } } /// <summary> /// Returns the string version of the parameter /// </summary> /// <returns>The string representation of the parameter</returns> public override string ToString() { return ParameterStarter + ID; } } }
40.67907
185
0.586325
3dc51267b2b37fb146d6a173ac93825bcb8c8840
5,155
cs
C#
Pc/ReflowController/ReflowControllerDeviceSerial.cs
DerekGn/AVRReflowController
652d1550bdd84bdc89323da279e3a70086953708
[ "MIT" ]
null
null
null
Pc/ReflowController/ReflowControllerDeviceSerial.cs
DerekGn/AVRReflowController
652d1550bdd84bdc89323da279e3a70086953708
[ "MIT" ]
null
null
null
Pc/ReflowController/ReflowControllerDeviceSerial.cs
DerekGn/AVRReflowController
652d1550bdd84bdc89323da279e3a70086953708
[ "MIT" ]
null
null
null
using Google.Protobuf; using RJCP.IO.Ports; using System; using System.IO; using System.Linq; namespace ReflowController { internal class ReflowControllerDeviceSerial : IReflowControllerDevice, IDisposable { private const int TcInputStateMask = 0x4; private object _lock = new object(); private SerialPortStream _serialPortStream; private SerialError _lastError; private SerialData _serialData; public ThermoCoupleStatus GetThermoCoupleStatus() { var response = SendRequest(new Request() { Command = Request.Types.RequestType.Tcstate }); var isOpen = (response.TcState & TcInputStateMask) > 0; var temp = (response.TcState >> 3) * 0.25; return new ThermoCoupleStatus(temp, isOpen); } public void Ping() { SendRequest(new Request() { Command = Request.Types.RequestType.Ping }); } public void SetRelayState(bool state) { SendRequest(new Request() { Command = state ? Request.Types.RequestType.Relayon : Request.Types.RequestType.Relayoff }); } public void StartProfile() { SendRequest(new Request() { Command = Request.Types.RequestType.Startprofile }); } public void StopProfile() { SendRequest(new Request() { Command = Request.Types.RequestType.Stopprofile }); } public ProfileStage GetProfileStage() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getprofilestage }).Stage; } public ReflowProfile GetReflowProfile() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getprofile }).Profile; } public void SetReflowProfile(ReflowProfile reflowProfile) { SendRequest(new Request() { Command = Request.Types.RequestType.Setprofile, Profile = reflowProfile }); } public Pid GetPid() { return SendRequest(new Request() { Command = Request.Types.RequestType.Getpid }).PidGains; } public void SetPid(Pid pid) { SendRequest(new Request() { Command = Request.Types.RequestType.Setpid, PidGains = pid }); } public void Open(string port) { if (!SerialPortStream.GetPortNames().Contains(port)) { throw new ReflowControllerException($"Port does not exist: {port}" ); } if (_serialPortStream == null) { _serialPortStream = new SerialPortStream(port); _serialPortStream.Open(); } else throw new ReflowControllerException("Device aplready open"); } public void Close() { lock (_lock) { if (_serialPortStream != null) { _serialPortStream.Close(); _serialPortStream.Dispose(); _serialPortStream = null; } } } private Response SendRequest(Request request) { lock(_lock) { var requestBytes = request.ToByteArray(); _serialPortStream.Write(requestBytes, 0, requestBytes.Length); byte[] readBuffer = new byte[64]; int readLen = 0; if (_lastError == SerialError.NoError) { readLen = _serialPortStream.Read(readBuffer, 0, 64); } else { throw new ReflowControllerException(_lastError.ToString()); } Response response = Deserialise(readBuffer, readLen); if (response.Result == Response.Types.ResultType.Fail) { throw new ReflowControllerException($"ReflowController Error Code: {response.ErrorCode}"); } return response; } } private Response Deserialise(byte[] readBuffer, int readLen) { using (MemoryStream stream = new MemoryStream()) { stream.Write(readBuffer, 0, readLen); stream.Seek(0, SeekOrigin.Begin); return Response.Parser.ParseFrom(stream); } } private void ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { _lastError = e.EventType; } private void DataReceived(object sender, SerialDataReceivedEventArgs e) { _serialData = e.EventType; } private void PinChanged(object sender, SerialPinChangedEventArgs e) { } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } #endregion } }
32.834395
132
0.547236
3dc6e7d259c18e9b172107663efce53538e925d2
4,388
cs
C#
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/FloatingFramework/Controls/ToolStripPanelExtened.cs
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
a03bbfc132e6f56775d5f3044f676b4dfdc365f7
[ "BSD-3-Clause" ]
43
2019-01-16T21:08:36.000Z
2020-03-02T06:14:28.000Z
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/FloatingFramework/Controls/ToolStripPanelExtened.cs
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
a03bbfc132e6f56775d5f3044f676b4dfdc365f7
[ "BSD-3-Clause" ]
82
2018-09-29T09:56:33.000Z
2020-02-14T23:03:16.000Z
Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended Controls/ExtendedToolkit/FloatingFramework/Controls/ToolStripPanelExtened.cs
Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.461
a03bbfc132e6f56775d5f3044f676b4dfdc365f7
[ "BSD-3-Clause" ]
7
2019-02-06T05:41:54.000Z
2019-10-28T08:33:36.000Z
#region License /* Copyright(c) 2010 2011 2012 ÌÆÈñ(also tr0217) mailto:tr0217@163.com The earliest release time: 2010-12-08 Last modification time:2010-12-20 Accompanying files of necessity: * This file and the accompanying files of this project may be freely used provided the following conditions are met: * This copyright statement is not removed or modified. * The code is not sold in uncompiled form. (Release as a compiled binary which is part of an application is fine) * The design, code, or compiled binaries are not "Re-branded". Optional: * Redistributions in binary form must reproduce the above copyright notice. * I receive a fully licensed copy of the product (regardless of whether the product is is free, shrinkwrap, or commercial). This is optional, though if you release products which use code I've contributed to, I would appreciate a fully licensed copy. In addition, you may not: * Publicly release modified versions of the code or publicly release works derived from the code without express written authorization. NO WARRANTY: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace ExtendedControls.ExtendedToolkit.FloatingFramework.Controls { [Browsable(false), Serializable] public class ToolStripPanelExtened : ToolStripPanel { #region Variables private Rectangle _activeRectangle; #endregion #region Property public Rectangle ActiveRectangle { get => _activeRectangle; } #endregion #region Overrides protected override void OnCreateControl() { base.OnCreateControl(); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); _activeRectangle = ClientRectangle; if (_activeRectangle.Width < 23 || _activeRectangle.Height < 23) { if (Orientation == Orientation.Horizontal) { _activeRectangle.Height = 23; } else { _activeRectangle.Width = 23; } switch (base.Dock) { case DockStyle.Bottom: _activeRectangle.Y -= 23; break; case DockStyle.Left: _activeRectangle.X += 23; break; case DockStyle.Right: _activeRectangle.X -= 23; break; default: break; } } } protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); ToolStrip toolStrip = e.Control as ToolStrip; if (toolStrip != null) { if (Orientation == Orientation.Horizontal) { toolStrip.LayoutStyle = ToolStripLayoutStyle.HorizontalStackWithOverflow; } else { toolStrip.LayoutStyle = ToolStripLayoutStyle.VerticalStackWithOverflow; } } } #endregion } }
36.87395
100
0.582042
3dc6fb6de598e8a352272091badf6e3dea4803fe
5,356
cs
C#
Legacy/HPBar.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
Legacy/HPBar.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
Legacy/HPBar.cs
k76-0G/0G
82acb75c8443e398cde295147300d9894b1ada56
[ "MIT" ]
null
null
null
using UnityEngine; namespace _0G.Legacy { /// <summary> /// HPBar: Hit Point Bar /// 1. HPBar will display the health of an IDamagable game object (e.g. a character that can lose life). /// 2. HPBar is used via G.damage.GetHPBar(IDamagable).Display(parameters). /// 3. HPBar consists of a prefab and a script (attached to said prefab's root game object). /// 4. HPBar can be extended, and a custom HPBar prefab can be assigned in the KRGConfig scriptable object. /// </summary> public class HPBar : MonoBehaviour { #region FIELDS : SERIALIZED [Header("Parameters")] [SerializeField, Enum(typeof(TimeThreadInstance))] protected int _timeThreadIndex = (int) TimeThreadInstance.UseDefault; [SerializeField, BoolObjectDisable(false, "Always"), Tooltip( "The default display duration. If checked, display for this many seconds. If unchecked, display always.")] protected BoolFloat _displayDuration = new BoolFloat(true, 2); [Header("References")] [SerializeField] protected GameObject _hpBarFill; #endregion #region FIELDS : PROTECTED protected float _displayDurationMin = 0.01f; protected TimeTrigger _displayTimeTrigger; protected SpriteRenderer _hpBarFillSR; protected Transform _hpBarFillTF; protected DamageTaker _target; #endregion #region PROPERTIES public virtual DamageTaker target { get { return _target; } } protected virtual TimeThread timeThread { get { return G.time.GetTimeThread(_timeThreadIndex, TimeThreadInstance.Gameplay); } } #endregion #region METHODS : MonoBehaviour protected virtual void Awake() { if (_hpBarFill != null) { _hpBarFillSR = _hpBarFill.GetComponent<SpriteRenderer>(); _hpBarFillTF = _hpBarFill.transform; } } protected virtual void OnDestroy() { KillDisplayTimer(); } protected virtual void OnValidate() { _displayDuration.floatValue = Mathf.Max(_displayDurationMin, _displayDuration.floatValue); } protected virtual void Update() { float value = _target.HPMax > 0 ? _target.HP / _target.HPMax : 0; //size _hpBarFillTF.localScale = _hpBarFillTF.localScale.SetX(value); _hpBarFillTF.localPosition = _hpBarFillTF.localPosition.SetX((value - 1f) / 2f); //color _hpBarFillSR.color = value >= 0.7f ? Color.green : (value >= 0.4f ? Color.yellow : Color.red); } #endregion #region METHODS : PUBLIC /// <summary> /// Display the HPBar for the default display duration specified on the game object / prefab. /// If always is set to true, default display duration is ignored; instead, always display the HPBar! /// </summary> /// <param name="always">If set to <c>true</c> always display the HPBar.</param> public void Display(bool always = false) { Display(!always, false, 0); } /// <summary> /// Display the HPBar for the specified duration. /// The duration is for this call only; it does NOT set a new default display duration. /// </summary> /// <param name="duration">Duration.</param> public void Display(float duration) { if (duration < _displayDurationMin) { G.U.Err("The duration must be at least {0}, but the provided value was {1}. " + "Did you mean to call Display(bool) or Hide()?", _displayDurationMin, duration); return; } Display(false, true, duration); } /// <summary> /// Hide the HPBar. /// </summary> public void Hide() { KillDisplayTimer(); gameObject.SetActive(false); } /// <summary> /// Initialize the HPBar. /// </summary> public void Init(DamageTaker target) { _target = target; Hide(); } #endregion #region METHODS : PROTECTED protected virtual void OnDisplay() { } #endregion #region METHODS : PRIVATE void Display(bool useDefault, bool useDuration, float duration) { KillDisplayTimer(); gameObject.SetActive(true); if (useDefault) { useDuration = _displayDuration.boolValue; duration = _displayDuration.floatValue; } if (useDuration) { G.U.Assert(duration >= _displayDurationMin); _displayTimeTrigger = timeThread.AddTrigger(duration, Hide); } OnDisplay(); } void Hide(TimeTrigger tt) { Hide(); } void KillDisplayTimer() { if (_displayTimeTrigger != null) { _displayTimeTrigger.Dispose(); _displayTimeTrigger = null; } } #endregion } }
30.089888
118
0.561426
3dc9a814d9b4cf920887288db8f97aef3eb6cfbe
13,598
cs
C#
Assets/Scripts/Internal/DaggerfallStaticDoors.cs
Arcane21/daggerfall-unity
e0a0861c852731ee5765d367f8163aba67bae931
[ "MIT" ]
1
2021-12-24T08:13:09.000Z
2021-12-24T08:13:09.000Z
Assets/Scripts/Internal/DaggerfallStaticDoors.cs
Arcane21/daggerfall-unity
e0a0861c852731ee5765d367f8163aba67bae931
[ "MIT" ]
null
null
null
Assets/Scripts/Internal/DaggerfallStaticDoors.cs
Arcane21/daggerfall-unity
e0a0861c852731ee5765d367f8163aba67bae931
[ "MIT" ]
2
2020-08-02T07:14:01.000Z
2021-11-01T03:26:14.000Z
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2019 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: Numidium // // Notes: // using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using DaggerfallConnect; using DaggerfallConnect.Utility; using DaggerfallConnect.Arena2; using DaggerfallWorkshop.Utility; namespace DaggerfallWorkshop { /// <summary> /// Stores an array of static doors. /// Exposes helpers to check doors in correct world space. /// </summary> [Serializable] public class DaggerfallStaticDoors : MonoBehaviour { public StaticDoor[] Doors; // Array of doors attached this building or group of buildings void Start() { //// Debug trigger placement at start //for (int i = 0; i < Doors.Length; i++) //{ // GameObject go = new GameObject(); // go.name = "DoorTrigger"; // go.transform.parent = transform; // go.transform.position = transform.rotation * Doors[i].buildingMatrix.MultiplyPoint3x4(Doors[i].centre); // go.transform.position += transform.position; // go.transform.rotation = transform.rotation; // BoxCollider c = go.AddComponent<BoxCollider>(); // c.size = GameObjectHelper.QuaternionFromMatrix(Doors[i].buildingMatrix) * Doors[i].size; // c.size = new Vector3(Mathf.Abs(c.size.x), Mathf.Abs(c.size.y), Mathf.Abs(c.size.z)); // Abs size components so not negative for collider // c.isTrigger = true; //} //Debug.LogFormat("Added {0} door triggers to scene", Doors.Length); } /// <summary> /// Check for a door hit in world space. /// </summary> /// <param name="point">Hit point from ray test in world space.</param> /// <param name="doorOut">StaticDoor out if hit found.</param> /// <returns>True if point hits a static door.</returns> public bool HasHit(Vector3 point, out StaticDoor doorOut) { doorOut = new StaticDoor(); if (Doors == null) return false; // Using a single hidden trigger created when testing door positions // This avoids problems with AABBs as trigger rotates nicely with model transform // A trigger is also more useful for debugging as its drawn by editor GameObject go = new GameObject(); go.hideFlags = HideFlags.HideAndDontSave; go.transform.parent = transform; BoxCollider c = go.AddComponent<BoxCollider>(); c.isTrigger = true; // Test each door in array bool found = false; for (int i = 0; i < Doors.Length; i++) { // Setup single trigger position and size over each door in turn // This method plays nice with transforms c.size = GameObjectHelper.QuaternionFromMatrix(Doors[i].buildingMatrix) * Doors[i].size; go.transform.position = transform.rotation * Doors[i].buildingMatrix.MultiplyPoint3x4(Doors[i].centre); go.transform.position += transform.position; go.transform.rotation = transform.rotation; // Check if hit was inside trigger if (c.bounds.Contains(point)) { found = true; doorOut = Doors[i]; break; } } // Remove temp trigger if (go) Destroy(go); return found; } /// <summary> /// Find closest door to player position in world space. /// </summary> /// <param name="playerPos">Player position in world space.</param> /// <param name="record">Door record index.</param> /// <param name="doorPosOut">Position of closest door in world space.</param> /// <param name="doorIndexOut">Door index in Doors array of closest door.</param> /// <returns></returns> public bool FindClosestDoorToPlayer(Vector3 playerPos, int record, out Vector3 doorPosOut, out int doorIndexOut, DoorTypes requiredDoorType = DoorTypes.None) { // Init output doorPosOut = Vector3.zero; doorIndexOut = -1; // Must have door array if (Doors == null) return false; // Find closest door to player position float minDistance = float.MaxValue; bool found = false; for (int i = 0; i < Doors.Length; i++) { // Must be of door type if set if (requiredDoorType != DoorTypes.None && Doors[i].doorType != requiredDoorType) continue; // Check if door belongs to same building record or accept any record if (record == -1 || Doors[i].recordIndex == record) { // Get this door centre in world space Vector3 centre = transform.rotation * Doors[i].buildingMatrix.MultiplyPoint3x4(Doors[i].centre) + transform.position; // Check distance and save closest float distance = Vector3.Distance(playerPos, centre); if (distance < minDistance) { doorPosOut = centre; doorIndexOut = i; minDistance = distance; found = true; } } } return found; } /// <summary> /// Find lowest door position in world space. /// </summary> /// <param name="record">Door record index.</param> /// <param name="doorPosOut">Position of closest door in world space.</param> /// <param name="doorIndexOut">Door index in Doors array of closest door.</param> /// <returns>Whether or not we found a door</returns> public bool FindLowestDoor(int record, out Vector3 doorPosOut, out int doorIndexOut) { doorPosOut = Vector3.zero; doorIndexOut = -1; if (Doors == null) return false; // Find lowest door in interior float lowestY = float.MaxValue; for (int i = 0; i < Doors.Length; i++) { // Get this door centre in world space Vector3 centre = transform.rotation * Doors[i].buildingMatrix.MultiplyPoint3x4(Doors[i].centre) + transform.position; // Check if door belongs to same building record or accept any record if (Doors[i].recordIndex == record || record == -1) { float y = centre.y; if (y < lowestY) { doorPosOut = centre; doorIndexOut = i; lowestY = y; } } } return true; } /// <summary> /// Find closest door to player position in world space. /// Owner position and rotation must be set. /// </summary> /// <param name="playerPos">Player position in world space.</param> /// <param name="record">Door record index.</param> /// <param name="doorPosOut">Position of closest door in world space.</param> /// <param name="doorIndexOut">Door index in Doors array of closest door.</param> /// <returns></returns> public static bool FindClosestDoorToPlayer(Vector3 playerPos, StaticDoor[] doors, out Vector3 doorPosOut, out int doorIndexOut) { // Init output doorPosOut = playerPos; doorIndexOut = -1; // Must have door array if (doors == null || doors.Length == 0) return false; // Find closest door to player position float minDistance = float.MaxValue; for (int i = 0; i < doors.Length; i++) { // Get this door centre in world space Vector3 centre = doors[i].ownerRotation * doors[i].buildingMatrix.MultiplyPoint3x4(doors[i].centre) + doors[i].ownerPosition; // Check distance and save closest float distance = Vector3.Distance(playerPos, centre); if (distance < minDistance) { doorPosOut = centre; doorIndexOut = i; minDistance = distance; } } return true; } /// <summary> /// Finds closest door in any array of static doors. /// Owner position and rotation must be set. /// </summary> /// <param name="position">Position to find closest door to.</param> /// <param name="doors">Door array.</param> /// <returns>Position of closest door in world space.</returns> public static Vector3 FindClosestDoor(Vector3 position, StaticDoor[] doors, out StaticDoor closestDoorOut) { closestDoorOut = new StaticDoor(); Vector3 closestDoorPos = position; float minDistance = float.MaxValue; for (int i = 0; i < doors.Length; i++) { // Get this door centre in world space Vector3 centre = doors[i].ownerRotation * doors[i].buildingMatrix.MultiplyPoint3x4(doors[i].centre) + doors[i].ownerPosition; // Check distance and store closest float distance = Vector3.Distance(position, centre); if (distance < minDistance) { closestDoorPos = centre; minDistance = distance; closestDoorOut = doors[i]; } } return closestDoorPos; } /// <summary> /// Gets door position in world space. /// Owner position and rotation must be set. /// </summary> /// <param name="index">Door index.</param> /// <returns>Door position in world space.</returns> public static Vector3 GetDoorPosition(StaticDoor door) { Vector3 centre = door.ownerRotation * door.buildingMatrix.MultiplyPoint3x4(door.centre) + door.ownerPosition; return centre; } /// <summary> /// Gets door normal in world space. /// Owner position and rotation must be set. /// </summary> /// <param name="door">Door to calculate normal for.</param> /// <returns>Normal pointing away from door in world.</returns> public static Vector3 GetDoorNormal(StaticDoor door) { return Vector3.Normalize(door.ownerRotation * door.buildingMatrix.MultiplyVector(door.normal)); } /// <summary> /// Finds all doors of type across multiple door collections. /// </summary> /// <param name="doorCollections">Door collections.</param> /// <param name="type">Type of door to search for.</param> /// <returns>Array of matching doors.</returns> public static StaticDoor[] FindDoorsInCollections(DaggerfallStaticDoors[] doorCollections, DoorTypes type) { List<StaticDoor> doorsOut = new List<StaticDoor>(); foreach (var collection in doorCollections) { for (int i = 0; i < collection.Doors.Length; i++) { if (collection.Doors[i].doorType == type) { StaticDoor newDoor = collection.Doors[i]; newDoor.ownerPosition = collection.transform.position; newDoor.ownerRotation = collection.transform.rotation; doorsOut.Add(newDoor); } } } return doorsOut.ToArray(); } /// <summary> /// Gets door position in world space. /// </summary> /// <param name="index">Door index.</param> /// <returns>Door position in world space.</returns> public Vector3 GetDoorPosition(int index) { Vector3 centre = transform.rotation * Doors[index].buildingMatrix.MultiplyPoint3x4(Doors[index].centre) + transform.position; return centre; } /// <summary> /// Gets world transformed normal of door at index. /// </summary> /// <param name="index">Door index.</param> /// <returns>Normal pointing away from door in world.</returns> public Vector3 GetDoorNormal(int index) { return Vector3.Normalize(transform.rotation * Doors[index].buildingMatrix.MultiplyVector(Doors[index].normal)); } /// <summary> /// Gets the first parent RMB block of this door component. /// </summary> public DaggerfallRMBBlock GetParentRMBBlock() { return GetComponentInParent<DaggerfallRMBBlock>(); } } }
40.470238
165
0.550007
3dcb8b921bd09bcbb36bf87d5f54d9fa315235cf
2,057
cs
C#
Source/PortKit.MVVM/Commands/RelayCommand.generic.cs
bagabont/PortKit
4a8fdb9cbac77bf0a31c0e76388b35ad09eeb1e9
[ "MIT" ]
null
null
null
Source/PortKit.MVVM/Commands/RelayCommand.generic.cs
bagabont/PortKit
4a8fdb9cbac77bf0a31c0e76388b35ad09eeb1e9
[ "MIT" ]
null
null
null
Source/PortKit.MVVM/Commands/RelayCommand.generic.cs
bagabont/PortKit
4a8fdb9cbac77bf0a31c0e76388b35ad09eeb1e9
[ "MIT" ]
null
null
null
using System; namespace PortKit.MVVM.Commands { /// <inheritdoc cref="IRelayCommand"/>> /// <typeparam name="TParameter">Type of the command parameter.</typeparam> public class RelayCommand<TParameter> : BaseRelayCommand { private readonly Action<TParameter> _action; private readonly Func<TParameter, bool> _canExecute; /// <summary> /// Creates a new instance of the <see cref="RelayCommand{T}"/> class. /// </summary> /// <param name="action">Action to be invoked by the command.</param> /// <param name="canExecute">Predicate which checks if the command's action can be invoked.</param> public RelayCommand(Action<TParameter> action, Func<TParameter, bool> canExecute) { _action = action ?? throw new ArgumentNullException(nameof(action)); _canExecute = canExecute ?? throw new ArgumentNullException(nameof(canExecute)); } /// <summary> /// Creates a new instance of the <see cref="RelayCommand{T}"/> class /// which has an always true invocation predicate. /// </summary> /// <param name="action">Action to be invoked by the command.</param> public RelayCommand(Action<TParameter> action) : this(action, _ => true) { } /// <summary> /// Checks if the command's action can be invoked. /// </summary> /// <param name="parameter">Parameter passed to the invocation predicated.</param> /// <returns>True if the action can be invoked, otherwise false.</returns> public override bool CanExecute(object parameter) { return _canExecute == null || _canExecute((TParameter)parameter); } /// <summary> /// Executes the command's action. /// </summary> /// <param name="parameter">Parameter passed to the invoked action.</param> public override void Execute(object parameter) { _action((TParameter)parameter); } } }
39.557692
107
0.612056
3dcbe82c65596f4e3b5c08692b17fddbfdd58b7a
1,477
cs
C#
Assets/Plugins/Usink/Editor/Utilities/SceneState.cs
willnode/Usink
a533943db1d510b7ac2e3d1034411c9d111b6527
[ "MIT" ]
3
2018-01-29T04:21:50.000Z
2019-07-17T06:33:08.000Z
Assets/Plugins/Usink/Editor/Utilities/SceneState.cs
willnode/Usink
a533943db1d510b7ac2e3d1034411c9d111b6527
[ "MIT" ]
null
null
null
Assets/Plugins/Usink/Editor/Utilities/SceneState.cs
willnode/Usink
a533943db1d510b7ac2e3d1034411c9d111b6527
[ "MIT" ]
1
2019-11-17T12:36:03.000Z
2019-11-17T12:36:03.000Z
using UnityEditor; using UnityEditor.AnimatedValues; using UnityEngine; namespace Usink { [System.Serializable] public struct SceneState { public Vector3 pivot; public Quaternion rotation; public float size; public SceneState(SceneView view) { // to get the accurate (not the ongoing/current state) result we need to do it this way pivot = view.IGetField<AnimVector3>("m_Position").target; rotation = view.IGetField<AnimQuaternion>("m_Rotation").target; size = view.IGetField<AnimFloat>("m_Size").target; } public void Apply(SceneView view) { view.LookAt(pivot, rotation, size); } // override object.Equals public override bool Equals(object obj) { if (obj is SceneState) { var o = (SceneState)obj; return o.pivot == pivot && o.rotation == rotation && o.size == size; } else return false; } // override object.GetHashCode public override int GetHashCode() { return base.GetHashCode(); } public static bool operator ==(SceneState lhs, SceneState rhs) { return lhs.Equals(rhs); } public static bool operator !=(SceneState lhs, SceneState rhs) { return !lhs.Equals(rhs); } } }
25.033898
99
0.549763
3dccb6018f67a7e540dd2e0a29d035cd945d2a3e
4,018
cs
C#
Twice.Tests/ViewModels/Columns/ColumnFactoryTests.cs
TheSylence/Twice
c6fc4ea4682e28dc4ba0fbc393ca65a87718d9fc
[ "MIT" ]
20
2016-06-04T16:40:19.000Z
2020-04-02T00:55:42.000Z
Twice.Tests/ViewModels/Columns/ColumnFactoryTests.cs
TheSylence/Twice
c6fc4ea4682e28dc4ba0fbc393ca65a87718d9fc
[ "MIT" ]
151
2016-05-30T19:14:18.000Z
2017-11-24T11:52:36.000Z
Twice.Tests/ViewModels/Columns/ColumnFactoryTests.cs
TheSylence/Twice
c6fc4ea4682e28dc4ba0fbc393ca65a87718d9fc
[ "MIT" ]
8
2016-06-04T18:00:30.000Z
2018-04-10T23:16:49.000Z
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Twice.Models.Columns; using Twice.Models.Configuration; using Twice.Models.Twitter; using Twice.Models.Twitter.Streaming; using Twice.ViewModels.Columns; namespace Twice.Tests.ViewModels.Columns { [TestClass, ExcludeFromCodeCoverage] public class ColumnFactoryTests { [TestMethod, TestCategory( "ViewModels.Columns" )] public void CorrectColumnIsConstructedForType() { // Arrange var context = new Mock<IContextEntry>(); context.SetupGet( c => c.UserId ).Returns( 1 ); var contextList = new[] { context.Object }; var contexts = new Mock<ITwitterContextList>(); contexts.SetupGet( c => c.Contexts ).Returns( contextList ); var parser = new Mock<IStreamParser>(); var config = new Mock<IConfig>(); config.SetupGet( c => c.General ).Returns( new GeneralConfig() ); var streamingRepo = new Mock<IStreamingRepository>(); streamingRepo.Setup( s => s.GetParser( It.Is<ColumnDefinition>( d => d.SourceAccounts.Contains( (ulong)1 ) ) ) ) .Returns( parser.Object ); var factory = new ColumnFactory { Contexts = contexts.Object, StreamingRepo = streamingRepo.Object, Configuration = config.Object }; var testCases = new Dictionary<ColumnType, Type> { {ColumnType.Mentions, typeof(MentionsColumn)}, {ColumnType.User, typeof(UserColumn)}, {ColumnType.Timeline, typeof(TimelineColumn)} }; // Act & Assert foreach( var kvp in testCases ) { var constructed = factory.Construct( new ColumnDefinition( kvp.Key ) { SourceAccounts = new ulong[] { 1 }, TargetAccounts = new ulong[] { 1 } } ); Assert.IsNotNull( constructed ); var type = constructed.GetType(); Assert.IsTrue( kvp.Value.IsAssignableFrom( type ) ); } } [TestMethod, TestCategory( "ViewModels.Columns" )] public void NoColumnIsConstructedWhenNoContextIsFound() { // Arrange var context = new Mock<IContextEntry>(); context.SetupGet( c => c.UserId ).Returns( 2 ); var contextList = new[] { context.Object }; var contexts = new Mock<ITwitterContextList>(); contexts.SetupGet( c => c.Contexts ).Returns( contextList ); var config = new Mock<IConfig>(); config.SetupGet( c => c.General ).Returns( new GeneralConfig() ); var streamingRepo = new Mock<IStreamingRepository>(); var factory = new ColumnFactory { Contexts = contexts.Object, StreamingRepo = streamingRepo.Object, Configuration = config.Object }; // Act var constructed = factory.Construct( new ColumnDefinition( ColumnType.User ) { SourceAccounts = new ulong[] { 1 }, TargetAccounts = new ulong[] { 1 } } ); // Assert Assert.IsNull( constructed ); } [TestMethod, TestCategory( "ViewModels.Columns" )] public void UnknownColumnTypeIsNotConstructed() { // Arrange var context = new Mock<IContextEntry>(); context.SetupGet( c => c.UserId ).Returns( 1 ); var contextList = new[] { context.Object }; var contexts = new Mock<ITwitterContextList>(); contexts.SetupGet( c => c.Contexts ).Returns( contextList ); var parser = new Mock<IStreamParser>(); var config = new Mock<IConfig>(); config.SetupGet( c => c.General ).Returns( new GeneralConfig() ); var streamingRepo = new Mock<IStreamingRepository>(); streamingRepo.Setup( s => s.GetParser( It.Is<ColumnDefinition>( d => d.SourceAccounts.Contains( (ulong)1 ) ) ) ) .Returns( parser.Object ); var factory = new ColumnFactory { Contexts = contexts.Object, StreamingRepo = streamingRepo.Object, Configuration = config.Object }; // Act var constructed = factory.Construct( new ColumnDefinition( ColumnType.Unknown ) { SourceAccounts = new ulong[] { 1 }, TargetAccounts = new ulong[] { 1 } } ); // Assert Assert.IsNull( constructed ); } } }
27.710345
115
0.678198
3dcd280a11cff11e6a1291da9e22e2ba94a99e5a
7,564
cs
C#
src/Razor/src/Microsoft.AspNetCore.Razor.Language/DefaultTagHelperDescriptorBuilder.cs
JalilAzzad1993/ASPNET
7c2f8a465fb296567aef89004d3d7f60b1d970ba
[ "Apache-2.0" ]
792
2015-01-01T04:40:37.000Z
2022-02-22T07:22:30.000Z
src/Razor/src/Microsoft.AspNetCore.Razor.Language/DefaultTagHelperDescriptorBuilder.cs
JalilAzzad1993/ASPNET
7c2f8a465fb296567aef89004d3d7f60b1d970ba
[ "Apache-2.0" ]
2,113
2015-01-05T21:18:49.000Z
2018-12-18T23:11:53.000Z
src/Razor/src/Microsoft.AspNetCore.Razor.Language/DefaultTagHelperDescriptorBuilder.cs
JalilAzzad1993/ASPNET
7c2f8a465fb296567aef89004d3d7f60b1d970ba
[ "Apache-2.0" ]
311
2015-01-09T08:10:04.000Z
2022-01-18T16:36:17.000Z
// 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.Generic; using System.Linq; namespace Microsoft.AspNetCore.Razor.Language { internal class DefaultTagHelperDescriptorBuilder : TagHelperDescriptorBuilder { // Required values private readonly Dictionary<string, string> _metadata; private List<DefaultAllowedChildTagDescriptorBuilder> _allowedChildTags; private List<DefaultBoundAttributeDescriptorBuilder> _attributeBuilders; private List<DefaultTagMatchingRuleDescriptorBuilder> _tagMatchingRuleBuilders; private RazorDiagnosticCollection _diagnostics; public DefaultTagHelperDescriptorBuilder(string kind, string name, string assemblyName) { Kind = kind; Name = name; AssemblyName = assemblyName; _metadata = new Dictionary<string, string>(StringComparer.Ordinal); // Tells code generation that these tag helpers are compatible with ITagHelper. // For now that's all we support. _metadata.Add(TagHelperMetadata.Runtime.Name, TagHelperConventions.DefaultKind); } public override string Name { get; } public override string AssemblyName { get; } public override string Kind { get; } public override string DisplayName { get; set; } public override string TagOutputHint { get; set; } public override string Documentation { get; set; } public override IDictionary<string, string> Metadata => _metadata; public override RazorDiagnosticCollection Diagnostics { get { if (_diagnostics == null) { _diagnostics = new RazorDiagnosticCollection(); } return _diagnostics; } } public override IReadOnlyList<AllowedChildTagDescriptorBuilder> AllowedChildTags { get { EnsureAllowedChildTags(); return _allowedChildTags; } } public override IReadOnlyList<BoundAttributeDescriptorBuilder> BoundAttributes { get { EnsureAttributeBuilders(); return _attributeBuilders; } } public override IReadOnlyList<TagMatchingRuleDescriptorBuilder> TagMatchingRules { get { EnsureTagMatchingRuleBuilders(); return _tagMatchingRuleBuilders; } } public override void AllowChildTag(Action<AllowedChildTagDescriptorBuilder> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EnsureAllowedChildTags(); var builder = new DefaultAllowedChildTagDescriptorBuilder(this); configure(builder); _allowedChildTags.Add(builder); } public override void BindAttribute(Action<BoundAttributeDescriptorBuilder> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EnsureAttributeBuilders(); var builder = new DefaultBoundAttributeDescriptorBuilder(this, Kind); configure(builder); _attributeBuilders.Add(builder); } public override void TagMatchingRule(Action<TagMatchingRuleDescriptorBuilder> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } EnsureTagMatchingRuleBuilders(); var builder = new DefaultTagMatchingRuleDescriptorBuilder(); configure(builder); _tagMatchingRuleBuilders.Add(builder); } public override TagHelperDescriptor Build() { var diagnostics = new HashSet<RazorDiagnostic>(); if (_diagnostics != null) { diagnostics.UnionWith(_diagnostics); } var allowedChildTags = Array.Empty<AllowedChildTagDescriptor>(); if (_allowedChildTags != null) { var allowedChildTagsSet = new HashSet<AllowedChildTagDescriptor>(AllowedChildTagDescriptorComparer.Default); for (var i = 0; i < _allowedChildTags.Count; i++) { allowedChildTagsSet.Add(_allowedChildTags[i].Build()); } allowedChildTags = allowedChildTagsSet.ToArray(); } var tagMatchingRules = Array.Empty<TagMatchingRuleDescriptor>(); if (_tagMatchingRuleBuilders != null) { var tagMatchingRuleSet = new HashSet<TagMatchingRuleDescriptor>(TagMatchingRuleDescriptorComparer.Default); for (var i = 0; i < _tagMatchingRuleBuilders.Count; i++) { tagMatchingRuleSet.Add(_tagMatchingRuleBuilders[i].Build()); } tagMatchingRules = tagMatchingRuleSet.ToArray(); } var attributes = Array.Empty<BoundAttributeDescriptor>(); if (_attributeBuilders != null) { var attributeSet = new HashSet<BoundAttributeDescriptor>(BoundAttributeDescriptorComparer.Default); for (var i = 0; i < _attributeBuilders.Count; i++) { attributeSet.Add(_attributeBuilders[i].Build()); } attributes = attributeSet.ToArray(); } var descriptor = new DefaultTagHelperDescriptor( Kind, Name, AssemblyName, GetDisplayName(), Documentation, TagOutputHint, tagMatchingRules, attributes, allowedChildTags, new Dictionary<string, string>(_metadata), diagnostics.ToArray()); return descriptor; } public override void Reset() { Documentation = null; TagOutputHint = null; _allowedChildTags?.Clear(); _attributeBuilders?.Clear(); _tagMatchingRuleBuilders?.Clear(); _metadata.Clear(); _diagnostics?.Clear(); } public string GetDisplayName() { if (DisplayName != null) { return DisplayName; } return this.GetTypeName() ?? Name; } private void EnsureAllowedChildTags() { if (_allowedChildTags == null) { _allowedChildTags = new List<DefaultAllowedChildTagDescriptorBuilder>(); } } private void EnsureAttributeBuilders() { if (_attributeBuilders == null) { _attributeBuilders = new List<DefaultBoundAttributeDescriptorBuilder>(); } } private void EnsureTagMatchingRuleBuilders() { if (_tagMatchingRuleBuilders == null) { _tagMatchingRuleBuilders = new List<DefaultTagMatchingRuleDescriptorBuilder>(); } } } }
31.781513
124
0.572316
3dce4579d4ce0291032289099dba852da81ce890
1,632
cs
C#
ModernTlSharp/TLSharp.Extensions/Types/Update.cs
immmdreza/ModernTLSharp
95e65ffe223d9d9e59c98188b2a821022af56576
[ "MIT" ]
10
2020-09-26T14:19:25.000Z
2021-07-28T11:48:29.000Z
ModernTlSharp/TLSharp.Extensions/Types/Update.cs
immmdreza/ModernTLSharp
95e65ffe223d9d9e59c98188b2a821022af56576
[ "MIT" ]
4
2020-08-05T12:44:11.000Z
2021-05-02T12:32:12.000Z
ModernTlSharp/TLSharp.Extensions/Types/Update.cs
immmdreza/ModernTLSharp
95e65ffe223d9d9e59c98188b2a821022af56576
[ "MIT" ]
1
2021-12-03T14:28:52.000Z
2021-12-03T14:28:52.000Z
using ModernTlSharp.TLSharp.Tl; using ModernTlSharp.TLSharp.Tl.TL; using System; namespace ModernTlSharp.TLSharp.Extensions.Types { public class Update { public Update() { Users = new TLVector<TLAbsUser>(); Chats = new TLVector<TLAbsChat>(); Messages = new TLVector<TLAbsMessage>(); ChannelMessages = new TLVector<TLAbsMessage>(); OtherUpdates = new TLVector<TLAbsUpdate>(); ChannelOtherUpdates = new TLVector<TLAbsUpdate>(); } /// <summary> /// User that sends updates /// </summary> public TLVector<TLAbsUser> Users { get; set; } /// <summary> /// Chats that update occured /// </summary> public TLVector<TLAbsChat> Chats { get; set; } /// <summary> /// Time of condition /// </summary> public DateTime DateTime { get; set; } public int Seq { get; set; } /// <summary> /// Messages recieved (channels(super groups) not included) /// </summary> public TLVector<TLAbsMessage> Messages { get; set; } /// <summary> /// Messages recieved from channels(super groups) /// </summary> public TLVector<TLAbsMessage> ChannelMessages { get; set; } /// <summary> /// Other updates /// </summary> public TLVector<TLAbsUpdate> OtherUpdates { get; set; } /// <summary> /// Other updates from channels(super groups) /// </summary> public TLVector<TLAbsUpdate> ChannelOtherUpdates { get; set; } } }
29.142857
70
0.560662
3dd25d70c17af094fb5665c715c38ada319244b7
11,264
cs
C#
vApus.Stresstest/Scenarios/PlainTextScenarioView.cs
sizingservers/vApus
ee00b3ffe4cc75dd2d047541dbe25a1f738e246b
[ "MIT" ]
10
2018-10-24T17:45:07.000Z
2021-04-22T17:50:34.000Z
vApus.Stresstest/Scenarios/PlainTextScenarioView.cs
sizingservers/vApus
ee00b3ffe4cc75dd2d047541dbe25a1f738e246b
[ "MIT" ]
null
null
null
vApus.Stresstest/Scenarios/PlainTextScenarioView.cs
sizingservers/vApus
ee00b3ffe4cc75dd2d047541dbe25a1f738e246b
[ "MIT" ]
null
null
null
/* * 2013 Sizing Servers Lab, affiliated with IT bachelor degree NMCT * University College of West-Flanders, Department GKG (www.sizingservers.be, www.nmct.be, www.howest.be/en) * * Author(s): * Dieter Vandroemme */ using RandomUtils.Log; using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using vApus.SolutionTree; using vApus.Util; namespace vApus.StressTest { public partial class PlaintTextScenarioView : BaseSolutionComponentView { #region Fields private readonly Scenario _scenario; private ScenarioRuleSets _scenarioRuleSets; //For the find. private List<int> _foundRows = new List<int>(); private List<int> _foundColumns = new List<int>(); private List<int> _foundMatchLengths = new List<int>(); private int _findIndex = 0; private string _find = string.Empty; private bool _findWholeWords = false; private bool _findIgnoreCase = true; private FindAndReplaceDialog _findAndReplaceDialog; private const string VBLRn = "<16 0C 02 12n>"; private const string VBLRr = "<16 0C 02 12r>"; #endregion #region Constructors /// <summary> /// Design time constructor. /// </summary> public PlaintTextScenarioView() { InitializeComponent(); } public PlaintTextScenarioView(SolutionComponent solutionComponent) : base(solutionComponent) { InitializeComponent(); _scenario = solutionComponent as Scenario; _scenarioRuleSets = Solution.ActiveSolution.GetSolutionComponent(typeof(ScenarioRuleSets)) as ScenarioRuleSets; if (IsHandleCreated) { FillCboRuleSet(); SetScenario(); } else { HandleCreated += _HandleCreated; } SolutionComponent.SolutionComponentChanged += SolutionComponent_SolutionComponentChanged; fctxt.DefaultContextMenu(true); } #endregion #region Functions private void SolutionComponent_SolutionComponentChanged(object sender, SolutionComponentChangedEventArgs e) { if (!IsDisposed && _scenario != null && IsHandleCreated) { if (sender == _scenario || sender.GetParent() == _scenario || sender.GetParent().GetParent() == _scenario) { _foundRows.Clear(); _foundColumns.Clear(); _foundMatchLengths.Clear(); _findIndex = 0; } if (sender == _scenario.ScenarioRuleSet || sender == _scenarioRuleSets || sender is ScenarioRuleSet) FillCboRuleSet(); } } private void _HandleCreated(object sender, EventArgs e) { HandleCreated -= _HandleCreated; FillCboRuleSet(); SetScenario(); } private void SetScenario() { var sb = new StringBuilder(); foreach (UserAction userAction in _scenario) { sb.Append("<!--"); sb.Append(userAction.Label); sb.AppendLine("-->"); foreach (Request request in userAction) sb.AppendLine(request.RequestString.Replace("\n", VBLRn).Replace("\r", VBLRr)); } string text = sb.ToString(); if (text.EndsWith(Environment.NewLine)) text.Substring(0, text.Length - Environment.NewLine.Length); fctxt.Text = text; fctxt.ClearUndo(); fctxt.TextChanged += fctxt_TextChanged; } private void FillCboRuleSet() { try { if (!IsDisposed) { cboRuleSet.SelectedIndexChanged -= cboRuleSet_SelectedIndexChanged; cboRuleSet.Items.Clear(); if (_scenarioRuleSets != null) foreach (ScenarioRuleSet ruleSet in _scenarioRuleSets) cboRuleSet.Items.Add(ruleSet); if (_scenario != null && _scenario.ScenarioRuleSet != null && cboRuleSet.Items.Contains(_scenario.ScenarioRuleSet)) cboRuleSet.SelectedItem = _scenario.ScenarioRuleSet; else if (cboRuleSet.Items.Count != 0) cboRuleSet.SelectedIndex = 0; cboRuleSet.SelectedIndexChanged += cboRuleSet_SelectedIndexChanged; } } catch (Exception ex) { Loggers.Log(Level.Error, "Failed filling cbo rule set.", ex); } } private void cboRuleSet_SelectedIndexChanged(object sender, EventArgs e) { btnApply.Enabled = true; } private void fctxt_TextChanged(object sender, FastColoredTextBoxNS.TextChangedEventArgs e) { btnUndo.Enabled = btnApply.Enabled = true; } private void txtFind_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter && txtFind.Text.Length != 0) Find(false, true); } private void picFind_Click(object sender, EventArgs e) { Find(false, true); } private void _findAndReplaceDialog_FindClicked(object sender, FindAndReplaceDialog.FindEventArgs e) { if (txtFind.Text != e.Find) txtFind.Text = e.Find; else if (_findWholeWords != e.WholeWords || _findIgnoreCase != e.IgnoreCase) ResetFindCache(); //The above checked variables will be set here. Find(e.WholeWords, e.IgnoreCase); } private void Find(bool wholeWords, bool ignoreCase) { _findWholeWords = wholeWords; _findIgnoreCase = ignoreCase; if (_foundMatchLengths.Count == 0) { _findIndex = 0; _find = txtFind.Text.TrimEnd(); vApus.Util.FindAndReplace.Find(_find, fctxt.Text, out _foundRows, out _foundColumns, out _foundMatchLengths, wholeWords, ignoreCase); } if (_foundMatchLengths.Count != 0) { SelectFound(_foundRows[_findIndex], _foundColumns[_findIndex], _foundMatchLengths[_findIndex]); if (++_findIndex >= _foundMatchLengths.Count) _findIndex = 0; } txtFind.Select(); txtFind.Focus(); } public void SelectFound(int row, int column, int matchLength) { if (row < fctxt.LinesCount) { int line = 0, start = 0; foreach (char c in fctxt.Text) { if (line < row) ++start; if (c == '\n' && ++line >= row) break; } start += column; if (start + matchLength < fctxt.Text.Length) { fctxt.SelectionStart = start; fctxt.SelectionLength = matchLength; fctxt.DoSelectionVisible(); } Focus(); } } private void txtFind_TextChanged(object sender, EventArgs e) { if (_find != txtFind.Text) { ResetFindCache(); if (_findAndReplaceDialog == null || _findAndReplaceDialog.IsDisposed) { _findAndReplaceDialog = new FindAndReplaceDialog(); _findAndReplaceDialog.FindClicked += _findAndReplaceDialog_FindClicked; _findAndReplaceDialog.ReplaceClicked += _findAndReplaceDialog_ReplaceClicked; } _findAndReplaceDialog.SetFind(_find); } picFind.Enabled = (txtFind.Text.Length != 0); } private void _findAndReplaceDialog_ReplaceClicked(object sender, FindAndReplaceDialog.ReplaceEventArgs e) { txtFind.Text = e.Find; ResetFindCache(); Replace(e.WholeWords, e.IgnoreCase, e.With, e.All); } private void Replace(bool wholeWords, bool ignoreCase, string with, bool all) { if (_foundMatchLengths.Count == 0) { Find(wholeWords, ignoreCase); if (--_findIndex < 0) _findIndex = 0; } if (all) { fctxt.Text = vApus.Util.FindAndReplace.Replace(_foundRows, _foundColumns, _foundMatchLengths, fctxt.Text, with); } else { fctxt.Text = vApus.Util.FindAndReplace.Replace(_foundRows[_findIndex], _foundColumns[_findIndex], _foundMatchLengths[_findIndex], fctxt.Text, with); } _foundMatchLengths[_findIndex] = with.Length; SelectFound(_foundRows[_findIndex], _foundColumns[_findIndex], _foundMatchLengths[_findIndex]); ResetFindCache(); } private void llblFindAndReplace_Click(object sender, EventArgs e) { if (_findAndReplaceDialog == null || _findAndReplaceDialog.IsDisposed) { _findAndReplaceDialog = new FindAndReplaceDialog(); _findAndReplaceDialog.FindClicked += _findAndReplaceDialog_FindClicked; _findAndReplaceDialog.ReplaceClicked += _findAndReplaceDialog_ReplaceClicked; } _findAndReplaceDialog.SetFind(_find); if (!_findAndReplaceDialog.Visible) _findAndReplaceDialog.Show(); } private void ResetFindCache() { _find = txtFind.Text; _foundRows.Clear(); _foundColumns.Clear(); _foundMatchLengths.Clear(); _findIndex = 0; } private void btnUndo_Click(object sender, EventArgs e) { fctxt.Undo(); } private void btnApply_Click(object sender, EventArgs e) { btnApply.Enabled = false; _scenario.ClearWithoutInvokingEvent(); if (!IsDisposed && cboRuleSet.Items.Count != 0 && _scenarioRuleSets != null) try { _scenario.ScenarioRuleSet = _scenarioRuleSets[cboRuleSet.SelectedIndex] as ScenarioRuleSet; } catch(Exception ex) { Loggers.Log(Level.Error, "Failed setting scenario rule set.", ex, new object[] { sender, e }); } UserAction currentUserAction = null; string userActionBegin = "<!--", userActionEnd = "-->"; foreach (string s in fctxt.Lines) if (s.StartsWith(userActionBegin) && s.EndsWith(userActionEnd)) { currentUserAction = new UserAction(s.Substring(userActionBegin.Length, s.Length - 7)); _scenario.AddWithoutInvokingEvent(currentUserAction); } else if (currentUserAction != null && s.Trim().Length != 0) { currentUserAction.AddWithoutInvokingEvent(new Request(s.Replace(VBLRn, "\n").Replace(VBLRr, "\r"))); } _scenario.InvokeSolutionComponentChangedEvent(SolutionComponentChangedEventArgs.DoneAction.Edited); } #endregion } }
41.718519
165
0.572798
3dd37080778627f18d3ed46b3af162a3d40aba54
3,022
cs
C#
src/SolarStack/SolarStack.cs
software-is-art/fronius-data-shovel
b0984d2a5f2455351d2882b9e7fdc513c8d3a8a1
[ "Unlicense" ]
null
null
null
src/SolarStack/SolarStack.cs
software-is-art/fronius-data-shovel
b0984d2a5f2455351d2882b9e7fdc513c8d3a8a1
[ "Unlicense" ]
1
2020-12-09T08:54:13.000Z
2020-12-09T08:54:13.000Z
src/SolarStack/SolarStack.cs
software-is-art/fronius-data-shovel
b0984d2a5f2455351d2882b9e7fdc513c8d3a8a1
[ "Unlicense" ]
null
null
null
using Amazon.CDK; using Amazon.CDK.AWS.Lambda; using Amazon.CDK.AWS.Lambda.EventSources; using Amazon.CDK.AWS.SQS; using Amazon.CDK.AWS.DynamoDB; namespace SolarStack { public class SolarStack : Stack { internal SolarStack(Construct scope, IStackProps props = null) : base(scope, AWSConstructs.Names.Stack, props) { const string lambdaSource = "src/LambdaHandlers/bin/release/netcoreapp3.1/LambdaHandlers.zip"; var ingressQueue = new Queue(this, nameof(AWSConstructs.Names.FroniusIngressQueue), new QueueProps { Encryption = QueueEncryption.KMS_MANAGED, QueueName = AWSConstructs.Names.FroniusIngressQueue, VisibilityTimeout = Duration.Seconds(43200) }); var realtimeDataTable = new Table(this, AWSConstructs.Names.RealtimeDataTable, new TableProps { PartitionKey = new Attribute { Name = AWSConstructs.Names.RealtimeDataTablePartitionKey, Type = AttributeType.STRING }, SortKey = new Attribute { Name = AWSConstructs.Names.RealtimeDataTableSortKey, Type = AttributeType.NUMBER }, BillingMode = BillingMode.PAY_PER_REQUEST, TableName = AWSConstructs.Names.RealtimeDataTable, Stream = StreamViewType.NEW_IMAGE }); var ingressFunction = new Function(this, nameof(AWSConstructs.Names.FroniusIngressHandler), new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Code = Code.FromAsset(lambdaSource), Handler = LambdaHandlers.FroniusRealtimeHandler.HandlerName, FunctionName = AWSConstructs.Names.FroniusIngressHandler, Timeout = Duration.Minutes(5) }); ingressFunction.AddEventSource(new SqsEventSource(ingressQueue)); _ = realtimeDataTable.GrantReadWriteData(ingressFunction); _ = realtimeDataTable.Grant(ingressFunction, "dynamodb:DescribeTable"); var aggregateFunction = new Function(this, nameof(AWSConstructs.Names.RealtimeDataAggregatorHandler), new FunctionProps { Runtime = Runtime.DOTNET_CORE_3_1, Code = Code.FromAsset(lambdaSource), Handler = LambdaHandlers.RealtimeDataAggregatorHandler.HandlerName, FunctionName = AWSConstructs.Names.RealtimeDataAggregatorHandler, Timeout = Duration.Minutes(5) }); aggregateFunction.AddEventSource(new DynamoEventSource(realtimeDataTable, new DynamoEventSourceProps { StartingPosition = StartingPosition.LATEST, ParallelizationFactor = 10, BatchSize = 1 })); _ = realtimeDataTable.GrantReadWriteData(aggregateFunction); _ = realtimeDataTable.Grant(aggregateFunction, "dynamodb:DescribeTable"); } } }
45.104478
135
0.641628
3dd67c6ccdbc25865cf5b6c5d2720df8c21cbd28
5,326
cs
C#
src/Microsoft.Health.Fhir.Shared.Api.UnitTests/Features/Audit/AuditHelperTests.cs
gauravgupta98/fhir-server
6eadd127946f3abe7eaf20cffd32b8295aff992c
[ "MIT" ]
1
2021-02-22T12:31:11.000Z
2021-02-22T12:31:11.000Z
src/Microsoft.Health.Fhir.Shared.Api.UnitTests/Features/Audit/AuditHelperTests.cs
gauravgupta98/fhir-server
6eadd127946f3abe7eaf20cffd32b8295aff992c
[ "MIT" ]
27
2021-02-23T07:11:49.000Z
2022-03-30T02:17:17.000Z
src/Microsoft.Health.Fhir.Shared.Api.UnitTests/Features/Audit/AuditHelperTests.cs
gauravgupta98/fhir-server
6eadd127946f3abe7eaf20cffd32b8295aff992c
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Net; using Microsoft.AspNetCore.Http; using Microsoft.Health.Api.Features.Audit; using Microsoft.Health.Core.Features.Security; using Microsoft.Health.Fhir.Api.Features.Audit; using Microsoft.Health.Fhir.Core.Features.Context; using NSubstitute; using Xunit; namespace Microsoft.Health.Fhir.Api.UnitTests.Features.Audit { public class AuditHelperTests { private const string AuditEventType = "audit"; private const string CorrelationId = "correlation"; private static readonly Uri Uri = new Uri("http://localhost/123"); private static readonly IReadOnlyCollection<KeyValuePair<string, string>> Claims = new List<KeyValuePair<string, string>>(); private static readonly IPAddress CallerIpAddress = new IPAddress(new byte[] { 0xA, 0x0, 0x0, 0x0 }); // 10.0.0.0 private const string CallerIpAddressInString = "10.0.0.0"; private readonly IFhirRequestContextAccessor _fhirRequestContextAccessor = Substitute.For<IFhirRequestContextAccessor>(); private readonly IAuditLogger _auditLogger = Substitute.For<IAuditLogger>(); private readonly IAuditHeaderReader _auditHeaderReader = Substitute.For<IAuditHeaderReader>(); private readonly IFhirRequestContext _fhirRequestContext = Substitute.For<IFhirRequestContext>(); private readonly IAuditHelper _auditHelper; private readonly HttpContext _httpContext = new DefaultHttpContext(); private readonly IClaimsExtractor _claimsExtractor = Substitute.For<IClaimsExtractor>(); public AuditHelperTests() { _fhirRequestContext.Uri.Returns(Uri); _fhirRequestContext.CorrelationId.Returns(CorrelationId); _fhirRequestContext.ResourceType.Returns("Patient"); _fhirRequestContextAccessor.FhirRequestContext = _fhirRequestContext; _httpContext.Connection.RemoteIpAddress = CallerIpAddress; _claimsExtractor.Extract().Returns(Claims); _auditHelper = new AuditHelper(_fhirRequestContextAccessor, _auditLogger, _auditHeaderReader); } [Fact] public void GivenNoAuditEventType_WhenLogExecutingIsCalled_ThenAuditLogShouldNotBeLogged() { _auditHelper.LogExecuting(_httpContext, _claimsExtractor); _auditLogger.DidNotReceiveWithAnyArgs().LogAudit( auditAction: default, operation: default, resourceType: default, requestUri: default, statusCode: default, correlationId: default, callerIpAddress: default, callerClaims: default); } [Fact] public void GivenAuditEventType_WhenLogExecutingIsCalled_ThenAuditLogShouldBeLogged() { _fhirRequestContext.AuditEventType.Returns(AuditEventType); _auditHelper.LogExecuting(_httpContext, _claimsExtractor); _auditLogger.Received(1).LogAudit( AuditAction.Executing, AuditEventType, resourceType: "Patient", requestUri: Uri, statusCode: null, correlationId: CorrelationId, callerIpAddress: CallerIpAddressInString, callerClaims: Claims, customHeaders: _auditHeaderReader.Read(_httpContext)); } [Fact] public void GivenNoAuditEventType_WhenLogExecutedIsCalled_ThenAuditLogShouldNotBeLogged() { _auditHelper.LogExecuted(_httpContext, _claimsExtractor); _auditLogger.DidNotReceiveWithAnyArgs().LogAudit( auditAction: default, operation: default, resourceType: default, requestUri: default, statusCode: default, correlationId: default, callerIpAddress: default, callerClaims: default); } [Fact] public void GivenAuditEventType_WhenLogExecutedIsCalled_ThenAuditLogShouldBeLogged() { const HttpStatusCode expectedStatusCode = HttpStatusCode.Created; const string expectedResourceType = "Patient"; _fhirRequestContext.AuditEventType.Returns(AuditEventType); _fhirRequestContext.ResourceType.Returns(expectedResourceType); _httpContext.Response.StatusCode = (int)expectedStatusCode; _auditHelper.LogExecuted(_httpContext, _claimsExtractor); _auditLogger.Received(1).LogAudit( AuditAction.Executed, AuditEventType, expectedResourceType, Uri, expectedStatusCode, CorrelationId, CallerIpAddressInString, Claims, customHeaders: _auditHeaderReader.Read(_httpContext)); } } }
40.656489
132
0.639129
3dd99de1c33ac16df246099aea55fc3f7d85af29
2,524
cs
C#
EzRide.Core/Domain/User.cs
mstr-code/EzRide
8b6ea4a683135d81f352d1410ffb7974d2a2a27f
[ "MIT" ]
null
null
null
EzRide.Core/Domain/User.cs
mstr-code/EzRide
8b6ea4a683135d81f352d1410ffb7974d2a2a27f
[ "MIT" ]
null
null
null
EzRide.Core/Domain/User.cs
mstr-code/EzRide
8b6ea4a683135d81f352d1410ffb7974d2a2a27f
[ "MIT" ]
null
null
null
using System; using System.Text.RegularExpressions; namespace EzRide.Core.Domain { public class User { // private string firstName; // public string middleName; // public string lastName; // User's unique email address. // Can be changed if needed. private string email; // User's unique username. // Used for login purposes. public string username; // User's salted password. private string password; private static readonly Regex RegexName = new Regex("[a-zA-Z]"); // User's unique identifier. public Guid Id { get; protected set; } public string Email { get => email; set { if (string.IsNullOrWhiteSpace(value)) throw new System.Exception("Please provide a valid Email address."); if (email == value.ToLowerInvariant()) return; email = value.ToLowerInvariant(); UpdatedAt = DateTime.UtcNow; } } public string Username { get => username; set { if (!RegexName.IsMatch(value)) throw new System.Exception("Please provide a valid Username."); if (username == value) return; username = value; UpdatedAt = DateTime.UtcNow; } } public string Password { get => password; set { if (string.IsNullOrWhiteSpace(value)) throw new System.Exception("Please provide a valid Password."); if (password == value) return; password = value; UpdatedAt = DateTime.UtcNow; } } public string Salt { get; protected set; } // User's role (either regular 'user' or 'admin'). public string Role { get; set; } public DateTime UpdatedAt { get; protected set; } protected User() { } public User(Guid id, string email, string username, string password, string salt, string role) { Id = id; Email = email.ToLowerInvariant(); Username = username; Password = password; Salt = salt; Role = role; UpdatedAt = DateTime.UtcNow; } } }
29.011494
103
0.494453
3ddb9cd78701cffc35dfd031fdb9ca392c647a25
1,840
cs
C#
src/SuperMassive/Helpers/AssemblyHelper.cs
PulsarBlow/SuperMassive
2bb5381085dd7625aec1487448272bda59dace72
[ "MIT" ]
6
2015-10-05T08:21:40.000Z
2020-06-03T20:10:49.000Z
src/SuperMassive/Helpers/AssemblyHelper.cs
PulsarBlow/SuperMassive
2bb5381085dd7625aec1487448272bda59dace72
[ "MIT" ]
6
2020-04-26T21:47:59.000Z
2020-09-19T09:44:29.000Z
src/SuperMassive/Helpers/AssemblyHelper.cs
PulsarBlow/SuperMassive
2bb5381085dd7625aec1487448272bda59dace72
[ "MIT" ]
1
2018-04-16T06:31:02.000Z
2018-04-16T06:31:02.000Z
namespace SuperMassive { using System.Reflection; /// <summary> /// Provides helping methods for manipulating assemblies /// </summary> public static class AssemblyHelper { /// <summary> /// Returns the file version of the executing assembly /// </summary> /// <returns>The file version of the executing assembly</returns> public static string? GetFileVersion() { return GetFileVersion(typeof(AssemblyHelper).Assembly); } /// <summary> /// Returns the file version of a given assembly /// </summary> /// <param name="assembly">Assembly used to get the file version</param> /// <returns>The file version of the assembly</returns> public static string? GetFileVersion(Assembly assembly) { return assembly .GetCustomAttribute<AssemblyFileVersionAttribute>()? .Version; } /// <summary> /// Returns the informational version of the executing assembly. /// </summary> /// <returns>The informational version of the assembly</returns> public static string? GetInformationalVersion() { return GetInformationalVersion(typeof(AssemblyHelper).Assembly); } /// <summary> /// Returns the informational version of the given assembly. /// </summary> /// <param name="assembly">Assembly used to get the informational version</param> /// <returns>The informational version of the assembly</returns> public static string? GetInformationalVersion(Assembly assembly) { return assembly .GetCustomAttribute<AssemblyInformationalVersionAttribute>()? .InformationalVersion; } } }
34.716981
89
0.605978
3dddf55f0eeec1eae45ee00285f1841672f28569
2,969
cs
C#
Framework/Assets/Asset.cs
Macabresoft/Macabre2D.Framework
8b11a506eb1dd7eb07c75060a2b75abf684c729c
[ "MIT" ]
7
2017-03-12T19:22:27.000Z
2020-05-16T03:09:03.000Z
Framework/Assets/Asset.cs
Macabresoft/Macabresoft.MonoGame
4a177d2869d3bdd19e489461b2f335f46b79e0a3
[ "MIT" ]
1
2018-05-29T05:03:12.000Z
2018-05-30T08:44:58.000Z
Framework/Assets/Asset.cs
Macabresoft/Macabresoft.MonoGame
4a177d2869d3bdd19e489461b2f335f46b79e0a3
[ "MIT" ]
2
2018-08-25T20:09:07.000Z
2019-04-06T19:30:42.000Z
namespace Macabresoft.Macabre2D.Framework; using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Text; /// <summary> /// Interface for an object that is an asset. /// </summary> public interface IAsset : INotifyPropertyChanged { /// <summary> /// Gets the content identifier. /// </summary> /// <value>The content identifier.</value> Guid ContentId { get; } /// <summary> /// Gets a value indicating whether or not this should include the file extension in its content path. /// </summary> bool IncludeFileExtensionInContentPath { get; } /// <summary> /// Gets the content build commands used by MGCB to compile this piece of content. /// </summary> /// <param name="contentPath">The content path.</param> /// <param name="fileExtension">The file extension.</param> /// <returns>The content build commands.</returns> string GetContentBuildCommands(string contentPath, string fileExtension); } /// <summary> /// Interface for an asset that contains content. /// </summary> public interface IAsset<TContent> : IAsset { /// <summary> /// Gets the content. /// </summary> TContent? Content { get; } /// <summary> /// Loads content for this asset. /// </summary> /// <param name="content">The content.</param> void LoadContent(TContent content); } /// <summary> /// A base implementation for assets that contains an identifier and name. /// </summary> [DataContract] public abstract class Asset<TContent> : NotifyPropertyChanged, IAsset<TContent> { private IAssetManager _assetManager = AssetManager.Empty; private TContent? _content; /// <summary> /// Initializes a new instance of the <see cref="Asset{TContent}" /> class. /// </summary> protected Asset() { this.ContentId = Guid.NewGuid(); } /// <inheritdoc /> public abstract bool IncludeFileExtensionInContentPath { get; } /// <inheritdoc /> public TContent? Content { get => this._content; protected set => this.Set(ref this._content, value); } /// <inheritdoc /> [DataMember] [EditorExclude] public Guid ContentId { get; private set; } /// <inheritdoc /> public virtual string GetContentBuildCommands(string contentPath, string fileExtension) { var contentStringBuilder = new StringBuilder(); contentStringBuilder.AppendLine($"#begin {contentPath}"); contentStringBuilder.AppendLine($@"/copy:{contentPath}"); contentStringBuilder.AppendLine($"#end {contentPath}"); return contentStringBuilder.ToString(); } /// <inheritdoc /> public virtual void LoadContent(TContent content) { this.Content = content; } /// <inheritdoc /> protected override void OnDisposing() { base.OnDisposing(); if (this.Content is IDisposable disposable) { disposable.Dispose(); } } }
29.989899
106
0.654766
3dde2db92af32544aa75ed466c1d63318655aeab
52,075
cs
C#
Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TeamsController.cs
mikelapierre/Microsoft-Teams-Shifts-WFM-Connectors
6d0fb6cdc05fbfda034e81a441791cf1ff4d007f
[ "MIT" ]
null
null
null
Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TeamsController.cs
mikelapierre/Microsoft-Teams-Shifts-WFM-Connectors
6d0fb6cdc05fbfda034e81a441791cf1ff4d007f
[ "MIT" ]
null
null
null
Kronos-Shifts-Connector/Microsoft.Teams.Shifts.Integration/Microsoft.Teams.Shifts.Integration.API/Controllers/TeamsController.cs
mikelapierre/Microsoft-Teams-Shifts-WFM-Connectors
6d0fb6cdc05fbfda034e81a441791cf1ff4d007f
[ "MIT" ]
1
2021-06-22T22:32:53.000Z
2021-06-22T22:32:53.000Z
// <copyright file="TeamsController.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace Microsoft.Teams.Shifts.Integration.API.Controllers { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Teams.App.KronosWfc.Common; using Microsoft.Teams.Shifts.Encryption.Encryptors; using Microsoft.Teams.Shifts.Integration.API.Common; using Microsoft.Teams.Shifts.Integration.API.Models.IntegrationAPI; using Microsoft.Teams.Shifts.Integration.API.Models.IntegrationAPI.Incoming; using Microsoft.Teams.Shifts.Integration.BusinessLogic.Models; using Microsoft.Teams.Shifts.Integration.BusinessLogic.Providers; using Microsoft.Teams.Shifts.Integration.BusinessLogic.ResponseModels; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// This is the teams controller that is being used here. /// </summary> [Route("/v1/teams")] [ApiController] public class TeamsController : Controller { private readonly AppSettings appSettings; private readonly TelemetryClient telemetryClient; private readonly IConfigurationProvider configurationProvider; private readonly OpenShiftRequestController openShiftRequestController; private readonly SwapShiftController swapShiftController; private readonly Common.Utility utility; private readonly IUserMappingProvider userMappingProvider; private readonly IShiftMappingEntityProvider shiftMappingEntityProvider; private readonly IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider; private readonly IOpenShiftMappingEntityProvider openShiftMappingEntityProvider; private readonly ISwapShiftMappingEntityProvider swapShiftMappingEntityProvider; private readonly ITeamDepartmentMappingProvider teamDepartmentMappingProvider; /// <summary> /// Initializes a new instance of the <see cref="TeamsController"/> class. /// </summary> /// <param name="appSettings">Configuration DI.</param> /// <param name="telemetryClient">ApplicationInsights DI.</param> /// <param name="configurationProvider">ConfigurationProvider DI.</param> /// <param name="openShiftRequestController">OpenShiftRequestController DI.</param> /// <param name="swapShiftController">SwapShiftController DI.</param> /// <param name="utility">The common utility methods DI.</param> /// <param name="userMappingProvider">The user mapping provider DI.</param> /// <param name="shiftMappingEntityProvider">The shift entity mapping provider DI.</param> /// <param name="openShiftRequestMappingEntityProvider">The open shift request mapping entity provider DI.</param> /// <param name="openShiftMappingEntityProvider">The open shift mapping entity provider DI.</param> /// <param name="swapShiftMappingEntityProvider">The swap shift mapping entity provider DI.</param> /// <param name="teamDepartmentMappingProvider">The team department mapping entity provider DI.</param> public TeamsController( AppSettings appSettings, TelemetryClient telemetryClient, IConfigurationProvider configurationProvider, OpenShiftRequestController openShiftRequestController, SwapShiftController swapShiftController, Common.Utility utility, IUserMappingProvider userMappingProvider, IShiftMappingEntityProvider shiftMappingEntityProvider, IOpenShiftRequestMappingEntityProvider openShiftRequestMappingEntityProvider, IOpenShiftMappingEntityProvider openShiftMappingEntityProvider, ISwapShiftMappingEntityProvider swapShiftMappingEntityProvider, ITeamDepartmentMappingProvider teamDepartmentMappingProvider) { this.appSettings = appSettings; this.telemetryClient = telemetryClient; this.configurationProvider = configurationProvider; this.openShiftRequestController = openShiftRequestController; this.swapShiftController = swapShiftController; this.utility = utility; this.userMappingProvider = userMappingProvider; this.shiftMappingEntityProvider = shiftMappingEntityProvider; this.openShiftRequestMappingEntityProvider = openShiftRequestMappingEntityProvider; this.openShiftMappingEntityProvider = openShiftMappingEntityProvider; this.swapShiftMappingEntityProvider = swapShiftMappingEntityProvider; this.teamDepartmentMappingProvider = teamDepartmentMappingProvider; } /// <summary> /// Method to update the Workforce Integration ID to the schedule. /// </summary> /// <returns>A unit of execution that contains the HTTP Response.</returns> [HttpGet] [Route("/api/teams/CheckSetup")] public async Task<HttpResponseMessage> CheckSetupAsync() { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); var isSetUpDone = await this.utility.IsSetUpDoneAsync().ConfigureAwait(false); // Check for all the setup i.e User to user mapping, team department mapping, user logged in to configuration web app if (isSetUpDone) { httpResponseMessage.StatusCode = HttpStatusCode.OK; } else { httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError; } return httpResponseMessage; } /// <summary> /// The method that will be called from Shifts. /// </summary> /// <param name="aadGroupId">The AAD Group Id for the Team.</param> /// <returns>An action result.</returns> [HttpPost] [Route("/v1/teams/{aadGroupId}/update")] public async Task<ActionResult> UpdateTeam([FromRoute] string aadGroupId) { var request = this.Request; var requestHeaders = request.Headers; Microsoft.Extensions.Primitives.StringValues passThroughValue = string.Empty; this.telemetryClient.TrackTrace("IncomingRequest, starts for method: UpdateTeam - " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); // Step 1 - Obtain the secret from the database. var configurationEntities = await this.configurationProvider.GetConfigurationsAsync().ConfigureAwait(false); var configurationEntity = configurationEntities?.FirstOrDefault(); // Check whether Request coming from correct workforce integration is present and is equal to workforce integration id. // Request is valid for OpenShift and SwapShift request FLM approval when the value of X-MS-WFMRequest coming // from correct workforce integration is equal to current workforce integration id. var isRequestFromCorrectIntegration = requestHeaders.TryGetValue("X-MS-WFMPassthrough", out passThroughValue) && string.Equals(passThroughValue, configurationEntity.WorkforceIntegrationId, StringComparison.Ordinal); // Step 2 - Create/declare the byte arrays, and other data types required. byte[] secretKeyBytes = Encoding.UTF8.GetBytes(configurationEntity?.WorkforceIntegrationSecret); // Step 3 - Extract the incoming request using the symmetric key, and the HttpRequest. var jsonModel = await DecryptEncryptedRequestFromShiftsAsync( secretKeyBytes, this.Request).ConfigureAwait(false); IntegrationApiResponseModel responseModel = new IntegrationApiResponseModel(); ShiftsIntegResponse integrationResponse; List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>(); string responseModelStr = string.Empty; var updateProps = new Dictionary<string, string>() { { "IncomingAadGroupId", aadGroupId }, }; // get the kronos org job mapping information for the team and get the timezone for the first mapping // logically all mappings for the team must have the same time zone set var mappedTeams = await this.teamDepartmentMappingProvider.GetMappedTeamDetailsAsync(aadGroupId).ConfigureAwait(false); var mappedTeam = mappedTeams.FirstOrDefault(); var kronosTimeZone = string.IsNullOrEmpty(mappedTeam?.KronosTimeZone) ? this.appSettings.KronosTimeZone : mappedTeam.KronosTimeZone; // Check if payload is for open shift request. if (jsonModel.Requests.Any(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture))) { // Process payload for open shift request. responseModelList = await this.ProcessOpenShiftRequest(jsonModel, updateProps, aadGroupId, isRequestFromCorrectIntegration, kronosTimeZone).ConfigureAwait(false); } // Check if payload is for swap shift request. else if (jsonModel.Requests.Any(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture))) { this.telemetryClient.TrackTrace("Teams Controller swapRequests " + JsonConvert.SerializeObject(jsonModel)); // Process payload for swap shift request. responseModelList = await this.ProcessSwapShiftRequest(jsonModel, aadGroupId, isRequestFromCorrectIntegration, kronosTimeZone).ConfigureAwait(true); } // Check if payload is for open shift. else if (jsonModel.Requests.Any(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture))) { // Acknowledge with status OK for open shift as solution does not synchronize open shifts into Kronos, Kronos being single source of truth for front line manager actions. integrationResponse = ProcessOpenShiftAcknowledgement(jsonModel, updateProps); responseModelList.Add(integrationResponse); } // Check if payload is for shift. else if (jsonModel.Requests.Any(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture))) { // Acknowledge with status OK for shift as solution does not synchronize shifts into Kronos, Kronos being single source of truth for front line manager actions. integrationResponse = ProcessShiftAcknowledgement(jsonModel, updateProps); responseModelList.Add(integrationResponse); } responseModel.ShiftsIntegResponses = responseModelList; responseModelStr = JsonConvert.SerializeObject(responseModel); this.telemetryClient.TrackTrace("IncomingRequest, ends for method: UpdateTeam - " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); // Sends response back to Shifts. return this.Ok(responseModelStr); } /// <summary> /// This method will create the necessary acknowledgement response whenever Shift entities are created, or updated. /// </summary> /// <param name="jsonModel">The decrypted JSON payload.</param> /// <param name="updateProps">The type of <see cref="Dictionary{TKey, TValue}"/> that contains properties that are being logged to ApplicationInsights.</param> /// <returns>A type of <see cref="ShiftsIntegResponse"/>.</returns> private static ShiftsIntegResponse ProcessShiftAcknowledgement(RequestModel jsonModel, Dictionary<string, string> updateProps) { if (jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Body != null) { var incomingShift = JsonConvert.DeserializeObject<Shift>(jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Body.ToString()); updateProps.Add("ShiftId", incomingShift.Id); updateProps.Add("UserIdForShift", incomingShift.UserId); updateProps.Add("SchedulingGroupId", incomingShift.SchedulingGroupId); var integrationResponse = GenerateResponse(incomingShift.Id, HttpStatusCode.OK, null, null); return integrationResponse; } else { var nullBodyShiftId = jsonModel.Requests.First(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)).Id; updateProps.Add("NullBodyShiftId", nullBodyShiftId); // The outbound acknowledgement does not honor the null Etag, 502 Bad Gateway is thrown if so. // Checking for the null eTag value, from the attributes in the payload and generate a non-null value in GenerateResponse method. var integrationResponse = GenerateResponse( nullBodyShiftId, HttpStatusCode.OK, null, null); return integrationResponse; } } /// <summary> /// This method will generate the necessary response for acknowledging the open shift being created or changed. /// </summary> /// <param name="jsonModel">The decrypted JSON payload.</param> /// <param name="updateProps">The type of <see cref="Dictionary{TKey, TValue}"/> which contains various properties to log to ApplicationInsights.</param> /// <returns>A type of <see cref="ShiftsIntegResponse"/>.</returns> private static ShiftsIntegResponse ProcessOpenShiftAcknowledgement(RequestModel jsonModel, Dictionary<string, string> updateProps) { ShiftsIntegResponse integrationResponse; if (jsonModel.Requests.First(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)).Body != null) { var incomingOpenShift = JsonConvert.DeserializeObject<OpenShiftIS>(jsonModel.Requests.First().Body.ToString()); updateProps.Add("OpenShiftId", incomingOpenShift.Id); updateProps.Add("SchedulingGroupId", incomingOpenShift.SchedulingGroupId); integrationResponse = GenerateResponse(incomingOpenShift.Id, HttpStatusCode.OK, null, null); } else { var nullBodyIncomingOpenShiftId = jsonModel.Requests.First(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)).Id; updateProps.Add("NullBodyOpenShiftId", nullBodyIncomingOpenShiftId); integrationResponse = GenerateResponse(nullBodyIncomingOpenShiftId, HttpStatusCode.OK, null, null); } return integrationResponse; } /// <summary> /// Generates the response for each outbound request. /// </summary> /// <param name="itemId">Id for response.</param> /// <param name="statusCode">HttpStatusCode for the request been processed.</param> /// <param name="eTag">Etag based on response.</param> /// <param name="error">Forward error to Shifts if any.</param> /// <returns>ShiftsIntegResponse.</returns> private static ShiftsIntegResponse GenerateResponse(string itemId, HttpStatusCode statusCode, string eTag, ResponseError error) { // The outbound acknowledgement does not honor the null Etag, 502 Bad Gateway is thrown if so. // Checking for the null eTag value, from the attributes in the payload. string responseEtag; if (string.IsNullOrEmpty(eTag)) { responseEtag = GenerateNewGuid(); } else { responseEtag = eTag; } var integrationResponse = new ShiftsIntegResponse() { Id = itemId, Status = (int)statusCode, Body = new Body { Error = error, ETag = responseEtag, }, }; return integrationResponse; } /// <summary> /// Generates the Guid for outbound call response. /// </summary> /// <returns>Returns newly generated GUID string.</returns> private static string GenerateNewGuid() { return Guid.NewGuid().ToString(); } /// <summary> /// This method will properly decrypt the encrypted payload that is being received from Shifts. /// </summary> /// <param name="secretKeyBytes">The sharedSecret from Shifts casted into a byte array.</param> /// <param name="request">The incoming request from Shifts UI that contains an encrypted payload.</param> /// <returns>A unit of execution which contains the RequestModel.</returns> private static async Task<RequestModel> DecryptEncryptedRequestFromShiftsAsync(byte[] secretKeyBytes, HttpRequest request) { string decryptedRequestBody = null; // Step 1 - using a memory stream for the processing of the request. using (MemoryStream ms = new MemoryStream()) { await request.Body.CopyToAsync(ms).ConfigureAwait(false); byte[] encryptedRequestBytes = ms.ToArray(); Aes256CbcHmacSha256Encryptor decryptor = new Aes256CbcHmacSha256Encryptor(secretKeyBytes); byte[] decryptedRequestBodyBytes = decryptor.Decrypt(encryptedRequestBytes); decryptedRequestBody = Encoding.UTF8.GetString(decryptedRequestBodyBytes); } // Step 2 - Parse the decrypted request into the correct model. return JsonConvert.DeserializeObject<RequestModel>(decryptedRequestBody); } /// <summary> /// Generate response to prevent actions. /// </summary> /// <param name="jsonModel">The request payload.</param> /// <param name="errorMessage">Error message to send while preventing action.</param> /// <returns>List of ShiftsIntegResponse.</returns> private static List<ShiftsIntegResponse> GenerateResponseToPreventAction(RequestModel jsonModel, string errorMessage) { List<ShiftsIntegResponse> shiftsIntegResponses = new List<ShiftsIntegResponse>(); var integrationResponse = new ShiftsIntegResponse(); foreach (var item in jsonModel.Requests) { ResponseError responseError = new ResponseError(); responseError.Code = HttpStatusCode.BadRequest.ToString(); responseError.Message = errorMessage; integrationResponse = GenerateResponse(item.Id, HttpStatusCode.BadRequest, null, responseError); shiftsIntegResponses.Add(integrationResponse); } return shiftsIntegResponses; } /// <summary> /// Process open shift requests outbound calls. /// </summary> /// <param name="jsonModel">Incoming payload for the request been made in Shifts.</param> /// <param name="updateProps">telemetry properties.</param> /// <param name="teamsId">The ID of the team from which the request originated.</param> /// <param name="isRequestFromCorrectIntegration">Whether the request originated from the correct workforce integration or not</param> /// <param name="kronosTimeZone">The time zone to use when converting the times.</param> /// <returns>Returns list of ShiftIntegResponse for request.</returns> private async Task<List<ShiftsIntegResponse>> ProcessOpenShiftRequest(RequestModel jsonModel, Dictionary<string, string> updateProps, string teamsId, bool isRequestFromCorrectIntegration, string kronosTimeZone) { List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>(); var requestBody = jsonModel.Requests.First(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture)).Body; if (requestBody != null) { switch (requestBody["state"].Value<string>()) { // The Open shift request is submitted in Shifts and is pending with manager for approval. case ApiConstants.ShiftsPending: { var openShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(requestBody.ToString()); responseModelList = await this.ProcessOutboundOpenShiftRequestAsync(openShiftRequest, updateProps, teamsId).ConfigureAwait(false); } break; // The Open shift request is approved by manager. case ApiConstants.ShiftsApproved: { // The request is coming from intended workforce integration. if (isRequestFromCorrectIntegration) { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest approval outbound call."); responseModelList = await this.ProcessOpenShiftRequestApprovalAsync(jsonModel, updateProps, kronosTimeZone).ConfigureAwait(false); } // Request is coming from either Shifts UI or from incorrect workforce integration. else { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest approval outbound call."); responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval); } } break; // The code below would be when there is a decline. case ApiConstants.ShiftsDeclined: { // The request is coming from intended workforce integration. if (isRequestFromCorrectIntegration) { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest decline outbound call."); var integrationResponse = new ShiftsIntegResponse(); foreach (var item in jsonModel.Requests) { integrationResponse = GenerateResponse(item.Id, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponse); } } // Request is coming from either Shifts UI or from incorrect workforce integration. else { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for OpenShiftRequest decline outbound call."); responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval); } } break; } } return responseModelList; } /// <summary> /// Process swap shift requests outbound calls. /// </summary> /// <param name="jsonModel">Incoming payload for the request been made in Shifts.</param> /// <param name="aadGroupId">AAD Group id.</param> /// <param name="kronosTimeZone">The time zone to use when converting the times.</param> /// <returns>Returns list of ShiftIntegResponse for request.</returns> private async Task<List<ShiftsIntegResponse>> ProcessSwapShiftRequest(RequestModel jsonModel, string aadGroupId, bool isRequestFromCorrectIntegration, string kronosTimeZone) { List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>(); var requestBody = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Body; ShiftsIntegResponse integrationResponseSwap = null; try { // If the requestBody is not null - represents either a new Swap Shift request being created by FLW1, // FLW2 accepts or declines FLW1's request, or FLM approves or declines the Swap Shift request. // If the requestBody is null - represents FLW1's cancellation of the Swap Shift Request. if (requestBody != null) { var requestState = requestBody?["state"].Value<string>(); var requestAssignedTo = requestBody?["assignedTo"].Value<string>(); var swapRequest = JsonConvert.DeserializeObject<SwapRequest>(requestBody.ToString()); // FLW1 has requested for swap shift, submit the request in Kronos. if (requestState == ApiConstants.ShiftsPending && requestAssignedTo == ApiConstants.ShiftsRecipient) { integrationResponseSwap = await this.swapShiftController.SubmitSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false); responseModelList.Add(integrationResponseSwap); } // FLW2 has approved the swap shift, updates the status in Kronos to submitted and request goes to manager for approval. else if (requestState == ApiConstants.ShiftsPending && requestAssignedTo == ApiConstants.ShiftsManager) { integrationResponseSwap = await this.swapShiftController.ApproveOrDeclineSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false); responseModelList.Add(integrationResponseSwap); } // FLW2 has declined the swap shift, updates the status in Kronos to refused. else if (requestState == ApiConstants.Declined && requestAssignedTo == ApiConstants.ShiftsRecipient) { integrationResponseSwap = await this.swapShiftController.ApproveOrDeclineSwapShiftRequestToKronosAsync(swapRequest, aadGroupId).ConfigureAwait(false); responseModelList.Add(integrationResponseSwap); } // Manager has declined the request in Kronos, which declines the request in Shifts also. else if (requestState == ApiConstants.ShiftsDeclined && requestAssignedTo == ApiConstants.ShiftsManager) { // The request is coming from intended workforce integration. if (isRequestFromCorrectIntegration) { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest decline outbound call."); integrationResponseSwap = GenerateResponse(swapRequest.Id, HttpStatusCode.OK, swapRequest.ETag, null); responseModelList.Add(integrationResponseSwap); } // Request is coming from either Shifts UI or from incorrect workforce integration. else { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest decline outbound call."); responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval); } } // Manager has approved the request in Kronos. else if (requestState == ApiConstants.ShiftsApproved && requestAssignedTo == ApiConstants.ShiftsManager) { // The request is coming from intended workforce integration. if (isRequestFromCorrectIntegration) { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest approval outbound call."); responseModelList = await this.ProcessSwapShiftRequestApprovalAsync(jsonModel, aadGroupId, kronosTimeZone).ConfigureAwait(false); } // Request is coming from either Shifts UI or from incorrect workforce integration. else { this.telemetryClient.TrackTrace($"Request coming from correct workforce integration is {isRequestFromCorrectIntegration} for SwapShiftRequest approval outbound call."); responseModelList = GenerateResponseToPreventAction(jsonModel, Resource.InvalidApproval); } } // There is a System decline with the Swap Shift Request else if (requestState == ApiConstants.Declined && requestAssignedTo == ApiConstants.System) { var systemDeclineSwapReqId = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Id; ResponseError responseError = new ResponseError { Message = Resource.SystemDeclined, }; integrationResponseSwap = GenerateResponse(systemDeclineSwapReqId, HttpStatusCode.OK, null, responseError); responseModelList.Add(integrationResponseSwap); } } else if (jsonModel.Requests.Any(c => c.Method == "DELETE")) { // Code below handles the delete swap shift request. var deleteSwapRequestId = jsonModel.Requests.First(x => x.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)).Id; // Logging to telemetry the incoming cancelled request by FLW1. this.telemetryClient.TrackTrace($"The Swap Shift Request: {deleteSwapRequestId} has been declined by FLW1."); var entityToCancel = await this.swapShiftMappingEntityProvider.GetKronosReqAsync(deleteSwapRequestId).ConfigureAwait(false); // Updating the ShiftsStatus to Cancelled. entityToCancel.ShiftsStatus = ApiConstants.SwapShiftCancelled; // Updating the entity accordingly await this.swapShiftMappingEntityProvider.AddOrUpdateSwapShiftMappingAsync(entityToCancel).ConfigureAwait(false); integrationResponseSwap = GenerateResponse(deleteSwapRequestId, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponseSwap); } } catch (Exception) { this.telemetryClient.TrackTrace("Teams Controller swapRequests responseModelList Exception" + JsonConvert.SerializeObject(responseModelList)); throw; } this.telemetryClient.TrackTrace("Teams Controller swapRequests responseModelList" + JsonConvert.SerializeObject(responseModelList)); return responseModelList; } /// <summary> /// This method processes the open shift request approval, and proceeds to update the Azure table storage accordingly with the Shifts status /// of the open shift request, and also ensures that the ShiftMappingEntity table is properly in sync. /// </summary> /// <param name="jsonModel">The decrypted JSON payload.</param> /// <param name="updateProps">A dictionary of string, string that will be logged to ApplicationInsights.</param> /// <param name="kronosTimeZone">The time zone to use when converting the times.</param> /// <returns>A unit of execution.</returns> private async Task<List<ShiftsIntegResponse>> ProcessOpenShiftRequestApprovalAsync(RequestModel jsonModel, Dictionary<string, string> updateProps, string kronosTimeZone) { List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>(); ShiftsIntegResponse integrationResponse = null; var openShiftRequests = jsonModel?.Requests?.Where(x => x.Url.Contains("/openshiftrequests/", StringComparison.InvariantCulture)); var finalOpenShiftObj = jsonModel?.Requests?.FirstOrDefault(x => x.Url.Contains("/openshifts/", StringComparison.InvariantCulture)); var finalShiftObj = jsonModel?.Requests?.FirstOrDefault(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture)); // Filter all the system declined requests. var autoDeclinedRequests = openShiftRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.Declined && c.Body["assignedTo"].Value<string>() == ApiConstants.System).ToList(); // Filter approved open shift request. var approvedOpenShiftRequest = openShiftRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.ShiftsApproved && c.Body["assignedTo"].Value<string>() == ApiConstants.ShiftsManager).FirstOrDefault(); var finalShift = JsonConvert.DeserializeObject<Shift>(finalShiftObj.Body.ToString()); var finalOpenShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(approvedOpenShiftRequest.Body.ToString()); var finalOpenShift = JsonConvert.DeserializeObject<OpenShiftIS>(finalOpenShiftObj.Body.ToString()); updateProps.Add("NewShiftId", finalShift.Id); updateProps.Add("GraphOpenShiftRequestId", finalOpenShiftRequest.Id); updateProps.Add("GraphOpenShiftId", finalOpenShift.Id); // Step 1 - Create the Kronos Unique ID. var kronosUniqueId = this.utility.CreateUniqueId(finalShift, kronosTimeZone); this.telemetryClient.TrackTrace("KronosHash-OpenShiftRequestApproval-TeamsController: " + kronosUniqueId); try { this.telemetryClient.TrackTrace("Updating entities-OpenShiftRequestApproval started: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); // Step 1 - Get the temp shift record first by table scan against RowKey. var tempShiftRowKey = $"SHFT_PENDING_{finalOpenShiftRequest.Id}"; var tempShiftEntity = await this.shiftMappingEntityProvider.GetShiftMappingEntityByRowKeyAsync(tempShiftRowKey).ConfigureAwait(false); // We need to check if the tempShift is not null because in the Open Shift Request controller, the tempShift was created // as part of the Graph API call to approve the Open Shift Request. if (tempShiftEntity != null) { // Step 2 - Form the new shift record. var shiftToInsert = new TeamsShiftMappingEntity() { RowKey = finalShift.Id, KronosPersonNumber = tempShiftEntity.KronosPersonNumber, KronosUniqueId = tempShiftEntity.KronosUniqueId, PartitionKey = tempShiftEntity.PartitionKey, AadUserId = tempShiftEntity.AadUserId, ShiftStartDate = this.utility.UTCToKronosTimeZone(finalShift.SharedShift.StartDateTime, kronosTimeZone), }; // Step 3 - Save the new shift record. await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync(shiftToInsert, shiftToInsert.RowKey, shiftToInsert.PartitionKey).ConfigureAwait(false); // Step 4 - Delete the temp shift record. await this.shiftMappingEntityProvider.DeleteOrphanDataFromShiftMappingAsync(tempShiftEntity).ConfigureAwait(false); // Adding response for create new shift. integrationResponse = GenerateResponse(finalShift.Id, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponse); } else { // We are logging to ApplicationInsights that the tempShift entity could not be found. this.telemetryClient.TrackTrace(string.Format(CultureInfo.InvariantCulture, Resource.EntityNotFoundWithRowKey, tempShiftRowKey)); } // Logging to ApplicationInsights the OpenShiftRequestId. this.telemetryClient.TrackTrace("OpenShiftRequestId = " + finalOpenShiftRequest.Id); // Find the open shift request for which we update the ShiftsStatus to Approved. var openShiftRequestEntityToUpdate = await this.openShiftRequestMappingEntityProvider.GetOpenShiftRequestMappingEntityByOpenShiftIdAsync( finalOpenShift.Id, finalOpenShiftRequest.Id).ConfigureAwait(false); openShiftRequestEntityToUpdate.ShiftsStatus = finalOpenShiftRequest.State; // Update the open shift request to Approved in the ShiftStatus column. await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(openShiftRequestEntityToUpdate).ConfigureAwait(false); // Delete the open shift entity accordingly from the OpenShiftEntityMapping table in Azure Table storage as the open shift request has been approved. await this.openShiftMappingEntityProvider.DeleteOrphanDataFromOpenShiftMappingByOpenShiftIdAsync(finalOpenShift.Id).ConfigureAwait(false); // Adding response for delete open shift. integrationResponse = GenerateResponse(finalOpenShift.Id, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponse); // Adding response for approved open shift request. integrationResponse = GenerateResponse(finalOpenShiftRequest.Id, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponse); foreach (var declinedRequest in autoDeclinedRequests) { this.telemetryClient.TrackTrace($"SystemDeclinedOpenShiftRequestId: {declinedRequest.Id}"); var declinedOpenShiftRequest = JsonConvert.DeserializeObject<OpenShiftRequestIS>(declinedRequest.Body.ToString()); // Update the status in Azure table storage. var entityToUpdate = await this.openShiftRequestMappingEntityProvider.GetOpenShiftRequestMappingEntityByOpenShiftRequestIdAsync( declinedRequest.Id).ConfigureAwait(false); entityToUpdate.KronosStatus = declinedOpenShiftRequest.State; entityToUpdate.ShiftsStatus = declinedOpenShiftRequest.State; // Commit the change to the database. await this.openShiftRequestMappingEntityProvider.SaveOrUpdateOpenShiftRequestMappingEntityAsync(entityToUpdate).ConfigureAwait(false); this.telemetryClient.TrackTrace($"OpenShiftRequestId: {declinedOpenShiftRequest.Id}, assigned to: {declinedOpenShiftRequest.AssignedTo}, state: {declinedOpenShiftRequest.State}"); // Adding response for system declined open shift request. integrationResponse = GenerateResponse(declinedOpenShiftRequest.Id, HttpStatusCode.OK, null, null); responseModelList.Add(integrationResponse); } this.telemetryClient.TrackTrace("Updating entities-OpenShiftRequestApproval complete: " + DateTime.Now.ToString(CultureInfo.InvariantCulture)); } catch (Exception ex) { if (ex.InnerException != null) { this.telemetryClient.TrackTrace($"Shift mapping has failed for {finalOpenShiftRequest.Id}: " + ex.InnerException.ToString()); } this.telemetryClient.TrackTrace($"Shift mapping has resulted in some type of error with the following: {ex.StackTrace.ToString(CultureInfo.InvariantCulture)}"); throw; } return responseModelList; } /// <summary> /// This method further processes the Swap Shift request approval. /// </summary> /// <param name="jsonModel">The decryped JSON payload from Shifts/MS Graph.</param> /// <param name="aadGroupId">The team ID for which the Swap Shift request has been approved.</param> /// <param name="kronosTimeZone">The time zone to use when converting the times.</param> /// <returns>A unit of execution that contains the type of <see cref="ShiftsIntegResponse"/>.</returns> private async Task<List<ShiftsIntegResponse>> ProcessSwapShiftRequestApprovalAsync(RequestModel jsonModel, string aadGroupId, string kronosTimeZone) { List<ShiftsIntegResponse> swapShiftsIntegResponses = new List<ShiftsIntegResponse>(); ShiftsIntegResponse integrationResponse = null; var swapShiftApprovalRes = from requests in jsonModel.Requests group requests by requests.Url; var swapRequests = jsonModel.Requests.Where(c => c.Url.Contains("/swapRequests/", StringComparison.InvariantCulture)); // Filter all the system declined requests. var autoDeclinedRequests = swapRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.Declined && c.Body["assignedTo"].Value<string>() == ApiConstants.System).ToList(); // Filter approved swap shift request. var approvedSwapShiftRequest = swapRequests.Where(c => c.Body != null && c.Body["state"].Value<string>() == ApiConstants.ShiftsApproved && c.Body["assignedTo"].Value<string>() == ApiConstants.ShiftsManager).FirstOrDefault(); var swapShiftRequest = JsonConvert.DeserializeObject<SwapRequest>(approvedSwapShiftRequest.Body.ToString()); var postedShifts = jsonModel.Requests.Where(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture) && x.Method == "POST").ToList(); var deletedShifts = jsonModel.Requests.Where(x => x.Url.Contains("/shifts/", StringComparison.InvariantCulture) && x.Method == "DELETE").ToList(); if (swapShiftRequest != null) { var newShiftFirst = JsonConvert.DeserializeObject<Shift>(postedShifts.First().Body.ToString()); var newShiftSecond = JsonConvert.DeserializeObject<Shift>(postedShifts.Last().Body.ToString()); // Step 1 - Create the Kronos Unique ID. var kronosUniqueIdFirst = this.utility.CreateUniqueId(newShiftFirst, kronosTimeZone); var kronosUniqueIdSecond = this.utility.CreateUniqueId(newShiftSecond, kronosTimeZone); try { var userMappingRecord = await this.userMappingProvider.GetUserMappingEntityAsyncNew( newShiftFirst?.UserId, aadGroupId).ConfigureAwait(false); // When getting the month partition key, make sure to take into account the Kronos Time Zone as well var provider = CultureInfo.InvariantCulture; var actualStartDateTimeStr = this.utility.CalculateStartDateTime( newShiftFirst.SharedShift.StartDateTime.Date, kronosTimeZone).ToString("M/dd/yyyy", provider); var actualEndDateTimeStr = this.utility.CalculateEndDateTime( newShiftFirst.SharedShift.EndDateTime.Date, kronosTimeZone).ToString("M/dd/yyyy", provider); // Create the month partition key based on the finalShift object. var monthPartitions = Common.Utility.GetMonthPartition(actualStartDateTimeStr, actualEndDateTimeStr); var monthPartition = monthPartitions?.FirstOrDefault(); // Create the shift mapping entity based on the finalShift object also. var shiftEntity = this.utility.CreateShiftMappingEntity(newShiftFirst, userMappingRecord, kronosUniqueIdFirst, kronosTimeZone); await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync( shiftEntity, newShiftFirst.Id, monthPartition).ConfigureAwait(false); var userMappingRecordSec = await this.userMappingProvider.GetUserMappingEntityAsyncNew( newShiftSecond?.UserId, aadGroupId).ConfigureAwait(false); integrationResponse = GenerateResponse(newShiftFirst.Id, HttpStatusCode.OK, null, null); swapShiftsIntegResponses.Add(integrationResponse); // When getting the month partition key, make sure to take into account the Kronos Time Zone as well var actualStartDateTimeStrSec = this.utility.CalculateStartDateTime( newShiftSecond.SharedShift.StartDateTime, kronosTimeZone).ToString("M/dd/yyyy", provider); var actualEndDateTimeStrSec = this.utility.CalculateEndDateTime( newShiftSecond.SharedShift.EndDateTime, kronosTimeZone).ToString("M/dd/yyyy", provider); // Create the month partition key based on the finalShift object. var monthPartitionsSec = Common.Utility.GetMonthPartition(actualStartDateTimeStrSec, actualEndDateTimeStrSec); var monthPartitionSec = monthPartitionsSec?.FirstOrDefault(); // Create the shift mapping entity based on the finalShift object also. var shiftEntitySec = this.utility.CreateShiftMappingEntity(newShiftSecond, userMappingRecordSec, kronosUniqueIdSecond, kronosTimeZone); await this.shiftMappingEntityProvider.SaveOrUpdateShiftMappingEntityAsync( shiftEntitySec, newShiftSecond.Id, monthPartitionSec).ConfigureAwait(false); integrationResponse = GenerateResponse(newShiftSecond.Id, HttpStatusCode.OK, null, null); swapShiftsIntegResponses.Add(integrationResponse); foreach (var delShifts in deletedShifts) { integrationResponse = GenerateResponse(delShifts.Id, HttpStatusCode.OK, null, null); swapShiftsIntegResponses.Add(integrationResponse); } integrationResponse = GenerateResponse(approvedSwapShiftRequest.Id, HttpStatusCode.OK, swapShiftRequest.ETag, null); swapShiftsIntegResponses.Add(integrationResponse); foreach (var declinedRequest in autoDeclinedRequests) { this.telemetryClient.TrackTrace($"SystemDeclinedOpenShiftRequestId: {declinedRequest.Id}"); var declinedSwapShiftRequest = JsonConvert.DeserializeObject<SwapRequest>(declinedRequest.Body.ToString()); // Get the requests from storage. var entityToUpdate = await this.swapShiftMappingEntityProvider.GetKronosReqAsync( declinedRequest.Id).ConfigureAwait(false); entityToUpdate.KronosStatus = declinedSwapShiftRequest.State; entityToUpdate.ShiftsStatus = declinedSwapShiftRequest.State; // Commit the change to the database. await this.swapShiftMappingEntityProvider.AddOrUpdateSwapShiftMappingAsync(entityToUpdate).ConfigureAwait(false); this.telemetryClient.TrackTrace($"OpenShiftRequestId: {declinedSwapShiftRequest.Id}, assigned to: {declinedSwapShiftRequest.AssignedTo}, state: {declinedSwapShiftRequest.State}"); // Adding response for system declined open shift request. integrationResponse = GenerateResponse(declinedSwapShiftRequest.Id, HttpStatusCode.OK, declinedSwapShiftRequest.ETag, null); swapShiftsIntegResponses.Add(integrationResponse); } } catch (Exception ex) { var exceptionProps = new Dictionary<string, string>() { { "NewFirstShiftId", newShiftFirst.Id }, { "NewSecondShiftId", newShiftSecond.Id }, }; this.telemetryClient.TrackException(ex, exceptionProps); throw; } } return swapShiftsIntegResponses; } /// <summary> /// Process outbound open shift request. /// </summary> /// <param name="openShiftRequest">Open shift request payload.</param> /// <param name="updateProps">Telemetry properties.</param> /// <param name="teamsId">The Shifts team id.</param> /// <returns>Returns list of shiftIntegResponse.</returns> private async Task<List<ShiftsIntegResponse>> ProcessOutboundOpenShiftRequestAsync( OpenShiftRequestIS openShiftRequest, Dictionary<string, string> updateProps, string teamsId) { this.telemetryClient.TrackTrace($"{Resource.ProcessOutboundOpenShiftRequestAsync} starts at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}"); List<ShiftsIntegResponse> responseModelList = new List<ShiftsIntegResponse>(); ShiftsIntegResponse openShiftReqSubmitResponse; updateProps.Add("OpenShiftRequestId", openShiftRequest.Id); updateProps.Add("OpenShiftId", openShiftRequest.OpenShiftId); this.telemetryClient.TrackTrace(Resource.IncomingOpenShiftRequest, updateProps); // This code will be submitting the Open Shift request to Kronos. openShiftReqSubmitResponse = await this.openShiftRequestController.SubmitOpenShiftRequestToKronosAsync(openShiftRequest, teamsId).ConfigureAwait(false); responseModelList.Add(openShiftReqSubmitResponse); this.telemetryClient.TrackTrace($"{Resource.ProcessOutboundOpenShiftRequestAsync} ends at: {DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)}"); return responseModelList; } } }
60.063437
241
0.643303
3de012cd3553662fc6a66f21392f52419ef62065
22,580
cs
C#
BrawlLib/Modeling/Triangle Converter/Deque/Deque.cs
ilazoja/BrawlCrate
0204b441d27c19697a6888f4eb478f7079d483c6
[ "MIT" ]
102
2018-08-26T14:30:49.000Z
2022-03-19T08:49:19.000Z
BrawlLib/Modeling/Triangle Converter/Deque/Deque.cs
ilazoja/BrawlCrate
0204b441d27c19697a6888f4eb478f7079d483c6
[ "MIT" ]
35
2018-11-15T05:02:53.000Z
2022-03-18T19:12:28.000Z
BrawlLib/Modeling/Triangle Converter/Deque/Deque.cs
ilazoja/BrawlCrate
0204b441d27c19697a6888f4eb478f7079d483c6
[ "MIT" ]
32
2018-09-11T22:28:06.000Z
2022-03-19T21:19:08.000Z
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections; using System.Diagnostics; namespace BrawlLib.Modeling.Triangle_Converter.Deque { /// <summary> /// Represents a simple double-ended-queue collection of objects. /// </summary> [Serializable()] public class Deque : ICollection, IEnumerable, ICloneable { #region Deque Members #region Fields // The node at the front of the deque. private Node front; // The node at the back of the deque. private Node back; // The number of elements in the deque. private int count; // The version of the deque. private long version; #endregion #region Construction /// <summary> /// Initializes a new instance of the Deque class. /// </summary> public Deque() { } /// <summary> /// Initializes a new instance of the Deque class that contains /// elements copied from the specified collection. /// </summary> /// <param name="col"> /// The ICollection to copy elements from. /// </param> public Deque(ICollection col) { #region Require if (col == null) { throw new ArgumentNullException("col"); } #endregion foreach (object obj in col) { PushBack(obj); } } #endregion #region Methods /// <summary> /// Removes all objects from the Deque. /// </summary> public virtual void Clear() { count = 0; front = back = null; version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Determines whether or not an element is in the Deque. /// </summary> /// <param name="obj"> /// The Object to locate in the Deque. /// </param> /// <returns> /// <b>true</b> if <i>obj</i> if found in the Deque; otherwise, /// <b>false</b>. /// </returns> public virtual bool Contains(object obj) { foreach (object o in this) { if (o == null && obj == null) { return true; } if (o.Equals(obj)) { return true; } } return false; } /// <summary> /// Inserts an object at the front of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushFront(object obj) { // The new node to add to the front of the deque. Node newNode = new Node(obj) { // Link the new node to the front node. The current front node at // the front of the deque is now the second node in the deque. Next = front }; // If the deque isn't empty. if (Count > 0) { // Link the current front to the new node. front.Previous = newNode; } // Make the new node the front of the deque. front = newNode; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if (Count == 1) { // The front and back nodes are the same. back = front; } version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Inserts an object at the back of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushBack(object obj) { // The new node to add to the back of the deque. Node newNode = new Node(obj) { // Link the new node to the back node. The current back node at // the back of the deque is now the second to the last node in the // deque. Previous = back }; // If the deque is not empty. if (Count > 0) { // Link the current back node to the new node. back.Next = newNode; } // Make the new node the back of the deque. back = newNode; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if (Count == 1) { // The front and back nodes are the same. front = back; } version++; #region Invariant AssertValid(); #endregion } /// <summary> /// Removes and returns the object at the front of the Deque. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopFront() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the front of the deque. object obj = front.Value; // Move the front back one node. front = front.Next; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if (Count > 0) { // Tie off the previous link in the front node. front.Previous = null; } // Else the deque is empty. else { // Indicate that there is no back node. back = null; } version++; #region Invariant AssertValid(); #endregion return obj; } /// <summary> /// Removes and returns the object at the back of the Deque. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopBack() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the back of the deque. object obj = back.Value; // Move back node forward one node. back = back.Previous; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if (Count > 0) { // Tie off the next link in the back node. back.Next = null; } // Else the deque is empty. else { // Indicate that there is no front node. front = null; } version++; #region Invariant AssertValid(); #endregion return obj; } /// <summary> /// Returns the object at the front of the Deque without removing it. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekFront() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return front.Value; } /// <summary> /// Returns the object at the back of the Deque without removing it. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekBack() { #region Require if (Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return back.Value; } /// <summary> /// Copies the Deque to a new array. /// </summary> /// <returns> /// A new array containing copies of the elements of the Deque. /// </returns> public virtual object[] ToArray() { object[] array = new object[Count]; int index = 0; foreach (object obj in this) { array[index] = obj; index++; } return array; } /// <summary> /// Returns a synchronized (thread-safe) wrapper for the Deque. /// </summary> /// <param name="deque"> /// The Deque to synchronize. /// </param> /// <returns> /// A synchronized wrapper around the Deque. /// </returns> public static Deque Synchronized(Deque deque) { #region Require if (deque == null) { throw new ArgumentNullException("deque"); } #endregion return new SynchronizedDeque(deque); } [Conditional("DEBUG")] private void AssertValid() { int n = 0; Node current = front; while (current != null) { n++; current = current.Next; } Debug.Assert(n == Count); if (Count > 0) { Debug.Assert(front != null && back != null, "Front/Back Null Test - Count > 0"); Node f = front; Node b = back; while (f.Next != null && b.Previous != null) { f = f.Next; b = b.Previous; } Debug.Assert(f.Next == null && b.Previous == null, "Front/Back Termination Test"); Debug.Assert(f == back && b == front, "Front/Back Equality Test"); } else { Debug.Assert(front == null && back == null, "Front/Back Null Test - Count == 0"); } } #endregion #region Node Class // Represents a node in the deque. [Serializable()] private class Node { private readonly object value; private Node previous; private Node next; public Node(object value) { this.value = value; } public object Value => value; public Node Previous { get => previous; set => previous = value; } public Node Next { get => next; set => next = value; } } #endregion #region DequeEnumerator Class [Serializable()] private class DequeEnumerator : IEnumerator { private readonly Deque owner; private Node currentNode; private object current; private bool moveResult; private readonly long version; public DequeEnumerator(Deque owner) { this.owner = owner; currentNode = owner.front; version = owner.version; } #region IEnumerator Members public void Reset() { #region Require if (version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion currentNode = owner.front; moveResult = false; } public object Current { get { #region Require if (!moveResult) { throw new InvalidOperationException( "The enumerator is positioned before the first " + "element of the Deque or after the last element."); } #endregion return current; } } public bool MoveNext() { #region Require if (version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion if (currentNode != null) { current = currentNode.Value; currentNode = currentNode.Next; moveResult = true; } else { moveResult = false; } return moveResult; } #endregion } #endregion #region SynchronizedDeque Class // Implements a synchronization wrapper around a deque. [Serializable()] private class SynchronizedDeque : Deque { #region SynchronziedDeque Members #region Fields // The wrapped deque. private readonly Deque deque; // The object to lock on. private readonly object root; #endregion #region Construction public SynchronizedDeque(Deque deque) { #region Require if (deque == null) { throw new ArgumentNullException("deque"); } #endregion this.deque = deque; root = deque.SyncRoot; } #endregion #region Methods public override void Clear() { lock (root) { deque.Clear(); } } public override bool Contains(object obj) { bool result; lock (root) { result = deque.Contains(obj); } return result; } public override void PushFront(object obj) { lock (root) { deque.PushFront(obj); } } public override void PushBack(object obj) { lock (root) { deque.PushBack(obj); } } public override object PopFront() { object obj; lock (root) { obj = deque.PopFront(); } return obj; } public override object PopBack() { object obj; lock (root) { obj = deque.PopBack(); } return obj; } public override object PeekFront() { object obj; lock (root) { obj = deque.PeekFront(); } return obj; } public override object PeekBack() { object obj; lock (root) { obj = deque.PeekBack(); } return obj; } public override object[] ToArray() { object[] array; lock (root) { array = deque.ToArray(); } return array; } public override object Clone() { object clone; lock (root) { clone = deque.Clone(); } return clone; } public override void CopyTo(Array array, int index) { lock (root) { deque.CopyTo(array, index); } } public override IEnumerator GetEnumerator() { IEnumerator e; lock (root) { e = deque.GetEnumerator(); } return e; } #endregion #region Properties public override int Count { get { lock (root) { return deque.Count; } } } public override bool IsSynchronized => true; #endregion #endregion } #endregion #endregion #region ICollection Members /// <summary> /// Gets a value indicating whether access to the Deque is synchronized /// (thread-safe). /// </summary> public virtual bool IsSynchronized => false; /// <summary> /// Gets the number of elements contained in the Deque. /// </summary> public virtual int Count => count; /// <summary> /// Copies the Deque elements to an existing one-dimensional Array, /// starting at the specified array index. /// </summary> /// <param name="array"> /// The one-dimensional Array that is the destination of the elements /// copied from Deque. The Array must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in array at which copying begins. /// </param> public virtual void CopyTo(Array array, int index) { #region Require if (array == null) { throw new ArgumentNullException("array"); } if (index < 0) { throw new ArgumentOutOfRangeException("index", index, "Index is less than zero."); } if (array.Rank > 1) { throw new ArgumentException("Array is multidimensional."); } if (index >= array.Length) { throw new ArgumentException("Index is equal to or greater " + "than the length of array."); } if (Count > array.Length - index) { throw new ArgumentException( "The number of elements in the source Deque is greater " + "than the available space from index to the end of the " + "destination array."); } #endregion int i = index; foreach (object obj in this) { array.SetValue(obj, i); i++; } } /// <summary> /// Gets an object that can be used to synchronize access to the Deque. /// </summary> public virtual object SyncRoot => this; #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that can iterate through the Deque. /// </summary> /// <returns> /// An IEnumerator for the Deque. /// </returns> public virtual IEnumerator GetEnumerator() { return new DequeEnumerator(this); } #endregion #region ICloneable Members /// <summary> /// Creates a shallow copy of the Deque. /// </summary> /// <returns> /// A shallow copy of the Deque. /// </returns> public virtual object Clone() { Deque clone = new Deque(this) { version = version }; return clone; } #endregion } }
25.061043
98
0.445438
3de102f5918f0949878be1908734b43f32e3f76a
8,661
cs
C#
sdk/src/Services/EC2/Generated/Model/ServiceDetail.cs
sudoudaisuke/aws-sdk-net
cadac9b1488084bcfe6de18aff02aaaf41e30292
[ "Apache-2.0" ]
2
2022-02-24T09:39:37.000Z
2022-02-24T11:20:07.000Z
sdk/src/Services/EC2/Generated/Model/ServiceDetail.cs
sudoudaisuke/aws-sdk-net
cadac9b1488084bcfe6de18aff02aaaf41e30292
[ "Apache-2.0" ]
null
null
null
sdk/src/Services/EC2/Generated/Model/ServiceDetail.cs
sudoudaisuke/aws-sdk-net
cadac9b1488084bcfe6de18aff02aaaf41e30292
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes a VPC endpoint service. /// </summary> public partial class ServiceDetail { private bool? _acceptanceRequired; private List<string> _availabilityZones = new List<string>(); private List<string> _baseEndpointDnsNames = new List<string>(); private bool? _managesVpcEndpoints; private string _owner; private string _privateDnsName; private DnsNameState _privateDnsNameVerificationState; private string _serviceId; private string _serviceName; private List<ServiceTypeDetail> _serviceType = new List<ServiceTypeDetail>(); private List<Tag> _tags = new List<Tag>(); private bool? _vpcEndpointPolicySupported; /// <summary> /// Gets and sets the property AcceptanceRequired. /// <para> /// Indicates whether VPC endpoint connection requests to the service must be accepted /// by the service owner. /// </para> /// </summary> public bool AcceptanceRequired { get { return this._acceptanceRequired.GetValueOrDefault(); } set { this._acceptanceRequired = value; } } // Check to see if AcceptanceRequired property is set internal bool IsSetAcceptanceRequired() { return this._acceptanceRequired.HasValue; } /// <summary> /// Gets and sets the property AvailabilityZones. /// <para> /// The Availability Zones in which the service is available. /// </para> /// </summary> public List<string> AvailabilityZones { get { return this._availabilityZones; } set { this._availabilityZones = value; } } // Check to see if AvailabilityZones property is set internal bool IsSetAvailabilityZones() { return this._availabilityZones != null && this._availabilityZones.Count > 0; } /// <summary> /// Gets and sets the property BaseEndpointDnsNames. /// <para> /// The DNS names for the service. /// </para> /// </summary> public List<string> BaseEndpointDnsNames { get { return this._baseEndpointDnsNames; } set { this._baseEndpointDnsNames = value; } } // Check to see if BaseEndpointDnsNames property is set internal bool IsSetBaseEndpointDnsNames() { return this._baseEndpointDnsNames != null && this._baseEndpointDnsNames.Count > 0; } /// <summary> /// Gets and sets the property ManagesVpcEndpoints. /// <para> /// Indicates whether the service manages its VPC endpoints. Management of the service /// VPC endpoints using the VPC endpoint API is restricted. /// </para> /// </summary> public bool ManagesVpcEndpoints { get { return this._managesVpcEndpoints.GetValueOrDefault(); } set { this._managesVpcEndpoints = value; } } // Check to see if ManagesVpcEndpoints property is set internal bool IsSetManagesVpcEndpoints() { return this._managesVpcEndpoints.HasValue; } /// <summary> /// Gets and sets the property Owner. /// <para> /// The AWS account ID of the service owner. /// </para> /// </summary> 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; } /// <summary> /// Gets and sets the property PrivateDnsName. /// <para> /// The private DNS name for the service. /// </para> /// </summary> public string PrivateDnsName { get { return this._privateDnsName; } set { this._privateDnsName = value; } } // Check to see if PrivateDnsName property is set internal bool IsSetPrivateDnsName() { return this._privateDnsName != null; } /// <summary> /// Gets and sets the property PrivateDnsNameVerificationState. /// <para> /// The verification state of the VPC endpoint service. /// </para> /// /// <para> /// Consumers of the endpoint service cannot use the private name when the state is not /// <code>verified</code>. /// </para> /// </summary> public DnsNameState PrivateDnsNameVerificationState { get { return this._privateDnsNameVerificationState; } set { this._privateDnsNameVerificationState = value; } } // Check to see if PrivateDnsNameVerificationState property is set internal bool IsSetPrivateDnsNameVerificationState() { return this._privateDnsNameVerificationState != null; } /// <summary> /// Gets and sets the property ServiceId. /// <para> /// The ID of the endpoint service. /// </para> /// </summary> public string ServiceId { get { return this._serviceId; } set { this._serviceId = value; } } // Check to see if ServiceId property is set internal bool IsSetServiceId() { return this._serviceId != null; } /// <summary> /// Gets and sets the property ServiceName. /// <para> /// The Amazon Resource Name (ARN) of the service. /// </para> /// </summary> public string ServiceName { get { return this._serviceName; } set { this._serviceName = value; } } // Check to see if ServiceName property is set internal bool IsSetServiceName() { return this._serviceName != null; } /// <summary> /// Gets and sets the property ServiceType. /// <para> /// The type of service. /// </para> /// </summary> public List<ServiceTypeDetail> ServiceType { get { return this._serviceType; } set { this._serviceType = value; } } // Check to see if ServiceType property is set internal bool IsSetServiceType() { return this._serviceType != null && this._serviceType.Count > 0; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Any tags assigned to the service. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property VpcEndpointPolicySupported. /// <para> /// Indicates whether the service supports endpoint policies. /// </para> /// </summary> public bool VpcEndpointPolicySupported { get { return this._vpcEndpointPolicySupported.GetValueOrDefault(); } set { this._vpcEndpointPolicySupported = value; } } // Check to see if VpcEndpointPolicySupported property is set internal bool IsSetVpcEndpointPolicySupported() { return this._vpcEndpointPolicySupported.HasValue; } } }
31.725275
101
0.574876
3de811f64a3cadc2b5ecd008cf468c8497596b28
4,950
cs
C#
ToMigrate/Raven.Tests/Bugs/TransformerThatReturnAnArray.cs
ryanheath/ravendb
f32ee65b73912aa1532929164d004e027d266270
[ "Linux-OpenIB" ]
1
2017-03-02T13:05:14.000Z
2017-03-02T13:05:14.000Z
ToMigrate/Raven.Tests/Bugs/TransformerThatReturnAnArray.cs
ryanheath/ravendb
f32ee65b73912aa1532929164d004e027d266270
[ "Linux-OpenIB" ]
1
2019-03-12T12:10:52.000Z
2019-03-12T12:10:52.000Z
ToMigrate/Raven.Tests/Bugs/TransformerThatReturnAnArray.cs
aviv86/ravendb
3ee33d576fecd2c47dc7a9f5b671a46731fed659
[ "Linux-OpenIB" ]
null
null
null
using System.Collections.Generic; using System.Linq; using Raven.Client; using Raven.Client.Indexes; using Raven.Tests.Common; using Xunit; namespace Raven.Tests.Bugs { public class TransformerThatReturnAnArray : RavenTest { [Fact] public void ShouldReturnNullForNotExistDocument() { using (var store = NewDocumentStore()) { new BigContainerReferenceTransformer().Execute(store); using (var session = store.OpenSession()) { StoreSampleData(session); session.SaveChanges(); } using (var session = store.OpenSession()) { var existId = session.Load<BigContainerReferenceTransformer, BigContainer[]>("BigContainer1"); Assert.Equal(4, existId.Length); // It should return null rather then an empty array, so the user can distinguish between a not exist document and an empty result of a transformer function. var notExistId = session.Load<BigContainerReferenceTransformer, BigContainer[]>("BigContainerThatDoesNotExist"); Assert.Null(notExistId); } } } public class BigContainer { public string Id { get; set; } public IList<SmallContainer> SmallContainers { get; set; } } public class SmallContainer { public Reference Reference { get; set; } } public class Reference { public string BigContainerId { get; set; } } public class BigContainerReferenceTransformer : AbstractTransformerCreationTask<BigContainer> { public BigContainerReferenceTransformer() { TransformResults = bigContainers => bigContainers .SelectMany(bigContainer => Recurse(bigContainer, bigContainerRecurse => bigContainerRecurse.SmallContainers .Where(smallContainer => smallContainer.Reference != null) .Select(smallContainer => LoadDocument<BigContainer>(smallContainer.Reference.BigContainerId)))); } } public static void StoreSampleData(IDocumentSession documentSession) { documentSession.Store(new BigContainer { Id = "BigContainer1", SmallContainers = new[] { new SmallContainer { Reference = new Reference { BigContainerId = "BigContainer2" } } } }); documentSession.Store(new BigContainer { Id = "BigContainer2", SmallContainers = new[] { new SmallContainer { Reference = new Reference { BigContainerId = "BigContainer3" } }, new SmallContainer { Reference = new Reference { BigContainerId = "BigContainer4" } } } }); documentSession.Store(new BigContainer { Id = "BigContainer3", SmallContainers = new[] { new SmallContainer() } }); documentSession.Store(new BigContainer { Id = "BigContainer4", SmallContainers = new[] { new SmallContainer { Reference = new Reference { BigContainerId = "BigContainer1" } } } }); documentSession.Store(new BigContainer { Id = "BigContainer5", SmallContainers = new[] { new SmallContainer { Reference = new Reference { BigContainerId = "BigContainer1" } } } }); } } }
34.137931
210
0.420808
3deb7f862070bf08e0411900cf620e94d527c409
18,716
cs
C#
Web/Db/Enums/PpeTypes.cs
WeAreBeep/FrontlineUkraine
9ace8222af347f8ebbcaf444f375b2736f49cd9f
[ "MIT" ]
null
null
null
Web/Db/Enums/PpeTypes.cs
WeAreBeep/FrontlineUkraine
9ace8222af347f8ebbcaf444f375b2736f49cd9f
[ "MIT" ]
null
null
null
Web/Db/Enums/PpeTypes.cs
WeAreBeep/FrontlineUkraine
9ace8222af347f8ebbcaf444f375b2736f49cd9f
[ "MIT" ]
null
null
null
using System.Collections.Generic; using System.Collections.Immutable; using Web.Snippets.System; namespace Web.Db { public enum PpeTypes { [EnumText("Type IIR Surgical Masks")] TypeIIRSurgicalMasks = 1, [EnumText("FFP1 Respirator Masks")] FFP1RespiratorMasks, [EnumText("FFP2 Respirator Masks")] FFP2RespiratorMasks, [EnumText("FFP3 Respirator Masks")] FFP3RespiratorMasks, Gowns, Aprons, Gloves, Scrubs, SafetyGlasses, FaceVisors, AlcoholHandGel, [EnumText("Other...")] Other, // Domestic - Sanitary [EnumText("Sanitary Towels (Tampons/Pads)")] DomesticSanitarySanitaryTowels, [EnumText("Nappies Size 0 (1-2.5kg, 2-5lbs")] DomesticSanitaryNappiesSize0, [EnumText("Nappies Size 1 (2 -5kg, 5-11lbs")] DomesticSanitaryNappiesSize1, [EnumText("Nappies Size 2 (3-6kg, 7-14lbs")] DomesticSanitaryNappiesSize2, [EnumText("Nappies Size 3 (4-9kg, 8-20lbs")] DomesticSanitaryNappiesSize3, [EnumText("Nappies Size 4 (7-18kg, 15-40lbs")] DomesticSanitaryNappiesSize4, [EnumText("Nappies Size 5 (11-25kg, 24-55lbs")] DomesticSanitaryNappiesSize5, [EnumText("Nappies Size 6 (16kg +, 35lbs +)")] DomesticSanitaryNappiesSize6, [EnumText("Breast pads (for breastfeeding mothers)")] DomesticSanitaryBreastPads, [EnumText("Hairbrushes")] DomesticSanitaryHairbrushes, [EnumText("Liquid soap/ Shampoo")] DomesticSanitaryLiquidSoap, [EnumText("Wet wipes (adults/children)")] DomesticSanitaryWetWipes, [EnumText("Toothbrushes")] DomesticSanitaryToothbrushes, [EnumText("Toothpaste")] DomesticSanitaryToothpaste, [EnumText("Towels")] DomesticSanitaryTowels, [EnumText("Toilet paper")] DomesticSanitaryToiletPaper, [EnumText("Pocket tissues")] DomesticSanitaryPocketTissues, [EnumText("Shaving gels and razors")] DomesticSanitaryShavingGelRazors, [EnumText("Other sanitary products")] DomesticSanitaryOther, // Domestic - Non perishable food/ drink [EnumText("Protein bars")] DomesticNonPerishableFoodDrinkProteinBars, [EnumText("Canned food")] DomesticNonPerishableFoodDrinkCannedFood, [EnumText("Dry food (i.e.: rice, pasta, nuts, dried fruit) / Fast cooking grains (couscous)")] DomesticNonPerishableFoodDrinkDryFood, [EnumText("Instant food (i.e.: Cup-a-soups)")] DomesticNonPerishableFoodDrinkInstantFood, [EnumText("Baby food (i.e.: powdered milk, ready-meal pouches)")] DomesticNonPerishableFoodDrinkBabyFood, [EnumText("Energy drinks")] DomesticNonPerishableFoodDrinkEnergyDrinks, [EnumText("Other (please specify)")] DomesticNonPerishableOther, // Domestic - Other [EnumText("Foil survival blankets")] DomesticOtherFoilSurvivalBlankets, [EnumText("Thermal clothing (new)")] DomesticOtherThermalClothingNew, [EnumText("Sleeping bags")] DomesticOtherSleepingBags, [EnumText("Bed (Hospital use)")] DomesticOtherBedHospital, [EnumText("Large/medium-sized backpacks")] DomesticOtherLargeOrMediumBackpacks, [EnumText("Power banks and charging cables")] DomesticOtherPowerBanksAndChargingCables, [EnumText("Torches with batteries/ Head torches (in sealed packs)")] DomesticOtherTorches, [EnumText("Electricity generators")] DomesticOtherElectricityGenerators, [EnumText("Boot driers")] DomesticOtherBootDriers, [EnumText("Hot water bottles")] DomesticOtherHotWaterBottles, [EnumText("Insulated flasks")] DomesticOtherInsulatedFlasks, [EnumText("Disposable tableware (cup, plates, cutlery)")] DomesticOtherDisposableTableware, [EnumText("Cooking stoves (without gas)")] DomesticOtherCookingStoves, [EnumText("Bin bags")] DomesticOtherBinBags, [EnumText("Other basics")] DomesticOtherOther, // (Non Drug) Medical Supplies - Equipment [EnumText("PATIENT MONITOR, w/CO2 IBP ECG NIBP TEMP, SPO2, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentPatientMonitor, [EnumText("ANAESTHESIA MACHINE, closed-circuit, trolley, w/acc")] NonDrugMedicalSuppliesMedicalEquipmentAnaesthesiaMachine, [EnumText("ECG RECORDER, portable, 12 leads, with printer and access")] NonDrugMedicalSuppliesMedicalEquipmentECGRecorder, [EnumText("DEFIBRILLATOR, AED, w/access")] NonDrugMedicalSuppliesMedicalEquipmentDefibrillator, [EnumText("SYRINGE PUMP, single-channel, AC and battery-powered, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentSyringePump, [EnumText("INFUSION PUMP, LCD, flow 0.1-1500mL/h, 220V, batt., w/acc")] NonDrugMedicalSuppliesMedicalEquipmentInfusionPump, [EnumText("EXAMINATION LIGHT, Led, overhead, mobile, adjustable, on wheels")] NonDrugMedicalSuppliesMedicalEquipmentExaminationLightLed, [EnumText("PUMP, SUCTION, FOOT-OPERATED, with tubes and connector")] NonDrugMedicalSuppliesMedicalEquipmentFootOperatedSuctionPump, [EnumText("PATIENT VENTILATOR, intensive care, for adult and paediatric, with breathing circuits and patient interface (TYPE 2)")] NonDrugMedicalSuppliesMedicalEquipmentPatientVentilator, [EnumText("SCANNER, ULTRASOUND, mobile, w/access")] NonDrugMedicalSuppliesMedicalEquipmentMobileUltrasoundScanner, [EnumText("SELF-INFLATING BAG SET, self-refilling, capacity > 1500 m adult + 3 masks (S, M, L)")] NonDrugMedicalSuppliesMedicalEquipmentSelfInflatingBagSet, [EnumText("CAPNOMETER portable, EtCO2/RR monitoring, AAA battery, w/acc.")] NonDrugMedicalSuppliesMedicalEquipmentCapnometer, [EnumText("X-RAY UNIT BASIC, mobile")] NonDrugMedicalSuppliesMedicalEquipmentXRayUnit, [EnumText("SURGICAL DRILL, cordless +accessories + drill bit")] NonDrugMedicalSuppliesMedicalEquipmentSurgicalDrill, [EnumText("DERMATOME, ELECTRICAL with battery + access.")] NonDrugMedicalSuppliesMedicalEquipmentDermatome, [EnumText("LEG TRACTION SPLINT, pre-hospital care and transport")] NonDrugMedicalSuppliesMedicalEquipmentLegTractionSplint, [EnumText("OTHER (please specify)")] NonDrugMedicalSuppliesMedicalEquipmentOther, // (Non Drug) Medical Supplies - Consumables [EnumText("Medical tourniquets")] NonDrugMedicalSuppliesConsumablesMedicalTourniquets, [EnumText("First aid kits (bandages, plasters, antiseptic creams, burn gels, micropore tape)")] NonDrugMedicalSuppliesConsumablesFirstAidKits, [EnumText("Viral bacterial filters & circuits for mechanical ventilation")] NonDrugMedicalSuppliesConsumablesViralBacteriaFilter, [EnumText("CENTRAL VENOUS CATHETERS, Y and straight needle, triple lumen")] NonDrugMedicalSuppliesConsumablesCentralVenousCatheters, [EnumText("SET, INTRAOSSEOUS INFUSION KIT, w/ needles and IV set")] NonDrugMedicalSuppliesConsumablesSetIntraosseousInfusionKit, [EnumText("SET, INFUSION, adult, sterile, s.u.")] NonDrugMedicalSuppliesConsumablesSetInfusionAdult, [EnumText("SET, INFUSION, paediatric, precision, sterile, s.u.")] NonDrugMedicalSuppliesConsumablesSetInfusionPaediatric, [EnumText("DRAIN, THORACIC, INSERTION-SET, complete, sterile, disposable")] NonDrugMedicalSuppliesConsumablesDrainThoracicInsertionSet, [EnumText("Insulin syringes/needles")] NonDrugMedicalSuppliesConsumablesInsulinSyringes, [EnumText("Syringe pens for diabetics")] NonDrugMedicalSuppliesConsumablesSyringePensDiabetics, [EnumText("Glucometers with test strips")] NonDrugMedicalSuppliesConsumablesGlucometers, [EnumText("X-ray cartridges")] NonDrugMedicalSuppliesConsumablesXRayCartridges, [EnumText("[(Non Drug) Medical Supplies - Consumables] OTHER (please specify)")] NonDrugMedicalSuppliesConsumablesOther, // (Non Drug) Medical Supplies - Surgical Instruments & Fixators [EnumText("SET, GENERAL SURGERY INSTRUMENTS, BASIC SURGERY")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsBasicSurgery, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DRESSING")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDressing, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, CRANIOTOMY,")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsCraniotomy, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, LAPAROTOMY, + caesarean")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsLaparotomyAndCaesarean, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DPC (suture)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDPCSuture, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, DEBRIDEMENT")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDebridement, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, SKIN GRAFT")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsSkinGraft, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, FINE (paediatrics)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsFinePaediatrics, [EnumText("SET, GENERAL SURGERY INSTRUMENTS, THORACOTOMY, complementary")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsThoracotomyComplementary, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, AMPUTATION")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsAmputation, [EnumText("SET, ORTHO.SURGERY INSTRUMENTS, BASIC BONE SURGERY")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgery, [EnumText("SET, ORTHO.SURGERY INSTRUMENTS, BASIC BONE SURGERY, curettes")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgeryCurettes, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, BONE WIRING and KIRSHNER")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBoneWiringAndKirshner, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, PLASTER CASTS REMOVAL")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsPlasterCastsRemoval, [EnumText("SET, ORTHO. SURGERY INSTRUMENTS, TRACTION, + 10 bows")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsTractionPlusTenBows, [EnumText("SET, EXTERNAL FIXATION, LARGE, FIXATORS & INSTRUMENTS")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetExternalFixationLargeFixatorsAndInstruments, [EnumText("OTHER (please specify)")] NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther } public static class PpeTypesEnumExtension { private static List<PpeTypes> OTHER_PPE_TYPES = new List<PpeTypes> { PpeTypes.Other, PpeTypes.DomesticSanitaryOther, PpeTypes.DomesticNonPerishableOther, PpeTypes.DomesticOtherOther, PpeTypes.NonDrugMedicalSuppliesConsumablesOther, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentOther, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther }; public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticSanitary = new HashSet<PpeTypes> { PpeTypes.DomesticSanitarySanitaryTowels, PpeTypes.DomesticSanitaryNappiesSize0, PpeTypes.DomesticSanitaryNappiesSize1, PpeTypes.DomesticSanitaryNappiesSize2, PpeTypes.DomesticSanitaryNappiesSize3, PpeTypes.DomesticSanitaryNappiesSize4, PpeTypes.DomesticSanitaryNappiesSize5, PpeTypes.DomesticSanitaryNappiesSize6, PpeTypes.DomesticSanitaryBreastPads, PpeTypes.DomesticSanitaryHairbrushes, PpeTypes.DomesticSanitaryLiquidSoap, PpeTypes.DomesticSanitaryWetWipes, PpeTypes.DomesticSanitaryToothbrushes, PpeTypes.DomesticSanitaryToothpaste, PpeTypes.DomesticSanitaryTowels, PpeTypes.DomesticSanitaryToiletPaper, PpeTypes.DomesticSanitaryPocketTissues, PpeTypes.DomesticSanitaryShavingGelRazors, PpeTypes.DomesticSanitaryOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticNonPerishableFoodDrink = new HashSet<PpeTypes> { PpeTypes.DomesticNonPerishableFoodDrinkProteinBars, PpeTypes.DomesticNonPerishableFoodDrinkCannedFood, PpeTypes.DomesticNonPerishableFoodDrinkDryFood, PpeTypes.DomesticNonPerishableFoodDrinkInstantFood, PpeTypes.DomesticNonPerishableFoodDrinkBabyFood, PpeTypes.DomesticNonPerishableFoodDrinkEnergyDrinks, PpeTypes.DomesticNonPerishableOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryDomesticOther = new HashSet<PpeTypes> { PpeTypes.DomesticOtherFoilSurvivalBlankets, PpeTypes.DomesticOtherThermalClothingNew, PpeTypes.DomesticOtherSleepingBags, PpeTypes.DomesticOtherBedHospital, PpeTypes.DomesticOtherLargeOrMediumBackpacks, PpeTypes.DomesticOtherPowerBanksAndChargingCables, PpeTypes.DomesticOtherTorches, PpeTypes.DomesticOtherElectricityGenerators, PpeTypes.DomesticOtherBootDriers, PpeTypes.DomesticOtherHotWaterBottles, PpeTypes.DomesticOtherInsulatedFlasks, PpeTypes.DomesticOtherDisposableTableware, PpeTypes.DomesticOtherCookingStoves, PpeTypes.DomesticOtherBinBags, PpeTypes.DomesticOtherOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesEquip = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentPatientMonitor, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentAnaesthesiaMachine, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentECGRecorder, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentDefibrillator, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSyringePump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentInfusionPump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentExaminationLightLed, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentFootOperatedSuctionPump, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentPatientVentilator, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentMobileUltrasoundScanner, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSelfInflatingBagSet, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentCapnometer, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentXRayUnit, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentSurgicalDrill, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentDermatome, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentLegTractionSplint, PpeTypes.NonDrugMedicalSuppliesMedicalEquipmentOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesConsumable = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesConsumablesMedicalTourniquets, PpeTypes.NonDrugMedicalSuppliesConsumablesFirstAidKits, PpeTypes.NonDrugMedicalSuppliesConsumablesViralBacteriaFilter, PpeTypes.NonDrugMedicalSuppliesConsumablesCentralVenousCatheters, PpeTypes.NonDrugMedicalSuppliesConsumablesSetIntraosseousInfusionKit, PpeTypes.NonDrugMedicalSuppliesConsumablesSetInfusionAdult, PpeTypes.NonDrugMedicalSuppliesConsumablesSetInfusionPaediatric, PpeTypes.NonDrugMedicalSuppliesConsumablesDrainThoracicInsertionSet, PpeTypes.NonDrugMedicalSuppliesConsumablesInsulinSyringes, PpeTypes.NonDrugMedicalSuppliesConsumablesSyringePensDiabetics, PpeTypes.NonDrugMedicalSuppliesConsumablesGlucometers, PpeTypes.NonDrugMedicalSuppliesConsumablesXRayCartridges, PpeTypes.NonDrugMedicalSuppliesConsumablesOther, }.ToImmutableHashSet(); public static ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesSurgicalInstrumentsAndFixators = new HashSet<PpeTypes> { PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsBasicSurgery, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDressing, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsCraniotomy, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsLaparotomyAndCaesarean, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDPCSuture, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsDebridement, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsSkinGraft, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsFinePaediatrics, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetGeneralSurgeryInstrumentsThoracotomyComplementary, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsAmputation, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgery, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBasicBoneSurgeryCurettes, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsBoneWiringAndKirshner, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsPlasterCastsRemoval, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetOrthoSurgeryInstrumentsTractionPlusTenBows, PpeTypes .NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsSetExternalFixationLargeFixatorsAndInstruments, PpeTypes.NonDrugMedicalSuppliesSurgicalInstrumentsAndFixatorsOther, }.ToImmutableHashSet(); public static readonly ImmutableHashSet<PpeTypes> CategoryNonDrugMedicalSuppliesPpe = new HashSet<PpeTypes> { PpeTypes.TypeIIRSurgicalMasks, PpeTypes.FFP1RespiratorMasks, PpeTypes.FFP2RespiratorMasks, PpeTypes.FFP3RespiratorMasks, PpeTypes.Gowns, PpeTypes.Aprons, PpeTypes.Gloves, PpeTypes.Scrubs, PpeTypes.SafetyGlasses, PpeTypes.FaceVisors, PpeTypes.AlcoholHandGel, PpeTypes.Other, }.ToImmutableHashSet(); public static readonly List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> DomesticCategories = new List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> { (Name: "SANITARY PRODUCTS", CategorySet: CategoryDomesticSanitary), (Name: "NON-PERISHABLE FOOD/DRINK", CategorySet: CategoryDomesticNonPerishableFoodDrink), (Name: "OTHER BASICS / SHELTER EQUIPMENT", CategorySet: CategoryDomesticOther), }; public static readonly List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> NonDrugMedicalSuppliesCategory = new List<(string Name, ImmutableHashSet<PpeTypes> CategorySet)> { (Name: "MEDICAL EQUIPMENT", CategorySet: CategoryNonDrugMedicalSuppliesEquip), (Name: "CONSUMABLES", CategorySet: CategoryNonDrugMedicalSuppliesConsumable), (Name: "SURGICAL INSTRUMENTS & FIXATORS", CategorySet: CategoryNonDrugMedicalSuppliesSurgicalInstrumentsAndFixators), (Name: "PPE", CategorySet: CategoryNonDrugMedicalSuppliesPpe), }; public static bool IsOther(this PpeTypes ppeType) { return PpeTypesEnumExtension.OTHER_PPE_TYPES.Contains(ppeType); } } }
49.12336
181
0.831267
3dedead6804ba1bad2c9ab8e53fdce9805322657
4,856
cs
C#
src/Lucene.Net.Tests/Util/TestBytesRefArray.cs
Ref12/lucenenet
aaba4cee2482f2908439e2fac44d7d27e6e40af6
[ "Apache-2.0" ]
1
2020-08-31T09:28:21.000Z
2020-08-31T09:28:21.000Z
src/Lucene.Net.Tests/Util/TestBytesRefArray.cs
Ref12/lucenenet
aaba4cee2482f2908439e2fac44d7d27e6e40af6
[ "Apache-2.0" ]
null
null
null
src/Lucene.Net.Tests/Util/TestBytesRefArray.cs
Ref12/lucenenet
aaba4cee2482f2908439e2fac44d7d27e6e40af6
[ "Apache-2.0" ]
null
null
null
using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Util { /* * 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. */ [TestFixture] public class TestBytesRefArray : LuceneTestCase { [Test] public virtual void TestAppend() { Random random = Random; BytesRefArray list = new BytesRefArray(Util.Counter.NewCounter()); IList<string> stringList = new List<string>(); for (int j = 0; j < 2; j++) { if (j > 0 && random.NextBoolean()) { list.Clear(); stringList.Clear(); } int entries = AtLeast(500); BytesRef spare = new BytesRef(); int initSize = list.Length; for (int i = 0; i < entries; i++) { string randomRealisticUnicodeString = TestUtil.RandomRealisticUnicodeString(random); spare.CopyChars(randomRealisticUnicodeString); Assert.AreEqual(i + initSize, list.Append(spare)); stringList.Add(randomRealisticUnicodeString); } for (int i = 0; i < entries; i++) { Assert.IsNotNull(list.Get(spare, i)); Assert.AreEqual(stringList[i], spare.Utf8ToString(), "entry " + i + " doesn't match"); } // check random for (int i = 0; i < entries; i++) { int e = random.Next(entries); Assert.IsNotNull(list.Get(spare, e)); Assert.AreEqual(stringList[e], spare.Utf8ToString(), "entry " + i + " doesn't match"); } for (int i = 0; i < 2; i++) { IBytesRefIterator iterator = list.GetIterator(); foreach (string @string in stringList) { Assert.AreEqual(@string, iterator.Next().Utf8ToString()); } } } } [Test] public virtual void TestSort() { Random random = Random; BytesRefArray list = new BytesRefArray(Util.Counter.NewCounter()); List<string> stringList = new List<string>(); for (int j = 0; j < 2; j++) { if (j > 0 && random.NextBoolean()) { list.Clear(); stringList.Clear(); } int entries = AtLeast(500); BytesRef spare = new BytesRef(); int initSize = list.Length; for (int i = 0; i < entries; i++) { string randomRealisticUnicodeString = TestUtil.RandomRealisticUnicodeString(random); spare.CopyChars(randomRealisticUnicodeString); Assert.AreEqual(initSize + i, list.Append(spare)); stringList.Add(randomRealisticUnicodeString); } // LUCENENET NOTE: Must sort using ArrayUtil.GetNaturalComparator<T>() // to ensure culture isn't taken into consideration during the sort, // which will match the sort order of BytesRef.UTF8SortedAsUTF16Comparer. CollectionUtil.TimSort(stringList); #pragma warning disable 612, 618 IBytesRefIterator iter = list.GetIterator(BytesRef.UTF8SortedAsUTF16Comparer); #pragma warning restore 612, 618 int a = 0; while ((spare = iter.Next()) != null) { Assert.AreEqual(stringList[a], spare.Utf8ToString(), "entry " + a + " doesn't match"); a++; } Assert.IsNull(iter.Next()); Assert.AreEqual(a, stringList.Count); } } } }
41.152542
106
0.524506