content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Microsoft.Maui.Hosting.Internal { internal class AppHost : IHost, IAsyncDisposable { readonly ILogger<AppHost>? _logger; public AppHost(IServiceProvider services, ILogger<AppHost>? logger) { Services = services ?? throw new ArgumentNullException(nameof(services)); _logger = logger; } public IServiceProvider Services { get; } public async Task StartAsync(CancellationToken cancellationToken = default) { _logger?.Starting(); await Task.Run(() => { }); _logger?.Started(); } public async Task StopAsync(CancellationToken cancellationToken = default) { _logger?.Stopping(); _ = await Task.FromResult(new object()); _logger?.Stopped(); } public void Dispose() => DisposeAsync().AsTask().GetAwaiter().GetResult(); public async ValueTask DisposeAsync() { switch (Services) { case IAsyncDisposable asyncDisposable: await asyncDisposable.DisposeAsync().ConfigureAwait(false); break; case IDisposable disposable: disposable.Dispose(); break; } } } }
21.818182
77
0.7125
[ "MIT" ]
pictos/maui
src/Core/src/Hosting/Internal/AppHost.cs
1,200
C#
using Avalonia.Markup.Xaml; using nkyUI.Controls; using nkyUI.Demo.Helpers; using nkyUI.Demo.VM; namespace nkyUI.Demo { public class MainWindow : KYUIWindow, IWindowView { public MainWindow() { this.InitializeComponent(); DataContext = new MainWindowVM(); App.AttachDevTools(this); (DataContext as WindowViewModel).View = this; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } public KYUIWindow Window => this; } }
22.76
57
0.601054
[ "Apache-2.0" ]
0xFireball/nkyUI
nkyUI/nkyUI.Demo/MainWindow.xaml.cs
571
C#
using System.Collections.Generic; using System.Management; namespace WindowsMonitor.Hardware.Sensors { /// <summary> /// </summary> public sealed class CollectionOfSensors { public string GroupComponent { get; private set; } public string PartComponent { get; private set; } public static IEnumerable<CollectionOfSensors> Retrieve(string remote, string username, string password) { var options = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, Username = username, Password = password }; var managementScope = new ManagementScope(new ManagementPath($"\\\\{remote}\\root\\cimv2"), options); managementScope.Connect(); return Retrieve(managementScope); } public static IEnumerable<CollectionOfSensors> Retrieve() { var managementScope = new ManagementScope(new ManagementPath("root\\cimv2")); return Retrieve(managementScope); } public static IEnumerable<CollectionOfSensors> Retrieve(ManagementScope managementScope) { var objectQuery = new ObjectQuery("SELECT * FROM CIM_CollectionOfSensors"); var objectSearcher = new ManagementObjectSearcher(managementScope, objectQuery); var objectCollection = objectSearcher.Get(); foreach (ManagementObject managementObject in objectCollection) yield return new CollectionOfSensors { GroupComponent = (string) (managementObject.Properties["GroupComponent"]?.Value ?? default(string)), PartComponent = (string) (managementObject.Properties["PartComponent"]?.Value ?? default(string)) }; } } }
37.9375
121
0.640857
[ "MIT" ]
Biztactix/WindowsMonitor
WindowsMonitor.Standard/Hardware/Sensors/CollectionOfSensors.cs
1,821
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20160330.Inputs { /// <summary> /// Frontend Port of application gateway /// </summary> public sealed class ApplicationGatewayFrontendPortArgs : Pulumi.ResourceArgs { /// <summary> /// A unique read-only string that changes whenever the resource is updated /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// Resource Id /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Gets name of the resource that is unique within a resource group. This name can be used to access the resource /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// Gets or sets the frontend port /// </summary> [Input("port")] public Input<int>? Port { get; set; } /// <summary> /// Gets or sets Provisioning state of the frontend port resource Updating/Deleting/Failed /// </summary> [Input("provisioningState")] public Input<string>? ProvisioningState { get; set; } public ApplicationGatewayFrontendPortArgs() { } } }
30.037736
122
0.599874
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20160330/Inputs/ApplicationGatewayFrontendPortArgs.cs
1,592
C#
using System; namespace Org.BouncyCastle.Bcpg.OpenPgp { /// <remarks>A list of PGP signatures - normally in the signature block after literal data.</remarks> public class PgpSignatureList : PgpObject { private PgpSignature[] sigs; public PgpSignatureList( PgpSignature[] sigs) { this.sigs = (PgpSignature[]) sigs.Clone(); } public PgpSignatureList( PgpSignature sig) { this.sigs = new PgpSignature[]{ sig }; } public PgpSignature this[int index] { get { return sigs[index]; } } [Obsolete("Use 'object[index]' syntax instead")] public PgpSignature Get( int index) { return this[index]; } [Obsolete("Use 'Count' property instead")] public int Size { get { return sigs.Length; } } public int Count { get { return sigs.Length; } } public bool IsEmpty { get { return (sigs.Length == 0); } } } }
20.25
103
0.54321
[ "BSD-3-Clause" ]
GaloisInc/hacrypto
src/C#/BouncyCastle/BouncyCastle-1.7/crypto/src/openpgp/PgpSignatureList.cs
1,053
C#
// Copyright © Serilog Contributors // // 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.IO; using Seq.App.HttpRequest.Expressions; namespace Seq.App.HttpRequest.Templates.Compilation { class CompiledExceptionToken : CompiledTemplate { public override void Evaluate(EvaluationContext ctx, TextWriter output) { // Padding and alignment are not applied by this renderer. if (ctx.LogEvent.Exception is null) return; var lines = new StringReader(ctx.LogEvent.Exception.ToString()); string? nextLine; while ((nextLine = lines.ReadLine()) != null) { output.WriteLine(nextLine); } } } }
33.026316
79
0.668526
[ "Apache-2.0" ]
datalust/seq-app-http
src/Seq.App.HttpRequest/Templates/Compilation/CompiledExceptionToken.cs
1,258
C#
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class FB_Score { public string UserId; public string UserName; public string AppId; public string AppName; public int value; private Dictionary<FB_ProfileImageSize, Texture2D> profileImages = new Dictionary<FB_ProfileImageSize, Texture2D>(); public event Action<FB_Score> OnProfileImageLoaded = delegate {}; public string GetProfileUrl(FB_ProfileImageSize size) { return "https://graph.facebook.com/" + UserId + "/picture?type=" + size.ToString(); } public Texture2D GetProfileImage(FB_ProfileImageSize size) { if(profileImages.ContainsKey(size)) { return profileImages[size]; } else { return null; } } public void LoadProfileImage(FB_ProfileImageSize size) { if(GetProfileImage(size) != null) { Debug.LogWarning("Profile image already loaded, size: " + size); OnProfileImageLoaded(this); } switch(size) { case FB_ProfileImageSize.large: SA.Common.Util.Loader.LoadWebTexture(GetProfileUrl(size), OnLargeImageLoaded); break; case FB_ProfileImageSize.normal: SA.Common.Util.Loader.LoadWebTexture(GetProfileUrl(size), OnNormalImageLoaded); break; case FB_ProfileImageSize.small: SA.Common.Util.Loader.LoadWebTexture(GetProfileUrl(size), OnSmallImageLoaded); break; case FB_ProfileImageSize.square: SA.Common.Util.Loader.LoadWebTexture(GetProfileUrl(size), OnSquareImageLoaded); break; } Debug.Log("LOAD IMAGE URL: " + GetProfileUrl(size)); } //-------------------------------------- // EVENTS //-------------------------------------- private void OnSquareImageLoaded(Texture2D image) { if(this == null) {return;} if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.square)) { profileImages.Add(FB_ProfileImageSize.square, image); } OnProfileImageLoaded(this); } private void OnLargeImageLoaded(Texture2D image) { if(this == null) {return;} if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.large)) { profileImages.Add(FB_ProfileImageSize.large, image); } OnProfileImageLoaded(this); } private void OnNormalImageLoaded(Texture2D image) { if(this == null) {return;} if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.normal)) { profileImages.Add(FB_ProfileImageSize.normal, image); } OnProfileImageLoaded(this); } private void OnSmallImageLoaded(Texture2D image) { if(this == null) {return;} if(image != null && !profileImages.ContainsKey(FB_ProfileImageSize.small)) { profileImages.Add(FB_ProfileImageSize.small, image); } OnProfileImageLoaded(this); } }
24.697248
118
0.712481
[ "MIT" ]
KingOfFawns/Special_Course
Special Course/Assets/Plugins/StansAssets/Modules/AndroidNative/Scripts/Social/Facebook/Models/FB_Score.cs
2,692
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FileHelpers; namespace patch_table_builder.model { [IgnoreFirst(1)] [DelimitedRecord(",")] class Patch { public string file_name { get; set; } public long file_size { get; set; } public string checksum { get; set; } public long compressed_file_size { get; set; } public string compressed_checksum { get; set; } public int acquire_on_demand { get; set; } public int compressed { get; set; } public string platform { get; set; } public string tag { get; set; } public string unused { get; set; } } }
26.777778
55
0.636238
[ "BSD-2-Clause" ]
samnyan/DMTQ-Tools
patch_table_builder/model/Patch.cs
725
C#
//<unit_header> //---------------------------------------------------------------- // // Martin Korneffel: IT Beratung/Softwareentwicklung // Stuttgart, den 18.9.2015 // // Projekt.......: mko.BI // Name..........: ICrud.cs // Aufgabe/Fkt...: Allgemeine Einfüge und Löschoperationen auf Repositories // // // // //<unit_environment> //------------------------------------------------------------------ // Zielmaschine..: PC // Betriebssystem: Windows 7 mit .NET 4.5 // Werkzeuge.....: Visual Studio 2013 // Autor.........: Martin Korneffel (mko) // Version 1.0...: // // </unit_environment> // //<unit_history> //------------------------------------------------------------------ // // Version.......: 1.1 // Autor.........: Martin Korneffel (mko) // Datum.........: // Änderungen....: // //</unit_history> //</unit_header> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace mko.BI.Repositories.Interfaces { public interface ICrud<TBo, TBoId> { //---------------------------------------------------------------------------------------------------------------- // Einfügen, Löschen und Aktualisieren /// <summary> /// Erzeugt ein neues Entity. Kann bei der Implementierung eines Insert- Befehls /// eines Geschäftsobjektes eingesetzt werden, um z.B. den Schlüssel des Entities zu definieren /// </summary> /// <returns></returns> TBo CreateBo(); /// <summary> /// Hinzufügen eines Entity zu einer Entitycollection. Erst durch /// SubmitChanges wird das Entity der Datenbank hinzugefügt. /// </summary> /// <param name="entity"></param> void AddToCollection(TBo entity); /// <summary> /// Ein Entity für das Löschen in der EntityCollection markieren /// </summary> /// <param name="entity"></param> void RemoveFromCollection(TBo entity); /// <summary> /// Löschen des durch die ID definierten Entity /// </summary> /// <param name="id"></param> void RemoveFromCollection(TBoId id); /// <summary> /// Löschen aller Entities /// </summary> void RemoveAll(); /// <summary> /// Aktualisierungen am ORMContext mit der Datenbank abgleichen /// </summary> void SubmitChanges(); } }
27.285714
122
0.505437
[ "MIT" ]
mk-prg-net/mk-prg-net.lib
mko.BI/Repositories/Interfaces/deprecated/ICrud.cs
2,498
C#
/* * 2012 - 2016 Ted Spence, http://tedspence.com * License: http://www.apache.org/licenses/LICENSE-2.0 * Home page: https://github.com/tspence/CRTG * * This program uses icons from http://www.famfamfam.com/lab/icons/silk/ */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.IO; using CRTG.Common; using CRTG.Common.Interfaces; using System.ComponentModel; using CRTG.Common.Data; namespace CRTG.Charts { public class CrtgChart : IDisposable, INotifyPropertyChanged { private SensorDataCollection _raw_data; private List<SensorData> _filtered; private DateTime _min_date, _max_date; private decimal _min_value, _max_value; private double _range_in_seconds, _range_in_value; private Rectangle _chart_rect; #region Constructor public CrtgChart() { } #endregion #region Rendering Chart private Point PlotPoint(SensorData sensorData) { return new Point(GetTimePosition(sensorData.Time), GetValuePosition((double)sensorData.Value)); } private int GetValuePosition(double d) { double ypos = d / _range_in_value; return (int)(_chart_rect.Y + _chart_rect.Height - (ypos * _chart_rect.Height)); } private int GetTimePosition(DateTime time) { TimeSpan ts = time - _min_date; double xpos = ts.TotalSeconds / _range_in_seconds; return (int)(_chart_rect.X + (xpos * _chart_rect.Width)); } private void DrawToImage() { // Kick out if we just don't have anything worthwhile if (_width <= 0 || _height <= 0 || _sensor == null || _datastore == null) { return; } var start = DateTime.UtcNow; // Figure out window _max_date = DateTime.UtcNow; _min_date = _max_date; _chart_rect = new Rectangle() { X = 5, Y = 5, Width = _width - 10, Height = _height - 10 }; _min_value = decimal.MaxValue; _max_value = decimal.MinValue; _range_in_value = 100.0; // If there's an artificial limitation on the time window, use that instead if (_chartTimeframe == ViewTimeframe.AllTime) { if (_raw_data != null && _raw_data.Data.Count > 0) { _min_date = (from r in _raw_data.Data select r.Time).Min(); } else { _min_date = _max_date.AddHours(-1); } } else { _min_date = _max_date.AddMinutes(-(int)_chartTimeframe); } _range_in_seconds = (double)(_max_date - _min_date).TotalSeconds; // Filter data by time if (_raw_data == null) { _raw_data = _datastore.RetrieveData(_sensor, _min_date, _max_date, true); } _filtered = (from r in _raw_data.Data where r.Time > _min_date && r.Time < _max_date orderby r.Time ascending select r).ToList(); if (_filtered.Any()) { // Range checks and clamping _min_value = (from r in _filtered select r.Value).Min(); _max_value = (from r in _filtered select r.Value).Max(); if (_min_value > 0) _min_value = 0; if (_max_value < 0) _max_value = 0; // Increase the maximum slightly so we can see the peak if (_max_value > 0m) _max_value = _max_value * 1.03m; _range_in_value = (double)(_max_value - _min_value); } // New version of drawing code does it all ourselves Bitmap bmp = new Bitmap(_width, _height); Graphics g = Graphics.FromImage(bmp); g.FillRectangle(Brushes.White, new Rectangle(new Point(0, 0), new Size(_width, _height))); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //System.Diagnostics.Debug.WriteLine("Startup chart in " + (DateTime.UtcNow - start).ToString()); // We have a 5px border around each edge, and remember the positions Pen black = new Pen(Color.Black); g.DrawRectangle(black, _chart_rect); //System.Diagnostics.Debug.WriteLine("Rectangle in " + (DateTime.UtcNow - start).ToString()); // Only draw something if values make sense if (_range_in_value > 0 && _range_in_seconds > 0) { DrawGraphLines(g); //System.Diagnostics.Debug.WriteLine("GraphLines in " + (DateTime.UtcNow - start).ToString()); DrawSensorData(g); //System.Diagnostics.Debug.WriteLine("SensorData in " + (DateTime.UtcNow - start).ToString()); } // Save this to a temporary filename g.Dispose(); _chart_image = bmp; //System.Diagnostics.Debug.WriteLine("Updated chart in " + (DateTime.UtcNow - start).ToString()); Notify("ChartImage"); } private void DrawGraphLines(Graphics g) { DateTime start = DateTime.UtcNow; Pen graphline = new Pen(Color.DarkSlateGray); graphline.DashPattern = new float[] { 4, 4 }; Brush tb = new SolidBrush(Color.Black); Font graph_label = new Font(FontFamily.GenericSansSerif, 10.0f, FontStyle.Regular); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; //System.Diagnostics.Debug.WriteLine("Setup graphlines in " + (DateTime.UtcNow - start).ToString()); // Calculate number of grid lines to draw horizontally int gridline_scale = ChooseScale(); int pos = gridline_scale; while (pos < _range_in_value) { // Draw a dotted line at this position int ypos = GetValuePosition(pos); g.DrawLine(graphline, _chart_rect.Left, ypos, _chart_rect.Right, ypos); // Label the line g.DrawString(pos.ToString("#,##0"), graph_label, tb, _chart_rect.Left, ypos); // Move on to next line pos += gridline_scale; } //System.Diagnostics.Debug.WriteLine("Finish lines in " + (DateTime.UtcNow - start).ToString()); // Now let's do some vertical gridlines string date_time_format = null; int time_scale_in_seconds = ChooseTimeScale(out date_time_format); DateTime dtpos = _min_date.AddSeconds(time_scale_in_seconds); dtpos = RoundDateTime(dtpos, time_scale_in_seconds); string current_date = null; //System.Diagnostics.Debug.WriteLine("Prep for text in " + (DateTime.UtcNow - start).ToString()); while (dtpos < _max_date) { // Draw a dotted line at this position int xpos = GetTimePosition(dtpos); g.DrawLine(graphline, xpos, _chart_rect.Top, xpos, _chart_rect.Bottom); // Label the line, based on whether the user wants to see local time or UTC string time_utc = dtpos.ToString("HH:mm:ss") + " UTC"; string time_local = dtpos.ToLocalTime().ToString("HH:mm:ss") + " Local"; string date = dtpos.ToString("yyyy-MM-dd"); var r = g.MeasureString(time_utc, graph_label); g.DrawString(time_local, graph_label, tb, xpos, _chart_rect.Bottom - r.Height); g.DrawString(time_utc, graph_label, tb, xpos, _chart_rect.Bottom - r.Height - r.Height); if (current_date != date) { g.DrawString(date, graph_label, tb, xpos, _chart_rect.Bottom - r.Height - r.Height - r.Height); current_date = date; } // Move on to next line dtpos = dtpos.AddSeconds(time_scale_in_seconds); } //System.Diagnostics.Debug.WriteLine("Finish graphlines in " + (DateTime.UtcNow - start).ToString()); } private DateTime RoundDateTime(DateTime dtpos, int time_scale_in_seconds) { TimeSpan span = new TimeSpan(0, 0, time_scale_in_seconds); long ticks = dtpos.Ticks / span.Ticks; return new DateTime(ticks * span.Ticks); } /// <summary> /// This list describes base scales in terms of seconds /// </summary> private static int[] TIME_OF_DAY_SCALE_VALUES = new int[] { 10, 30, 60, // seconds 60 * 2, 60 * 5, 60 * 10, 60 * 15, 60 * 20, 60 * 30, // 2 minutes - 30 minutes 3600, 3600 * 2, 3600 * 4, 3600 * 12, // 1 hour - 12 hours }; /// <summary> /// This list describes base scales in terms of days /// </summary> private static int[] DAY_OF_YEAR_SCALE_VALUES = new int[] { 86400, 86400 * 4, // 1 day - 4 days 604800 * 2, // 2 weeks 2592000, 2592000 * 6, // 1 month - 6 months }; private int ChooseTimeScale(out string date_time_format) { date_time_format = null; // Ideally, we'd like a vertical line every 200 pixels int vertical_lines = (int)(_chart_rect.Width / 200.0d); double base_scale = _range_in_seconds / vertical_lines; // What magnitude makes sense? First, let's try a few seconds-based times. date_time_format = "HH:mm:ss"; foreach (var scale in TIME_OF_DAY_SCALE_VALUES) { if (base_scale <= scale) { return scale; } } // From here on out, formatting is best done in days date_time_format = "yyyy-MM-dd"; foreach (var scale in DAY_OF_YEAR_SCALE_VALUES) { if (base_scale <= scale) { return scale; } } // Return maximum 1 year scale (365.25 days in seconds) return 31557600; } private int ChooseScale() { // How many lines should we have? At least one line every 40 pixels... int horizontal_lines = (int)(_chart_rect.Height / 40.0d); // Now that we know how many lines we want to have, what scale corresponds to that? double val = _range_in_value / (horizontal_lines + 1); // Now, let's make the scale human friendly... int magnitude = 1; while (true) { int scale = (int)val / magnitude; if (scale <= 1) { return 1 * magnitude; } else if (scale <= 2) { return 2 * magnitude; } else if (scale <= 5) { return 5 * magnitude; } else if (scale <= 10) { return 10 * magnitude; } else if (scale <= 20) { return 20 * magnitude; } else if (scale <= 50) { return 50 * magnitude; } else if (scale <= 100) { return 100 * magnitude; } else if (scale <= 200) { return 200 * magnitude; } else if (scale <= 500) { return 500 * magnitude; } // Scale up magnitude *= 1000; } } /// <summary> /// Draw all data from the sensors /// </summary> /// <param name="g"></param> private void DrawSensorData(Graphics g) { if (_filtered.Count > 0) { Pen blue = new Pen(Color.Blue, 2.5f); blue.LineJoin = System.Drawing.Drawing2D.LineJoin.Bevel; Point last_point = PlotPoint(_filtered[0]); for (int i = 1; i < _filtered.Count; i++) { Point p = PlotPoint(_filtered[i]); g.DrawLine(blue, last_point, p); last_point = p; } } } #endregion #region Member Properties /// <summary> /// Update both width and height so you don't force two draws for one change /// </summary> /// <param name="width"></param> /// <param name="height"></param> public void SetSize(int width, int height) { if ((width != _width) || (height != _height)) { _width = width; _height = height; DrawToImage(); } } /// <summary> /// Width of the chart in pixels /// </summary> public int Width { get { return _width; } set { _width = value; Notify("Width"); DrawToImage(); } } private int _width; /// <summary> /// Height of the chart in pixels /// </summary> public int Height { get { return _height; } set { _height = value; Notify("Height"); DrawToImage(); } } private int _height; /// <summary> /// Timeframe for the chart, relative to now /// </summary> public ViewTimeframe ChartTimeframe { get { return _chartTimeframe; } set { _chartTimeframe = value; Notify("ChartTimeframe"); DrawToImage(); } } private ViewTimeframe _chartTimeframe; /// <summary> /// The sensor this chart is attached to /// </summary> public ISensor Sensor { get { return _sensor; } set { // Remove notifications from existing sensor, if any if (_sensor != null) { _sensor.SensorCollect -= Sensor_Collect; } // Update the sensor _sensor = value; _raw_data = null; Notify("Sensor"); DrawToImage(); // Add notifications from the new sensor, if any if (_sensor != null) { _sensor.SensorCollect += Sensor_Collect; } } } private void Sensor_Collect(ISensor sender, SensorCollectEventArgs e) { _raw_data.Data.Add(e.Data); DrawToImage(); } private ISensor _sensor; /// <summary> /// The sensor this chart is attached to /// </summary> public IDataStore DataStore { get { return _datastore; } set { _datastore = value; _raw_data = null; Notify("DataStore"); DrawToImage(); } } private IDataStore _datastore; /// <summary> /// Current image of this chart /// </summary> public Bitmap ChartImage { get { if (_chart_image == null) { DrawToImage(); if (_chart_image != null) { if (File.Exists("test.png")) File.Delete("test.png"); _chart_image.Save("test.png", System.Drawing.Imaging.ImageFormat.Png); } } return _chart_image; } } private Bitmap _chart_image; /// <summary> /// Save the chart to a file /// </summary> /// <param name="png_filename"></param> public void SaveToFile(string png_filename) { ChartImage.Save(png_filename, System.Drawing.Imaging.ImageFormat.Png); } /// <summary> /// Determine the most useful information to show /// </summary> /// <param name="distance"></param> /// <returns></returns> public string TooltipFromPoint(float horizontal_distance) { if (_raw_data != null && _raw_data.Data.Count > 0) { // Figure out what time point this distance represents double num_seconds_from_chart_left_side = (_range_in_seconds * horizontal_distance); DateTime best_available_time = _min_date.AddSeconds((int)num_seconds_from_chart_left_side); // Find the best available data point SensorData sd = null; foreach (var r in _raw_data.Data) { if (r.Time > best_available_time) break; sd = r; } if (sd != null) { return String.Format("{0} UTC\r\n{1} Local\r\nMeasurement: {2}", sd.Time, sd.Time.ToLocalTime(), sd.Value); } } return ""; } #endregion #region Notification public event PropertyChangedEventHandler PropertyChanged; public void Notify(string name) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(name)); } } #endregion #region Cleanup /// <summary> /// Ensure safe cleanup /// </summary> public void Dispose() { if (_chart_image != null) _chart_image.Dispose(); } #endregion } }
36.056338
141
0.516462
[ "Apache-2.0" ]
ted-spence-avalara/CRTG
crtg-common/CRTG.Charts/CrtgChart.cs
17,922
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using MediatR; using PacMan.GameComponents.Canvas; namespace PacMan.GameComponents { public class GameStats : IGameStats { readonly IMediator _mediator; readonly IGameStorage _storage; int _currentPlayerIndex; List<PlayerStats> _playerStats; int _ghostsThatAreEyes; public GameStats(IMediator mediator, IGameStorage storage) { _mediator = mediator; _storage = storage; _playerStats = new(); #pragma warning disable 4014 Reset(0); #pragma warning restore 4014 } public async ValueTask Reset(int players) { _ghostsThatAreEyes = 0; HighScore = Math.Max(await _storage.GetHighScore(), HighScore); HasPlayedIntroTune = false; IsDemo = false; // ReSharper disable once HeapView.ObjectAllocation.Evident _playerStats = new(); for (int i = 0; i < players; i++) { _playerStats.Add(new(i, _mediator)); } _currentPlayerIndex = -1; } public bool IsDemo { get; private set; } public bool HasPlayedIntroTune { get; set; } public bool AreAnyGhostsInEyeState => _ghostsThatAreEyes > 0; [SuppressMessage("ReSharper", "HeapView.ObjectAllocation.Evident")] public PlayerStats ResetForDemo() { IsDemo = true; _playerStats = new(); var playerStats = new DemoPlayerStats(_mediator); _playerStats.Add(playerStats); _currentPlayerIndex = -1; ChoseNextPlayer(); return playerStats; } public void Update(CanvasTimingInformation timing) { CurrentPlayerStats?.Update(timing); } public PlayerStats GetPlayerStats(int index) => _playerStats[index]; public ValueTask FruitEaten() => CurrentPlayerStats.FruitEaten(); public int HighScore { get; private set; } = 10000; public bool HasPlayerStats(int playerNumber) => _playerStats.Count > playerNumber; public int AmountOfPlayers => _playerStats.Count; public bool AnyonePlaying => _currentPlayerIndex != -1; public bool IsGameOver => _playerStats.All(p => p.LivesRemaining == 0); public PlayerStats CurrentPlayerStats { get { if (_currentPlayerIndex < 0) { throw new InvalidOperationException("Nobody playing!"); } return _playerStats[_currentPlayerIndex]; } } public void ChoseNextPlayer() { PlayerStats[] players = _playerStats.Where(p => p.PlayerIndex > _currentPlayerIndex && p.LivesRemaining > 0) .ToArray(); if (players.Length == 0) { players = _playerStats.Where(p => p.LivesRemaining > 0).ToArray(); } if (players.Length > 0) { _currentPlayerIndex = players[0].PlayerIndex; } else { _currentPlayerIndex = -1; } } void updateHighScore() { HighScore = _playerStats.Count switch { 1 => Math.Max(_playerStats[0].Score, HighScore), 2 => Math.Max(_playerStats[1].Score, HighScore), _ => HighScore }; } public async ValueTask PillEaten(CellIndex point) { await _playerStats[_currentPlayerIndex].PillEaten(point); updateHighScore(); } public async ValueTask PowerPillEaten(CellIndex point) { await _playerStats[_currentPlayerIndex].PowerPillEaten(point); updateHighScore(); } public void PacManEaten() { _playerStats[_currentPlayerIndex].PacManEaten(); _ghostsThatAreEyes = 0; } public async ValueTask<int> GhostEaten() { ++_ghostsThatAreEyes; var points = await _playerStats[_currentPlayerIndex].GhostEaten(); updateHighScore(); return points; } public void LevelFinished() { CurrentPlayerStats.NewLevel(); } public ValueTask HandleGhostBackInsideHouse() { --_ghostsThatAreEyes; return default; } } }
25.880435
100
0.550189
[ "MIT" ]
SteveDunn/PacManBlazor
src/PacMan.GameComponents/GameStats.cs
4,764
C#
using System; using System.Collections.Generic; using SolastaCommunityExpansion.Api; using SolastaCommunityExpansion.Api.Extensions; using SolastaCommunityExpansion.Builders; using SolastaCommunityExpansion.Builders.Features; using static SolastaCommunityExpansion.Api.DatabaseHelper.FeatureDefinitionAdditionalActions; namespace SolastaCommunityExpansion.Feats; internal static class ElAntoniousFeats { public static void CreateFeats(List<FeatDefinition> feats) { feats.Add(DualFlurryFeatBuilder.DualFlurryFeat); feats.Add(TorchbearerFeatBuilder.TorchbearerFeat); } } internal sealed class DualFlurryFeatBuilder : FeatDefinitionBuilder { private const string DualFlurryFeatName = "DualFlurryFeat"; public static readonly Guid DualFlurryGuid = new("03C523EB-91B9-4F1B-A697-804D1BC2D6DD"); private static readonly string DualFlurryFeatNameGuid = GuidHelper.Create(DualFlurryGuid, DualFlurryFeatName).ToString(); public static readonly FeatDefinition DualFlurryFeat = CreateAndAddToDB(DualFlurryFeatName, DualFlurryFeatNameGuid); private DualFlurryFeatBuilder(string name, string guid) : base(DatabaseHelper.FeatDefinitions.Ambidextrous, name, guid) { Definition.GuiPresentation.Title = "Feat/&DualFlurryTitle"; Definition.GuiPresentation.Description = "Feat/&DualFlurryDescription"; Definition.Features.Clear(); Definition.Features.Add(BuildFeatureDualFlurry()); Definition.minimalAbilityScorePrerequisite = false; } private static FeatDefinition CreateAndAddToDB(string name, string guid) { return new DualFlurryFeatBuilder(name, guid).AddToDB(); } private static FeatureDefinition BuildFeatureDualFlurry() { return FeatureDefinitionOnAttackDamageEffectBuilder .Create("FeatureDualFlurry", DualFlurryGuid) .SetGuiPresentation("DualFlurry", Category.Feature) .SetOnAttackDamageDelegates(null, AfterOnAttackDamage) .AddToDB(); } private static void AfterOnAttackDamage(GameLocationCharacter attacker, GameLocationCharacter defender, ActionModifier attackModifier, RulesetAttackMode attackMode, bool rangedAttack, RuleDefinitions.AdvantageType advantageType, List<EffectForm> actualEffectForms, RulesetEffect rulesetEffect, bool criticalHit, bool firstTarget) { // Note the game code currently always passes attackMode = null for magic attacks, // if that changes this will need to be updated. if (rangedAttack || attackMode == null) { return; } var condition = attacker.RulesetCharacter.HasConditionOfType(ConditionDualFlurryApplyBuilder.GetOrAdd().Name) ? ConditionDualFlurryGrantBuilder.GetOrAdd() : ConditionDualFlurryApplyBuilder.GetOrAdd(); var active_condition = RulesetCondition.CreateActiveCondition(attacker.RulesetCharacter.Guid, condition, RuleDefinitions.DurationType.Round, 0, RuleDefinitions.TurnOccurenceType.EndOfTurn, attacker.RulesetCharacter.Guid, attacker.RulesetCharacter.CurrentFaction.Name); attacker.RulesetCharacter.AddConditionOfCategory("10Combat", active_condition); } } internal sealed class ConditionDualFlurryApplyBuilder : ConditionDefinitionBuilder { private ConditionDualFlurryApplyBuilder(string name, string guid) : base( DatabaseHelper.ConditionDefinitions.ConditionSurged, name, guid) { Definition.GuiPresentation.Title = "Condition/&ConditionDualFlurryApplyTitle"; Definition.GuiPresentation.Description = "Condition/&ConditionDualFlurryApplyDescription"; Definition.allowMultipleInstances = false; Definition.durationParameter = 0; Definition.durationType = RuleDefinitions.DurationType.Round; Definition.turnOccurence = RuleDefinitions.TurnOccurenceType.EndOfTurn; Definition.possessive = true; Definition.silentWhenAdded = true; Definition.silentWhenRemoved = true; Definition.conditionType = RuleDefinitions.ConditionType.Beneficial; Definition.Features.Clear(); } private static ConditionDefinition CreateAndAddToDB() { return new ConditionDualFlurryApplyBuilder("ConditionDualFlurryApply", GuidHelper.Create(DualFlurryFeatBuilder.DualFlurryGuid, "ConditionDualFlurryApply").ToString()) .AddToDB(); } // TODO: eliminate internal static ConditionDefinition GetOrAdd() { var db = DatabaseRepository.GetDatabase<ConditionDefinition>(); return db.TryGetElement("ConditionDualFlurryApply", GuidHelper.Create(DualFlurryFeatBuilder.DualFlurryGuid, "ConditionDualFlurryApply") .ToString()) ?? CreateAndAddToDB(); } } internal sealed class ConditionDualFlurryGrantBuilder : ConditionDefinitionBuilder { private ConditionDualFlurryGrantBuilder(string name, string guid) : base( DatabaseHelper.ConditionDefinitions.ConditionSurged, name, guid) { Definition.GuiPresentation.Title = "Condition/&ConditionDualFlurryGrantTitle"; Definition.GuiPresentation.Description = "Condition/&ConditionDualFlurryGrantDescription"; Definition.GuiPresentation.hidden = true; Definition.allowMultipleInstances = false; Definition.durationParameter = 0; Definition.durationType = RuleDefinitions.DurationType.Round; Definition.turnOccurence = RuleDefinitions.TurnOccurenceType.EndOfTurn; Definition.possessive = true; Definition.silentWhenAdded = false; Definition.silentWhenRemoved = false; Definition.conditionType = RuleDefinitions.ConditionType.Beneficial; Definition.Features.Clear(); Definition.Features.Add(BuildAdditionalActionDualFlurry()); } private static ConditionDefinition CreateAndAddToDB() { return new ConditionDualFlurryGrantBuilder("ConditionDualFlurryGrant", GuidHelper.Create(DualFlurryFeatBuilder.DualFlurryGuid, "ConditionDualFlurryGrant").ToString()) .AddToDB(); } // TODO: eliminate internal static ConditionDefinition GetOrAdd() { var db = DatabaseRepository.GetDatabase<ConditionDefinition>(); return db.TryGetElement("ConditionDualFlurryGrant", GuidHelper.Create(DualFlurryFeatBuilder.DualFlurryGuid, "ConditionDualFlurryGrant") .ToString()) ?? CreateAndAddToDB(); } private static FeatureDefinition BuildAdditionalActionDualFlurry() { return FeatureDefinitionAdditionalActionBuilder .Create(AdditionalActionSurgedMain, "AdditionalActionDualFlurry", DualFlurryFeatBuilder.DualFlurryGuid) .SetGuiPresentation(Category.Feature, AdditionalActionSurgedMain.GuiPresentation.SpriteReference) .SetActionType(ActionDefinitions.ActionType.Bonus) .SetRestrictedActions(ActionDefinitions.Id.AttackOff) .AddToDB(); } } internal sealed class TorchbearerFeatBuilder : FeatDefinitionBuilder { private const string TorchbearerFeatName = "TorchbearerFeat"; private static readonly Guid TorchbearerGuid = new("03C523EB-91B9-4F1B-A697-804D1BC2D6DD"); private static readonly string TorchbearerFeatNameGuid = GuidHelper.Create(TorchbearerGuid, TorchbearerFeatName).ToString(); public static readonly FeatDefinition TorchbearerFeat = CreateAndAddToDB(TorchbearerFeatName, TorchbearerFeatNameGuid); private TorchbearerFeatBuilder(string name, string guid) : base(DatabaseHelper.FeatDefinitions.Ambidextrous, name, guid) { Definition.GuiPresentation.Title = "Feat/&TorchbearerTitle"; Definition.GuiPresentation.Description = "Feat/&TorchbearerDescription"; Definition.Features.Clear(); Definition.Features.Add(BuildFeatureTorchbearer()); Definition.minimalAbilityScorePrerequisite = false; } private static FeatDefinition CreateAndAddToDB(string name, string guid) { return new TorchbearerFeatBuilder(name, guid).AddToDB(); } private static FeatureDefinition BuildFeatureTorchbearer() { var burn_effect = new EffectForm(); burn_effect.formType = EffectForm.EffectFormType.Condition; burn_effect.ConditionForm = new ConditionForm { Operation = ConditionForm.ConditionOperation.Add, ConditionDefinition = DatabaseHelper.ConditionDefinitions.ConditionOnFire1D4 }; var burn_description = new EffectDescription(); burn_description.Copy(DatabaseHelper.SpellDefinitions.Fireball.EffectDescription); burn_description.SetCreatedByCharacter(true); burn_description.SetTargetSide(RuleDefinitions.Side.Enemy); burn_description.SetTargetType(RuleDefinitions.TargetType.Individuals); burn_description.SetTargetParameter(1); burn_description.SetRangeType(RuleDefinitions.RangeType.Touch); burn_description.SetDurationType(RuleDefinitions.DurationType.Round); burn_description.SetDurationParameter(3); burn_description.SetCanBePlacedOnCharacter(false); burn_description.SetHasSavingThrow(true); burn_description.SetSavingThrowAbility(AttributeDefinitions.Dexterity); burn_description.SetSavingThrowDifficultyAbility(AttributeDefinitions.Dexterity); burn_description.SetDifficultyClassComputation(RuleDefinitions.EffectDifficultyClassComputation .AbilityScoreAndProficiency); burn_description.SetSpeedType(RuleDefinitions.SpeedType.Instant); burn_description.EffectForms.Clear(); burn_description.EffectForms.Add(burn_effect); return FeatureDefinitionConditionalPowerBuilder .Create("PowerTorchbearer", TorchbearerGuid) .SetGuiPresentation(Category.Feature) .SetActivation(RuleDefinitions.ActivationTime.BonusAction, 0) .SetEffectDescription(burn_description) .SetUsesFixed(1) .SetRechargeRate(RuleDefinitions.RechargeRate.AtWill) .SetShowCasting(false) .SetIsActive(IsActive).AddToDB(); } private static bool IsActive(RulesetCharacterHero hero) { if (hero == null) { return false; } var off_item = hero.CharacterInventory.InventorySlotsByName[EquipmentDefinitions.SlotTypeOffHand] .EquipedItem; return off_item != null && off_item.ItemDefinition != null && off_item.ItemDefinition.IsLightSourceItem; } }
42.85259
115
0.731964
[ "MIT" ]
ChrisPJohn/SolastaCommunityExpansion
SolastaCommunityExpansion/Feats/ElAntoniousFeats.cs
10,758
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("CookiesNSession")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("CookiesNSession")] [assembly: System.Reflection.AssemblyTitleAttribute("CookiesNSession")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.541667
80
0.652959
[ "MIT" ]
MustafaCelal/CookiesNSession
obj/Release/net5.0/CookiesNSession.AssemblyInfo.cs
997
C#
using Xunit; using Ocelot.Logging; using Ocelot.Headers.Middleware; using TestStack.BDDfy; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Moq; using Ocelot.Configuration; using Ocelot.DownstreamRouteFinder; using Ocelot.Configuration.Builder; using Ocelot.Headers; using System.Net.Http; using Ocelot.Authorisation.Middleware; using Ocelot.Middleware; namespace Ocelot.UnitTests.Headers { using System.Threading.Tasks; using Ocelot.Request.Middleware; public class HttpHeadersTransformationMiddlewareTests { private Mock<IHttpContextRequestHeaderReplacer> _preReplacer; private Mock<IHttpResponseHeaderReplacer> _postReplacer; private Mock<IOcelotLoggerFactory> _loggerFactory; private Mock<IOcelotLogger> _logger; private HttpHeadersTransformationMiddleware _middleware; private DownstreamContext _downstreamContext; private OcelotRequestDelegate _next; private Mock<IAddHeadersToResponse> _addHeaders; public HttpHeadersTransformationMiddlewareTests() { _preReplacer = new Mock<IHttpContextRequestHeaderReplacer>(); _postReplacer = new Mock<IHttpResponseHeaderReplacer>(); _downstreamContext = new DownstreamContext(new DefaultHttpContext()); _loggerFactory = new Mock<IOcelotLoggerFactory>(); _logger = new Mock<IOcelotLogger>(); _loggerFactory.Setup(x => x.CreateLogger<AuthorisationMiddleware>()).Returns(_logger.Object); _next = context => Task.CompletedTask; _addHeaders = new Mock<IAddHeadersToResponse>(); _middleware = new HttpHeadersTransformationMiddleware(_next, _loggerFactory.Object, _preReplacer.Object, _postReplacer.Object, _addHeaders.Object); } [Fact] public void should_call_pre_and_post_header_transforms() { this.Given(x => GivenTheFollowingRequest()) .And(x => GivenTheDownstreamRequestIs()) .And(x => GivenTheReRouteHasPreFindAndReplaceSetUp()) .And(x => GivenTheHttpResponseMessageIs()) .When(x => WhenICallTheMiddleware()) .Then(x => ThenTheIHttpContextRequestHeaderReplacerIsCalledCorrectly()) .And(x => ThenTheIHttpResponseHeaderReplacerIsCalledCorrectly()) .And(x => ThenAddHeadersIsCalledCorrectly()) .BDDfy(); } private void ThenAddHeadersIsCalledCorrectly() { _addHeaders .Verify(x => x.Add(_downstreamContext.DownstreamReRoute.AddHeadersToDownstream, _downstreamContext.DownstreamResponse), Times.Once); } private void WhenICallTheMiddleware() { _middleware.Invoke(_downstreamContext).GetAwaiter().GetResult(); } private void GivenTheDownstreamRequestIs() { _downstreamContext.DownstreamRequest = new DownstreamRequest(new HttpRequestMessage(HttpMethod.Get, "http://test.com")); } private void GivenTheHttpResponseMessageIs() { _downstreamContext.DownstreamResponse = new HttpResponseMessage(); } private void GivenTheReRouteHasPreFindAndReplaceSetUp() { var fAndRs = new List<HeaderFindAndReplace>(); var reRoute = new ReRouteBuilder() .WithDownstreamReRoute(new DownstreamReRouteBuilder().WithUpstreamHeaderFindAndReplace(fAndRs) .WithDownstreamHeaderFindAndReplace(fAndRs).Build()) .Build(); var dR = new DownstreamRoute(null, reRoute); _downstreamContext.TemplatePlaceholderNameAndValues = dR.TemplatePlaceholderNameAndValues; _downstreamContext.DownstreamReRoute = dR.ReRoute.DownstreamReRoute[0]; } private void ThenTheIHttpContextRequestHeaderReplacerIsCalledCorrectly() { _preReplacer.Verify(x => x.Replace(It.IsAny<HttpContext>(), It.IsAny<List<HeaderFindAndReplace>>()), Times.Once); } private void ThenTheIHttpResponseHeaderReplacerIsCalledCorrectly() { _postReplacer.Verify(x => x.Replace(It.IsAny<HttpResponseMessage>(), It.IsAny<List<HeaderFindAndReplace>>(), It.IsAny<DownstreamRequest>()), Times.Once); } private void GivenTheFollowingRequest() { _downstreamContext.HttpContext.Request.Headers.Add("test", "test"); } } }
41.927273
166
0.666522
[ "MIT" ]
myloveCc/Ocelot
test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs
4,612
C#
using System; class DecimalToBinaryNumber { static void Main() { long decimalNumber = long.Parse(Console.ReadLine()); string binaryNumber = string.Empty; while (decimalNumber != 0) { int remainder = (int)decimalNumber % 2; decimalNumber /= 2; binaryNumber = remainder + binaryNumber; } Console.WriteLine(binaryNumber); } }
21.15
60
0.576832
[ "MIT" ]
b-slavov/Telerik-Software-Academy
01.C# Part 1/06.Loops/14.DecimalToBinaryNumber/DecimalToBinaryNumber.cs
425
C#
//----------------------------------------------------------------------- // <copyright file="VoiceMidiEvent.cs" company="Stephen Toub"> // Copyright (c) Stephen Toub. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Globalization; using System.IO; namespace MidiSharp.Events.Voice { /// <summary>Represents a voice category message.</summary> public abstract class VoiceMidiEvent : MidiEvent { /// <summary>The status identifier (0x0 through 0xF) for this voice event.</summary> private byte m_category; /// <summary>The channel (0x0 through 0xF) for this voice event.</summary> private byte m_channel; /// <summary>Intializes the voice MIDI event.</summary> /// <param name="deltaTime">The amount of time before this event.</param> /// <param name="category">The category identifier (0x0 through 0xF) for this voice event.</param> /// <param name="channel">The channel (0x0 through 0xF) for this voice event.</param> internal VoiceMidiEvent(long deltaTime, byte category, byte channel) : base(deltaTime) { Validate.SetIfInRange("category", ref m_category, category, 0x0, 0xF); Channel = channel; } /// <summary>Generate a string representation of the event.</summary> /// <returns>A string representation of the event.</returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "{0}\t0x{1:X1}", base.ToString(), Channel); } /// <summary>Write the event to the output stream.</summary> /// <param name="outputStream">The stream to which the event should be written.</param> public override void Write(Stream outputStream) { base.Write(outputStream); outputStream.WriteByte(Status); } /// <summary>Gets the status identifier (0x0 through 0xF) for this voice event.</summary> public byte Category { get { return m_category; } } /// <summary>Gets or sets the channel (0x0 through 0xF) for this voice event.</summary> public byte Channel { get { return m_channel; } set { Validate.SetIfInRange("Channel", ref m_channel, value, 0x0, 0xF); } } /// <summary>Gets the status byte for the event message (combination of category and channel).</summary> public byte Status { get { return (byte)((((int)m_category) << 4) | m_channel); } } // The command is the upper 4 bits and the channel is the lower 4. /// <summary>Gets the Dword that represents this event as a MIDI event message.</summary> internal int Message { get { return Status | (Parameter1 << 8) | (Parameter2 << 16); } } /// <summary>The first parameter as sent in the MIDI message.</summary> internal abstract byte Parameter1 { get; } /// <summary>The second parameter as sent in the MIDI message.</summary> internal abstract byte Parameter2 { get; } } }
48.90625
158
0.607668
[ "MIT" ]
Connor14/MidiSharp
MidiSharp/Events/Voice/VoiceMidiEvent.cs
3,132
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; namespace AppAdvisory.MathGame { public class AnswerMA40 : ButtonHelper { Text text; //do the state for mobile normal on highlightened void Awake() { if (Application.isMobilePlatform) GetComponent<Button>().animationTriggers.highlightedTrigger = "Normal"; else GetComponent<Button>().animationTriggers.highlightedTrigger = "Highlighted"; } override public void OnClicked() { if (text == null) text = GetComponentInChildren<Text>(); MA40.OnClicked(text); } } }
19.2
80
0.71875
[ "MIT" ]
MrD005/Math-Game
BODMAS/Assets/MathGame/Scripts/addition/Answer In Game/AnswerMA40.cs
578
C#
namespace Transcoding.Transcoder.Options { public enum AudioSampleRate { Default, Hz22050, Hz44100, Hz48000 } }
15.6
41
0.576923
[ "MIT" ]
Lutando/Entropy
Transcoding.Prototype/src/Transcoding.Transcoder/Options/ConversionEnums.cs
158
C#
using UnityEngine; using UnityEngine.UI; public class WorldspaceHealthBar : MonoBehaviour { [Tooltip("Health component to track")] public Health health; [Tooltip("Image component displaying health left")] public Image healthBarImage; [Tooltip("The floating healthbar pivot transform")] public Transform healthBarPivot; [Tooltip("Whether the health bar is visible when at full health or not")] public bool hideFullHealthBar = true; void Update() { // update health bar value healthBarImage.fillAmount = health.currentHealth / health.maxHealth; // rotate health bar to face the camera/player healthBarPivot.LookAt(Camera.main.transform.position); // hide health bar if needed if (hideFullHealthBar) healthBarPivot.gameObject.SetActive(healthBarImage.fillAmount != 1); } }
32.642857
81
0.673961
[ "MIT" ]
IPFPS/ipfps
Assets/FPS/Scripts/UI/WorldspaceHealthBar.cs
916
C#
namespace XamarinFormsGoogleDriveAPI.Services.Service.Interface { public interface ICachedUserData { bool GetCachedUser(); } }
18.5
64
0.716216
[ "MIT" ]
Dineshbala1/GoogleDriveAPI-XamarinForms
XamarinFormsGoogleDriveAPI.Services/Service/Interface/ICachedUserData.cs
150
C#
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using System.Collections; using System.Windows.Forms; using DowUtils; using System.Drawing; namespace Factotum{ public class EBoundaryPoint : IEntity { // Mapped database columns // Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not). // Use int?, decimal?, etc for numbers (whether they're nullable or not). // Strings, images, etc, are reference types already private Guid? BptDBid; private Guid? BptBdrID; private int BptX; private int BptY; private byte BptIdx; //-------------------------------------------------------- // Field Properties //-------------------------------------------------------- // Primary key accessor public Guid? ID { get { return BptDBid; } } public Guid? BoundaryPointBdrID { get { return BptBdrID; } set { BptBdrID = value; } } public int BoundaryPointX { get { return BptX; } set { BptX = value; } } public int BoundaryPointY { get { return BptY; } set { BptY = value; } } public byte BoundaryPointIdx { get { return BptIdx; } set { BptIdx = value; } } //-------------------------------------- // Constructors //-------------------------------------- // Default constructor. Field defaults must be set here. // Any defaults set by the database will be overridden. public EBoundaryPoint() { } // Constructor which loads itself from the supplied id. // If the id is null, this gives the same result as using the default constructor. public EBoundaryPoint(Guid? id) : this() { Load(id); } //-------------------------------------- // Public Methods //-------------------------------------- //---------------------------------------------------- // Load the object from the database given a Guid? //---------------------------------------------------- public void Load(Guid? id) { if (id == null) return; SqlCeCommand cmd = Globals.cnn.CreateCommand(); SqlCeDataReader dr; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select BptDBid, BptBdrID, BptX, BptY, BptIdx from BoundaryPoints where BptDBid = @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // The query should return one record. // If it doesn't return anything (no match) the object is not affected if (dr.Read()) { // For all nullable values, replace dbNull with null BptDBid = (Guid?)dr[0]; BptBdrID = (Guid?)dr[1]; BptX = (int)dr[2]; BptY = (int)dr[3]; BptIdx = (byte)dr[4]; } dr.Close(); } //-------------------------------------- // Save the current record if it's valid //-------------------------------------- public Guid? Save() { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; if (ID == null) { // we are inserting a new record // first ask the database for a new Guid cmd.CommandText = "Select Newid()"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); BptDBid = (Guid?)(cmd.ExecuteScalar()); // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", BptDBid), new SqlCeParameter("@p1", BptBdrID), new SqlCeParameter("@p2", BptX), new SqlCeParameter("@p3", BptY), new SqlCeParameter("@p4", BptIdx) }); cmd.CommandText = @"Insert Into BoundaryPoints ( BptDBid, BptBdrID, BptX, BptY, BptIdx ) values (@p0,@p1,@p2,@p3,@p4)"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to insert BoundaryPoints row"); } } else { // we are updating an existing record // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", BptDBid), new SqlCeParameter("@p1", BptBdrID), new SqlCeParameter("@p2", BptX), new SqlCeParameter("@p3", BptY), new SqlCeParameter("@p4", BptIdx)}); cmd.CommandText = @"Update BoundaryPoints set BptBdrID = @p1, BptX = @p2, BptY = @p3, BptIdx = @p4 Where BptDBid = @p0"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to update boundarypoints row"); } } return ID; } //-------------------------------------- // Delete the current record //-------------------------------------- public bool Delete(bool promptUser) { // If the current object doesn't reference a database record, there's nothing to do. if (BptDBid == null) { return false; } DialogResult rslt = DialogResult.None; if (promptUser) { rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); } // If an error occurs when attempting to delete... // Use transactions?? // Raise an event right before the deletion? if (!promptUser || rslt == DialogResult.OK) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Delete from BoundaryPoints where BptDBid = @p0"; cmd.Parameters.Add("@p0", BptDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // Todo: figure out how I really want to do this. // Is there a problem with letting the database try to do cascading deletes? // How should the user be notified of the problem?? if (rowsAffected < 1) { return false; } else return true; } else { return false; } } //-------------------------------------------------------------------- // Static listing methods which return collections of boundarypoints //-------------------------------------------------------------------- // This helper function builds the collection for you based on the flags you send it // I originally had a flag that would let you indicate inactive items by appending '(inactive)' // to the name. This was a bad idea, because sometimes the objects in this collection // will get modified and saved back to the database -- with the extra text appended to the name. public static EBoundaryPointCollection ListByIndex() { EBoundaryPoint boundarypoint; EBoundaryPointCollection boundarypoints = new EBoundaryPointCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select BptDBid, BptBdrID, BptX, BptY, BptIdx from BoundaryPoints"; qry += " order by BptIdx"; cmd.CommandText = qry; SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { boundarypoint = new EBoundaryPoint((Guid?)dr[0]); boundarypoint.BptBdrID = (Guid?)(dr[1]); boundarypoint.BptX = (int)(dr[2]); boundarypoint.BptY = (int)(dr[3]); boundarypoint.BptIdx = (byte)(dr[4]); boundarypoints.Add(boundarypoint); } // Finish up dr.Close(); return boundarypoints; } public static PointF[] GetArrayByIndexForBoundary(Guid BoundaryID) { ArrayList al = new ArrayList(10); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select BptX, BptY from BoundaryPoints where BptBdrID = @p1"; qry += " order by BptIdx"; cmd.CommandText = qry; cmd.Parameters.Add("@p1", BoundaryID); SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { PointF bPoint = new PointF(Convert.ToSingle(dr[0]), Convert.ToSingle(dr[1])); al.Add(bPoint); } // Finish up dr.Close(); return (PointF[])al.ToArray(typeof(PointF)); } public static bool SaveForBoundaryFromArray(Guid BoundaryID, PointF[] ptArray) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); string qry = @"Insert into BoundaryPoints (BptBdrID, BptX, BptY, BptIdx) values (@p1, @p2, @p3, @p4)"; cmd.CommandText = qry; cmd.Parameters.Add("@p1", BoundaryID); cmd.Parameters.Add("@p2", 0.0); cmd.Parameters.Add("@p3", 0.0); cmd.Parameters.Add("@p4", 0); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); // Build new objects and add them to the collection int nPoints = ptArray.Length; for (int i=0;i < nPoints; i++) { cmd.Parameters[1].Value = ptArray[i].X; cmd.Parameters[2].Value = ptArray[i].Y; cmd.Parameters[3].Value = i; cmd.ExecuteNonQuery(); } return true; } // Get a Default data view with all columns that a user would likely want to see. // You can bind this view to a DataGridView, hide the columns you don't need, filter, etc. // I decided not to indicate inactive in the names of inactive items. The 'user' // can always show the inactive column if they wish. public static DataView GetDefaultDataView() { DataSet ds = new DataSet(); DataView dv; SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and // makes the column sortable. // You'll likely want to modify this query further, joining in other tables, etc. string qry = @"Select BptDBid as ID, BptBdrID as BoundaryPointBdrID, BptX as BoundaryPointX, BptY as BoundaryPointY, BptIdx as BoundaryPointIdx from BoundaryPoints"; cmd.CommandText = qry; da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); dv = new DataView(ds.Tables[0]); return dv; } //-------------------------------------- // Private utilities //-------------------------------------- // Check for required fields, setting the individual error messages private bool RequiredFieldsFilled() { bool allFilled = true; return allFilled; } } //-------------------------------------- // BoundaryPoint Collection class //-------------------------------------- public class EBoundaryPointCollection : CollectionBase { //this event is fired when the collection's items have changed public event EventHandler Changed; //this is the constructor of the collection. public EBoundaryPointCollection() { } //the indexer of the collection public EBoundaryPoint this[int index] { get { return (EBoundaryPoint)this.List[index]; } } //this method fires the Changed event. protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } public bool ContainsID(Guid? ID) { if (ID == null) return false; foreach (EBoundaryPoint boundarypoint in InnerList) { if (boundarypoint.ID == ID) return true; } return false; } //returns the index of an item in the collection public int IndexOf(EBoundaryPoint item) { return InnerList.IndexOf(item); } //adds an item to the collection public void Add(EBoundaryPoint item) { this.List.Add(item); OnChanged(EventArgs.Empty); } //inserts an item in the collection at a specified index public void Insert(int index, EBoundaryPoint item) { this.List.Insert(index, item); OnChanged(EventArgs.Empty); } //removes an item from the collection. public void Remove(EBoundaryPoint item) { this.List.Remove(item); OnChanged(EventArgs.Empty); } } }
27.243243
98
0.612765
[ "MIT" ]
ddrake/Factotum
Factotum/EBoundaryPoint.cs
12,096
C#
using Phone_Bill_Analyzer.ViewModels; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Controls; namespace Phone_Bill_Analyzer.Views { public sealed partial class UploadBill : Page { public UploadBill() { InitializeComponent(); NavigationCacheMode = NavigationCacheMode.Disabled; } } }
20.222222
63
0.659341
[ "MIT" ]
Phone-Bill-Analyzer/PBA-WindowsApp
Phone-Bill-Analyzer/Views/UploadBill.xaml.cs
364
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.Cx.V3Beta1.Snippets { using Google.Cloud.Dialogflow.Cx.V3Beta1; public sealed partial class GeneratedExperimentsClientStandaloneSnippets { /// <summary>Snippet for CreateExperiment</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void CreateExperimentRequestObject() { // Create client ExperimentsClient experimentsClient = ExperimentsClient.Create(); // Initialize request argument(s) CreateExperimentRequest request = new CreateExperimentRequest { ParentAsEnvironmentName = EnvironmentName.FromProjectLocationAgentEnvironment("[PROJECT]", "[LOCATION]", "[AGENT]", "[ENVIRONMENT]"), Experiment = new Experiment(), }; // Make the request Experiment response = experimentsClient.CreateExperiment(request); } } }
39.930233
149
0.680839
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/cx/v3beta1/google-cloud-dialogflow-cx-v3beta1-csharp/Google.Cloud.Dialogflow.Cx.V3Beta1.StandaloneSnippets/ExperimentsClient.CreateExperimentRequestObjectSnippet.g.cs
1,717
C#
using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sql.Net.Types { public partial class DoubleType { [SqlFunction()] public static String DoubleToString(Double? value, String format) { String result = null; if (value.HasValue == true && format != null) { result = value.Value.ToString(format); } return result; } [SqlFunction()] public static Double? DoubleTryParse(String value) { Double? result = null; if (value != null) { Double parsedValue; if (Double.TryParse(value, out parsedValue) == true) { result = parsedValue; } } return result; } } }
19.5
68
0.62888
[ "MIT" ]
DataGenSoftware/Sql.Net
Sql.Net/Sql.Net/Types/Double.cs
743
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Test")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34f4c859-67cc-40d2-97ae-27e8c7157052")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.25
84
0.745712
[ "Apache-2.0" ]
hputtick/ImageProcessor
src/Test/Test/Properties/AssemblyInfo.cs
1,344
C#
namespace ArsAffiliate.Domain.Dtos.MedicalBill { public class UpdateMedicalBillDto : CreateMedicalBillDto { public int Id { get; set; } } }
20.125
60
0.68323
[ "MIT" ]
LuisEduardoFrias/Back-End
ArsAffiliate.Domain/Dtos/MedicalBill/UpdateMedicalBillDto.cs
163
C#
namespace System.Runtime.CompilerServices; internal static class IsExternalInit {}
27.666667
42
0.855422
[ "MIT" ]
idarb-oss/CloudNative.CloudEvents.NATS
test/CloudNative.CloudEvents.NATS.UnitTests/ExternalInit.cs
83
C#
namespace Ploeh.AutoFixtureDocumentationTest.Greedy { public interface IFoo { } }
14.428571
53
0.663366
[ "MIT" ]
TeaDrivenDev/AutoFixture
Src/AutoFixtureDocumentationTest/Greedy/IFoo.cs
103
C#
using System; using HarmonyLib; using KKAPI.Utilities; using UnityEngine; using VRGIN.Controls; using VRGIN.Core; namespace KKS_VR.Fixes { /// <summary> /// Fix custom tool icons not being on top of the black circle /// </summary> public class TopmostToolIcons { public static void Patch() { new Harmony("TopmostToolIconsHook").PatchAll(typeof(TopmostToolIcons)); } private static Shader _guiShader; public static Shader GetGuiShader() { if (_guiShader == null) { var bundle = AssetBundle.LoadFromMemory(ResourceUtils.GetEmbeddedResource("topmostguishader")); _guiShader = bundle.LoadAsset<Shader>("topmostgui"); if (_guiShader == null) throw new ArgumentNullException(nameof(_guiShader)); //_guiShader = new Material(guiShader); bundle.Unload(false); } return _guiShader; } [HarmonyPostfix] [HarmonyPatch(typeof(Controller), "OnUpdate")] private static void ToolIconFixHook(Controller __instance) { var tools = __instance.Tools; var any = 0; foreach (var tool in tools) { var canvasRenderer = tool.Icon?.GetComponent<CanvasRenderer>(); if (canvasRenderer == null) return; var orig = canvasRenderer.GetMaterial(); if (orig == null || orig.shader == _guiShader) continue; any++; var copy = new Material(GetGuiShader()); canvasRenderer.SetMaterial(copy, 0); } if (any == 0) return; Canvas.ForceUpdateCanvases(); VRLog.Debug($"Replaced materials on {any} tool icon renderers"); } } }
28.646154
111
0.565521
[ "MIT" ]
IllusionMods/KKS_VR
Shared/Fixes/TopmostToolIcons.cs
1,864
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Devices.I2c; using System.Drawing; using System.Runtime.CompilerServices; using System.Threading; namespace System.Devices.Gpio.Samples { public enum RgbColorSensorIntegrationTime : byte { Milliseconds2_4 = 0xFF, // 2.4ms - 1 cycle - Max Count: 1024 Milliseconds24 = 0xF6, // 24ms - 10 cycles - Max Count: 10240 Milliseconds50 = 0xEB, // 50ms - 20 cycles - Max Count: 20480 Milliseconds101 = 0xD5, // 101ms - 42 cycles - Max Count: 43008 Milliseconds154 = 0xC0, // 154ms - 64 cycles - Max Count: 65535 Milliseconds700 = 0x00 // 700ms - 256 cycles - Max Count: 65535 } public enum RgbColorSensorGain : byte { Gain1X = 0x00, // No gain Gain4X = 0x01, // 2x gain Gain16X = 0x02, // 16x gain Gain60X = 0x03 // 60x gain } /// <summary> /// Supports TCS34725 RGB Color sensor /// </summary> public class RgbColorSensor : IDisposable { public const byte DefaultI2cAddress = 0x29; public const byte AlternativeI2cAddress = 0x39; private const byte COMMAND_BIT = 0x80; private const byte REGISTER_ENABLE = 0x00; private const byte REGISTER_ATIME = 0x01; private const byte REGISTER_AILT = 0x04; private const byte REGISTER_AIHT = 0x06; private const byte REGISTER_ID = 0x12; private const byte REGISTER_APERS = 0x0c; private const byte REGISTER_CONTROL = 0x0f; private const byte REGISTER_SENSORID = 0x12; private const byte REGISTER_STATUS = 0x13; private const byte REGISTER_CDATA = 0x14; private const byte REGISTER_RDATA = 0x16; private const byte REGISTER_GDATA = 0x18; private const byte REGISTER_BDATA = 0x1a; private const byte ENABLE_AIEN = 0x10; private const byte ENABLE_WEN = 0x08; private const byte ENABLE_AEN = 0x02; private const byte ENABLE_PON = 0x01; private static readonly byte[] s_cycles = { 0, 1, 2, 3, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60 }; private struct RawColor { public ushort Red, Green, Blue, Clear; } private readonly I2cConnectionSettings _i2cSettings; private I2cDevice _i2cDevice; private RgbColorSensorIntegrationTime _integrationTime; private RawColor _rawColor; public RgbColorSensor(I2cConnectionSettings i2cSettings) { _i2cSettings = i2cSettings ?? throw new ArgumentNullException(nameof(i2cSettings)); } public void Dispose() { if (_i2cDevice != null) { _i2cDevice.Dispose(); _i2cDevice = null; } } /// <summary> /// Gets the detected color. /// </summary> public Color Color { get; private set; } /// <summary> /// Gets the detected color temperature in degrees. /// </summary> public float Temperature { get; private set; } /// <summary> /// Gets the detected light level in lux. /// </summary> public float Luminosity { get; private set; } /// <summary> /// Gets the active state of the sensor. /// </summary> public bool IsActive { get; private set; } /// <summary> /// Sets the active state of the sensor. /// </summary> public void SetActive(bool value) { if (IsActive == value) { return; } IsActive = value; byte enable = Read8(REGISTER_ENABLE); if (value) { Write8(REGISTER_ENABLE, (byte)(enable | ENABLE_PON)); Thread.Sleep(3); Write8(REGISTER_ENABLE, (byte)(enable | ENABLE_PON | ENABLE_AEN)); } else { Write8(REGISTER_ENABLE, (byte)(enable & ~(ENABLE_PON | ENABLE_AEN))); } } /// <summary> /// Gets the integration time of the sensor. /// </summary> public RgbColorSensorIntegrationTime GetIntegrationTime() { byte control = Read8(REGISTER_ATIME); RgbColorSensorIntegrationTime result = (RgbColorSensorIntegrationTime)control; return result; } /// <summary> /// Sets the integration time of the sensor. /// </summary> public void SetIntegrationTime(RgbColorSensorIntegrationTime value) { _integrationTime = value; Write8(REGISTER_ATIME, (byte)value); } /// <summary> /// Gets the gain of the sensor. /// </summary> public RgbColorSensorGain GetGain() { byte control = Read8(REGISTER_CONTROL); RgbColorSensorGain result = (RgbColorSensorGain)control; return result; } /// <summary> /// Sets the gain of the sensor. /// </summary> public void SetGain(RgbColorSensorGain value) { Write8(REGISTER_CONTROL, (byte)value); } /// <summary> /// Returns true if the interrupt is set. /// </summary> public bool IsInterruptEnabled() { byte result = Read8(REGISTER_STATUS); result = (byte)(result & ENABLE_AIEN); return result != 0; } /// <summary> /// Sets the interrupt. /// </summary> /// <param name="value"></param> public void SetInterrupt(bool value) { byte res = Read8(REGISTER_ENABLE); if (value) { res |= ENABLE_AIEN; } else { res = (byte)(res & ~ENABLE_AIEN); } Write8(REGISTER_ENABLE, res); } /// <summary> /// Clear the interrupt. /// </summary> public void ClearInterrupt() { _i2cDevice.Write(0x66 | COMMAND_BIT); } public bool Begin() { Dispose(); _i2cDevice = new UnixI2cDevice(_i2cSettings); byte sensorId = Read8(REGISTER_SENSORID); if (sensorId != 0x44 && sensorId != 0x10) { Console.WriteLine($"sensorId = '{sensorId:X2}'"); return false; } SetIntegrationTime(RgbColorSensorIntegrationTime.Milliseconds2_4); return true; } /// <summary> /// Reads the RGB color detected by the sensor. /// </summary> public void ReadSensor() { ReadColor(); FillColor(); FillTemperatureAndLuminosity(); } /// <summary> /// Gets the persistence cycles of the sensor. /// </summary> public int GetCycles() { int result = -1; byte enable = Read8(REGISTER_ENABLE); if ((enable & ENABLE_AIEN) > 0) { byte apers = Read8(REGISTER_APERS); result = s_cycles[apers & 0x0f]; } return result; } /// <summary> /// Sets the persistence cycles of the sensor. /// </summary> public void SetCycles(int value) { byte enable = Read8(REGISTER_ENABLE); if (value == -1) { Write8(REGISTER_ENABLE, (byte)(enable & ~ENABLE_AIEN)); } else { int index = Array.IndexOf(s_cycles, value); if (index < 0) { throw new ArgumentOutOfRangeException($"The value of parameter {nameof(value)} must be 0, 1, 2, 3, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 or 60."); } Write8(REGISTER_ENABLE, (byte)(enable | ENABLE_AIEN)); Write8(REGISTER_APERS, (byte)index); } } /// <summary> /// Gets the minimum threshold value of the sensor. /// </summary> public ushort GetMinValue() { ushort result = Read16(REGISTER_AILT); return result; } /// <summary> /// Sets the minimum threshold value of the sensor. /// </summary> public void SetMinValue(ushort value) { Write16(REGISTER_AILT, value); } /// <summary> /// Gets the maximum threshold value of the sensor. /// </summary> public ushort GetMaxValue() { ushort result = Read16(REGISTER_AIHT); return result; } /// <summary> /// Sets the maximum threshold value of the sensor. /// </summary> public void SetMaxValue(ushort value) { Write16(REGISTER_AIHT, value); } /// <summary> /// Check if the status bit is set and the chip is ready. /// </summary> private bool IsValid() { byte result = Read8(REGISTER_STATUS); return result > 0; } /// <summary> /// Read the raw RGBC color detected by the sensor. /// Reads a raw color of 16-bit red, green, blue, clear component values (0-65535). /// </summary> private void ReadColor() { bool wasActive = IsActive; SetActive(true); while (!IsValid()) { SleepIntegrationTime(); } _rawColor.Red = Read16LittleEndian(REGISTER_RDATA); _rawColor.Green = Read16LittleEndian(REGISTER_GDATA); _rawColor.Blue = Read16LittleEndian(REGISTER_BDATA); _rawColor.Clear = Read16LittleEndian(REGISTER_CDATA); SetActive(wasActive); // Console.WriteLine($"R = {_rawColor.Red}, G = {_rawColor.Green}, B = {_rawColor.Blue}, C = {_rawColor.Clear}"); } private void SleepIntegrationTime() { int time = 0; switch (_integrationTime) { case RgbColorSensorIntegrationTime.Milliseconds2_4: time = 3; break; case RgbColorSensorIntegrationTime.Milliseconds24: time = 24; break; case RgbColorSensorIntegrationTime.Milliseconds50: time = 50; break; case RgbColorSensorIntegrationTime.Milliseconds101: time = 101; break; case RgbColorSensorIntegrationTime.Milliseconds154: time = 154; break; case RgbColorSensorIntegrationTime.Milliseconds700: time = 700; break; default: throw new NotSupportedException($"Unknown integration time: '{_integrationTime}'"); } Thread.Sleep(time); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Write8(byte register, byte value) { WriteRegister(register, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte Read8(byte register) { return (byte)ReadRegister(register, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Write16(byte register, ushort value) { WriteRegister(register, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ushort Read16(byte register) { return (ushort)ReadRegister(register, 2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ushort Read16LittleEndian(byte register) { ushort result = Read16(register); result = Utils.SwapBytes(result); return result; } private void WriteRegister(byte register, byte value) { _i2cDevice.Write((byte)(register | COMMAND_BIT), value); } private void WriteRegister(byte register, ushort value) { var buffer = new byte[] { (byte)(register | COMMAND_BIT), (byte)((value >> 8) & 0xFF), (byte)(value & 0xFF) }; _i2cDevice.Write(buffer); } private uint ReadRegister(byte register, uint byteCount) { _i2cDevice.Write((byte)(register | COMMAND_BIT)); uint result = (uint)_i2cDevice.Read(byteCount); return result; } private void FillColor() { byte red = (byte)(Math.Pow(((((float)_rawColor.Red / _rawColor.Clear) * 256) / 255), 2.5f) * 255); byte green = (byte)(Math.Pow(((((float)_rawColor.Green / _rawColor.Clear) * 256) / 255), 2.5f) * 255); byte blue = (byte)(Math.Pow(((((float)_rawColor.Blue / _rawColor.Clear) * 256) / 255), 2.5f) * 255); Color = Color.FromArgb(red, green, blue); } /// <summary> /// Converts RGBC data to color temperature and lux values. /// Returns a tuple of color temperature and luminosity. /// </summary> private void FillTemperatureAndLuminosity() { float x = -0.14282f * _rawColor.Red + 1.54924f * _rawColor.Green + -0.95641f * _rawColor.Blue; float y = -0.32466f * _rawColor.Red + 1.57837f * _rawColor.Green + -0.73191f * _rawColor.Blue; float z = -0.68202f * _rawColor.Red + 0.77073f * _rawColor.Green + 0.56332f * _rawColor.Blue; float divisor = x + y + z; if (divisor == 0) { Temperature = 0; Luminosity = 0; } else { float n = (x / divisor - 0.3320f) / (0.1858f - y / divisor); float cct = 449.0f * (float)Math.Pow(n, 3) + 3525.0f * (float)Math.Pow(n, 2) + 6823.3f * n + 5520.33f; Temperature = cct; Luminosity = y; } } } }
30.878723
170
0.527114
[ "MIT" ]
dagood/corefxlab
samples/System.Devices.Gpio.Samples/RgbColorSensor.cs
14,515
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Petlja_primjeri_while")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Petlja_primjeri_while")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c4b28fe6-9f7c-4f4f-b7f7-9a2dec0e89b3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.108108
84
0.751064
[ "MIT" ]
robertlucic66/AlgebraCSharp2019-1
ConsoleApp1/Petlja_primjeri_while/Properties/AssemblyInfo.cs
1,413
C#
using System; namespace TQL.RDL.Parser.Nodes { public class OrNode : BinaryNode { public OrNode(RdlSyntaxNode left, RdlSyntaxNode right) : base(left, right) { } public override Type ReturnType => typeof(bool); public override string ToString() => ToString("or"); public override void Accept(INodeVisitor visitor) => visitor.Visit(this); } }
24.411765
81
0.624096
[ "Apache-2.0" ]
Puchaczov/TQL.RDL
TQL.RDL/TQL.RDL.Parser/Nodes/OrNode.cs
415
C#
// ReSharper disable once CheckNamespace namespace System.Runtime.CompilerServices { // ReSharper disable once UnusedType.Global internal static class IsExternalInit { } }
18.9
47
0.746032
[ "MIT" ]
LokiVKlokeNaAndoke/RimWorld_Mod_AutoPriorities
Source/AutoPriorities/AutoPriorities/IsExternalInit.cs
189
C#
using System; using System.Collections.Generic; [Flags] public enum EUIOption { None = 1 << 1, HideBefore = 1 << 2, // 隐藏前UI Disable3DCamera = 1 << 3, // 关闭3d相机 CheckQuality = 1 << 4, // 调整整体game的quality DisableBeforeRaycaster = 1 << 5, // 关闭前UI的raycaster, 如果前ui被hide,则没必要执行此设置 Mask = 1 << 6, // 背景遮挡蒙版, 方便整体调控 CheckGuide = 1 << 7, // 检测引导 CheckNetwork = 1 << 8, // 网络等待,网络转圈 } public enum EUILayer { BasementStack = 1, // 只允许场景的第一个UI,比如主界面,战斗主界面 进行该设置 NormalStack = 2, TopStack = 3, Max, // 禁止使用 } [Serializable] public class FUIEntry { #if UNITY_EDITOR public int uiType; public string prefabPath; public Type ui; public EUIOption option; public EUILayer layer; #else public int uiType { get; private set; } public string prefabPath { get; private set; } public Type ui { get; private set; } public EUIOption option { get; private set; } public EUILayer layer { get; private set; } #endif public FUIEntry() { } public FUIEntry Reset(int uiType, string prefabPath, Type ui, EUIOption option = EUIOption.None, EUILayer layer = EUILayer.NormalStack) { this.uiType = uiType; this.prefabPath = prefabPath; this.ui = ui; this.layer = layer; this.option = option; return this; } public virtual FUIBase CreateInstance() { return Activator.CreateInstance(ui) as FUIBase; } public bool Contains(EUIOption target) { return ((option & target) == target); } public static bool TryGetNextLayer(EUILayer layer, out EUILayer nextLayer) { if (layer < EUILayer.TopStack) { nextLayer = layer + 1; return true; } nextLayer = layer; return false; } public static bool TryGetPreLayer(EUILayer layer, out EUILayer preLayer) { if (layer > EUILayer.BasementStack) { preLayer = layer - 1; return true; } preLayer = layer; return false; } } // ui配置 // 热更层动态插入框架层 public class FUIEntryRegistry { #if UNITY_EDITOR public static readonly Dictionary<int, FUIEntry> registry = new Dictionary<int, FUIEntry>(); #else private static readonly Dictionary<int, FUIEntry> registry = new Dictionary<int, FUIEntry>(); #endif public static bool TryGet(int uiType, out FUIEntry entry) { return registry.TryGetValue(uiType, out entry); } public static void Clear() { registry.Clear(); } public static void Register(FUIEntry entry) { if (entry != null && !registry.TryGetValue(entry.uiType, out _)) { registry.Add(entry.uiType, entry); } } }
26.480392
141
0.627545
[ "MIT" ]
3-Delta/Unity-UI
Assets/Scripts/Framework/UI/FUIEntryRegistry.cs
2,895
C#
// // System.Web.Compilation.DesignTimeResourceProviderFactoryAttribute // // Authors: // Chris Toshok (toshok@ximian.com) // // (C) 2006 Novell, Inc (http://www.novell.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.CodeDom; using System.Web.UI; namespace System.Web.Compilation { [AttributeUsage (AttributeTargets.Class)] public sealed class DesignTimeResourceProviderFactoryAttribute : Attribute { string factoryTypeName; public DesignTimeResourceProviderFactoryAttribute (string factoryTypeName) { this.factoryTypeName = factoryTypeName; } public DesignTimeResourceProviderFactoryAttribute (System.Type factoryType) { this.factoryTypeName = factoryType.AssemblyQualifiedName; } public override bool IsDefaultAttribute () { return factoryTypeName == null; } public string FactoryTypeName { get { return factoryTypeName; } } } }
28.75
77
0.759079
[ "Apache-2.0" ]
121468615/mono
mcs/class/System.Web/System.Web.Compilation/DesignTimeResourceProviderFactoryAttribute.cs
1,955
C#
// This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2019 Riley Labrecque // Please see the included LICENSE.txt for additional information. using System.Runtime.InteropServices; using IntPtr = System.IntPtr; namespace Steamworks { [System.Serializable] public struct ControllerHandle_t : System.IEquatable<ControllerHandle_t>, System.IComparable<ControllerHandle_t> { public ulong m_ControllerHandle; public ControllerHandle_t(ulong value) { m_ControllerHandle = value; } public override string ToString() { return m_ControllerHandle.ToString(); } public override bool Equals(object other) { return other is ControllerHandle_t && this == (ControllerHandle_t)other; } public override int GetHashCode() { return m_ControllerHandle.GetHashCode(); } public static bool operator ==(ControllerHandle_t x, ControllerHandle_t y) { return x.m_ControllerHandle == y.m_ControllerHandle; } public static bool operator !=(ControllerHandle_t x, ControllerHandle_t y) { return !(x == y); } public static explicit operator ControllerHandle_t(ulong value) { return new ControllerHandle_t(value); } public static explicit operator ulong(ControllerHandle_t that) { return that.m_ControllerHandle; } public bool Equals(ControllerHandle_t other) { return m_ControllerHandle == other.m_ControllerHandle; } public int CompareTo(ControllerHandle_t other) { return m_ControllerHandle.CompareTo(other.m_ControllerHandle); } } }
39.684211
115
0.773873
[ "MIT" ]
rfht/Steamworks-nosteam
Steamworks.NET/types/SteamController/ControllerHandle_t.cs
1,508
C#
using System; using System.Collections.Generic; using System.Text; namespace Bitbird.Core.Json.Helpers.JsonDataModel.Attributes { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class JsonApiRelationIdAttribute : Attribute { public string PropertyName { get; set; } public JsonApiRelationIdAttribute(string propertyName) { PropertyName = propertyName; } } }
24.833333
70
0.704698
[ "MIT" ]
bitbird-dev/Bitbird.Core
Bitbird.Core.Json.Helpers.JsonDataModel/Attributes/JsonApiRelationIdAttribute.cs
449
C#
using Objects.Geometry; using Objects.Utils; using Speckle.Core.Kits; using Speckle.Core.Models; using System.Collections.Generic; namespace Objects.BuiltElements { public class Duct : Base, IDisplayMesh { public Line baseLine { get; set; } public double width { get; set; } public double height { get; set; } public double diameter { get; set; } public double length { get; set; } public double velocity { get; set; } [DetachProperty] public Mesh displayMesh { get; set; } public string units { get; set; } public Duct() { } /// <summary> /// SchemaBuilder constructor for a Speckle duct /// </summary> /// <param name="baseLine"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="diameter"></param> /// <param name="velocity"></param> /// <remarks>Assign units when using this constructor due to <paramref name="width"/>, <paramref name="height"/>, and <paramref name="diameter"/> params</remarks> [SchemaInfo("Duct", "Creates a Speckle duct", "BIM", "MEP")] public Duct([SchemaMainParam] Line baseLine, double width, double height, double diameter, double velocity = 0) { this.baseLine = baseLine; this.width = width; this.height = height; this.diameter = diameter; this.velocity = velocity; } } } namespace Objects.BuiltElements.Revit { public class RevitDuct : Duct { public string family { get; set; } public string type { get; set; } public string systemName { get; set; } public string systemType { get; set; } public Level level { get; set; } public Base parameters { get; set; } public string elementId { get; set; } public RevitDuct() { } /// <summary> /// SchemaBuilder constructor for a Revit duct /// </summary> /// <param name="family"></param> /// <param name="type"></param> /// <param name="baseLine"></param> /// <param name="systemName"></param> /// <param name="systemType"></param> /// <param name="level"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="diameter"></param> /// <param name="velocity"></param> /// <param name="parameters"></param> /// <remarks>Assign units when using this constructor due to <paramref name="width"/>, <paramref name="height"/>, and <paramref name="diameter"/> params</remarks> [SchemaInfo("RevitDuct", "Creates a Revit duct", "Revit", "MEP")] public RevitDuct(string family, string type, [SchemaMainParam] Line baseLine, string systemName, string systemType, Level level, double width, double height, double diameter, double velocity = 0, List<Parameter> parameters = null) { this.baseLine = baseLine; this.family = family; this.type = type; this.width = width; this.height = height; this.diameter = diameter; this.velocity = velocity; this.systemName = systemName; this.systemType = systemType; this.parameters = parameters.ToBase(); this.level = level; } } }
33.913043
234
0.633013
[ "Apache-2.0" ]
arup-group/speckle-sharp
Objects/Objects/BuiltElements/Duct.cs
3,122
C#
//----------------------------------------------------------------------- // <copyright file="DockingManagerBehavior.cs" company="Development In Progress Ltd"> // Copyright © 2012. All rights reserved. // </copyright> // <author>Grant Colley</author> //----------------------------------------------------------------------- using DevelopmentInProgress.TradeView.Wpf.Host.Controller.Navigation; using DevelopmentInProgress.TradeView.Wpf.Host.Controller.View; using Prism.Regions; using Prism.Regions.Behaviors; using System; using System.Collections.Specialized; using System.Linq; using System.Windows; using Xceed.Wpf.AvalonDock; using Xceed.Wpf.AvalonDock.Controls; using Xceed.Wpf.AvalonDock.Layout; namespace DevelopmentInProgress.TradeView.Wpf.Host.Controller.RegionAdapters { /// <summary> /// Encapsulates behaviours related to the docking manager, keeping /// the documents source in sync with the active views of the <see cref="IRegion"/>. /// </summary> public class DockingManagerBehavior : RegionBehavior, IHostAwareRegionBehavior { private DockingManager dockingManager; /// <summary> /// The target control for the <see cref="IRegion"/>. /// </summary> public DependencyObject HostControl { get { return dockingManager; } set { dockingManager = value as DockingManager; } } /// <summary> /// The DockingManagerBehavior's key used to /// identify it in the region's behavior collection. /// </summary> public static readonly string BehaviorKey = "DockingManagerBehavior"; /// <summary> /// Register to handle region events. /// </summary> protected override void OnAttach() { dockingManager.ActiveContentChanged += DockingManagerActiveContentChanged; Region.ActiveViews.CollectionChanged += ActiveViewsCollectionChanged; Region.Views.CollectionChanged += ViewsCollectionChanged; ModulesNavigationView.ModuleSelected += ModuleSelected; } /// <summary> /// Handles the changing of the active content. /// Notify the active content that it is now 'active' /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DockingManagerActiveContentChanged(object sender, EventArgs e) { var documentViewHost = dockingManager.ActiveContent as DocumentViewHost; documentViewHost?.View?.OnActiveChanged(true); } /// <summary> /// Handles changes to the <see cref="IRegion"/> views collection, adding /// or removing items to the <see cref="HostControl"/> document source. /// </summary> /// <param name="sender">The <see cref="IRegion"/> views collection.</param> /// <param name="e">Event arguments.</param> private void ViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { foreach (object newItem in e.NewItems) { if (newItem is DocumentViewBase documentViewBase) { // Get the LayoutDocumentPane from the // LayoutDocumentPaneControl and add the // new document to it. var layoutDocumentPaneControl = dockingManager .FindVisualChildren<LayoutDocumentPaneControl>() .First(); var layoutDocumentPane = (LayoutDocumentPane)layoutDocumentPaneControl.Model; // Create an AvalonDock LayoutAnchorable object and set it as the HostControl of the // documentViewBase. Through the HostControl property of the DocumentViewBase we are // able to access properties on the AvalonDock LayoutAnchorable control such as IsActive. var layoutAnchorable = new LayoutAnchorable(); layoutAnchorable.Closed += LayoutAnchorableClosed; documentViewBase.HostControl = layoutAnchorable; // Create a DocumentView object passing the documentViewBase into its // constructor, where it gets set as the main content of the DocumentView. var documentView = new DocumentViewHost(documentViewBase); // Then set the documentView as the content // of the AvalonDock LayoutAnchorable control // and add the LayoutAnchorable control to the // LayoutDocumentPane's childrens's collection, // and set the LayoutAnchorable control as the // dockingManager's active content. layoutAnchorable.Content = documentView; layoutDocumentPane.Children.Add(layoutAnchorable); dockingManager.ActiveContent = layoutAnchorable; } } } } /// <summary> /// Removes the document from the <see cref="IRegion"/> after it has been closed. /// If you don't do this the document will not be removed but just hidden and you /// will not be able to open it again as prism will already think it exists. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">LayoutAnchorable closed event arguments.</param> private void LayoutAnchorableClosed(object sender, EventArgs e) { if (!(sender is LayoutAnchorable layoutAnchorable)) { return; } layoutAnchorable.Closed -= LayoutAnchorableClosed; var view = ((DocumentViewHost)layoutAnchorable.Content).View; if (Region.Views.Contains(view)) { view.CloseDocument(); Region.RegionManager.Regions["DocumentRegion"].Remove(view); } } /// <summary> /// Keeps the active content of the <see cref="IRegion"/> in sync with the <see cref="HostControl"/>. /// </summary> /// <param name="sender">The <see cref="IRegion"/> views collection.</param> /// <param name="e">Event arguments.</param> private void ActiveViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { if (dockingManager.ActiveContent != null && dockingManager.ActiveContent != e.NewItems[0] && Region.ActiveViews.Contains(dockingManager.ActiveContent)) { Region.Deactivate(dockingManager.ActiveContent); } dockingManager.ActiveContent = e.NewItems[0]; } else if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems.Contains(dockingManager.ActiveContent)) { dockingManager.ActiveContent = null; } } /// <summary> /// Toggles between modules, showing documents available to the current /// selected module, while hidding documents relating to other modules. /// </summary> /// <param name="sender">The <see cref="ModulesNavigationView"/>.</param> /// <param name="e">Module event arguments.</param> private void ModuleSelected(object sender, ModuleEventArgs e) { var layoutAnchorablesHide = dockingManager.Layout.Descendents() .OfType<LayoutAnchorable>() .Where(la => !((DocumentViewHost)la.Content).ModuleName.Equals(e.ModuleName, StringComparison.OrdinalIgnoreCase)); var anchorablesHide = layoutAnchorablesHide.ToList(); var layoutAnchorablesShow = dockingManager.Layout.Descendents() .OfType<LayoutAnchorable>() .Where(la => ((DocumentViewHost)la.Content).ModuleName.Equals(e.ModuleName, StringComparison.OrdinalIgnoreCase)); var anchorablesShow = layoutAnchorablesShow.ToList(); for (int i = 0; i < anchorablesHide.Count; i++) { anchorablesHide[i].Hide(); var documentViewHost = anchorablesHide[i].Content as DocumentViewHost; documentViewHost.View.OnActiveChanged(false); } for (int i = 0; i < anchorablesShow.Count; i++) { anchorablesShow[i].Show(); } } } }
43.839024
130
0.57739
[ "Apache-2.0" ]
CasparsTools/tradeview
src/DevelopmentInProgress.TradeView.WPF.Host.Controller/RegionAdapters/DockingManagerBehavior.cs
8,990
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Drawing.Tests { public class ImageAnimatorTests { [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_WithNothingAnimating() { ImageAnimator.UpdateFrames(); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData("1bit.png")] [InlineData("48x48_one_entry_1bit.ico")] [InlineData("81773-interlaced.gif")] public void CanAnimate_ReturnsFalse_ForNonAnimatedImages(string imageName) { using (var image = new Bitmap(Helpers.GetTestBitmapPath(imageName))) { Assert.False(ImageAnimator.CanAnimate(image)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Animate_Succeeds_ForNonAnimatedImages_WithNothingAnimating() { var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.Animate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Animate_Succeeds_ForNonAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.Animate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_ForNonAnimatedImages_WithNothingAnimating() { var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.UpdateFrames(image); } [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_ForNonAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.UpdateFrames(image); } [ConditionalFact(Helpers.IsDrawingSupported)] public void StopAnimate_Succeeds_ForNonAnimatedImages_WithNothingAnimating() { var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.StopAnimate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void StopAnimate_Succeeds_ForNonAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); var image = new Bitmap(Helpers.GetTestBitmapPath("1bit.png")); ImageAnimator.StopAnimate(image, (object o, EventArgs e) => { }); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData("animated-timer-1fps-repeat-2.gif")] [InlineData("animated-timer-1fps-repeat-infinite.gif")] [InlineData("animated-timer-10fps-repeat-2.gif")] [InlineData("animated-timer-10fps-repeat-infinite.gif")] [InlineData("animated-timer-100fps-repeat-2.gif")] [InlineData("animated-timer-100fps-repeat-infinite.gif")] public void CanAnimate_ReturnsTrue_ForAnimatedImages(string imageName) { using (var image = new Bitmap(Helpers.GetTestBitmapPath(imageName))) { Assert.True(ImageAnimator.CanAnimate(image)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Animate_Succeeds_ForAnimatedImages_WithNothingAnimating() { var image = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Animate_Succeeds_ForAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); var image = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-infinite.gif")); ImageAnimator.Animate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_ForAnimatedImages_WithNothingAnimating() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.UpdateFrames(animatedImage); } [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); ImageAnimator.UpdateFrames(); } [ConditionalFact(Helpers.IsDrawingSupported)] public void UpdateFrames_Succeeds_ForAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); ImageAnimator.UpdateFrames(animatedImage); } [ConditionalFact(Helpers.IsDrawingSupported)] public void StopAnimate_Succeeds_ForAnimatedImages_WithNothingAnimating() { var image = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.StopAnimate(image, (object o, EventArgs e) => { }); } [ConditionalFact(Helpers.IsDrawingSupported)] public void StopAnimate_Succeeds_ForAnimatedImages_WithCurrentAnimations() { var animatedImage = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-2.gif")); ImageAnimator.Animate(animatedImage, (object o, EventArgs e) => { }); var image = new Bitmap(Helpers.GetTestBitmapPath("animated-timer-100fps-repeat-infinite.gif")); ImageAnimator.StopAnimate(animatedImage, (object o, EventArgs e) => { }); ImageAnimator.StopAnimate(image, (object o, EventArgs e) => { }); } } }
44.062893
108
0.666429
[ "MIT" ]
333fred/runtime
src/libraries/System.Drawing.Common/tests/System/Drawing/ImageAnimatorTests.cs
7,008
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.ResourceManager.Compute.Models { /// <summary> Specifies information about the SSH public key. </summary> public partial class PatchableSshPublicKeyData : UpdateResource { /// <summary> Initializes a new instance of PatchableSshPublicKeyData. </summary> public PatchableSshPublicKeyData() { } /// <summary> SSH public key used to authenticate to a virtual machine through ssh. If this property is not initially provided when the resource is created, the publicKey property will be populated when generateKeyPair is called. If the public key is provided upon resource creation, the provided public key needs to be at least 2048-bit and in ssh-rsa format. </summary> public string PublicKey { get; set; } } }
42.090909
379
0.726782
[ "MIT" ]
AikoBB/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/PatchableSshPublicKeyData.cs
926
C#
using System.IO; namespace GameEstate.Tes.Formats.Records { public class EYESRecord : Record { public override string ToString() => $"EYES: {EDID.Value}"; public STRVField EDID { get; set; } // Editor ID public STRVField FULL; public FILEField ICON; public BYTEField DATA; // Playable public override bool CreateField(BinaryReader r, TesFormat format, string type, int dataSize) { switch (type) { case "EDID": EDID = r.ReadSTRV(dataSize); return true; case "FULL": FULL = r.ReadSTRV(dataSize); return true; case "ICON": ICON = r.ReadFILE(dataSize); return true; case "DATA": DATA = r.ReadT<BYTEField>(dataSize); return true; default: return false; } } } }
34.96
102
0.552632
[ "MIT" ]
bclnet/GameEstate
src/Estates/Tes/GameEstate.Tes/Formats/Records/045-EYES.Eyes.cs
876
C#
using System.Threading.Tasks; namespace Messenger.Client.Console { public interface IMessenger { Task ConnectAsync(); Task StartChatAsync(); } }
15.3
34
0.751634
[ "MIT" ]
leodeg/CSharp.SignalR.Messenger
Messenger/Messenger.Client.Console/IMessenger.cs
155
C#
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2015 Ingo Herbote * http://www.yetanotherforum.net/ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace YAF.Providers.Roles { using System; using System.Collections.Concurrent; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Linq; using System.Web.Security; using YAF.Classes.Pattern; using YAF.Core; using YAF.Types.Extensions; using YAF.Types.Interfaces; using YAF.Types.Constants; using YAF.Types; using YAF.Utils; using YAF.Providers.Utils; /// <summary> /// The yaf role provider. /// </summary> public class YafRoleProvider : RoleProvider { #region Constants and Fields /// <summary> /// The conn str app key name. /// </summary> private static string _connStrAppKeyName = "YafRolesConnectionString"; /// <summary> /// The _app name. /// </summary> private string _appName; /// <summary> /// The _conn str name. /// </summary> private string _connStrName; #endregion #region Properties /// <summary> /// Gets the Connection String App Key Name. /// </summary> public static string ConnStrAppKeyName { get { return _connStrAppKeyName; } } /// <summary> /// Gets or sets ApplicationName. /// </summary> public override string ApplicationName { get { return this._appName; } set { if (value != this._appName) { this._appName = value; // clear the cache for obvious reasons... this.ClearUserRoleCache(); } } } private ConcurrentDictionary<string, StringCollection> _userRoleCache = null; /// <summary> /// Gets UserRoleCache. /// </summary> private ConcurrentDictionary<string, StringCollection> UserRoleCache { get { string key = this.GenerateCacheKey("UserRoleDictionary"); return this._userRoleCache ?? (this._userRoleCache = YafContext.Current.Get<IObjectStore>().GetOrSet( key, () => new ConcurrentDictionary<string, StringCollection>())); } } #endregion #region Public Methods /// <summary> /// Adds a list of users to a list of groups /// </summary> /// <param name="usernames"> /// List of Usernames /// </param> /// <param name="roleNames"> /// List of Rolenames /// </param> public override void AddUsersToRoles(string[] usernames, string[] roleNames) { if (usernames == null || usernames.Length == 0) { throw new ArgumentException("usernames is null or empty.", "usernames"); } if (roleNames == null || roleNames.Length == 0) { throw new ArgumentException("roleNames is null or empty.", "roleNames"); } // Loop through username foreach (string username in usernames) { var allRoles = this.GetAllRoles().ToList(); // Loop through roles foreach (string roleName in roleNames) { // only add user if this role actually exists... if (roleName.IsSet() && allRoles.Contains(roleName)) { DB.Current.AddUserToRole(this.ApplicationName, username, roleName); } } // invalidate the cache for this user... this.DeleteFromRoleCacheIfExists(username.ToLower()); } } /// <summary> /// Creates a role /// </summary> /// <param name="roleName"> /// </param> public override void CreateRole(string roleName) { if (roleName.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "ROLENAMEBLANK"); } DB.Current.CreateRole(this.ApplicationName, roleName); } /// <summary> /// Deletes a role /// </summary> /// <param name="roleName"> /// </param> /// <param name="throwOnPopulatedRole"> /// </param> /// <returns> /// True or False /// </returns> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { int returnValue = DB.Current.DeleteRole(this.ApplicationName, roleName, throwOnPopulatedRole); this.ClearUserRoleCache(); // zero means there were no complications... return returnValue == 0; } /// <summary> /// Adds a list of users to a list of groups /// </summary> /// <param name="roleName"> /// Rolename /// </param> /// <param name="usernameToMatch"> /// like Username used in search /// </param> /// <returns> /// List of Usernames /// </returns> public override string[] FindUsersInRole(string roleName, string usernameToMatch) { if (roleName.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "ROLENAMEBLANK"); } // Roles DataTable users = DB.Current.FindUsersInRole(this.ApplicationName, roleName); var usernames = new StringCollection(); foreach (DataRow user in users.Rows) { usernames.Add(user["Username"].ToStringDBNull()); } return usernames.ToStringArray(); } /// <summary> /// Grabs all the roles from the DB /// </summary> /// <returns> /// </returns> public override string[] GetAllRoles() { // get all roles... DataTable roles = DB.Current.GetRoles(this.ApplicationName, null); // make a string collection to store the role list... var roleNames = new StringCollection(); foreach (DataRow row in roles.Rows) { roleNames.Add(row["RoleName"].ToStringDBNull()); } return roleNames.ToStringArray(); // return as a string array } /// <summary> /// Grabs all the roles from the DB /// </summary> /// <param name="username"> /// The username. /// </param> /// <returns> /// </returns> public override string[] GetRolesForUser(string username) { if (username.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "USERNAMEBLANK"); } StringCollection roleNames = null; // get the users's collection from the dictionary if (!this.UserRoleCache.ContainsKey(username.ToLower())) { roleNames = new StringCollection(); DataTable roles = DB.Current.GetRoles(this.ApplicationName, username); foreach (DataRow dr in roles.Rows) { roleNames.Add(dr["Rolename"].ToStringDBNull()); // add rolename to collection } // add it to the dictionary cache... this.UserRoleCache.AddOrUpdate(username.ToLower(), (k) => roleNames, (s, v) => roleNames); } else { roleNames = this.UserRoleCache[username.ToLower()]; } return roleNames.ToStringArray(); // return as a string array } /// <summary> /// Gets a list of usernames in a a particular role /// </summary> /// <param name="roleName"> /// Rolename /// </param> /// <returns> /// List of Usernames /// </returns> public override string[] GetUsersInRole(string roleName) { if (roleName.IsNotSet()) { ExceptionReporter.ThrowArgument("ROLES", "ROLENAMEBLANK"); } DataTable users = DB.Current.FindUsersInRole(this.ApplicationName, roleName); var userNames = new StringCollection(); foreach (DataRow dr in users.Rows) { userNames.Add(dr["Username"].ToStringDBNull()); } return userNames.ToStringArray(); } /// <summary> /// Sets up the profile providers /// </summary> /// <param name="name"> /// </param> /// <param name="config"> /// </param> public override void Initialize(string name, NameValueCollection config) { // verify that the configuration section was properly passed if (config == null) { ExceptionReporter.ThrowArgument("ROLES", "CONFIGNOTFOUND"); } // Connection String Name this._connStrName = config["connectionStringName"].ToStringDBNull(); ConnStringHelpers.TrySetProviderConnectionString(this._connStrName, ConnStrAppKeyName); base.Initialize(name, config); // application name this._appName = config["applicationName"]; if (string.IsNullOrEmpty(this._appName)) { this._appName = "YetAnotherForum"; } } /// <summary> /// Check to see if user belongs to a role /// </summary> /// <param name="username"> /// Username /// </param> /// <param name="roleName"> /// Rolename /// </param> /// <returns> /// True/False /// </returns> public override bool IsUserInRole(string username, string roleName) { DataTable roles = DB.Current.IsUserInRole(this.ApplicationName, username, roleName); return roles.HasRows(); } /// <summary> /// Remove Users From Roles /// </summary> /// <param name="usernames"> /// Usernames /// </param> /// <param name="roleNames"> /// Rolenames /// </param> public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { // Loop through username foreach (string username in usernames) { // Loop through roles foreach (string roleName in roleNames) { DB.Current.RemoveUserFromRole(this.ApplicationName, username, roleName); // Remove role // invalidate cache for this user... this.DeleteFromRoleCacheIfExists(username.ToLower()); } } } /// <summary> /// Check to see if a role exists /// </summary> /// <param name="roleName"> /// Rolename /// </param> /// <returns> /// True/False /// </returns> public override bool RoleExists(string roleName) { // get this role... object exists = DB.Current.GetRoleExists(this.ApplicationName, roleName); // if there are any rows then this role exists... if (Convert.ToInt32(exists) > 0) { return true; } // doesn't exist return false; } #endregion #region Methods /// <summary> /// The clear user role cache. /// </summary> private void ClearUserRoleCache() { string key = this.GenerateCacheKey("UserRoleDictionary"); YafContext.Current.Get<IObjectStore>().Remove(key); } /// <summary> /// The delete from role cache if exists. /// </summary> /// <param name="key"> /// The key. /// </param> private void DeleteFromRoleCacheIfExists(string key) { StringCollection collection; this.UserRoleCache.TryRemove(key, out collection); } /// <summary> /// The generate cache key. /// </summary> /// <param name="name"> /// The name. /// </param> /// <returns> /// The generate cache key. /// </returns> private string GenerateCacheKey(string name) { return "YafRoleProvider-{0}-{1}".FormatWith(name, this.ApplicationName); } #endregion } }
31.202614
108
0.505167
[ "Apache-2.0" ]
TristanTong/bbsWirelessTag
yafsrc/YAF.Providers/Roles/YafRoleProvider.cs
13,865
C#
using SEDC.TryBeingFit.Domain.Core.Entities; using System; using System.Collections.Generic; using System.Text; namespace SEDC.TryBeingFit.Domain.Db { public interface IDb<T> where T : BaseEntity { List<T> GetAll(); T GetById(int id); int Insert(T entity); void RemoveById(int id); void Update(T entity); } }
19.058824
45
0.728395
[ "MIT" ]
sedc-codecademy/skwd8-06-csharpadv
g4/06-Fitness/SEDC.TryBeingFit/SEDC.TryBeingFit.Domain/Db/IDb.cs
326
C#
// Copyright (c) SimpleIdServer. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ProtectAPIFromUndesirableUsers.Api { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
31.526316
107
0.681135
[ "Apache-2.0" ]
LaTranche31/SimpleIdServer
samples/ProtectAPIFromUndesirableUsers/src/ProtectAPIFromUndesirableUsers.Api/Program.cs
601
C#
using System; using System.Collections.Generic; namespace DurandalAuth.Domain.Models { public partial class afm_cal_dates { public string day_type { get; set; } public string description { get; set; } public string transfer_status { get; set; } public System.DateTime cal_date { get; set; } } }
24.285714
53
0.664706
[ "MIT" ]
benitazz/AlcmSolutions
DurandalAuth.Domain/Models/afm_cal_dates.cs
340
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Metadata.Edm { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Entity.Core.Common; using System.Data.Entity.Spatial; using System.Data.Entity.Utilities; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; /// <summary> /// Class representing a primitive type /// </summary> public class PrimitiveType : SimpleType { // <summary> // Initializes a new instance of PrimitiveType // </summary> internal PrimitiveType() { // No initialization of item attributes in here, it's used as a pass thru in the case for delay population // of item attributes } // <summary> // The constructor for PrimitiveType. It takes the required information to identify this type. // </summary> // <param name="name"> The name of this type </param> // <param name="namespaceName"> The namespace name of this type </param> // <param name="dataSpace"> dataSpace in which this primitive type belongs to </param> // <param name="baseType"> The primitive type that this type is derived from </param> // <param name="providerManifest"> The ProviderManifest of the provider of this type </param> // <exception cref="System.ArgumentNullException">Thrown if name, namespaceName, version, baseType or providerManifest arguments are null</exception> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal PrimitiveType( string name, string namespaceName, DataSpace dataSpace, PrimitiveType baseType, DbProviderManifest providerManifest) : base(name, namespaceName, dataSpace) { Check.NotNull(baseType, "baseType"); Check.NotNull(providerManifest, "providerManifest"); BaseType = baseType; Initialize(this, baseType.PrimitiveTypeKind, providerManifest); } // <summary> // The constructor for PrimitiveType, it takes in a CLR type containing the identity information // </summary> // <param name="clrType"> The CLR type object for this primitive type </param> // <param name="baseType"> The base type for this primitive type </param> // <param name="providerManifest"> The ProviderManifest of the provider of this type </param> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] internal PrimitiveType( Type clrType, PrimitiveType baseType, DbProviderManifest providerManifest) : this(Check.NotNull(clrType, "clrType").Name, clrType.NestingNamespace(), DataSpace.OSpace, baseType, providerManifest) { Debug.Assert(clrType == ClrEquivalentType, "not equivalent to ClrEquivalentType"); } private PrimitiveTypeKind _primitiveTypeKind; private DbProviderManifest _providerManifest; /// <summary> /// Gets the built-in type kind for this <see cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" />. /// </summary> /// <returns> /// A <see cref="T:System.Data.Entity.Core.Metadata.Edm.BuiltInTypeKind" /> object that represents the built-in type kind for this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> public override BuiltInTypeKind BuiltInTypeKind { get { return BuiltInTypeKind.PrimitiveType; } } internal override Type ClrType { get { return ClrEquivalentType; } } /// <summary> /// Gets a <see cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveTypeKind" /> enumeration value that indicates a primitive type of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </summary> /// <returns> /// A <see cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveTypeKind" /> enumeration value that indicates a primitive type of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> [MetadataProperty(BuiltInTypeKind.PrimitiveTypeKind, false)] public virtual PrimitiveTypeKind PrimitiveTypeKind { get { return _primitiveTypeKind; } internal set { _primitiveTypeKind = value; } } // <summary> // Returns the ProviderManifest giving access to the Manifest that this type came from // </summary> // <returns> The types ProviderManifest value </returns> internal DbProviderManifest ProviderManifest { get { Debug.Assert( _providerManifest != null, "This primitive type should have been added to a manifest, which should have set this"); return _providerManifest; } set { DebugCheck.NotNull(value); _providerManifest = value; } } /// <summary> /// Gets the list of facet descriptions for this <see cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" />. /// </summary> /// <returns> /// A collection of type <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1" /> that contains the list of facet descriptions for this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> public virtual ReadOnlyCollection<FacetDescription> FacetDescriptions { get { return ProviderManifest.GetFacetDescriptions(this); } } /// <summary> /// Returns an equivalent common language runtime (CLR) type of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . Note that the /// <see /// cref="P:System.Data.Entity.Core.Metadata.Edm.PrimitiveType.ClrEquivalentType" /> /// property always returns a non-nullable type value. /// </summary> /// <returns> /// A <see cref="T:System.Type" /> object that represents an equivalent common language runtime (CLR) type of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> public Type ClrEquivalentType { get { switch (PrimitiveTypeKind) { case PrimitiveTypeKind.Binary: return typeof(byte[]); case PrimitiveTypeKind.Boolean: return typeof(bool); case PrimitiveTypeKind.Byte: return typeof(byte); case PrimitiveTypeKind.DateTime: return typeof(DateTime); case PrimitiveTypeKind.Time: return typeof(TimeSpan); case PrimitiveTypeKind.DateTimeOffset: return typeof(DateTimeOffset); case PrimitiveTypeKind.Decimal: return typeof(decimal); case PrimitiveTypeKind.Double: return typeof(double); case PrimitiveTypeKind.Geography: case PrimitiveTypeKind.GeographyPoint: case PrimitiveTypeKind.GeographyLineString: case PrimitiveTypeKind.GeographyPolygon: case PrimitiveTypeKind.GeographyMultiPoint: case PrimitiveTypeKind.GeographyMultiLineString: case PrimitiveTypeKind.GeographyMultiPolygon: case PrimitiveTypeKind.GeographyCollection: return typeof(DbGeography); case PrimitiveTypeKind.Geometry: case PrimitiveTypeKind.GeometryPoint: case PrimitiveTypeKind.GeometryLineString: case PrimitiveTypeKind.GeometryPolygon: case PrimitiveTypeKind.GeometryMultiPoint: case PrimitiveTypeKind.GeometryMultiLineString: case PrimitiveTypeKind.GeometryMultiPolygon: case PrimitiveTypeKind.GeometryCollection: return typeof(DbGeometry); case PrimitiveTypeKind.Guid: return typeof(Guid); case PrimitiveTypeKind.Single: return typeof(Single); case PrimitiveTypeKind.SByte: return typeof(sbyte); case PrimitiveTypeKind.Int16: return typeof(short); case PrimitiveTypeKind.Int32: return typeof(int); case PrimitiveTypeKind.Int64: return typeof(long); case PrimitiveTypeKind.String: return typeof(string); } return null; } } internal override IEnumerable<FacetDescription> GetAssociatedFacetDescriptions() { // return all general facets and facets associated with this type return base.GetAssociatedFacetDescriptions().Concat(FacetDescriptions); } // <summary> // Perform initialization that's common across all constructors // </summary> // <param name="primitiveType"> The primitive type to initialize </param> // <param name="primitiveTypeKind"> The primitive type kind of this primitive type </param> // <param name="providerManifest"> The ProviderManifest of the provider of this type </param> internal static void Initialize( PrimitiveType primitiveType, PrimitiveTypeKind primitiveTypeKind, DbProviderManifest providerManifest) { primitiveType._primitiveTypeKind = primitiveTypeKind; primitiveType._providerManifest = providerManifest; } /// <summary> /// Returns the equivalent <see cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" /> of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </summary> /// <remarks> /// For example if this instance is nvarchar and it's /// base type is Edm String then the return type is Edm String. /// If the type is actually already a model type then the /// return type is "this". /// </remarks> /// <returns> /// An <see cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" /> object that is an equivalent of this /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> public EdmType GetEdmPrimitiveType() { return EdmProviderManifest.GetPrimitiveType(PrimitiveTypeKind); } /// <summary>Returns the list of primitive types.</summary> /// <returns> /// A collection of type <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1" /> that contains the list of primitive types. /// </returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static ReadOnlyCollection<PrimitiveType> GetEdmPrimitiveTypes() { return EdmProviderManifest.GetStoreTypes(); } /// <summary> /// Returns the equivalent <see cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" /> of a /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </summary> /// <returns> /// An <see cref="T:System.Data.Entity.Core.Metadata.Edm.EdmType" /> object that is an equivalent of a specified /// <see /// cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" /> /// . /// </returns> /// <param name="primitiveTypeKind"> /// A value of type <see cref="T:System.Data.Entity.Core.Metadata.Edm.PrimitiveType" />. /// </param> public static PrimitiveType GetEdmPrimitiveType(PrimitiveTypeKind primitiveTypeKind) { return EdmProviderManifest.GetPrimitiveType(primitiveTypeKind); } } }
44.044068
157
0.589317
[ "Apache-2.0" ]
Engineerumair/EntityFramework6
src/EntityFramework/Core/Metadata/Edm/PrimitiveType.cs
12,993
C#
using System; using System.Collections.Generic; using LynnaLib; namespace LynnaLab { public class ValueReferenceEditor : Gtk.Alignment { ValueReferenceGroup valueReferenceGroup; IList<int> maxBounds; // List of "grid" objects corresponding to each widget IList<Gtk.Grid> widgetGrids; // X/Y positions where the widgets are in the grid IList<Tuple<int,int>> widgetPositions; // The widgets by index. IList<IList<Gtk.Widget>> widgetLists; event System.Action dataModifiedExternalEvent; event System.Action dataModifiedInternalEvent; Project Project {get; set;} public ValueReferenceGroup ValueReferenceGroup { get { return valueReferenceGroup; } } public ValueReferenceEditor(Project p, ValueReferenceGroup vrg, string frameText=null) : this(p, vrg, 50, frameText) { } public ValueReferenceEditor(Project p, ValueReferenceGroup vrg, int rows, string frameText=null) : base(1.0F,1.0F,1.0F,1.0F) { Project = p; valueReferenceGroup = vrg; maxBounds = new int[valueReferenceGroup.GetNumValueReferences()]; widgetGrids = new List<Gtk.Grid>(); widgetPositions = new Tuple<int,int>[maxBounds.Count]; widgetLists = new List<IList<Gtk.Widget>>(); Gtk.Box hbox = new Gtk.HBox(); hbox.Spacing = 6; Func<Gtk.Grid> newGrid = () => { Gtk.Grid g = new Gtk.Grid(); g.ColumnSpacing = 6; g.RowSpacing = 2; hbox.Add(g); return g; }; Gtk.Grid grid = newGrid(); int x=0,y=0; // Do not use "foreach" here. The "valueReferenceGroup" may be changed. So, whenever we // access a ValueReference from within an event handler, we must do so though the // "valueReferenceGroup" class variable, and NOT though an alias (like with foreach). for (int tmpCounter=0; tmpCounter < valueReferenceGroup.Count; tmpCounter++) { int i = tmpCounter; // Variable must be distinct within each closure if (y >= rows) { y = 0; x = 0; grid = newGrid(); } // Each ValueReference may use up to 3 widgets in the grid row Gtk.Widget[] widgetList = new Gtk.Widget[3]; widgetPositions[i] = new Tuple<int,int>(x,y); Action<Gtk.SpinButton> setSpinButtonLimits = (spinButton) => { if (valueReferenceGroup[i].MaxValue < 0x10) spinButton.Digits = 1; else if (valueReferenceGroup[i].MaxValue < 0x100) spinButton.Digits = 2; else if (valueReferenceGroup[i].MaxValue < 0x1000) spinButton.Digits = 3; else spinButton.Digits = 4; spinButton.Adjustment.Lower = valueReferenceGroup[i].MinValue; spinButton.Adjustment.Upper = valueReferenceGroup[i].MaxValue; }; int entryWidgetWidth = 1; // If it has a ConstantsMapping, use a combobox instead of anything else if (valueReferenceGroup[i].ConstantsMapping != null) { ComboBoxFromConstants comboBox = new ComboBoxFromConstants(showHelp:true, vertical:true); comboBox.SetConstantsMapping(valueReferenceGroup[i].ConstantsMapping); // Must put this before the "Changed" handler below to avoid // it being fired (for some reason?) setSpinButtonLimits(comboBox.SpinButton); comboBox.Changed += delegate(object sender, EventArgs e) { valueReferenceGroup[i].SetValue(comboBox.ActiveValue); OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { comboBox.ActiveValue = valueReferenceGroup[i].GetIntValue (); }; /* comboBox.MarginTop = 4; comboBox.MarginBottom = 4; */ widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); widgetList[1] = comboBox; entryWidgetWidth = 2; goto loopEnd; } // ConstantsMapping == null switch(valueReferenceGroup[i].ValueType) { case ValueReferenceType.String: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); Gtk.Entry entry = new Gtk.Entry(); if (!valueReferenceGroup[i].Editable) entry.Sensitive = false; dataModifiedExternalEvent += delegate() { entry.Text = valueReferenceGroup[i].GetStringValue(); OnDataModifiedInternal(); }; widgetList[1] = entry; break; } case ValueReferenceType.Int: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); SpinButtonHexadecimal spinButton = new SpinButtonHexadecimal(valueReferenceGroup[i].MinValue, valueReferenceGroup[i].MaxValue); if (!valueReferenceGroup[i].Editable) spinButton.Sensitive = false; setSpinButtonLimits(spinButton); spinButton.ValueChanged += delegate(object sender, EventArgs e) { Gtk.SpinButton button = sender as Gtk.SpinButton; if (maxBounds[i] == 0 || button.ValueAsInt <= maxBounds[i]) { valueReferenceGroup[i].SetValue(button.ValueAsInt); } else button.Value = maxBounds[i]; OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { spinButton.Value = valueReferenceGroup[i].GetIntValue(); }; widgetList[1] = spinButton; } break; case ValueReferenceType.Bool: { widgetList[0] = new Gtk.Label(valueReferenceGroup[i].Name); Gtk.CheckButton checkButton = new Gtk.CheckButton(); checkButton.FocusOnClick = false; if (!valueReferenceGroup[i].Editable) checkButton.Sensitive = false; checkButton.Toggled += delegate(object sender, EventArgs e) { Gtk.CheckButton button = sender as Gtk.CheckButton; valueReferenceGroup[i].SetValue(button.Active ? 1 : 0); OnDataModifiedInternal(); }; dataModifiedExternalEvent += delegate() { checkButton.Active = valueReferenceGroup[i].GetIntValue() == 1; }; widgetList[1] = checkButton; } break; } loopEnd: grid.Attach(widgetList[0], x, y, 1, 1); grid.Attach(widgetList[1], x+1, y, entryWidgetWidth, 1); widgetList[2] = new Gtk.Alignment(0, 0.5f, 0, 0); // Container for help button widgetList[2].Hexpand = true; // Let this absorb any extra space grid.Attach(widgetList[2], x+2, y, 1, 1); widgetGrids.Add(grid); widgetLists.Add(widgetList); if (valueReferenceGroup[i].Tooltip != null) { SetTooltip(i, valueReferenceGroup[i].Tooltip); } y++; } if (frameText != null) { var frame = new Gtk.Frame(frameText); frame.Add(hbox); this.Add(frame); } else this.Add(hbox); this.ShowAll(); // Initial values if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); UpdateHelpButtons(); AddModifiedHandlers(); this.Destroyed += (sender, args) => RemoveModifiedHandlers(); } void AddModifiedHandlers() { foreach (ValueReference vref in valueReferenceGroup.GetValueReferences()) { vref.AddValueModifiedHandler(OnDataModifiedExternal); } } void RemoveModifiedHandlers() { foreach (ValueReference vref in valueReferenceGroup.GetValueReferences()) { vref.RemoveValueModifiedHandler(OnDataModifiedExternal); } } // ONLY call this function if the new ValueReferenceGroup matches the exact structure of the // old one. If there is any mismatch, a new ValueReferenceEditor should be created instead. // But when the structures do match exactly, this is preferred, so that we don't need to // recreate all of the necessary widgets again. public void ReplaceValueReferenceGroup(ValueReferenceGroup vrg) { RemoveModifiedHandlers(); this.valueReferenceGroup = vrg; AddModifiedHandlers(); // Even if we're not rebuilding the widgets we can at least check for minor changes like // to the "editable" variable for (int i=0; i<ValueReferenceGroup.Count; i++) { Gtk.Widget w = widgetLists[i][1]; w.Sensitive = ValueReferenceGroup[i].Editable; SetTooltip(i, ValueReferenceGroup[i].Tooltip); } // Initial values if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); UpdateHelpButtons(); } public void SetMaxBound(int i, int max) { if (i == -1) return; maxBounds[i] = max; } // Substitute the widget for a value (index "i") with the new widget. (Currently unused) public void ReplaceWidget(string name, Gtk.Widget newWidget) { int i = GetValueIndex(name); widgetLists[i][1].Dispose(); var pos = widgetPositions[i]; widgetGrids[i].Attach(newWidget, pos.Item1+1, pos.Item2, 1, 1); widgetLists[i][1] = newWidget; } // Can replace the help button widget with something else. However if you put a container // there it could get overwritten with a help button again. public void AddWidgetToRight(string name, Gtk.Widget widget) { int i = GetValueIndex(name); widgetLists[i][2].Dispose(); // Removes help button widgetLists[i][2] = widget; var pos = widgetPositions[i]; widgetGrids[i].Attach(widget, pos.Item1+2, pos.Item2, 1, 1); } int GetValueIndex(string name) { for (int i = 0; i < valueReferenceGroup.Count; i++) { if (valueReferenceGroup[i].Name == name) return i; } throw new ArgumentException("Couldn't find '" + name + "' in ValueReferenceGroup."); } public void SetTooltip(int i, string tooltip) { for (int j=0; j<widgetLists[i].Count; j++) widgetLists[i][j].TooltipText = tooltip; } public void SetTooltip(ValueReference r, string tooltip) { SetTooltip(valueReferenceGroup.GetIndexOf(r), tooltip); } public void SetTooltip(string name, string tooltip) { SetTooltip(valueReferenceGroup.GetValueReference(name), tooltip); } public void AddDataModifiedHandler(System.Action handler) { dataModifiedInternalEvent += handler; } public void RemoveDataModifiedHandler(System.Action handler) { dataModifiedInternalEvent -= handler; } // Data modified externally void OnDataModifiedExternal(object sender, ValueModifiedEventArgs e) { if (dataModifiedExternalEvent != null) dataModifiedExternalEvent(); } // Data modified internally void OnDataModifiedInternal() { if (dataModifiedInternalEvent != null) dataModifiedInternalEvent(); } // Check if there are entries that should have help buttons public void UpdateHelpButtons() { IList<ValueReference> refs = valueReferenceGroup.GetValueReferences(); for (int i=0; i<refs.Count; i++) { if (widgetLists[i][1] is ComboBoxFromConstants) // These deal with documentation themselves continue; Gtk.Container container = widgetLists[i][2] as Gtk.Container; if (container == null) continue; bool isHelpButton = true; // Remove previous help button foreach (Gtk.Widget widget in container.Children) { // Really hacky way to check whether this is the help button as we expect, or // whether the "AddWidgetToRight" function was called to replace it, in which // case we don't try to add the help button at all if (!(widget is Gtk.Button && (widget as Gtk.Button).Label == "?")) { isHelpButton = false; continue; } container.Remove(widget); widget.Dispose(); } if (!isHelpButton) continue; ValueReference r = refs[i]; if (r.Documentation != null) { Gtk.Button helpButton = new Gtk.Button("?"); helpButton.FocusOnClick = false; helpButton.Clicked += delegate(object sender, EventArgs e) { DocumentationDialog d = new DocumentationDialog(r.Documentation); }; container.Add(helpButton); } } this.ShowAll(); } } }
40.486413
120
0.522451
[ "MIT" ]
Drenn1/LynnaLab
LynnaLab/UI/ValueReferenceEditor.cs
14,899
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.NetApp.V20190701 { /// <summary> /// NetApp account resource /// </summary> public partial class Account : Pulumi.CustomResource { /// <summary> /// Active Directories /// </summary> [Output("activeDirectories")] public Output<ImmutableArray<Outputs.ActiveDirectoryResponse>> ActiveDirectories { get; private set; } = null!; /// <summary> /// Resource location /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// Resource name /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Azure lifecycle management /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Resource tags /// </summary> [Output("tags")] public Output<object?> Tags { get; private set; } = null!; /// <summary> /// Resource type /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a Account resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public Account(string name, AccountArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:netapp/v20190701:Account", name, args ?? new AccountArgs(), MakeResourceOptions(options, "")) { } private Account(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:netapp/v20190701:Account", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:netapp/latest:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20170815:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190501:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190601:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20190801:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191001:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20191101:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200201:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200301:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200501:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200601:Account"}, new Pulumi.Alias { Type = "azure-nextgen:netapp/v20200701:Account"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing Account resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static Account Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new Account(name, id, options); } } public sealed class AccountArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the NetApp account /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; [Input("activeDirectories")] private InputList<Inputs.ActiveDirectoryArgs>? _activeDirectories; /// <summary> /// Active Directories /// </summary> public InputList<Inputs.ActiveDirectoryArgs> ActiveDirectories { get => _activeDirectories ?? (_activeDirectories = new InputList<Inputs.ActiveDirectoryArgs>()); set => _activeDirectories = value; } /// <summary> /// Resource location /// </summary> [Input("location", required: true)] public Input<string> Location { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Resource tags /// </summary> [Input("tags")] public Input<object>? Tags { get; set; } public AccountArgs() { } } }
39.266234
127
0.580288
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/NetApp/V20190701/Account.cs
6,047
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using BuildXL.Tracing; using BuildXL.Utilities.Instrumentation.Common; // Suppress missing XML comments on publicly visible types or members #pragma warning disable 1591 #nullable enable namespace BuildXL.FrontEnd.Download.Tracing { /// <summary> /// Logging for the Download frontend and resolvers /// </summary> [EventKeywordsType(typeof(Keywords))] [EventTasksType(typeof(Tasks))] [LoggingDetails("DownloadLogger")] public abstract partial class Logger { private const string ResolverSettingsPrefix = "Error processing download resolver settings: "; /// <summary> /// Returns the logger instance /// </summary> public static Logger Log { get; } = new LoggerImpl(); // Internal logger will prevent public users from creating an instance of the logger internal Logger() { } [GeneratedEvent( (ushort)LogEventId.DownloadFrontendMissingModuleId, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage | Keywords.UserError), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "Missing required field 'id' for download with url: '{url}'.")] public abstract void DownloadFrontendMissingModuleId(LoggingContext context, string url); [GeneratedEvent( (ushort)LogEventId.DownloadFrontendMissingUrl, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage | Keywords.UserError), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "Missing required field 'url' for download with id: '{id}'.")] public abstract void DownloadFrontendMissingUrl(LoggingContext context, string id); [GeneratedEvent( (ushort)LogEventId.DownloadFrontendInvalidUrl, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage | Keywords.UserError), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "Invalid 'url' specified to download id: '{id}' and url: '{url}'. The url must be an absolute url.")] public abstract void DownloadFrontendInvalidUrl(LoggingContext context, string id, string url); [GeneratedEvent( (ushort)LogEventId.DownloadFrontendDuplicateModuleId, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage | Keywords.UserError), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "Duplicate module id '{id}' declared in {kind} resolver named {name}.")] public abstract void DownloadFrontendDuplicateModuleId(LoggingContext context, string id, string kind, string name); [GeneratedEvent( (ushort)LogEventId.DownloadFrontendHashValueNotValidContentHash, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage | Keywords.UserError), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "Invalid hash value 'hash' for download id '{id}' with url '{url}'. It must be a valid content hash format i.e. 'VSO0:000000000000000000000000000000000000000000000000000000000000000000'.")] public abstract void DownloadFrontendHashValueNotValidContentHash(LoggingContext context, string id, string url, string hash); [GeneratedEvent( (ushort)LogEventId.NameContainsInvalidCharacters, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Error, Keywords = (ushort)(Keywords.UserMessage), EventTask = (ushort)Tasks.Parser, Message = ResolverSettingsPrefix + "The string '{name}' specified in '{fieldName}' is not a valid identifier.")] public abstract void NameContainsInvalidCharacters(LoggingContext context, string fieldName, string name); [GeneratedEvent( (ushort)LogEventId.ContextStatistics, EventGenerators = EventGenerators.LocalOnly, EventLevel = Level.Verbose, EventTask = (ushort)Tasks.Parser, Message = "[Download.{0}] contexts: {1} trees, {2} contexts.", Keywords = (int)Keywords.Performance | (int)Keywords.UserMessage)] public abstract void ContextStatistics(LoggingContext context, string name, long contextTrees, long contexts); [GeneratedEvent( (ushort)LogEventId.BulkStatistic, EventGenerators = Generators.Statistics, EventLevel = Level.Verbose, EventTask = (ushort)Tasks.CommonInfrastructure, Message = "N/A", Keywords = (int)Keywords.Diagnostics)] public abstract void BulkStatistic(LoggingContext context, IDictionary<string, long> statistics); } /// <summary> /// Statistics about the parse phase /// </summary> [SuppressMessage("Microsoft.Performance", "CA1815")] public struct DownloadStatistics : IHasEndTime { /// <nodoc /> public int FileSize; /// <inheritdoc /> public int ElapsedMilliseconds { get; set; } } }
45.976
237
0.655994
[ "MIT" ]
DamGouz/BuildXL
Public/Src/FrontEnd/Download/Tracing/Log.cs
5,747
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Nerdbank.Streams; using StreamJsonRpc; using StreamJsonRpc.Protocol; using Xunit; using Xunit.Abstractions; public class SpecialCaseTests : TestBase { public SpecialCaseTests(ITestOutputHelper logger) : base(logger) { } /// <summary> /// Verifies that if the server fails to transmit a response, it drops the connection to avoid a client hang /// while waiting for the response. /// </summary> [Fact] public async Task ResponseTransmissionFailureDropsConnection() { var pair = FullDuplexStream.CreatePair(); var clientRpc = JsonRpc.Attach(pair.Item1); var serverRpc = new JsonRpc(new ThrowingMessageHandler(pair.Item2), new Server()); serverRpc.StartListening(); await Assert.ThrowsAsync<ConnectionLostException>(() => clientRpc.InvokeAsync("Hi")); } private class Server { public void Hi() { } } private class ThrowingMessageHandler : HeaderDelimitedMessageHandler { public ThrowingMessageHandler(Stream duplexStream) : base(duplexStream) { } protected override void Write(JsonRpcMessage content, CancellationToken cancellationToken) { throw new FileNotFoundException(); } } }
28.2
112
0.680851
[ "MIT" ]
arjun27/vs-streamjsonrpc
src/StreamJsonRpc.Tests/SpecialCaseTests.cs
1,553
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Test.It.ApplicationBuilders { public interface IApplicationBuilder { Func<IDictionary<string, object>, CancellationToken, Task> Build(); void Use(IMiddleware middleware); } public interface IApplicationBuilder<in TController> { IApplicationBuilder WithController(TController controller); } }
25.222222
75
0.737885
[ "MIT" ]
Fresa/Test.It
src/Test.It/ApplicationBuilders/IApplicationBuilder.cs
456
C#
namespace Mallos.Serialization { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; public enum SerializeFormat { Json, Xml } public class Serializer { public SerializeFormat Format { get; private set; } public SerializerStream SerializerStream { get; private set; } public Serializer(SerializeFormat format = SerializeFormat.Json, IEnumerable<Type> knownTypes = null) { this.Format = format; this.SerializerStream = CreateSerializer(format, knownTypes); } public void Serialize<T>(string filepath, T value, bool binary = true) { if (binary) { using (var fileStream = new FileStream(filepath, FileMode.Create)) using (Stream stream = new GZipStream(fileStream, CompressionMode.Compress)) { SerializerStream.Serialize(value, stream); } } else { var content = SerializerStream.SerializeContent(value); File.WriteAllText(filepath, content); } } public T Deserialize<T>(string filepath, bool binary = true) { if (!File.Exists(filepath)) { throw new FileNotFoundException($"File doesn't exists. (${filepath})"); } if (binary) { var bytes = DeserializeBinary(filepath); return SerializerStream.Deserialize<T>(bytes); } else { var content = File.ReadAllText(filepath); return SerializerStream.DeserializeContent<T>(content); } } private static byte[] DeserializeBinary(string filepath) { using (var memoryStream = new MemoryStream()) using (var fileStream = new FileStream(filepath, FileMode.Open)) { using (var stream = new GZipStream(fileStream, CompressionMode.Decompress)) { stream.CopyTo(memoryStream); } return memoryStream.ToArray(); } } private static SerializerStream CreateSerializer(SerializeFormat format, IEnumerable<Type> knownTypes) { switch (format) { default: case SerializeFormat.Xml: return new DataContract.SerializerStreamXml(knownTypes: knownTypes); case SerializeFormat.Json: return new DataContract.SerializerStreamJson(knownTypes); } } } }
31.604651
110
0.549669
[ "MIT" ]
Mallos/Mallos.Serialization
src/Serializer.cs
2,718
C#
using System.Linq; using CppSharp.AST; using CppSharp.AST.Extensions; using CppSharp.Generators; namespace CppSharp.Passes { /// <summary> /// Checks for missing operator overloads required by C#. /// </summary> public class CheckOperatorsOverloadsPass : TranslationUnitPass { public CheckOperatorsOverloadsPass() { ClearVisitedDeclarations = false; } public override bool VisitClassDecl(Class @class) { if (@class.CompleteDeclaration != null) return VisitClassDecl(@class.CompleteDeclaration as Class); if (!VisitDeclarationContext(@class)) return false; // Check for C++ operators that cannot be represented in .NET. CheckInvalidOperators(@class); if (Options.IsCSharpGenerator) { // In C# the comparison operators, if overloaded, must be overloaded in pairs; // that is, if == is overloaded, != must also be overloaded. The reverse // is also true, and similar for < and >, and for <= and >=. HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.EqualEqual, CXXOperatorKind.ExclaimEqual); HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.Less, CXXOperatorKind.Greater); HandleMissingOperatorOverloadPair(@class, CXXOperatorKind.LessEqual, CXXOperatorKind.GreaterEqual); } return false; } private void CheckInvalidOperators(Class @class) { foreach (var @operator in @class.Operators.Where(o => o.IsGenerated)) { if (!IsValidOperatorOverload(@operator) || @operator.IsPure) { Diagnostics.Debug("Invalid operator overload {0}::{1}", @class.OriginalName, @operator.OperatorKind); @operator.ExplicitlyIgnore(); continue; } if (@operator.IsNonMemberOperator) continue; if (@operator.OperatorKind == CXXOperatorKind.Subscript) CreateIndexer(@class, @operator); else CreateOperator(@class, @operator); } } private static void CreateOperator(Class @class, Method @operator) { if (@operator.IsStatic) @operator.Parameters.RemoveAt(0); if (@operator.ConversionType.Type == null || @operator.Parameters.Count == 0) { var type = new PointerType { QualifiedPointee = new QualifiedType(new TagType(@class)), Modifier = PointerType.TypeModifier.LVReference }; @operator.Parameters.Insert(0, new Parameter { Name = Generator.GeneratedIdentifier("op"), QualifiedType = new QualifiedType(type), Kind = ParameterKind.OperatorParameter, Namespace = @operator }); } } private void CreateIndexer(Class @class, Method @operator) { var property = new Property { Name = "Item", QualifiedType = @operator.ReturnType, Access = @operator.Access, Namespace = @class, GetMethod = @operator }; var returnType = @operator.Type; if (returnType.IsAddress() && !returnType.GetQualifiedPointee().Type.Desugar().IsPrimitiveType(PrimitiveType.Void)) { var pointer = (PointerType) returnType; var qualifiedPointee = pointer.QualifiedPointee; if (!qualifiedPointee.Qualifiers.IsConst) property.SetMethod = @operator; } // If we've a setter use the pointee as the type of the property. var pointerType = property.Type as PointerType; if (pointerType != null && property.HasSetter) property.QualifiedType = new QualifiedType( pointerType.Pointee, property.QualifiedType.Qualifiers); if (Options.IsCLIGenerator) // C++/CLI uses "default" as the indexer property name. property.Name = "default"; property.Parameters.AddRange(@operator.Parameters); @class.Properties.Add(property); @operator.GenerationKind = GenerationKind.Internal; } private static void HandleMissingOperatorOverloadPair(Class @class, CXXOperatorKind op1, CXXOperatorKind op2) { foreach (var op in @class.Operators.Where( o => o.OperatorKind == op1 || o.OperatorKind == op2).ToList()) { int index; var missingKind = CheckMissingOperatorOverloadPair(@class, out index, op1, op2, op.Parameters.First().Type, op.Parameters.Last().Type); if (missingKind == CXXOperatorKind.None || !op.IsGenerated) continue; var method = new Method() { Name = Operators.GetOperatorIdentifier(missingKind), Namespace = @class, SynthKind = FunctionSynthKind.ComplementOperator, Kind = CXXMethodKind.Operator, OperatorKind = missingKind, ReturnType = op.ReturnType }; method.Parameters.AddRange(op.Parameters.Select( p => new Parameter(p) { Namespace = method })); @class.Methods.Insert(index, method); } } static CXXOperatorKind CheckMissingOperatorOverloadPair(Class @class, out int index, CXXOperatorKind op1, CXXOperatorKind op2, Type typeLeft, Type typeRight) { var first = @class.Operators.FirstOrDefault(o => o.IsGenerated && o.OperatorKind == op1 && o.Parameters.First().Type.Equals(typeLeft) && o.Parameters.Last().Type.Equals(typeRight)); var second = @class.Operators.FirstOrDefault(o => o.IsGenerated && o.OperatorKind == op2 && o.Parameters.First().Type.Equals(typeLeft) && o.Parameters.Last().Type.Equals(typeRight)); var hasFirst = first != null; var hasSecond = second != null; if (hasFirst && !hasSecond) { index = @class.Methods.IndexOf(first); return op2; } if (hasSecond && !hasFirst) { index = @class.Methods.IndexOf(second); return op1; } index = 0; return CXXOperatorKind.None; } static bool IsValidOperatorOverload(Method @operator) { // These follow the order described in MSDN (Overloadable Operators). switch (@operator.OperatorKind) { // These unary operators can be overloaded case CXXOperatorKind.Plus: case CXXOperatorKind.Minus: case CXXOperatorKind.Exclaim: case CXXOperatorKind.Tilde: // These binary operators can be overloaded case CXXOperatorKind.Slash: case CXXOperatorKind.Percent: case CXXOperatorKind.Amp: case CXXOperatorKind.Pipe: case CXXOperatorKind.Caret: // The array indexing operator can be overloaded case CXXOperatorKind.Subscript: // The conversion operators can be overloaded case CXXOperatorKind.Conversion: case CXXOperatorKind.ExplicitConversion: return true; // The comparison operators can be overloaded if their return type is bool case CXXOperatorKind.EqualEqual: case CXXOperatorKind.ExclaimEqual: case CXXOperatorKind.Less: case CXXOperatorKind.Greater: case CXXOperatorKind.LessEqual: case CXXOperatorKind.GreaterEqual: return @operator.ReturnType.Type.IsPrimitiveType(PrimitiveType.Bool); // Only prefix operators can be overloaded case CXXOperatorKind.PlusPlus: case CXXOperatorKind.MinusMinus: Class @class; var returnType = @operator.OriginalReturnType.Type.Desugar(); returnType = (returnType.GetFinalPointee() ?? returnType).Desugar(); return returnType.TryGetClass(out @class) && @class.GetNonIgnoredRootBase() == ((Class) @operator.Namespace).GetNonIgnoredRootBase() && @operator.Parameters.Count == 0; // Bitwise shift operators can only be overloaded if the second parameter is int case CXXOperatorKind.LessLess: case CXXOperatorKind.GreaterGreater: PrimitiveType primitiveType; return @operator.Parameters.Last().Type.IsPrimitiveType(out primitiveType) && primitiveType == PrimitiveType.Int; // No parameters means the dereference operator - cannot be overloaded case CXXOperatorKind.Star: return @operator.Parameters.Count > 0; // Assignment operators cannot be overloaded case CXXOperatorKind.PlusEqual: case CXXOperatorKind.MinusEqual: case CXXOperatorKind.StarEqual: case CXXOperatorKind.SlashEqual: case CXXOperatorKind.PercentEqual: case CXXOperatorKind.AmpEqual: case CXXOperatorKind.PipeEqual: case CXXOperatorKind.CaretEqual: case CXXOperatorKind.LessLessEqual: case CXXOperatorKind.GreaterGreaterEqual: // The conditional logical operators cannot be overloaded case CXXOperatorKind.AmpAmp: case CXXOperatorKind.PipePipe: // These operators cannot be overloaded. case CXXOperatorKind.Equal: case CXXOperatorKind.Comma: case CXXOperatorKind.ArrowStar: case CXXOperatorKind.Arrow: case CXXOperatorKind.Call: case CXXOperatorKind.Conditional: case CXXOperatorKind.Coawait: case CXXOperatorKind.New: case CXXOperatorKind.Delete: case CXXOperatorKind.Array_New: case CXXOperatorKind.Array_Delete: default: return false; } } } }
40.357143
106
0.542655
[ "MIT" ]
VPeruS/CppSharp
src/Generator/Passes/CheckOperatorsOverloads.cs
11,302
C#
// PathFilter.cs // // Copyright 2005 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; namespace ICSharpCode.SharpZipLib.Core { /// <summary> /// PathFilter filters directories and files using a form of <see cref="System.Text.RegularExpressions.Regex">regular expressions</see> /// by full path name. /// See <see cref="NameFilter">NameFilter</see> for more detail on filtering. /// </summary> public class PathFilter : IScanFilter { #region Constructors /// <summary> /// Initialise a new instance of <see cref="PathFilter"></see>. /// </summary> /// <param name="filter">The <see cref="NameFilter"></see>filter expression to apply.</param> public PathFilter(string filter) { nameFilter_ = new NameFilter(filter); } #endregion #region IScanFilter Members /// <summary> /// Test a name to see if it matches the filter. /// </summary> /// <param name="name">The name to test.</param> /// <returns>True if the name matches, false otherwise.</returns> public virtual bool IsMatch(string name) { bool result = false; if ( name != null ) { string cooked = (name.Length > 0) ? Path.GetFullPath(name) : ""; result = nameFilter_.IsMatch(cooked); } return result; } #endregion #region Instance Fields NameFilter nameFilter_; #endregion } /// <summary> /// ExtendedPathFilter filters based on name, file size, and the last write time of the file. /// </summary> /// <remarks>Provides an example of how to customise filtering.</remarks> public class ExtendedPathFilter : PathFilter { #region Constructors /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> public ExtendedPathFilter(string filter, long minSize, long maxSize) : base(filter) { MinSize = minSize; MaxSize = maxSize; } /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param> /// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param> public ExtendedPathFilter(string filter, DateTime minDate, DateTime maxDate) : base(filter) { MinDate = minDate; MaxDate = maxDate; } /// <summary> /// Initialise a new instance of ExtendedPathFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> /// <param name="minDate">The minimum <see cref="DateTime"/> to include.</param> /// <param name="maxDate">The maximum <see cref="DateTime"/> to include.</param> public ExtendedPathFilter(string filter, long minSize, long maxSize, DateTime minDate, DateTime maxDate) : base(filter) { MinSize = minSize; MaxSize = maxSize; MinDate = minDate; MaxDate = maxDate; } #endregion #region IScanFilter Members /// <summary> /// Test a filename to see if it matches the filter. /// </summary> /// <param name="name">The filename to test.</param> /// <returns>True if the filter matches, false otherwise.</returns> public override bool IsMatch(string name) { bool result = base.IsMatch(name); if ( result ) { FileInfo fileInfo = new FileInfo(name); result = (MinSize <= fileInfo.Length) && (MaxSize >= fileInfo.Length) && (MinDate <= fileInfo.LastWriteTime) && (MaxDate >= fileInfo.LastWriteTime) ; } return result; } #endregion #region Properties /// <summary> /// Get/set the minimum size for a file that will match this filter. /// </summary> public long MinSize { get { return minSize_; } set { if ( (value < 0) || (maxSize_ < value) ) { throw new ArgumentOutOfRangeException("value"); } minSize_ = value; } } /// <summary> /// Get/set the maximum size for a file that will match this filter. /// </summary> public long MaxSize { get { return maxSize_; } set { if ( (value < 0) || (minSize_ > value) ) { throw new ArgumentOutOfRangeException("value"); } maxSize_ = value; } } /// <summary> /// Get/set the minimum <see cref="DateTime"/> value that will match for this filter. /// </summary> /// <remarks>Files with a LastWrite time less than this value are excluded by the filter.</remarks> public DateTime MinDate { get { return minDate_; } set { if ( value > maxDate_ ) { throw new ArgumentException("Exceeds MaxDate", "value"); } minDate_ = value; } } /// <summary> /// Get/set the maximum <see cref="DateTime"/> value that will match for this filter. /// </summary> /// <remarks>Files with a LastWrite time greater than this value are excluded by the filter.</remarks> public DateTime MaxDate { get { return maxDate_; } set { if ( minDate_ > value ) { throw new ArgumentException("Exceeds MinDate", "value"); } maxDate_ = value; } } #endregion #region Instance Fields long minSize_; long maxSize_ = long.MaxValue; DateTime minDate_ = DateTime.MinValue; DateTime maxDate_ = DateTime.MaxValue; #endregion } /// <summary> /// NameAndSizeFilter filters based on name and file size. /// </summary> /// <remarks>A sample showing how filters might be extended.</remarks> [Obsolete("Use ExtendedPathFilter instead")] public class NameAndSizeFilter : PathFilter { /// <summary> /// Initialise a new instance of NameAndSizeFilter. /// </summary> /// <param name="filter">The filter to apply.</param> /// <param name="minSize">The minimum file size to include.</param> /// <param name="maxSize">The maximum file size to include.</param> public NameAndSizeFilter(string filter, long minSize, long maxSize) : base(filter) { MinSize = minSize; MaxSize = maxSize; } /// <summary> /// Test a filename to see if it matches the filter. /// </summary> /// <param name="name">The filename to test.</param> /// <returns>True if the filter matches, false otherwise.</returns> public override bool IsMatch(string name) { bool result = base.IsMatch(name); if ( result ) { FileInfo fileInfo = new FileInfo(name); long length = fileInfo.Length; result = (MinSize <= length) && (MaxSize >= length); } return result; } /// <summary> /// Get/set the minimum size for a file that will match this filter. /// </summary> public long MinSize { get { return minSize_; } set { if ( (value < 0) || (maxSize_ < value) ) { throw new ArgumentOutOfRangeException("value"); } minSize_ = value; } } /// <summary> /// Get/set the maximum size for a file that will match this filter. /// </summary> public long MaxSize { get { return maxSize_; } set { if ( (value < 0) || (minSize_ > value) ) { throw new ArgumentOutOfRangeException("value"); } maxSize_ = value; } } #region Instance Fields long minSize_; long maxSize_ = long.MaxValue; #endregion } }
34.642424
140
0.527642
[ "MIT" ]
CMU-SAFARI/HWASim
Common/gzip/PathFilter.cs
11,432
C#
using System; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Elsa.Serialization.Handlers { public abstract class PrimitiveValueHandler<T> : IValueHandler { public virtual int Priority => 0; public bool CanSerialize(JToken value, Type type) => type == typeof(T); public bool CanDeserialize(JToken value, Type type) => value.Type == JTokenType.Object && value["Type"]?.Value<string>() == TypeName; protected virtual string TypeName => typeof(T).Name; public virtual object Deserialize(JsonReader reader, JsonSerializer serializer, Type type, JToken value) { var valueToken = value["Value"]; return ParseValue(valueToken); } public virtual void Serialize(JsonWriter writer, JsonSerializer serializer, Type type, JToken value) { var token = new JObject { ["Type"] = TypeName, ["Value"] = value }; token.WriteTo(writer, serializer.Converters.ToArray()); } protected abstract object ParseValue(JToken value); } }
35.030303
141
0.624567
[ "BSD-3-Clause" ]
1000sprites/elsa-core
src/core/Elsa.Abstractions/Serialization/Handlers/PrimitiveValueHandler.cs
1,158
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace reportapp.Reports { using System; using System.ComponentModel; using CrystalDecisions.Shared; using CrystalDecisions.ReportSource; using CrystalDecisions.CrystalReports.Engine; public class GACSSegCashFlow : ReportClass { public GACSSegCashFlow() { } public override string ResourceName { get { return "GACSSegCashFlow.rpt"; } set { // Do nothing } } public override bool NewGenerator { get { return true; } set { // Do nothing } } public override string FullResourceName { get { return "reportapp.Reports.GACSSegCashFlow.rpt"; } set { // Do nothing } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section ReportHeaderSection1 { get { return this.ReportDefinition.Sections[0]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section PageHeaderSection1 { get { return this.ReportDefinition.Sections[1]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection1 { get { return this.ReportDefinition.Sections[2]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection2 { get { return this.ReportDefinition.Sections[3]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection3 { get { return this.ReportDefinition.Sections[4]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupHeaderSection4 { get { return this.ReportDefinition.Sections[5]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section DetailSection1 { get { return this.ReportDefinition.Sections[6]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection4 { get { return this.ReportDefinition.Sections[7]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection3 { get { return this.ReportDefinition.Sections[8]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection2 { get { return this.ReportDefinition.Sections[9]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection5 { get { return this.ReportDefinition.Sections[10]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection6 { get { return this.ReportDefinition.Sections[11]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section GroupFooterSection1 { get { return this.ReportDefinition.Sections[12]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section ReportFooterSection1 { get { return this.ReportDefinition.Sections[13]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section PageFooterSection1 { get { return this.ReportDefinition.Sections[14]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.Shared.IParameterField Parameter_vote_code { get { return this.DataDefinition.ParameterFields[0]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.Shared.IParameterField Parameter_curr_fiscal_yr { get { return this.DataDefinition.ParameterFields[1]; } } } [System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")] public class CachedGACSSegCashFlow : Component, ICachedReport { public CachedGACSSegCashFlow() { } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool IsCacheable { get { return true; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool ShareDBLogonInfo { get { return false; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.TimeSpan CacheTimeOut { get { return CachedReportConstants.DEFAULT_TIMEOUT; } set { // } } public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() { GACSSegCashFlow rpt = new GACSSegCashFlow(); rpt.Site = this.Site; return rpt; } public virtual string GetCustomizedCacheKey(RequestContext request) { String key = null; // // The following is the code used to generate the default // // cache key for caching report jobs in the ASP.NET Cache. // // Feel free to modify this code to suit your needs. // // Returning key == null causes the default cache key to // // be generated. // // key = RequestContext.BuildCompleteCacheKey( // request, // null, // sReportFilename // this.GetType(), // this.ShareDBLogonInfo ); return key; } } }
36.696
112
0.595051
[ "BSD-3-Clause" ]
mateso/gac
web/reportapp/reportapp/Reports/GACSSegCashFlow.cs
9,176
C#
using System; using System.Collections.Generic; using System.IO; using System.Xml; namespace Innovator.Client { /// <summary> /// MemoryTributary is a re-implementation of MemoryStream that uses a dynamic list of byte arrays as a backing store, instead of a single byte array, the allocation /// of which will fail for relatively small streams as it requires contiguous memory. /// </summary> /// <remarks>Adapted from <a href="https://www.codeproject.com/Articles/348590/A-replacement-for-MemoryStream">Code Project: A replacement for MemoryStream</a></remarks> public class MemoryTributary : Stream, IXmlStream { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MemoryTributary"/> class. /// </summary> public MemoryTributary() { Position = 0; } /// <summary> /// Initializes a new instance of the <see cref="MemoryTributary"/> class. /// </summary> /// <param name="source">The source data.</param> public MemoryTributary(byte[] source) { this.Write(source, 0, source.Length); Position = 0; } /// <summary> /// Initializes a new instance of the <see cref="MemoryTributary"/> class. /// </summary> /// <param name="length">The length.</param> /// <remarks><paramref name="length"/> is largely ignored because capacity has no meaning unless we implement an artifical limit</remarks> public MemoryTributary(int length) { SetLength(length); Position = length; byte[] d = Block; //access block to prompt the allocation of memory Position = 0; } #endregion #region Status Properties /// <summary>Gets a value indicating whether the current stream supports reading.</summary> /// <returns>Always <c>true</c> as the stream supports reading.</returns> public override bool CanRead { get { return true; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> /// <returns>Always <c>true</c> as the stream supports seeking.</returns> public override bool CanSeek { get { return true; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> /// <returns>Always <c>true</c> as the stream supports writing.</returns> public override bool CanWrite { get { return true; } } #endregion #region Public Properties /// <summary>Gets the length in bytes of the stream.</summary> /// <returns>A long value representing the length of the stream in bytes.</returns> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Length { get { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); return _length; } } /// <summary>Gets or sets the position within the current stream.</summary> /// <returns>The current position within the stream.</returns> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Position { get { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); return _position; } set { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); _position = value; } } #endregion #region Members private long _length = 0; private long _blockSize = 65536; private List<byte[]> _blocks = new List<byte[]>(); private long _position; #endregion #region Internal Properties /* Use these properties to gain access to the appropriate block of memory for the current Position */ /// <summary> /// The block of memory currently addressed by Position /// </summary> protected byte[] Block { get { while (_blocks.Count <= BlockId) _blocks.Add(new byte[_blockSize]); return _blocks[(int)BlockId]; } } /// <summary> /// The id of the block currently addressed by Position /// </summary> protected long BlockId { get { return Position / _blockSize; } } /// <summary> /// The offset of the byte currently addressed by Position, into the block that contains it /// </summary> protected long BlockOffset { get { return Position % _blockSize; } } #endregion #region Public Stream Methods /// <summary>Does nothing</summary> public override void Flush() { } /// <summary>Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.</summary> /// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source. </param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream. </param> /// <param name="count">The maximum number of bytes to be read from the current stream. </param> /// <exception cref="ArgumentNullException"><paramref name="buffer" /> is null. </exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset" /> or <paramref name="count" /> is negative. </exception> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override int Read(byte[] buffer, int offset, int count) { var lcount = (long)count; if (lcount < 0) throw new ArgumentOutOfRangeException("count", lcount, "Number of bytes to copy cannot be negative."); var remaining = (_length - Position); if (lcount > remaining) lcount = remaining; if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); if (buffer == null) throw new ArgumentNullException("buffer", "Buffer cannot be null."); if (offset < 0) throw new ArgumentOutOfRangeException("offset", offset, "Destination offset cannot be negative."); int read = 0; long copysize = 0; do { copysize = Math.Min(lcount, _blockSize - BlockOffset); Buffer.BlockCopy(Block, (int)BlockOffset, buffer, offset, (int)copysize); lcount -= copysize; offset += (int)copysize; read += (int)copysize; Position += copysize; } while (lcount > 0); return read; } /// <summary>Sets the position within the current stream.</summary> /// <returns>The new position within the current stream.</returns> /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter. </param> /// <param name="origin">A value of type <see cref="SeekOrigin" /> indicating the reference point used to obtain the new position. </param> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override long Seek(long offset, SeekOrigin origin) { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position += offset; break; case SeekOrigin.End: Position = Length - offset; break; } return Position; } /// <summary>Sets the length of the current stream.</summary> /// <param name="value">The desired length of the current stream in bytes. </param> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> /// <remarks><paramref name="value"/> is largely ignored because capacity has no meaning unless we implement an artifical limit</remarks> public override void SetLength(long value) { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); _length = value; } /// <summary>Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.</summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream. </param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream. </param> /// <param name="count">The number of bytes to be written to the current stream. </param> /// <exception cref="ObjectDisposedException"><see cref="Write(byte[], int, int)" /> was called after the stream was closed.</exception> public override void Write(byte[] buffer, int offset, int count) { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); long initialPosition = Position; int copysize; try { do { copysize = Math.Min(count, (int)(_blockSize - BlockOffset)); EnsureCapacity(Position + copysize); Buffer.BlockCopy(buffer, (int)offset, Block, (int)BlockOffset, copysize); count -= copysize; offset += copysize; Position += copysize; } while (count > 0); } catch (Exception) { Position = initialPosition; throw; } } /// <summary>Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.</summary> /// <returns>The unsigned byte cast to an <see cref="Int32"/>, or -1 if at the end of the stream.</returns> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override int ReadByte() { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); if (Position >= _length) return -1; byte b = Block[BlockOffset]; Position++; return b; } /// <summary>Writes a byte to the current position in the stream and advances the position within the stream by one byte.</summary> /// <param name="value">The byte to write to the stream. </param> /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception> public override void WriteByte(byte value) { if (_blocks == null) throw new ObjectDisposedException("MemoryTributary"); EnsureCapacity(Position + 1); Block[BlockOffset] = value; Position++; } /// <summary> /// Guarantees that the underlying memory has at least the specified number of bytes of capacity /// </summary> /// <param name="intendedLength">Intended length of the data</param> protected void EnsureCapacity(long intendedLength) { if (intendedLength > _length) _length = (intendedLength); } #endregion #region IDispose /// <summary>Releases the unmanaged resources used by the <see cref="Stream" /> and optionally releases the managed resources.</summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { _blocks = null; base.Dispose(disposing); } #endregion #region Public Additional Helper Methods /// <summary> /// Returns the entire content of the stream as a byte array. This is not safe because the call to new byte[] may /// fail if the stream is large enough. Where possible use methods which operate on streams directly instead. /// </summary> /// <returns>A byte[] containing the current data in the stream</returns> public byte[] ToArray() { long firstposition = Position; Position = 0; byte[] destination = new byte[Length]; Read(destination, 0, (int)Length); Position = firstposition; return destination; } /// <summary> /// Reads length bytes from source into the this instance at the current position. /// </summary> /// <param name="source">The stream containing the data to copy</param> /// <param name="length">The number of bytes to copy</param> public void ReadFrom(Stream source, long length) { byte[] buffer = new byte[4096]; int read; do { read = source.Read(buffer, 0, (int)Math.Min(4096, length)); length -= read; this.Write(buffer, 0, read); } while (length > 0); } /// <summary> /// Writes the entire stream into destination, regardless of Position, which remains unchanged. /// </summary> /// <param name="destination">The stream to write the content of this stream to</param> public void WriteTo(Stream destination) { long initialpos = Position; Position = 0; this.CopyTo(destination); Position = initialpos; } /// <summary> /// Creates an <see cref="XmlReader" /> for reading XML from the stream /// </summary> /// <returns>An <see cref="XmlReader" /> for reading XML</returns> public XmlReader CreateReader() { return XmlReader.Create(this); } #endregion } }
35.491049
295
0.647907
[ "MIT" ]
GCAE/Innovator.Client
src/Innovator.Client/IO/MemoryTributary.cs
13,879
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d11shader.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.DirectX.UnitTests; /// <summary>Provides validation of the <see cref="ID3D11ShaderReflectionVariable" /> struct.</summary> public static unsafe partial class ID3D11ShaderReflectionVariableTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ID3D11ShaderReflectionVariable" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ID3D11ShaderReflectionVariable).GUID, Is.EqualTo(IID_ID3D11ShaderReflectionVariable)); } /// <summary>Validates that the <see cref="ID3D11ShaderReflectionVariable" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ID3D11ShaderReflectionVariable>(), Is.EqualTo(sizeof(ID3D11ShaderReflectionVariable))); } /// <summary>Validates that the <see cref="ID3D11ShaderReflectionVariable" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ID3D11ShaderReflectionVariable).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ID3D11ShaderReflectionVariable" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ID3D11ShaderReflectionVariable), Is.EqualTo(8)); } else { Assert.That(sizeof(ID3D11ShaderReflectionVariable), Is.EqualTo(4)); } } }
38.823529
145
0.717172
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/DirectX/um/d3d11shader/ID3D11ShaderReflectionVariableTests.cs
1,982
C#
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // namespace NLog.Config { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using NLog.Common; using NLog.Internal; using NLog.Layouts; using JetBrains.Annotations; #if SILVERLIGHT // ReSharper disable once RedundantUsingDirective using System.Windows; #endif /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// /// Parsing of the XML file is also implemented in this class. /// </summary> ///<remarks> /// - This class is thread-safe.<c>.ToList()</c> is used for that purpose. /// - Update TemplateXSD.xml for changes outside targets /// </remarks> public class XmlLoggingConfiguration : LoggingConfigurationParser { #if __ANDROID__ /// <summary> /// Prefix for assets in Xamarin Android /// </summary> private const string AssetsPrefix = "assets/"; #endif private readonly Dictionary<string, bool> _fileMustAutoReloadLookup = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private string _originalFileName; private readonly Stack<string> _currentFilePath = new Stack<string>(); /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration([NotNull] string fileName) : this(fileName, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> public XmlLoggingConfiguration([NotNull] string fileName, LogFactory logFactory) : base(logFactory) { using (XmlReader reader = CreateFileReader(fileName)) { Initialize(reader, fileName); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors) : this(fileName, ignoreErrors, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] public XmlLoggingConfiguration([NotNull] string fileName, bool ignoreErrors, LogFactory logFactory) : base(logFactory) { using (XmlReader reader = CreateFileReader(fileName)) { Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader">XML reader to read from.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader) : this(reader, null) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName) : this(reader, fileName, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, LogFactory logFactory) : base(logFactory) { Initialize(reader, fileName); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors) : this(reader, fileName, ignoreErrors, LogManager.LogFactory) { } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> [Obsolete("Constructor with parameter ignoreErrors has limited effect. Instead use LogManager.ThrowConfigExceptions. Marked obsolete in NLog 4.7")] public XmlLoggingConfiguration([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors, LogFactory logFactory) : base(logFactory) { Initialize(reader, fileName, ignoreErrors); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="xmlContents">The XML contents.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="logFactory">The <see cref="LogFactory" /> to which to apply any applicable configuration values.</param> internal XmlLoggingConfiguration([NotNull] string xmlContents, [CanBeNull] string fileName, LogFactory logFactory) : base(logFactory) { using (var stringReader = new StringReader(xmlContents)) { using (XmlReader reader = XmlReader.Create(stringReader)) { Initialize(reader, fileName); } } } /// <summary> /// Parse XML string as NLog configuration /// </summary> /// <param name="xml">NLog configuration in XML to be parsed</param> public static XmlLoggingConfiguration CreateFromXmlString(string xml) { return CreateFromXmlString(xml, LogManager.LogFactory); } /// <summary> /// Parse XML string as NLog configuration /// </summary> /// <param name="xml">NLog configuration in XML to be parsed</param> /// <param name="logFactory">NLog LogFactory</param> public static XmlLoggingConfiguration CreateFromXmlString(string xml, LogFactory logFactory) { return new XmlLoggingConfiguration(xml, string.Empty, logFactory); } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Did the <see cref="Initialize"/> Succeeded? <c>true</c>= success, <c>false</c>= error, <c>null</c> = initialize not started yet. /// </summary> public bool? InitializeSucceeded { get; private set; } /// <summary> /// Gets or sets a value indicating whether all of the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get { if (_fileMustAutoReloadLookup.Count == 0) return false; else return _fileMustAutoReloadLookup.Values.All(mustAutoReload => mustAutoReload); } set { var autoReloadFiles = _fileMustAutoReloadLookup.Keys.ToList(); foreach (string nextFile in autoReloadFiles) _fileMustAutoReloadLookup[nextFile] = value; } } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { return _fileMustAutoReloadLookup.Where(entry => entry.Value).Select(entry => entry.Key); } } /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { if (!string.IsNullOrEmpty(_originalFileName)) return new XmlLoggingConfiguration(_originalFileName, LogFactory); else return base.Reload(); } /// <summary> /// Get file paths (including filename) for the possible NLog config files. /// </summary> /// <returns>The file paths to the possible config file</returns> public static IEnumerable<string> GetCandidateConfigFilePaths() { return LogManager.LogFactory.GetCandidateConfigFilePaths(); } /// <summary> /// Overwrite the paths (including filename) for the possible NLog config files. /// </summary> /// <param name="filePaths">The file paths to the possible config file</param> public static void SetCandidateConfigFilePaths(IEnumerable<string> filePaths) { LogManager.LogFactory.SetCandidateConfigFilePaths(filePaths); } /// <summary> /// Clear the candidate file paths and return to the defaults. /// </summary> public static void ResetCandidateConfigFilePath() { LogManager.LogFactory.ResetCandidateConfigFilePath(); } /// <summary> /// Create XML reader for (xml config) file. /// </summary> /// <param name="fileName">filepath</param> /// <returns>reader or <c>null</c> if filename is empty.</returns> private XmlReader CreateFileReader(string fileName) { if (!string.IsNullOrEmpty(fileName)) { fileName = fileName.Trim(); #if __ANDROID__ //support loading config from special assets folder in nlog.config if (fileName.StartsWith(AssetsPrefix, StringComparison.OrdinalIgnoreCase)) { //remove prefix fileName = fileName.Substring(AssetsPrefix.Length); Stream stream = Android.App.Application.Context.Assets.Open(fileName); return XmlReader.Create(stream); } #endif return LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName); } return null; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files). <c>null</c> is allowed.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize([NotNull] XmlReader reader, [CanBeNull] string fileName, bool ignoreErrors = false) { try { InitializeSucceeded = null; _originalFileName = fileName; reader.MoveToContent(); var content = new NLogXmlElement(reader); if (!string.IsNullOrEmpty(fileName)) { InternalLogger.Info("Configuring from an XML element in {0}...", fileName); ParseTopLevel(content, fileName, autoReloadDefault: false); } else { ParseTopLevel(content, null, autoReloadDefault: false); } InitializeSucceeded = true; CheckParsingErrors(content); } catch (Exception exception) { InitializeSucceeded = false; if (exception.MustBeRethrownImmediately()) { throw; } var configurationException = new NLogConfigurationException(exception, "Exception when parsing {0}. ", fileName); InternalLogger.Error(exception, configurationException.Message); if (!ignoreErrors && (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions || configurationException.MustBeRethrown())) throw configurationException; } } /// <summary> /// Checks whether any error during XML configuration parsing has occured. /// If there are any and <c>ThrowConfigExceptions</c> or <c>ThrowExceptions</c> /// setting is enabled - throws <c>NLogConfigurationException</c>, otherwise /// just write an internal log at Warn level. /// </summary> /// <param name="rootContentElement">Root NLog configuration xml element</param> private void CheckParsingErrors(NLogXmlElement rootContentElement) { var parsingErrors = rootContentElement.GetParsingErrors().ToArray(); if (parsingErrors.Any()) { if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions) { string exceptionMessage = string.Join(Environment.NewLine, parsingErrors); throw new NLogConfigurationException(exceptionMessage); } else { foreach (var parsingError in parsingErrors) { InternalLogger.Log(LogLevel.Warn, parsingError); } } } } /// <summary> /// Add a file with configuration. Check if not already included. /// </summary> /// <param name="fileName"></param> /// <param name="autoReloadDefault"></param> private void ConfigureFromFile([NotNull] string fileName, bool autoReloadDefault) { if (!_fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(fileName))) { using (var reader = LogFactory.CurrentAppEnvironment.LoadXmlFile(fileName)) { reader.MoveToContent(); ParseTopLevel(new NLogXmlElement(reader, true), fileName, autoReloadDefault); } } } /// <summary> /// Parse the root /// </summary> /// <param name="content"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseTopLevel(NLogXmlElement content, [CanBeNull] string filePath, bool autoReloadDefault) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpperInvariant()) { case "CONFIGURATION": ParseConfigurationElement(content, filePath, autoReloadDefault); break; case "NLOG": ParseNLogElement(content, filePath, autoReloadDefault); break; } } /// <summary> /// Parse {configuration} xml element. /// </summary> /// <param name="configurationElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseConfigurationElement(NLogXmlElement configurationElement, [CanBeNull] string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); var nlogElements = configurationElement.Elements("nlog").ToList(); foreach (var nlogElement in nlogElements) { ParseNLogElement(nlogElement, filePath, autoReloadDefault); } } /// <summary> /// Parse {NLog} xml element. /// </summary> /// <param name="nlogElement"></param> /// <param name="filePath">path to config file.</param> /// <param name="autoReloadDefault">The default value for the autoReload option.</param> private void ParseNLogElement(ILoggingConfigurationElement nlogElement, [CanBeNull] string filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); bool autoReload = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault); if (!string.IsNullOrEmpty(filePath)) _fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = autoReload; try { _currentFilePath.Push(filePath); base.LoadConfig(nlogElement, Path.GetDirectoryName(filePath)); } finally { _currentFilePath.Pop(); } } /// <summary> /// Parses a single config section within the NLog-config /// </summary> /// <param name="configSection"></param> /// <returns>Section was recognized</returns> protected override bool ParseNLogSection(ILoggingConfigurationElement configSection) { if (configSection.MatchesName("include")) { string filePath = _currentFilePath.Peek(); bool autoLoad = !string.IsNullOrEmpty(filePath) && _fileMustAutoReloadLookup[GetFileLookupKey(filePath)]; ParseIncludeElement(configSection, !string.IsNullOrEmpty(filePath) ? Path.GetDirectoryName(filePath) : null, autoLoad); return true; } else { return base.ParseNLogSection(configSection); } } private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string baseDirectory, bool autoReloadDefault) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredValue("file", "nlog"); var ignoreErrors = includeElement.GetOptionalBooleanValue("ignoreErrors", false); try { newFileName = ExpandSimpleVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); var fullNewFileName = newFileName; if (baseDirectory != null) { fullNewFileName = Path.Combine(baseDirectory, newFileName); } #if SILVERLIGHT && !WINDOWS_PHONE newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(fullNewFileName, UriKind.Relative)) != null) #else if (File.Exists(fullNewFileName)) #endif { InternalLogger.Debug("Including file '{0}'", fullNewFileName); ConfigureFromFile(fullNewFileName, autoReloadDefault); } else { //is mask? if (newFileName.Contains("*")) { ConfigureFromFilesByMask(baseDirectory, newFileName, autoReloadDefault); } else { if (ignoreErrors) { //quick stop for performances InternalLogger.Debug("Skipping included file '{0}' as it can't be found", fullNewFileName); return; } throw new FileNotFoundException("Included file not found: " + fullNewFileName); } } } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } var configurationException = new NLogConfigurationException(exception, "Error when including '{0}'.", newFileName); InternalLogger.Error(exception, configurationException.Message); if (!ignoreErrors) throw configurationException; } } /// <summary> /// Include (multiple) files by filemask, e.g. *.nlog /// </summary> /// <param name="baseDirectory">base directory in case if <paramref name="fileMask"/> is relative</param> /// <param name="fileMask">relative or absolute fileMask</param> /// <param name="autoReloadDefault"></param> private void ConfigureFromFilesByMask(string baseDirectory, string fileMask, bool autoReloadDefault) { var directory = baseDirectory; //if absolute, split to file mask and directory. if (Path.IsPathRooted(fileMask)) { directory = Path.GetDirectoryName(fileMask); if (directory == null) { InternalLogger.Warn("directory is empty for include of '{0}'", fileMask); return; } var filename = Path.GetFileName(fileMask); if (filename == null) { InternalLogger.Warn("filename is empty for include of '{0}'", fileMask); return; } fileMask = filename; } #if SILVERLIGHT && !WINDOWS_PHONE var files = Directory.EnumerateFiles(directory, fileMask); #else var files = Directory.GetFiles(directory, fileMask); #endif foreach (var file in files) { //note we exclude our self in ConfigureFromFile ConfigureFromFile(file, autoReloadDefault); } } private static string GetFileLookupKey([NotNull] string fileName) { #if SILVERLIGHT && !WINDOWS_PHONE // file names are relative to XAP return fileName; #else return Path.GetFullPath(fileName); #endif } /// <inheritdoc /> public override string ToString() { return $"{base.ToString()}, FilePath={_originalFileName}"; } } }
43.2864
159
0.596806
[ "BSD-3-Clause" ]
aTiKhan/NLog
src/NLog/Config/XmlLoggingConfiguration.cs
27,054
C#
namespace MusicallyApi.Data { public class RequestInfoParam { public string ac { get; set; } public string bz { get; set; } public string dm { get; set; } public string ver { get; set; } } }
17.071429
39
0.556485
[ "MIT" ]
AeonLucid/MusicallyRE
src-musically/MusicallyApi/Data/RequestInfoParam.cs
241
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Extensions; using System; /// <summary> /// Get all Application Insights web tests defined within a specified resource group. /// </summary> /// <remarks> /// [OpenAPI] ListByResourceGroup=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/webtests" /// </remarks> [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzApplicationInsightsWebTest_List")] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTest))] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Description(@"Get all Application Insights web tests defined within a specified resource group.")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Generated] public partial class GetAzApplicationInsightsWebTest_List : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>A flag to tell whether it is the first onOK call.</summary> private bool _isFirst = true; /// <summary>Link to retrieve next page.</summary> private string _nextLink; /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ApplicationInsightsManagementClient Client => Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary> /// <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary> private string _resourceGroupName; /// <summary>The name of the resource group. The name is case insensitive.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")] [Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Info( Required = true, ReadOnly = false, Description = @"The name of the resource group. The name is case insensitive.", SerializedName = @"resourceGroupName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Path)] public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; } /// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary> private string[] _subscriptionId; /// <summary>The ID of the target subscription.</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")] [Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Category(global::Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.ParameterCategory.Path)] public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestListResult" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestListResult> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { var telemetryId = Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.GetTelemetryId.Invoke(); if (telemetryId != "" && telemetryId != "internal") { __correlationId = telemetryId; } Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { } /// <summary> /// Intializes a new instance of the <see cref="GetAzApplicationInsightsWebTest_List" /> cmdlet class. /// </summary> public GetAzApplicationInsightsWebTest_List() { } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Information: { var data = messageData(); WriteInformation(data.Message, new string[]{}); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } } await Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token); } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { foreach( var SubscriptionId in this.SubscriptionId ) { await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.WebTestsListByResourceGroup(ResourceGroupName, SubscriptionId, onOk, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } } catch (Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { ResourceGroupName=ResourceGroupName,SubscriptionId=SubscriptionId}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestListResult" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Models.Api20180501Preview.IWebTestListResult> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // response should be returning an array of some kind. +Pageable // pageable / value / nextLink var result = await response; WriteObject(result.Value,true); _nextLink = result.NextLink; if (_isFirst) { _isFirst = false; while (_nextLink != null) { if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage ) { requestMessage = requestMessage.Clone(new global::System.Uri( _nextLink ),Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Method.Get ); await ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.ApplicationInsights.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.WebTestsListByResourceGroup_Call(requestMessage, onOk, this, Pipeline); } } } } } } }
73.167131
507
0.67857
[ "MIT" ]
arpit-gagneja/azure-powershell
src/ApplicationInsights/generated/cmdlets/GetAzApplicationInsightsWebTest_List.cs
25,909
C#
using System.Reflection; using System.Runtime.CompilerServices; using Android.App; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("Kwy.ProjectOxford.SpeechRecognition.Droid")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Xamarin Inc.")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("jessezhang")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
37.75
82
0.745506
[ "MIT" ]
builttoroam/BuildIt
src/BuildIt.CognitiveServices/Kwy.ProjectOxford.SpeechRecognition.Droid/Properties/AssemblyInfo.cs
1,059
C#
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Utilities; using ProjectFileTools.NuGetSearch.Contracts; using ProjectFileTools.NuGetSearch.Feeds; namespace ProjectFileTools.Exports { [Export(typeof(IPackageFeedFactorySelector))] [Name("Default Package Feed Factory Selector")] internal class ExportedPackageFeedFactorySelector : PackageFeedFactorySelector { [ImportingConstructor] public ExportedPackageFeedFactorySelector([ImportMany] IEnumerable<IPackageFeedFactory> feedFactories) : base(feedFactories) { } } }
33.473684
110
0.768868
[ "MIT" ]
KirillOsenkov/ProjFileTools
src/ProjectFileTools/Exports/ExportedPackageFeedFactorySelector.cs
638
C#
using System; using System.Linq; using System.Threading.Tasks; using MagusAppGateway.Services.IServices; using Microsoft.EntityFrameworkCore; using MagusAppGateway.Contexts; using MagusAppGateway.Models.Dtos; using MagusAppGateway.Util.Result; using MagusAppGateway.Models; using System.Collections.Generic; namespace MagusAppGateway.Services.Services { public class OcelotConfigService : IOcelotConfigService { private readonly UserDatabaseContext _userDatabaseContext; public OcelotConfigService(UserDatabaseContext userDatabaseContext) { _userDatabaseContext = userDatabaseContext; } public async Task<ResultModel> CreateConfig(OcelotConfigEditDto dto) { if (string.IsNullOrWhiteSpace(dto.GlobalConfiguration.BaseUrl)) { return new ResultModel(ResultCode.Fail, "请输入网关地址"); } var globalConfiguration = new GlobalConfiguration { BaseUrl = dto.GlobalConfiguration.BaseUrl }; var ocelotConfig = new OcelotConfig { IsEnable = dto.IsEnable, GlobalConfiguration = globalConfiguration }; try { _userDatabaseContext.OcelotConfigs.Add(ocelotConfig); await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "创建网关配置成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> CreateRoute(RoutesEditDto dto) { if (string.IsNullOrWhiteSpace(dto.DownstreamPathTemplate)) { return new ResultModel(ResultCode.Fail, "请输入下游路径模板"); } if (string.IsNullOrWhiteSpace(dto.DownstreamScheme)) { return new ResultModel(ResultCode.Fail, "请输入下游HTTP协议"); } if (string.IsNullOrWhiteSpace(dto.UpstreamPathTemplate)) { return new ResultModel(ResultCode.Fail, "请输入上游路径模板"); } var model = new Routes(); model.Id = Guid.NewGuid(); model.OcelotConfigGuid = dto.OcelotConfigGuid; model.DownstreamPathTemplate = dto.DownstreamPathTemplate; model.DownstreamScheme = dto.DownstreamScheme; model.UpstreamPathTemplate = dto.UpstreamPathTemplate; model.RouteIsCaseSensitive = dto.RouteIsCaseSensitive; model.LoadBalancerOption = new LoadBalancerOption { Id = Guid.NewGuid(), Type = dto.LoadBalancerOption.Type, RoutesGuid = model.Id }; if (!string.IsNullOrWhiteSpace(dto.AuthenticationOptions.AuthenticationProviderKey)) { model.AuthenticationOptions = new AuthenticationOptions { Id = Guid.NewGuid(), AuthenticationProviderKey = dto.AuthenticationOptions.AuthenticationProviderKey, RoutesGuid = model.Id }; } dto.DownstreamHostAndPorts.ForEach(x => { model.DownstreamHostAndPorts.Add(new DownstreamHostAndPorts { Id = new Guid(), Host = x.Host, Port = x.Port, RoutesGuid = model.Id }); }); dto.UpstreamHttpMethods.ForEach(x => { model.UpstreamHttpMethods.Add(new UpstreamHttpMethods { Id = new Guid(), Method = x.Method, RoutesGuid = model.Id }); }); try { _userDatabaseContext.Routes.Add(model); await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "创建路由成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> DeleteConfig(Guid id) { try { _userDatabaseContext.OcelotConfigs.Remove(_userDatabaseContext.OcelotConfigs.FirstOrDefault(x => x.Id == id)); await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "删除网关配置成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> DelteRoute(Guid id) { try { _userDatabaseContext.Routes.Remove(_userDatabaseContext.Routes.FirstOrDefault(x => x.Id == id)); _ = await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "删除路由成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> EnableConfig(Guid id) { var list = _userDatabaseContext.OcelotConfigs.Where(x => 1 == 1); foreach (var item in list) { if (item.Id != id) { item.IsEnable = false; } else { item.IsEnable = true; } }; try { await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "启用配置成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> GetAllConfig() { return await Task.Run(() => { try { var config = _userDatabaseContext.OcelotConfigs.Where(x => 1 == 1) .Select(x => new OcelotConfigDto { Id = x.Id, ConfigName = x.ConfigName, IsEnable = x.IsEnable }); return new ResultModel(ResultCode.Success, config); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } }); } public async Task<ResultModel> GetConfigById(Guid id) { try { var config = await _userDatabaseContext.OcelotConfigs .Include(x => x.GlobalConfiguration) .FirstOrDefaultAsync(x => x.Id == id); if (config == null) { return new ResultModel(ResultCode.Fail, "没有对应配置"); } var ocelotConfigDto = new OcelotConfigDto { Id = config.Id, ConfigName = config.ConfigName, IsEnable = config.IsEnable, GlobalConfiguration = new GlobalConfigurationDto { Id = config.GlobalConfiguration.Id, BaseUrl = config.GlobalConfiguration.BaseUrl, OcelotConfigGuid = config.Id } }; return new ResultModel(ResultCode.Success, ocelotConfigDto); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> GetConfigPageList(OcelotConfigQueryDto dto) { return await Task.Run(() => { try { var query = _userDatabaseContext.OcelotConfigs.Include(x => x.GlobalConfiguration).Where(x => 1 == 1); if (dto.IsEnable != null) { query = query.Where(x => x.IsEnable == dto.IsEnable); } if (!string.IsNullOrWhiteSpace(dto.ConfigName)) { query = query.Where(x => x.ConfigName.Contains(dto.ConfigName)); } var list = query.Select(x => new OcelotConfigDto { Id = x.Id, IsEnable = x.IsEnable, ConfigName = x.ConfigName, GlobalConfiguration = new GlobalConfigurationDto { BaseUrl = x.GlobalConfiguration.BaseUrl, Id = x.GlobalConfiguration.Id, OcelotConfigGuid = x.GlobalConfiguration.OcelotConfigGuid } }); var page = PagedList<OcelotConfigDto>.ToPagedList(list, dto.CurrentPage, dto.PageSize); return new ResultModel(ResultCode.Success, page); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } }); } public async Task<ResultModel> GetRouteById(Guid id) { try { var route = await _userDatabaseContext.Routes.Where(x => x.Id == id) .Include(x => x.AuthenticationOptions) .Include(x => x.DownstreamHostAndPorts) .Include(x => x.LoadBalancerOption) .Include(x => x.UpstreamHttpMethods) .FirstOrDefaultAsync(); if (route == null) { return new ResultModel(ResultCode.Fail, "没有对应路由"); } var routeDto = new RoutesDto { Id = route.Id, DownstreamPathTemplate = route.DownstreamPathTemplate, DownstreamScheme = route.DownstreamScheme, UpstreamPathTemplate = route.UpstreamPathTemplate, RouteIsCaseSensitive = route.RouteIsCaseSensitive }; if (route.LoadBalancerOption != null) { routeDto.LoadBalancerOption = new LoadBalancerOptionDto { Id = route.LoadBalancerOption.Id, Type = route.LoadBalancerOption.Type, RoutesGuid = route.Id }; } if (route.AuthenticationOptions != null) { routeDto.AuthenticationOptions = new AuthenticationOptionsDto { Id = route.AuthenticationOptions.Id, AuthenticationProviderKey = route.AuthenticationOptions.AuthenticationProviderKey, RoutesGuid = route.Id }; } route.DownstreamHostAndPorts.ForEach(x => { routeDto.DownstreamHostAndPorts.Add(new DownstreamHostAndPortsDto { Id = x.Id, Host = x.Host, Port = x.Port, RoutesGuid = x.RoutesGuid }); }); route.UpstreamHttpMethods.ForEach(x => { routeDto.UpstreamHttpMethods.Add(new UpstreamHttpMethodsDto { Id = x.Id, Method = x.Method, RoutesGuid = x.RoutesGuid }); }); return new ResultModel(ResultCode.Success, routeDto); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> GetRoutePageList(RoutesQueryDto dto) { return await Task.Run(async () => { try { var query = _userDatabaseContext.Routes.Where(x => 1 == 1); if (dto.OcelotConfigId != Guid.Empty) { query = query.Where(x => x.OcelotConfigGuid == dto.OcelotConfigId); } else { var model = await _userDatabaseContext.OcelotConfigs.Where(x => x.IsEnable == true).FirstOrDefaultAsync(); query = query.Where(x => x.OcelotConfigGuid == model.Id); } var list = query.Select(x => new RoutesDto { Id = x.Id, DownstreamPathTemplate = x.DownstreamPathTemplate, UpstreamPathTemplate = x.UpstreamPathTemplate, DownstreamScheme = x.DownstreamScheme, RouteIsCaseSensitive = x.RouteIsCaseSensitive, OcelotConfigGuid = x.OcelotConfigGuid }); var page = PagedList<RoutesDto>.ToPagedList(list, dto.CurrentPage, dto.PageSize); return new ResultModel(ResultCode.Success, page); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } }); } public async Task<ResultModel> UpdateConfig(OcelotConfigEditDto dto) { var configModel = await _userDatabaseContext.OcelotConfigs.Include(x => x.GlobalConfiguration).FirstOrDefaultAsync(x => x.Id == dto.Id); if (configModel == null) { return new ResultModel(ResultCode.Fail, "没有对应网关配置"); } configModel.IsEnable = dto.IsEnable; configModel.GlobalConfiguration.BaseUrl = dto.GlobalConfiguration.BaseUrl; try { _userDatabaseContext.OcelotConfigs.Update(configModel); await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "更新网关配置成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } public async Task<ResultModel> UpdateRoute(RoutesEditDto dto) { if (string.IsNullOrWhiteSpace(dto.DownstreamPathTemplate)) { return new ResultModel(ResultCode.Fail, "请输入下游路径模板"); } if (string.IsNullOrWhiteSpace(dto.DownstreamScheme)) { return new ResultModel(ResultCode.Fail, "请输入下游HTTP协议"); } if (string.IsNullOrWhiteSpace(dto.UpstreamPathTemplate)) { return new ResultModel(ResultCode.Fail, "请输入上游路径模板"); } if (dto.DownstreamHostAndPorts == null || dto.DownstreamHostAndPorts.Count <= 0) { return new ResultModel(ResultCode.Fail, "请填写至少一个下游地址"); } if (dto.UpstreamHttpMethods == null || dto.UpstreamHttpMethods.Count <= 0) { return new ResultModel(ResultCode.Fail, "请填写至少一个上游HTTP方法"); } try { var routeModel = await _userDatabaseContext.Routes.Where(x => x.Id == dto.Id) .Include(x => x.AuthenticationOptions) .Include(x => x.DownstreamHostAndPorts) .Include(x => x.LoadBalancerOption) .Include(x => x.UpstreamHttpMethods) .FirstOrDefaultAsync(); routeModel.DownstreamPathTemplate = dto.DownstreamPathTemplate; routeModel.DownstreamScheme = dto.DownstreamScheme; routeModel.UpstreamPathTemplate = dto.UpstreamPathTemplate; routeModel.RouteIsCaseSensitive = dto.RouteIsCaseSensitive; routeModel.LoadBalancerOption = null; routeModel.AuthenticationOptions = null; routeModel.DownstreamHostAndPorts = null; routeModel.UpstreamHttpMethods = null; var loadBalancerOption = new LoadBalancerOption { Id = new Guid(), Type = dto.LoadBalancerOption.Type, RoutesGuid = routeModel.Id }; routeModel.LoadBalancerOption = loadBalancerOption; if (!string.IsNullOrWhiteSpace(dto.AuthenticationOptions.AuthenticationProviderKey)) { routeModel.AuthenticationOptions = new AuthenticationOptions { AuthenticationProviderKey = dto.AuthenticationOptions.AuthenticationProviderKey, RoutesGuid = routeModel.Id }; } var downstreamHostAndPorts = new List<DownstreamHostAndPorts> { }; dto.DownstreamHostAndPorts.ForEach(x => { downstreamHostAndPorts.Add(new DownstreamHostAndPorts { Host = x.Host, Port = x.Port }); }); var upstreamHttpMethods = new List<UpstreamHttpMethods> { }; dto.UpstreamHttpMethods.ForEach(x => { upstreamHttpMethods.Add(new UpstreamHttpMethods { Method = x.Method, RoutesGuid = routeModel.Id }); }); routeModel.DownstreamHostAndPorts = downstreamHostAndPorts; routeModel.UpstreamHttpMethods = upstreamHttpMethods; _userDatabaseContext.Routes.Update(routeModel); await _userDatabaseContext.SaveChangesAsync(); return new ResultModel(ResultCode.Success, "更新路由配置成功"); } catch (Exception ex) { return new ResultModel(ResultCode.Fail, ex.Message); } } } }
38.991701
148
0.494732
[ "MIT" ]
ShadowGB/MagusAppGateway
MagusAppGateway.Services/Services/OcelotConfigService.cs
19,094
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using B83.MeshTools; using MeshDecimator; public class MeshLoaderNet { private const string FolderToRawGCodes = "RawGCodes/"; private string FolderToExportTo = "./"; internal IEnumerator LoadObject(string urlToFile, GCodeHandler source, MeshLoader loader, String path = "") { if (path != "") { FolderToExportTo = path; } if (!source.loading) { source.loading = true; int startindex = urlToFile.LastIndexOf("/") + 1; string savePath = loader.dataPath + FolderToRawGCodes + urlToFile.Substring(startindex); if (!loader.CheckForExsitingObject(urlToFile)) { if (!File.Exists(savePath)) { if (!Directory.Exists(loader.dataPath + "/RawGCodes/")) { Directory.CreateDirectory(loader.dataPath + "/RawGCodes/"); } using (var client = new WebClient()) { client.DownloadFile(urlToFile, savePath); } } string[] Lines = File.ReadAllLines(savePath); loader.gcodeMeshGenerator.CreateObjectFromGCode(Lines, loader, source); } else { if (loader.loadingFromDisk == false) { loader.path = urlToFile; loader.loadingFromDisk = true; } } } return null; } public void SaveLayerAsAsset(Mesh mesh, string name) { if (!Directory.Exists(FolderToExportTo)) { Directory.CreateDirectory(FolderToExportTo); } //Write the mesh to disk again mesh.name = name; File.WriteAllBytes(FolderToExportTo + name + ".mesh", MeshSerializer.SerializeMesh(mesh));// GOAAAL } }
29.121622
111
0.539675
[ "MIT" ]
FlorianJa/GCodeToMesh
GCodeToMesh/MeshLoaderNet.cs
2,157
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using Newtonsoft.Json; namespace Das.Marketo.RestApiClient.Models { /// <summary> /// ResponseOfLead /// </summary> [DataContract] public partial class ResponseOfLead : IEquatable<ResponseOfLead>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ResponseOfLead" /> class. /// </summary> [JsonConstructor] protected ResponseOfLead() { } /// <summary> /// Initializes a new instance of the <see cref="ResponseOfLead" /> class. /// </summary> /// <param name="errors">Array of errors that occurred if the request was unsuccessful (required).</param> /// <param name="moreResult">Boolean indicating if there are more results in subsequent pages.</param> /// <param name="nextPageToken">Paging token given if the result set exceeded the allowed batch size.</param> /// <param name="requestId">Id of the request made (required).</param> /// <param name="result">Array of results for individual records in the operation, may be empty (required).</param> /// <param name="success">Whether the request succeeded (required).</param> /// <param name="warnings">Array of warnings given for the operation (required).</param> public ResponseOfLead(List<Error> errors = default(List<Error>), bool moreResult = default(bool), string nextPageToken = default(string), string requestId = default(string), List<Lead> result = default(List<Lead>), bool success = default(bool), List<Warning> warnings = default(List<Warning>)) { // to ensure "errors" is required (not null) if (errors == null) { throw new InvalidDataException("errors is a required property for ResponseOfLead and cannot be null"); } else { this.Errors = errors; } // to ensure "requestId" is required (not null) if (requestId == null) { throw new InvalidDataException("requestId is a required property for ResponseOfLead and cannot be null"); } else { this.RequestId = requestId; } // to ensure "result" is required (not null) if (result == null) { throw new InvalidDataException("result is a required property for ResponseOfLead and cannot be null"); } else { this.Result = result; } // to ensure "success" is required (not null) if (success == null) { throw new InvalidDataException("success is a required property for ResponseOfLead and cannot be null"); } else { this.Success = success; } // to ensure "warnings" is required (not null) if (warnings == null) { throw new InvalidDataException("warnings is a required property for ResponseOfLead and cannot be null"); } else { this.Warnings = warnings; } this.MoreResult = moreResult; this.NextPageToken = nextPageToken; } /// <summary> /// Array of errors that occurred if the request was unsuccessful /// </summary> /// <value>Array of errors that occurred if the request was unsuccessful</value> [DataMember(Name="errors", EmitDefaultValue=false)] public List<Error> Errors { get; set; } /// <summary> /// Boolean indicating if there are more results in subsequent pages /// </summary> /// <value>Boolean indicating if there are more results in subsequent pages</value> [DataMember(Name="moreResult", EmitDefaultValue=false)] public bool MoreResult { get; set; } /// <summary> /// Paging token given if the result set exceeded the allowed batch size /// </summary> /// <value>Paging token given if the result set exceeded the allowed batch size</value> [DataMember(Name="nextPageToken", EmitDefaultValue=false)] public string NextPageToken { get; set; } /// <summary> /// Id of the request made /// </summary> /// <value>Id of the request made</value> [DataMember(Name="requestId", EmitDefaultValue=false)] public string RequestId { get; set; } /// <summary> /// Array of results for individual records in the operation, may be empty /// </summary> /// <value>Array of results for individual records in the operation, may be empty</value> [DataMember(Name="result", EmitDefaultValue=false)] public List<Lead> Result { get; set; } /// <summary> /// Whether the request succeeded /// </summary> /// <value>Whether the request succeeded</value> [DataMember(Name="success", EmitDefaultValue=false)] public bool Success { get; set; } /// <summary> /// Array of warnings given for the operation /// </summary> /// <value>Array of warnings given for the operation</value> [DataMember(Name="warnings", EmitDefaultValue=false)] public List<Warning> Warnings { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ResponseOfLead {\n"); sb.Append(" Errors: ").Append(Errors).Append("\n"); sb.Append(" MoreResult: ").Append(MoreResult).Append("\n"); sb.Append(" NextPageToken: ").Append(NextPageToken).Append("\n"); sb.Append(" RequestId: ").Append(RequestId).Append("\n"); sb.Append(" Result: ").Append(Result).Append("\n"); sb.Append(" Success: ").Append(Success).Append("\n"); sb.Append(" Warnings: ").Append(Warnings).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ResponseOfLead); } /// <summary> /// Returns true if ResponseOfLead instances are equal /// </summary> /// <param name="input">Instance of ResponseOfLead to be compared</param> /// <returns>Boolean</returns> public bool Equals(ResponseOfLead input) { if (input == null) return false; return ( this.Errors == input.Errors || this.Errors != null && input.Errors != null && this.Errors.SequenceEqual(input.Errors) ) && ( this.MoreResult == input.MoreResult || this.MoreResult.Equals(input.MoreResult) ) && ( this.NextPageToken == input.NextPageToken || (this.NextPageToken != null && this.NextPageToken.Equals(input.NextPageToken)) ) && ( this.RequestId == input.RequestId || (this.RequestId != null && this.RequestId.Equals(input.RequestId)) ) && ( this.Result == input.Result || this.Result != null && input.Result != null && this.Result.SequenceEqual(input.Result) ) && ( this.Success == input.Success || this.Success.Equals(input.Success) ) && ( this.Warnings == input.Warnings || this.Warnings != null && input.Warnings != null && this.Warnings.SequenceEqual(input.Warnings) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Errors != null) hashCode = hashCode * 59 + this.Errors.GetHashCode(); hashCode = hashCode * 59 + this.MoreResult.GetHashCode(); if (this.NextPageToken != null) hashCode = hashCode * 59 + this.NextPageToken.GetHashCode(); if (this.RequestId != null) hashCode = hashCode * 59 + this.RequestId.GetHashCode(); if (this.Result != null) hashCode = hashCode * 59 + this.Result.GetHashCode(); hashCode = hashCode * 59 + this.Success.GetHashCode(); if (this.Warnings != null) hashCode = hashCode * 59 + this.Warnings.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
39.900763
301
0.541228
[ "MIT" ]
SkillsFundingAgency/das-campaign-functions
src/Das.Marketo.RestApiClient/Models/ResponseOfLead.cs
10,454
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Windows.Forms; using TGC.Core.Geometry; using TGC.Core.Mathematica; using TGC.Core.SkeletalAnimation; using TGC.Core.Camara; using TGC.Core.Input; using Microsoft.DirectX.Direct3D; namespace TGC.Group.Model { class Depreca3 { private TgcSkeletalBoneAttach attachment; private TgcSkeletalMesh mesh; private string selectedAnim; private const float velocidad_movimiento = 100f; String MediaDir = "..\\..\\..\\Media\\"; public void InstanciarPersonaje() { //Paths para archivo XML de la malla var pathMesh = MediaDir + "SkeletalAnimations\\BasicHuman\\WomanJeans-TgcSkeletalMesh.xml"; //Path para carpeta de texturas de la malla var mediaPath = MediaDir + "SkeletalAnimations\\BasicHuman\\"; //Lista de animaciones disponibles string[] animationList = { "CrouchWalk", "FlyingKick", "HighKick", "Jump", "LowKick", "Push", "Run", "StandBy", "Talk", "Walk" }; //Crear rutas con cada animacion var animationsPath = new string[animationList.Length]; for (var i = 0; i < animationList.Length; i++) { animationsPath[i] = MediaDir + "SkeletalAnimations\\BasicHuman\\Animations\\" + animationList[i] + "-TgcSkeletalAnim.xml"; } //Cargar mesh y animaciones TgcSkeletalLoader loader = new TgcSkeletalLoader(); mesh = loader.loadMeshAndAnimationsFromFile(pathMesh, mediaPath, animationsPath); mesh.Transform = TGCMatrix.Scaling(2f, 2f, 2f); mesh.Position = new TGCVector3(100, 50, 100); //mesh.rotateY(Geometry.DegreeToRadian(180f)); //Crear esqueleto a modo Debug //meshito.buildSkletonMesh(); //Elegir animacion Caminando //mesh.playAnimation(selectedAnim, true); //Crear caja como modelo de Attachment del hueso "Bip01 L Hand" //Queremos que se haga un attachment de la linterna y la vela eventualmente /* attachment = new TgcSkeletalBoneAttach(); var attachmentBox = TGCBox.fromSize(new TGCVector3(5, 100, 5), Color.Blue); attachment.Mesh = attachmentBox.ToMesh("attachment"); attachment.Bone = mesh.getBoneByName("Bip01 L Hand"); attachment.Offset = TGCMatrix.Translation(10, -40, 0); attachment.updateValues(); */ } public void RenderPersonaje(float elapsedTime) { //Se puede renderizar todo mucho mas simple (sin esqueleto) de la siguiente forma: mesh.animateAndRender(elapsedTime); } public void DisposePersonaje() { mesh.Dispose(); } public TGCVector3 PosicionMesh() { return mesh.Position; } public void animarPersonaje(bool caminar) { if (caminar) { mesh.stopAnimation(); mesh.playAnimation("Walk", true); } else { mesh.stopAnimation(); mesh.playAnimation("StandBy", true); } } public void MoverPersonaje(char key, float elapsedTime) { var movimiento = TGCVector3.Empty; var posicionOriginal = mesh.Position; switch (key) { case 'W': movimiento.Z = -1; break; case 'A': movimiento.X = 1; break; case 'S': movimiento.Z = 1; mesh.Transform.RotateY(FastMath.PI_HALF); break; case 'D': movimiento.X = -1; mesh.Transform.RotateY(FastMath.PI_HALF); break; } movimiento *= velocidad_movimiento * elapsedTime; mesh.Position = mesh.Position + movimiento; mesh.Transform = TGCMatrix.Translation(mesh.Position); } } }
29.847682
138
0.535389
[ "MIT" ]
jjf-covello/2020_1C_3051_the-Salamanders
TGC.Group/Model/Depreca3.cs
4,509
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("01. Average Student Grades")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("01. Average Student Grades")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ad25ac54-bb39-481c-b6ab-16e6f0718572")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.378378
84
0.747183
[ "MIT" ]
melikpehlivanov/Programming-Fundamentals-C-
Nested Dictionaries - Lab/01. Average Student Grades/Properties/AssemblyInfo.cs
1,423
C#
namespace OJS.Web.Common.Extensions { using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; public static class ActionDescriptorExtensions { public static IEnumerable<Attribute> GetAppliedCustomAttributes(this ActionDescriptor actionDescriptor) { var attributes = actionDescriptor.ControllerDescriptor .GetCustomAttributes(true) .Concat(actionDescriptor.GetCustomAttributes(true)) .Cast<Attribute>(); return attributes; } } }
29.35
111
0.657581
[ "MIT" ]
Digid-GMAO/MyTested.AspNet.TV
src/Huge Code Base/Open Judge System/Web/OJS.Web.Common/Extensions/ActionDescriptorExtensions.cs
589
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SolutionAddedToRepo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SolutionAddedToRepo")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ea34f555-d603-4a3f-9296-8d82c56b5048")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.750356
[ "MIT" ]
diamontGit/CSharp-training
SolutionAddedToRepo/SolutionAddedToRepo/Properties/AssemblyInfo.cs
1,409
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace PoC_EFCF_Test.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Movie", columns: table => new { ID = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(type: "nvarchar(max)", nullable: true), ReleaseDate = table.Column<DateTime>(type: "datetime2", nullable: false), Genre = table.Column<string>(type: "nvarchar(max)", nullable: true), Price = table.Column<decimal>(type: "decimal(18,2)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Movie", x => x.ID); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Movie"); } } }
35.529412
93
0.525662
[ "MIT" ]
XenoSoul/POC_SDE-Appeltje_Eitje
PoC_EFCF_Test/Migrations/20201203123402_InitialCreate.cs
1,210
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.AppService.Proxy.Client; using Microsoft.Azure.WebJobs.Script.Binding; namespace Microsoft.Azure.WebJobs.Script.Description { internal sealed class ProxyFunctionDescriptorProvider : FunctionDescriptorProvider { private ProxyClientExecutor _proxyClient; public ProxyFunctionDescriptorProvider(ScriptHost host, ScriptHostConfiguration config, ProxyClientExecutor proxyClient) : base(host, config) { _proxyClient = proxyClient; } public override bool TryCreate(FunctionMetadata functionMetadata, out FunctionDescriptor functionDescriptor) { if (functionMetadata == null) { throw new ArgumentNullException("functionMetadata"); } functionDescriptor = null; if (functionMetadata.IsProxy) { return base.TryCreate(functionMetadata, out functionDescriptor); } return false; } protected override IFunctionInvoker CreateFunctionInvoker(string scriptFilePath, BindingMetadata triggerMetadata, FunctionMetadata functionMetadata, Collection<FunctionBinding> inputBindings, Collection<FunctionBinding> outputBindings) { return new ProxyFunctionInvoker(Host, functionMetadata, _proxyClient); } } }
34.854167
243
0.707711
[ "MIT" ]
Armandd123/azure-functions-host
src/WebJobs.Script/Description/Proxies/ProxyFunctionDescriptorProvider.cs
1,673
C#
using GameTimer; using Microsoft.Xna.Framework; using ResolutionBuddy; using System; namespace CameraBuddy { public class Panner { #region Properties public float PanSpeed { get; set; } public float ShakePan { get; set; } //The previous coordinate system private float PrevLeft { get; set; } private float PrevRight { get; set; } private float PrevTop { get; set; } private float PrevBottom { get; set; } //the target coordinate system, will fit every object onto the screen. public float Left { get; private set; } public float Right { get; private set; } public float Top { get; private set; } public float Bottom { get; private set; } public float LeftPadding { get; set; } public float RightPadding { get; set; } public float TopPadding { get; set; } public float BottomPadding { get; set; } public Rectangle WorldBoundary { get; set; } public bool IgnoreWorldBoundary { get; set; } private Vector2 _center; public Vector2 Center { get => _center; set => _center = value; } private bool _useManualOffset; public bool UseManualOffset { get => _useManualOffset; set { _useManualOffset = value; if (!UseManualOffset) { _manualOffset = Vector2.Zero; } } } private Vector2 _manualOffset; public Vector2 ManualOffset { get { return _manualOffset; } set { _useManualOffset = true; _manualOffset = value; } } #endregion //Properties #region Methods public Panner() { PanSpeed = 10f; ShakePan = 25f; PrevLeft = 0.0f; PrevRight = 0.0f; PrevTop = 0.0f; PrevBottom = 0.0f; Left = 0.0f; Right = 0.0f; Top = 0.0f; Bottom = 0.0f; WorldBoundary = new Rectangle(0, 0, 0, 0); IgnoreWorldBoundary = false; Center = Vector2.Zero; } /// <summary> /// Add a point to the scene. /// This gets called multiple times during the update loop to add all the points we want in frame. /// Later, it will calculate a scale and translation matrix to fit them all on screen. /// </summary> /// <param name="point">the point that we want to be seen in the camera</param> public void AddPoint(Vector2 point, bool cameraReset) { if (cameraReset) { //first point this frame, reset the viewport Left = point.X; Right = point.X; Bottom = point.Y; Top = point.Y; } else { //check the left & right if (point.X < Left) { Left = point.X; } else if (point.X > Right) { Right = point.X; } //check the top & bottom if (point.Y < Top) { Top = point.Y; } else if (point.Y > Bottom) { Bottom = point.Y; } } } public void MoveToViewport(bool forceToViewport, GameClock clock) { //Add the offset Top += ManualOffset.Y; Bottom += ManualOffset.Y; Left += ManualOffset.X; Right += ManualOffset.X; //Add the padding var vert = Bottom - Top; Top -= vert * TopPadding; Bottom += vert * BottomPadding; var horiz = Right - Left; Left -= horiz * LeftPadding; Right += horiz * RightPadding; //set the camera position if (forceToViewport) { PrevLeft = Left; PrevRight = Right; PrevTop = Top; PrevBottom = Bottom; } else { //move the left var leftDiff = (((Left - PrevLeft) * PanSpeed) * clock.TimeDelta); PrevLeft += leftDiff; Left = PrevLeft; //move the Right var rightDiff = (((Right - PrevRight) * PanSpeed) * clock.TimeDelta); PrevRight += rightDiff; Right = PrevRight; //move the Top var topDiff = (((Top - PrevTop) * PanSpeed) * clock.TimeDelta); PrevTop += topDiff; Top = PrevTop; //move the Bottom var bottomDiff = (((Bottom - PrevBottom) * PanSpeed) * clock.TimeDelta); PrevBottom += bottomDiff; Bottom = PrevBottom; } } public void AddShake(float shakeAmount, bool shakeLeft, CountdownTimer shakeTimer) { shakeAmount = ShakePan * shakeAmount; //add the camera spin if (shakeTimer.HasTimeRemaining) { //figure out the proper rotation for the camera shake var shakeX = (shakeAmount * (float)Math.Sin( ((shakeTimer.CurrentTime * (2.0f * Math.PI)) / shakeTimer.CountdownLength))); var shakeY = (shakeAmount * (float)Math.Cos( ((shakeTimer.CurrentTime * (2.0f * Math.PI)) / shakeTimer.CountdownLength))); shakeX = shakeX * (shakeLeft ? -1.0f : 1.0f); Left += shakeX; Right += shakeX; Top += shakeY; Bottom += shakeY; } } public float Constrain() { //Constrain the camera to stay in teh game world... or dont. if (!IgnoreWorldBoundary) { //hold all points inside the game world! if (Top < WorldBoundary.Top) { Top = WorldBoundary.Top; } if (Bottom > WorldBoundary.Bottom) { Bottom = WorldBoundary.Bottom; } if (Left < WorldBoundary.Left) { Left = WorldBoundary.Left; } if (Right > WorldBoundary.Right) { Right = WorldBoundary.Right; } } //check if we need to zoom to fit either horizontal or vertical //get the current aspect ratio var screenAspectRatio = (float)Resolution.ScreenArea.Width / (float)Resolution.ScreenArea.Height; //get the current target aspect ratio var width = Right - Left; var height = Bottom - Top; var aspectRatio = width / height; /* Here's the formula: X A+i - = --- Y B+j where x/y is the screen aspect ratio and A+i/B+j is the current target. */ //If the current target is less than gl aspect ratio, B is too big (too tall) var newScale = 1.0f; if (aspectRatio < screenAspectRatio) { //j = 0.0f, figure for i //increase the A (width) to fit the aspect ratio var totalAdjustment = (screenAspectRatio * height) - width; //don't let it go past the walls var adjustedRight = (Right + (totalAdjustment / 2.0f)); var adjustedLeft = (Left - (totalAdjustment / 2.0f)); var offRightWall = adjustedRight > WorldBoundary.Right; var offLeftWall = adjustedLeft < WorldBoundary.Left; if (IgnoreWorldBoundary || (!offRightWall && !offLeftWall)) { //those new limits are fine! Right = adjustedRight; Left = adjustedLeft; } else if (offRightWall && offLeftWall) { //both limits are screwed up Right = WorldBoundary.Right; Left = WorldBoundary.Left; } else { //have to adjust to keep the camera on the board if (offRightWall && !offLeftWall) { //put the right at the wall var fRightAdjustment = adjustedRight - WorldBoundary.Right; Right = WorldBoundary.Right; Left -= ((totalAdjustment / 2.0f) + fRightAdjustment); } else if (!offRightWall && offLeftWall) { //put the left at the wall var fLeftAdjustment = WorldBoundary.Left - adjustedLeft; Left = WorldBoundary.Left; Right += (totalAdjustment / 2.0f) + fLeftAdjustment; } //ok double check those limits are still good after being adjusted if (Right > WorldBoundary.Right) { Right = WorldBoundary.Right; } if (Left < WorldBoundary.Left) { Left = WorldBoundary.Left; } } newScale = Resolution.ScreenArea.Width / (Right - Left); } //If the current target is greater than gl aspect ratio, A is too big (too wide) else if (aspectRatio > screenAspectRatio) { //i = 0.0f, figure for j //increase the B (height) to fit the aspect ratio var totalAdjustment = ((width * (float)Resolution.ScreenArea.Height) / (float)Resolution.ScreenArea.Width) - height; //if that moves below the bottom, add it all to the top var adjustedBottom = (Bottom + (totalAdjustment / 2.0f)); //this is where the bottom will be var adjustedCeiling = (Top - (totalAdjustment / 2.0f)); //this is where ceiling will be var offBottomWall = adjustedBottom > WorldBoundary.Bottom; var offCeilingWall = adjustedCeiling < WorldBoundary.Top; if (IgnoreWorldBoundary || (!offBottomWall && !offCeilingWall)) { //those new limits are fine! Top = adjustedCeiling; Bottom = adjustedBottom; } else if (offBottomWall && offCeilingWall) { //both limits are screwed up Bottom = WorldBoundary.Bottom; Top = WorldBoundary.Top; } else { //have to adjust to keep the camera on the board if (offBottomWall && !offCeilingWall) { //put the bottom at the floor var fBottomAdjustment = adjustedBottom - WorldBoundary.Bottom; Bottom = WorldBoundary.Bottom; Top -= ((totalAdjustment / 2.0f) + fBottomAdjustment); } else if (!offBottomWall && offCeilingWall) { //put the top at the ceiling var fTopAdjustment = WorldBoundary.Top - adjustedCeiling; Top = WorldBoundary.Top; Bottom += (totalAdjustment / 2.0f) + fTopAdjustment; } //ok double check those limits are still good after being adjusted if (Bottom > WorldBoundary.Bottom) { Bottom = WorldBoundary.Bottom; } if (Top < WorldBoundary.Top) { Top = WorldBoundary.Top; } } newScale = Resolution.ScreenArea.Height / (Bottom - Top); } return newScale; } public void UpdateCenter(float scale) { //set teh camer position to be the center of the desired rectangle; _center.X = ((Left + Right) / 2.0f) - (Resolution.TitleSafeArea.Left / scale); _center.Y = ((Top + Bottom) / 2.0f) - (Resolution.TitleSafeArea.Top / scale); } #endregion //Methods } }
25.040921
121
0.618527
[ "MIT" ]
dmanning23/CameraBuddy
CameraBuddy/CameraBuddy.SharedProject/Panner.cs
9,793
C#
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions.Internal; using MvcTemplate.Components.Extensions; using System; using System.IO; using System.Text; namespace MvcTemplate.Components.Logging { public class FileLogger : ILogger { private Int64 RollSize { get; } private String LogPath { get; } private LogLevel Level { get; } private String LogDirectory { get; } private Func<Int32?> AccountId { get; } private String RollingFileFormat { get; } private static Object LogWriting { get; } = new Object(); public FileLogger(String path, LogLevel logLevel, Int64 rollSize) { IHttpContextAccessor accessor = new HttpContextAccessor(); String file = Path.GetFileNameWithoutExtension(path); String extension = Path.GetExtension(path); LogDirectory = Path.GetDirectoryName(path); RollingFileFormat = $"{file}-{{0:yyyyMMdd-HHmmss}}-{extension}"; AccountId = () => accessor.HttpContext?.User.Id(); RollSize = rollSize; Level = logLevel; LogPath = path; } public Boolean IsEnabled(LogLevel logLevel) { return Level <= logLevel; } public IDisposable BeginScope<TState>(TState state) { return NullScope.Instance; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, String> formatter) { if (IsEnabled(logLevel)) { StringBuilder log = new StringBuilder(); log.AppendLine($"{logLevel.ToString().PadRight(11)}: {DateTime.Now:yyyy-MM-dd HH:mm:ss.ffffff} [{AccountId()}]"); log.AppendLine($"Message : {formatter(state, exception)}"); AppendStackTrace(log, exception); log.AppendLine(); lock (LogWriting) { Directory.CreateDirectory(LogDirectory); File.AppendAllText(LogPath, log.ToString()); if (RollSize <= new FileInfo(LogPath).Length) File.Move(LogPath, Path.Combine(LogDirectory, String.Format(RollingFileFormat, DateTime.Now))); } } } private void AppendStackTrace(StringBuilder log, Exception exception) { if (exception != null) log.AppendLine($"Stack trace:"); while (exception != null) { log.AppendLine($" {exception.GetType()}: {exception.Message}"); foreach (String line in exception.StackTrace.Split('\n')) log.AppendLine(" " + line.TrimEnd('\r')); exception = exception.InnerException; } } } }
36.7875
145
0.577302
[ "MIT" ]
VoTranThi/MVC6.Template
src/MvcTemplate.Components/Logging/FileLogger.cs
2,945
C#
using System; using System.Runtime.InteropServices; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.IO; using System.Text; using System.Collections.Generic; namespace MonoJavaBridge { public class LogWriter : TextWriter { public override Encoding Encoding { get { return Encoding.ASCII; } } StringBuilder buffer = new StringBuilder(); public override void Write (char value) { if (value == '\n') { JavaBridge.Log(buffer.ToString()); buffer = new StringBuilder(); } else { buffer.Append(value); } } private LogWriter() { } static LogWriter myInstance = new LogWriter(); public static LogWriter Instance { get { return myInstance; } } } public static partial class JavaBridge { public static void Log(String s) { IntPtr p = Marshal.StringToHGlobalAnsi(s); log(p); Marshal.FreeHGlobal(p); } public static void Log(string format, params object[] args) { string s = String.Format(format, args); Log(s); } static JavaVM myVM; static List<Type> myActions = new List<Type>(); static List<Type> myFuncs = new List<Type>(); static MethodInfo mWrapJavaObject = null; static MethodInfo myCLRHandleToObject = null; static MethodInfo myExpressionLambda = null; static MethodInfo mWrapJavaArrayObject = null; static MethodInfo mWrapIJavaObject = null; static MethodInfo myReportException = null; static MethodInfo myReportExceptionNoResult = null; // this is to prevent an ambiguous method when searching for the wrapped method // even with exact parameters provided, I was getting ambiguous method exceptions public static Expression<TDelegate> LambdaPassthrough<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Expression.Lambda<TDelegate>(body, parameters); } static JavaBridge() { Console.SetOut(LogWriter.Instance); Console.SetError(LogWriter.Instance); Console.WriteLine("Mono initialized."); //myStrongJ2CpUntyped = null;//typeof(net.sf.jni4net.utils.Convertor).GetMethod("StrongJ2CpUntyped"); mWrapJavaObject = typeof(JavaBridge).GetMethod("WrapJavaObject", new Type[] { typeof(JniLocalHandle) }); mWrapJavaArrayObject = typeof(JavaBridge).GetMethod("WrapJavaArrayObject", new Type[] { typeof(JniLocalHandle) }); mWrapIJavaObject = typeof(JavaBridge).GetMethod("WrapIJavaObject", new Type[] { typeof(JniLocalHandle) }); myCLRHandleToObject = typeof(JavaBridge).GetMethod("CLRHandleToObject"); myExpressionLambda = typeof(JavaBridge).GetMethod("LambdaPassthrough"); myReportException = typeof(JavaBridge).GetMethod("ReportException"); myReportExceptionNoResult = typeof(JavaBridge).GetMethod("ReportExceptionNoResult"); //Console.WriteLine(myExpressionLambda); myActions.Add(typeof(JniAction)); myActions.Add(typeof(JniAction<int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myActions.Add(typeof(JniAction<int, int, int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); myFuncs.Add(typeof(JniFunc<int, int, int, int, int, int, int, int, int, int, int>).GetGenericTypeDefinition()); } static JNIEnv GetEnv() { return JNIEnv.GetEnvForVm(myVM); } static void Initialize(IntPtr vm) { myVM = new JavaVM(vm); Log("Setting JVM"); var env = JNIEnv.GetEnvForVm(myVM); myMonoProxyClass = env.NewGlobalRef(env.FindClass("com/koushikdutta/monojavabridge/MonoProxy")); myJavaExceptionClass = env.NewGlobalRef(env.FindClass("java/lang/Exception")); mySetGCHandle = env.GetMethodID(myMonoProxyClass, "setGCHandle", "(J)V"); myGetGCHandle = env.GetMethodID(myMonoProxyClass, "getGCHandle", "()J"); var classClass = env.FindClass("java/lang/Class"); var getClassLoader = env.GetMethodID(classClass, "getClassLoader", "()Ljava/lang/ClassLoader;"); var bridgeClass = env.FindClass("com/koushikdutta/monojavabridge/MonoBridge"); var classLoader = env.NewGlobalRef(env.CallObjectMethod(bridgeClass, getClassLoader)); myVM.DefaultClassLoader = classLoader; } static List<string> myAssemblies = new List<string>(); static void LoadAssembly(IntPtr assemblyNamePtr) { String assemblyName = GetEnv().ConvertToString(assemblyNamePtr); Console.WriteLine("Loading Assembly: {0}", assemblyName); var assembly = Assembly.LoadFile(assemblyName); if (assembly != null) { myAssemblies.Add(assembly.FullName); object[] attrs = assembly.GetCustomAttributes(typeof(MonoJavaBridgeAssemblyInitializerAttribute), false); if (attrs.Length >= 1) { var attr = attrs[0] as MonoJavaBridgeAssemblyInitializerAttribute; var type = attr.Type; var method = type.GetMethod("InitializeBridge"); method.Invoke(null, null); } } Console.WriteLine("Done loading assembly"); } [MethodImpl(MethodImplOptions.InternalCall)] extern static void log(IntPtr p); [MethodImpl(MethodImplOptions.InternalCall)] extern static object mono_pointer_to_object(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] extern static IntPtr mono_object_to_pointer(Object o); delegate void JniAction(IntPtr env, IntPtr obj); delegate void JniAction<T1>(IntPtr env, IntPtr obj, T1 t1); delegate void JniAction<T1, T2>(IntPtr env, IntPtr obj, T1 t1, T2 t2); delegate void JniAction<T1, T2, T3>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3); delegate void JniAction<T1, T2, T3, T4>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4); delegate void JniAction<T1, T2, T3, T4, T5>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); delegate void JniAction<T1, T2, T3, T4, T5, T6>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6); delegate void JniAction<T1, T2, T3, T4, T5, T6, T7>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7); delegate void JniAction<T1, T2, T3, T4, T5, T6, T7, T8>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8); delegate void JniAction<T1, T2, T3, T4, T5, T6, T7, T8, T9>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9); delegate void JniAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10); delegate TResult JniFunc<TResult>(IntPtr env, IntPtr obj); delegate TResult JniFunc<T1, TResult>(IntPtr env, IntPtr obj, T1 t1); delegate TResult JniFunc<T1, T2, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2); delegate TResult JniFunc<T1, T2, T3, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3); delegate TResult JniFunc<T1, T2, T3, T4, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4); delegate TResult JniFunc<T1, T2, T3, T4, T5, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5); delegate TResult JniFunc<T1, T2, T3, T4, T5, T6, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6); delegate TResult JniFunc<T1, T2, T3, T4, T5, T6, T7, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7); delegate TResult JniFunc<T1, T2, T3, T4, T5, T6, T7, T8, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8); delegate TResult JniFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9); delegate TResult JniFunc<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult>(IntPtr env, IntPtr obj, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10); static Expression MarshalArgument(Type argumentType, ParameterExpression parameter) { // marshal if necessary, ie intptr to object if (argumentType == parameter.Type) return parameter; if (!argumentType.IsInterface) return Expression.Convert(Expression.Call(mWrapJavaObject, Expression.Convert(parameter, typeof(JniLocalHandle))), argumentType); var wrapObject = mWrapIJavaObject.MakeGenericMethod(argumentType); return Expression.Convert(Expression.Call(wrapObject, Expression.Convert(parameter, typeof(JniLocalHandle))), argumentType); } static JniGlobalHandle myJavaExceptionClass; static JniGlobalHandle myMonoProxyClass; static MethodId myGetGCHandle; static MethodId mySetGCHandle; public static TRes CLRHandleToObject<TRes>(IntPtr obj) where TRes: JavaObject { var env = JNIEnv.ThreadEnv; long handleLong = env.CallLongMethod(obj, myGetGCHandle); TRes ret = null; if (handleLong != 0) { ret = (TRes)GCHandle.FromIntPtr(new IntPtr(handleLong)).Target; /* while (ret == null) { System.Threading.Thread.Sleep(100); ret = (TRes)GCHandle.FromIntPtr(new IntPtr(handleLong)).Target; if (ret != null) Console.WriteLine("Got it!"); } ResurrectObjectIfNeeded(ret, obj); */ } else { ret = (TRes)WrapJavaObject(obj); //var handle = GCHandle.Alloc(ret, GCHandleType.WeakTrackResurrection); var handle = GCHandle.Alloc(ret); long longHandle = GCHandle.ToIntPtr(handle).ToInt64(); //Console.WriteLine("Setting long handle: {0} for object {1}", longHandle, ret.GetType()); env.CallVoidMethod(obj, mySetGCHandle, ConvertToValue(longHandle)); } return ret; } public static void SetGCHandle(JNIEnv env, IJavaObject obj) { var handle = GCHandle.Alloc(obj, GCHandleType.Normal); env.CallVoidMethod(obj.JvmHandle, mySetGCHandle, ConvertToValue((long)GCHandle.ToIntPtr(handle))); } static Expression MarshalCLRHandle(ParameterExpression obj, Type type) { MethodInfo clrHandleToObject = myCLRHandleToObject.MakeGenericMethod(type); return Expression.Call(clrHandleToObject, obj); } static Type GetJNITypeForClrType(Type type) { if (type.IsPrimitive) return type; return typeof(IntPtr); } #if NET_4_0 public static T ReportException<T>(Exception ex) { ReportExceptionNoResult(ex); return default(T); } public static void ReportExceptionNoResult(Exception ex) { JavaException jex = ex as JavaException; if (jex != null) JNIEnv.ThreadEnv.Throw(jex); else JNIEnv.ThreadEnv.ThrowNew(myJavaExceptionClass, ex.Message); } static Expression MakeTryCatchWrapper(MethodCallExpression methodCallExpr) { var parExpr = Expression.Parameter(typeof(Exception), "ex"); MethodInfo reportCall = null; if (methodCallExpr.Type != typeof(void)) reportCall = myReportException.MakeGenericMethod(methodCallExpr.Type); else reportCall = myReportExceptionNoResult; return Expression.TryCatch( methodCallExpr, Expression.Catch( parExpr, Expression.Call(reportCall, parExpr))); } #else public static T ReportException<T>(MethodInfo methodInfo, object o, object[] parameters) { try { return (T)methodInfo.Invoke(o, parameters); } catch (JavaException jex) { JNIEnv.ThreadEnv.Throw(jex); } /* catch (Exception ex) { Console.WriteLine("Threw non java exception to Dalvik!"); Console.WriteLine(ex); JNIEnv.ThreadEnv.ThrowNew(myJavaExceptionClass, ex.Message); } */ return default(T); } public static void ReportExceptionNoResult(MethodInfo methodInfo, object o, object[] parameters) { ReportException<object>(methodInfo, o, parameters); } static Expression MakeTryCatchWrapper(MethodInfo methodInfo, Expression obj, Expression[] args) { //var parExpr = Expression.Parameter(typeof(Exception), "ex"); MethodInfo reportCall = null; if (methodInfo.ReturnType != typeof(void)) reportCall = myReportException.MakeGenericMethod(methodInfo.ReturnType); else reportCall = myReportExceptionNoResult; return Expression.Call(reportCall, Expression.Constant(methodInfo, typeof(MethodInfo)), obj, Expression.NewArrayInit(typeof(object), (from arg in args select Expression.Convert(arg, typeof(object))).ToArray())); } #endif public static Delegate MakeWrapper(MethodInfo method) { // first lets figure out the delegate we need to implement, and the lambda expression that needs to be constructed Type delegateType = null; var clrParameters = (from par in method.GetParameters() select par.ParameterType).ToArray(); var jniParameters = (from par in clrParameters select GetJNITypeForClrType(par)).ToArray(); List<Type> genericArguments = new List<Type>(); genericArguments.AddRange(jniParameters); if (method.ReturnType != typeof(void)) { genericArguments.Add(method.ReturnType); delegateType = myFuncs[genericArguments.Count - 1]; } else { delegateType = myActions[genericArguments.Count]; } if (method.ReturnType != typeof(void) || genericArguments.Count > 0) delegateType = delegateType.MakeGenericType(genericArguments.ToArray()); //Console.WriteLine("Constructed delegate type: {0}", delegateType); MethodInfo expressionMethodInfo = myExpressionLambda.MakeGenericMethod(delegateType); //Console.WriteLine("Constructed Expression.Lambda<T>: {0}", expressionMethodInfo); // now let's construct the parameter list to the expression lambda var parameterExpressions = (from par in method.GetParameters() select Expression.Parameter(GetJNITypeForClrType(par.ParameterType), par.Name)).ToArray(); List<ParameterExpression> fullParameterList = new List<ParameterExpression>(); ParameterExpression env; fullParameterList.Add(env = Expression.Parameter(typeof(IntPtr), "env")); ParameterExpression obj; fullParameterList.Add(obj = Expression.Parameter(typeof(IntPtr), "obj")); // and now we have it fullParameterList.AddRange(parameterExpressions); // we need to marshal the arguments in parameterExpressions to what the method expects. var marshaledParameterExpressions = new Expression[clrParameters.Length]; for (int i = 0; i < clrParameters.Length; i++) { marshaledParameterExpressions[i] = MarshalArgument(clrParameters[i], parameterExpressions[i]); } Expression marshaledObj = MarshalCLRHandle(obj, method.DeclaringType); #if NET_4_0 var methodExpression = Expression.Call(marshaledObj, method, marshaledParameterExpressions); var tryWrapped = MakeTryCatchWrapper(methodExpression); #else // I can maybe create a expanded list of N functions that can do the wrapping? // This may be faster? Could spam though. var tryWrapped = MakeTryCatchWrapper(method, marshaledObj, marshaledParameterExpressions); #endif var lambdaExpression = Expression.Lambda(delegateType, tryWrapped, fullParameterList.ToArray()); //Console.WriteLine("Lambda Expression: {0}", lambdaExpression); //var del = (Delegate)lambdaExpressionCompileMethod.Invoke(lambdaExpression, null); return lambdaExpression.Compile(); } public static void ReleaseGCHandle(long handle) { if (handle == 0) { Console.WriteLine("Request to release a null handle?"); return; } Console.WriteLine("Releasing GC Handle"); var ret = GCHandle.FromIntPtr(new IntPtr(handle)).Target; myMortuary.Remove(ret); } internal static void ResurrectObjectIfNeeded(IJavaObject o, JniLocalHandle obj) { var handle = o.JvmHandle; if (handle != null && !JniGlobalHandle.IsNull(handle)) return; Console.WriteLine("Resurrecting Object: " + o.GetType()); myMortuary.Remove(o); o.Init(JNIEnv.ThreadEnv, obj); } static HashSet<object> myMortuary = new HashSet<object>(); internal static void AddToMortuary(IJavaObject o) { // When a CLR object is destructor is called, we need to release the reference to its JVM twin. // Then add the CLR object to the mortuary to keep it "alive". // Once the JVM cleans up the twin Java object, we remove it from the mortuary. Console.WriteLine("Adding object to mortuary: " + o.GetType().ToString() + " " + System.Threading.Thread.CurrentThread.ManagedThreadId); JNIEnv.ThreadEnv.DeleteGlobalRef(o.JvmHandle); o.JvmHandle = null; myMortuary.Add(o); } public static void Link(IntPtr classHandle, IntPtr methodNameHandle, IntPtr methodSignatureHandle, IntPtr methodParametersHandle) { JNIEnv env = JNIEnv.GetEnvForVm(myVM); try { var methodName = env.ConvertToString(methodNameHandle); var methodSig = env.ConvertToString(methodSignatureHandle); var methodPars = methodParametersHandle == IntPtr.Zero ? null : env.ConvertToString(methodParametersHandle); string classCanonicalName = GetClassCanonicalName(env, classHandle); if (classCanonicalName.StartsWith("internal.")) classCanonicalName = classCanonicalName.Substring("internal.".Length); Console.WriteLine("Linking java class method: {0}.{1}", classCanonicalName, methodName); Type type = FindType(classCanonicalName); if (type == null) { type = FindType(classCanonicalName.Replace('_', '+')); if (type == null) throw new Exception("Unable to find class: " + classCanonicalName); } Type[] parameterTypes = null; if (!string.IsNullOrEmpty(methodPars)) { var parameterTypeStrings = methodPars.Split(','); parameterTypes = new Type[parameterTypeStrings.Length]; for (int i = 0; i < parameterTypeStrings.Length; i++) { parameterTypes[i] = FindType(parameterTypeStrings[i]); if (parameterTypes[i] == null) throw new Exception("Could not find parameter type: " + parameterTypeStrings[i]); } } var method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance, null, parameterTypes ?? new Type[] {}, null); Console.WriteLine("Linking Method: {0} to {1}", method, methodSig); var del = MakeWrapper(method); myLinks.Add(del); JNINativeMethod m = JNINativeMethod.Create(del, methodName, methodSig); m.Register(classHandle, env); Console.WriteLine("Registration complete"); } catch (Exception ex) { Console.WriteLine("ERROR: " + ex.Message); env.ThrowNew(myJavaExceptionClass, ex.Message); } } static List<Delegate> myLinks = new List<Delegate>(); } }
49.114583
223
0.602545
[ "MIT" ]
JeroMiya/androidmono
MonoJavaBridge/JavaBridge/Javabridge.link.cs
23,575
C#
using System.Collections.Generic; using System.Text.RegularExpressions; namespace AgateLib.UserInterface.Content.TextTokenizer { public class TokenDefinition { private Regex _regex; private readonly TokenType _returnsToken; private readonly int _precedence; public TokenDefinition(TokenType returnsToken, string regexPattern, int precedence) { _regex = new Regex(regexPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); _returnsToken = returnsToken; _precedence = precedence; } public IEnumerable<TokenMatch> FindMatches(string inputString) { var matches = _regex.Matches(inputString); for (int i = 0; i < matches.Count; i++) { yield return new TokenMatch() { StartIndex = matches[i].Index, EndIndex = matches[i].Index + matches[i].Length, TokenType = _returnsToken, Value = matches[i].Value, Precedence = _precedence }; } } } }
32.111111
94
0.573529
[ "MIT" ]
eylvisaker/AgateLib
src/AgateLib/UserInterface/Content/TextTokenizer/TokenDefinition.cs
1,158
C#
using System; using System.Collections; using System.Collections.Generic; using StrawberryShake; namespace CoolStore.WebUI.Host { [System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")] public partial class DeleteProductInputSerializer : IInputSerializer { private bool _needsInitialization = true; private IValueSerializer _uuidSerializer; public string Name { get; } = "DeleteProductInput"; public ValueKind Kind { get; } = ValueKind.InputObject; public Type ClrType => typeof(DeleteProductInput); public Type SerializationType => typeof(IReadOnlyDictionary<string, object>); public void Initialize(IValueSerializerCollection serializerResolver) { if (serializerResolver is null) { throw new ArgumentNullException(nameof(serializerResolver)); } _uuidSerializer = serializerResolver.Get("Uuid"); _needsInitialization = false; } public object Serialize(object value) { if (_needsInitialization) { throw new InvalidOperationException( $"The serializer for type `{Name}` has not been initialized."); } if (value is null) { return null; } var input = (DeleteProductInput)value; var map = new Dictionary<string, object>(); if (input.Id.HasValue) { map.Add("id", SerializeNullableUuid(input.Id.Value)); } return map; } private object SerializeNullableUuid(object value) { return _uuidSerializer.Serialize(value); } public object Deserialize(object value) { throw new NotSupportedException( "Deserializing input values is not supported."); } } }
28.449275
85
0.587876
[ "MIT" ]
ANgajasinghe/practical-dapr
src/WebUI/CoolStore.WebUI.Host/GraphQL/Generated/DeleteProductInputSerializer.cs
1,965
C#
using SugarChat.SignalR.Enums; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SugarChat.SignalR.Server.Models { public class SendCustomMessageModel { public SendWay SendWay { get; set; } public string Method { get; set; } public object[] Messages { get; set; } public string SendTo { get; set; } } }
20.45
46
0.674817
[ "Apache-2.0" ]
SugarChat/SugarChat
src/SugarChat.SignalR.ServerClient/Models/SendCustomMessageModel.cs
411
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. 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. #endregion using System.Xml; using System.Xml.Schema; using ClearCanvas.Common.Specifications; namespace ClearCanvas.ImageServer.Rules { /// <summary> /// Base class for server rule action operator compiler. /// </summary> public abstract class ActionOperatorCompilerBase { #region Private Memebers private string _operatorTag; private static readonly IExpressionFactory _defaultExpressionFactory = new ExpressionFactoryExtensionPoint().CreateExtension("dicom"); #endregion #region Constructors /// <summary> /// Creates an instance of <see cref="ActionOperatorCompilerBase"/> /// </summary> /// <param name="operatorTag">The operator tag for the operator</param> public ActionOperatorCompilerBase(string operatorTag) { _operatorTag = operatorTag; } #endregion #region Public Properties public string OperatorTag { get { return _operatorTag; } set { _operatorTag = value; } } #endregion #region Protected Static Methods protected static IExpressionFactory CreateExpressionFactory(string language) { IExpressionFactory factory = new ExpressionFactoryExtensionPoint().CreateExtension(language); if (factory == null) { return _defaultExpressionFactory; } else return factory; } protected static Expression CreateExpression(string text, string language) { IExpressionFactory exprFactory = CreateExpressionFactory(language); if (language != null) exprFactory = _defaultExpressionFactory; return exprFactory.CreateExpression(text); } protected static Expression CreateExpression(string text) { return _defaultExpressionFactory.CreateExpression(text); } protected static XmlSchemaElement GetTimeSchema(string elementName) { XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "minutes"; restriction.Facets.Add(enumeration); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "hours"; restriction.Facets.Add(enumeration); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "weeks"; restriction.Facets.Add(enumeration); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "days"; restriction.Facets.Add(enumeration); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "months"; restriction.Facets.Add(enumeration); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "years"; restriction.Facets.Add(enumeration); simpleType.Content = restriction; XmlSchemaSimpleType languageType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction languageEnum = new XmlSchemaSimpleTypeRestriction(); languageEnum.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "dicom"; languageEnum.Facets.Add(enumeration); languageType.Content = languageEnum; XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaAttribute attrib = new XmlSchemaAttribute(); attrib.Name = "time"; attrib.Use = XmlSchemaUse.Required; attrib.SchemaTypeName = new XmlQualifiedName("double", "http://www.w3.org/2001/XMLSchema"); type.Attributes.Add(attrib); attrib = new XmlSchemaAttribute(); attrib.Name = "unit"; attrib.Use = XmlSchemaUse.Required; attrib.SchemaType = simpleType; type.Attributes.Add(attrib); attrib = new XmlSchemaAttribute(); attrib.Name = "refValue"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); type.Attributes.Add(attrib); attrib = new XmlSchemaAttribute(); attrib.Name = "expressionLanguage"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaType = languageType; type.Attributes.Add(attrib); XmlSchemaElement element = new XmlSchemaElement(); element.Name = elementName; element.SchemaType = type; return element; } protected static XmlSchemaElement GetBaseSchema(string elementName) { XmlSchemaSimpleType languageType = new XmlSchemaSimpleType(); XmlSchemaSimpleTypeRestriction languageEnum = new XmlSchemaSimpleTypeRestriction(); languageEnum.BaseTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); enumeration.Value = "dicom"; languageEnum.Facets.Add(enumeration); languageType.Content = languageEnum; XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaAttribute attrib = new XmlSchemaAttribute(); attrib.Name = "refValue"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema"); type.Attributes.Add(attrib); attrib = new XmlSchemaAttribute(); attrib.Name = "expressionLanguage"; attrib.Use = XmlSchemaUse.Optional; attrib.SchemaType = languageType; type.Attributes.Add(attrib); XmlSchemaElement element = new XmlSchemaElement(); element.Name = elementName; element.SchemaType = type; return element; } #endregion } }
36.859223
143
0.697485
[ "Apache-2.0" ]
econmed/ImageServer20
ImageServer/Rules/ActionOperatorCompilerBase.cs
7,595
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information #region Usings using System; using System.Collections; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Host; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Profile; using DotNetNuke.Entities.Users; using DotNetNuke.Framework; using DotNetNuke.Instrumentation; using DotNetNuke.Security.Membership; using DotNetNuke.Services.Localization; using DotNetNuke.UI.Utilities; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.UI.WebControls; using DataCache = DotNetNuke.Common.Utilities.DataCache; using Globals = DotNetNuke.Common.Globals; using System.Web.UI.WebControls; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Services.Cache; using DotNetNuke.Web.Client; #endregion namespace DotNetNuke.Modules.Admin.Users { using Host = DotNetNuke.Entities.Host.Host; /// ----------------------------------------------------------------------------- /// <summary> /// The User UserModuleBase is used to manage the base parts of a User. /// </summary> /// <remarks> /// </remarks> public partial class User : UserUserControlBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (User)); #region Public Properties public UserCreateStatus CreateStatus { get; set; } /// ----------------------------------------------------------------------------- /// <summary> /// Gets whether the User is valid /// </summary> public bool IsValid { get { return Validate(); } } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and sets whether the Password section is displayed /// </summary> public bool ShowPassword { get { return Password.Visible; } set { Password.Visible = value; } } /// ----------------------------------------------------------------------------- /// <summary> /// Gets and sets whether the Update button /// </summary> public bool ShowUpdate { get { return actionsRow.Visible; } set { actionsRow.Visible = value; } } /// <summary> /// User Form's css class. /// </summary> public string CssClass { get { return pnlAddUser.CssClass; } set { userForm.CssClass = string.IsNullOrEmpty(userForm.CssClass) ? value : string.Format("{0} {1}", userForm.CssClass, value); pnlAddUser.CssClass = string.IsNullOrEmpty(pnlAddUser.CssClass) ? value : string.Format("{0} {1}", pnlAddUser.CssClass, value); ; } } #endregion #region Private Methods /// <summary> /// method checks to see if its allowed to change the username /// valid if a host, or an admin where the username is in only 1 portal /// </summary> /// <returns></returns> private bool CanUpdateUsername() { //do not allow for non-logged in users if (Request.IsAuthenticated==false || AddUser) { return false; } //can only update username if a host/admin and account being managed is not a superuser if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) { //only allow updates for non-superuser accounts if (User.IsSuperUser==false) { return true; } } //if an admin, check if the user is only within this portal if (UserController.Instance.GetCurrentUserInfo().IsInRole(PortalSettings.AdministratorRoleName)) { //only allow updates for non-superuser accounts if (User.IsSuperUser) { return false; } if (PortalController.GetPortalsByUser(User.UserID).Count == 1) return true; } return false; } private void UpdateDisplayName() { //Update DisplayName to conform to Format if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) { User.UpdateDisplayName(PortalSettings.Registration.DisplayNameFormat); } } /// ----------------------------------------------------------------------------- /// <summary> /// Validate validates the User /// </summary> private bool Validate() { //Check User Editor bool _IsValid = userForm.IsValid; //Check Password is valid if (AddUser && ShowPassword) { CreateStatus = UserCreateStatus.AddUser; if (!chkRandom.Checked) { //1. Check Password is Valid if (CreateStatus == UserCreateStatus.AddUser && !UserController.ValidatePassword(txtPassword.Text)) { CreateStatus = UserCreateStatus.InvalidPassword; } if (CreateStatus == UserCreateStatus.AddUser) { User.Membership.Password = txtPassword.Text; } } else { //Generate a random password for the user User.Membership.Password = UserController.GeneratePassword(); } //Check Question/Answer if (CreateStatus == UserCreateStatus.AddUser && MembershipProviderConfig.RequiresQuestionAndAnswer) { if (string.IsNullOrEmpty(txtQuestion.Text)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidQuestion; } else { User.Membership.PasswordQuestion = txtQuestion.Text; } if (CreateStatus == UserCreateStatus.AddUser) { if (string.IsNullOrEmpty(txtAnswer.Text)) { //Invalid Question CreateStatus = UserCreateStatus.InvalidAnswer; } else { User.Membership.PasswordAnswer = txtAnswer.Text; } } } if (CreateStatus != UserCreateStatus.AddUser) { _IsValid = false; } } return _IsValid; } #endregion #region Public Methods /// ----------------------------------------------------------------------------- /// <summary> /// CreateUser creates a new user in the Database /// </summary> public void CreateUser() { //Update DisplayName to conform to Format UpdateDisplayName(); if (IsRegister) { User.Membership.Approved = PortalSettings.UserRegistration == (int) Globals.PortalRegistrationType.PublicRegistration; } else { //Set the Approved status from the value in the Authorized checkbox User.Membership.Approved = chkAuthorize.Checked; } var user = User; // make sure username is set in UseEmailAsUserName" mode if (PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false)) { user.Username = User.Email; User.Username = User.Email; } var createStatus = UserController.CreateUser(ref user); var args = (createStatus == UserCreateStatus.Success) ? new UserCreatedEventArgs(User) {Notify = chkNotify.Checked} : new UserCreatedEventArgs(null); args.CreateStatus = createStatus; OnUserCreated(args); OnUserCreateCompleted(args); } /// ----------------------------------------------------------------------------- /// <summary> /// DataBind binds the data to the controls /// </summary> public override void DataBind() { if (Page.IsPostBack == false) { string confirmString = Localization.GetString("DeleteItem"); if (IsUser) { confirmString = Localization.GetString("ConfirmUnRegister", LocalResourceFile); } ClientAPI.AddButtonConfirm(cmdDelete, confirmString); chkRandom.Checked = false; } cmdDelete.Visible = false; cmdRemove.Visible = false; cmdRestore.Visible = false; if (!AddUser) { var deletePermitted = (User.UserID != PortalSettings.AdministratorId) && !(IsUser && User.IsSuperUser); if ((deletePermitted)) { if ((User.IsDeleted)) { cmdRemove.Visible = true; cmdRestore.Visible = true; } else { cmdDelete.Visible = true; } } } cmdUpdate.Text = Localization.GetString(IsUser ? "Register" : "CreateUser", LocalResourceFile); cmdDelete.Text = Localization.GetString(IsUser ? "UnRegister" : "Delete", LocalResourceFile); if (AddUser) { pnlAddUser.Visible = true; if (IsRegister) { AuthorizeNotify.Visible = false; randomRow.Visible = false; if (ShowPassword) { questionRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; answerRow.Visible = MembershipProviderConfig.RequiresQuestionAndAnswer; lblPasswordHelp.Text = Localization.GetString("PasswordHelpUser", LocalResourceFile); } } else { lblPasswordHelp.Text = Localization.GetString("PasswordHelpAdmin", LocalResourceFile); } txtConfirm.Attributes.Add("value", txtConfirm.Text); txtPassword.Attributes.Add("value", txtPassword.Text); } bool disableUsername = PortalController.GetPortalSettingAsBoolean("Registration_UseEmailAsUserName", PortalId, false); //only show username row once UseEmailAsUserName is disabled in site settings if (disableUsername) { userNameReadOnly.Visible = false; userName.Visible = false; } else { userNameReadOnly.Visible = !AddUser; userName.Visible = AddUser; } if (CanUpdateUsername() && !disableUsername) { renameUserName.Visible = true; userName.Visible = false; userNameReadOnly.Visible = false; ArrayList portals = PortalController.GetPortalsByUser(User.UserID); if (portals.Count>1) { numSites.Text=String.Format(Localization.GetString("UpdateUserName", LocalResourceFile), portals.Count.ToString()); cboSites.Visible = true; cboSites.DataSource = portals; cboSites.DataTextField = "PortalName"; cboSites.DataBind(); renameUserPortals.Visible = true; } } if (!string.IsNullOrEmpty(PortalSettings.Registration.UserNameValidator)) { userName.ValidationExpression = PortalSettings.Registration.UserNameValidator; } if (!string.IsNullOrEmpty(PortalSettings.Registration.EmailValidator)) { email.ValidationExpression = PortalSettings.Registration.EmailValidator; } if (!string.IsNullOrEmpty(PortalSettings.Registration.DisplayNameFormat)) { if (AddUser) { displayNameReadOnly.Visible = false; displayName.Visible = false; } else { displayNameReadOnly.Visible = true; displayName.Visible = false; } firstName.Visible = true; lastName.Visible = true; } else { displayNameReadOnly.Visible = false; displayName.Visible = true; firstName.Visible = false; lastName.Visible = false; } userForm.DataSource = User; if (!Page.IsPostBack) { userForm.DataBind(); renameUserName.Value = User.Username; } } #endregion #region Event Handlers /// ----------------------------------------------------------------------------- /// <summary> /// Page_Load runs when the control is loaded /// </summary> /// <remarks> /// </remarks> protected override void OnLoad(EventArgs e) { base.OnLoad(e); cmdDelete.Click += cmdDelete_Click; cmdUpdate.Click += cmdUpdate_Click; cmdRemove.Click += cmdRemove_Click; cmdRestore.Click += cmdRestore_Click; } protected override void OnPreRender(EventArgs e) { ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); ClientResourceManager.RegisterStyleSheet(Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); JavaScript.RequestRegistration(CommonJs.DnnPlugins); base.OnPreRender(e); if (Host.EnableStrengthMeter) { passwordContainer.CssClass = "password-strength-container"; txtPassword.CssClass = "password-strength"; txtConfirm.CssClass = string.Format("{0} checkStength", txtConfirm.CssClass); var options = new DnnPaswordStrengthOptions(); var optionsAsJsonString = Json.Serialize(options); var passwordScript = string.Format("dnn.initializePasswordStrength('.{0}', {1});{2}", "password-strength", optionsAsJsonString, Environment.NewLine); if (ScriptManager.GetCurrent(Page) != null) { // respect MS AJAX ScriptManager.RegisterStartupScript(Page, GetType(), "PasswordStrength", passwordScript, true); } else { Page.ClientScript.RegisterStartupScript(GetType(), "PasswordStrength", passwordScript, true); } } var confirmPasswordOptions = new DnnConfirmPasswordOptions() { FirstElementSelector = "#" + passwordContainer.ClientID + " input[type=password]", SecondElementSelector = ".password-confirm", ContainerSelector = ".dnnFormPassword", UnmatchedCssClass = "unmatched", MatchedCssClass = "matched" }; var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); if (ScriptManager.GetCurrent(Page) != null) { // respect MS AJAX ScriptManager.RegisterStartupScript(Page, GetType(), "ConfirmPassword", confirmScript, true); } else { Page.ClientScript.RegisterStartupScript(GetType(), "ConfirmPassword", confirmScript, true); } } /// ----------------------------------------------------------------------------- /// <summary> /// cmdDelete_Click runs when the delete Button is clicked /// </summary> private void cmdDelete_Click(Object sender, EventArgs e) { if (IsUserOrAdmin == false) { return; } string name = User.Username; int id = UserId; UserInfo user = User; if (UserController.DeleteUser(ref user, true, false)) { OnUserDeleted(new UserDeletedEventArgs(id, name)); } else { OnUserDeleteError(new UserUpdateErrorArgs(id, name, "UserDeleteError")); } } private void cmdRestore_Click(Object sender, EventArgs e) { if (IsUserOrAdmin == false) { return; } var name = User.Username; var id = UserId; var userInfo = User; if (UserController.RestoreUser(ref userInfo)) { OnUserRestored(new UserRestoredEventArgs(id, name)); } else { OnUserRestoreError(new UserUpdateErrorArgs(id, name, "UserRestoreError")); } } private void cmdRemove_Click(Object sender, EventArgs e) { if (IsUserOrAdmin == false) { return; } var name = User.Username; var id = UserId; if (UserController.RemoveUser(User)) { OnUserRemoved(new UserRemovedEventArgs(id, name)); } else { OnUserRemoveError(new UserUpdateErrorArgs(id, name, "UserRemoveError")); } } /// ----------------------------------------------------------------------------- /// <summary> /// cmdUpdate_Click runs when the Update Button is clicked /// </summary> private void cmdUpdate_Click(Object sender, EventArgs e) { if (IsUserOrAdmin == false) { return; } if (AddUser) { if (IsValid) { CreateUser(); DataCache.ClearPortalUserCountCache(PortalId); } } else { if (userForm.IsValid && (User != null)) { if (User.UserID == PortalSettings.AdministratorId) { //Clear the Portal Cache DataCache.ClearPortalUserCountCache(UserPortalID); } try { //Update DisplayName to conform to Format UpdateDisplayName(); //either update the username or update the user details if (CanUpdateUsername() && !PortalSettings.Registration.UseEmailAsUserName) { UserController.ChangeUsername(User.UserID, renameUserName.Value.ToString()); } //DNN-5874 Check if unique display name is required if (PortalSettings.Registration.RequireUniqueDisplayName) { var usersWithSameDisplayName = (System.Collections.Generic.List<UserInfo>)MembershipProvider.Instance().GetUsersBasicSearch(PortalId, 0, 2, "DisplayName", true, "DisplayName", User.DisplayName); if (usersWithSameDisplayName.Any(user => user.UserID != User.UserID)) { UI.Skins.Skin.AddModuleMessage(this, LocalizeString("DisplayNameNotUnique"), UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError); return; } } UserController.UpdateUser(UserPortalID, User); if (PortalSettings.Registration.UseEmailAsUserName && (User.Username.ToLower() != User.Email.ToLower())) { UserController.ChangeUsername(User.UserID, User.Email); } OnUserUpdated(EventArgs.Empty); OnUserUpdateCompleted(EventArgs.Empty); } catch (Exception exc) { Logger.Error(exc); var args = new UserUpdateErrorArgs(User.UserID, User.Username, "EmailError"); OnUserUpdateError(args); } } } } #endregion } }
35.995185
223
0.498194
[ "MIT" ]
Tychodewaard/Dnn.Platform
DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs
22,427
C#
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.HttpTransport.Specifications { using System; using System.Collections.Generic; using BusConfigurators; using Configuration; using EndpointSpecifications; using GreenPipes; using Hosting; using MassTransit.Builders; using Topology; using Transport; public class HttpBusFactoryConfigurator : BusFactoryConfigurator, IHttpBusFactoryConfigurator, IBusFactory { readonly IHttpBusConfiguration _configuration; readonly IHttpEndpointConfiguration _busEndpointConfiguration; public HttpBusFactoryConfigurator(IHttpBusConfiguration configuration, IHttpEndpointConfiguration busEndpointConfiguration) : base(configuration, busEndpointConfiguration) { _configuration = configuration; _busEndpointConfiguration = busEndpointConfiguration; } public IBusControl CreateBus() { var busReceiveEndpointConfiguration = _configuration.CreateReceiveEndpointConfiguration("bus", _busEndpointConfiguration); var builder = new ConfigurationBusBuilder(_configuration, busReceiveEndpointConfiguration, BusObservable); ApplySpecifications(builder); var bus = builder.Build(); return bus; } public override IEnumerable<ValidationResult> Validate() { foreach (var result in base.Validate()) yield return result; } public IHttpHost Host(HttpHostSettings settings) { var hostTopology = new HttpHostTopology(_busEndpointConfiguration.Topology); var host = new HttpHost(settings, hostTopology); _configuration.CreateHostConfiguration(host); return host; } public void ReceiveEndpoint(string queueName, Action<IReceiveEndpointConfigurator> configureEndpoint) { var configuration = _configuration.CreateReceiveEndpointConfiguration(queueName, _configuration.CreateEndpointConfiguration()); ConfigureReceiveEndpoint(configuration, configureEndpoint); } public void ReceiveEndpoint(IHttpHost host, string queueName, Action<IHttpReceiveEndpointConfigurator> configure) { if (!_configuration.TryGetHost(host, out var hostConfiguration)) throw new ArgumentException("The host was not configured on this bus", nameof(host)); var configuration = hostConfiguration.CreateReceiveEndpointConfiguration(queueName); ConfigureReceiveEndpoint(configuration, configure); } void ConfigureReceiveEndpoint(IHttpReceiveEndpointConfiguration configuration, Action<IHttpReceiveEndpointConfigurator> configure) { configuration.ConnectConsumerConfigurationObserver(this); configuration.ConnectSagaConfigurationObserver(this); configure?.Invoke(configuration.Configurator); var specification = new ConfigurationReceiveEndpointSpecification(configuration); AddReceiveEndpointSpecification(specification); } public void ReceiveEndpoint(Action<IHttpReceiveEndpointConfigurator> configure = null) { var configuration = _configuration.CreateReceiveEndpointConfiguration("", _configuration.CreateEndpointConfiguration()); ConfigureReceiveEndpoint(configuration, configure); } } }
39.101852
140
0.691688
[ "Apache-2.0" ]
OriginalDeveloper/MassTransit
src/MassTransit.HttpTransport/Configuration/Specifications/HttpBusFactoryConfigurator.cs
4,225
C#
namespace CCMS.Shared.Models { public class ActorTypeModel { public int ActorTypeId { get; init; } public string ActorTypeName { get; init; } } }
19.444444
50
0.622857
[ "MIT" ]
aditya119/CCMS
CCMS.Shared/Models/ActorTypeModel.cs
177
C#
#define COSMOSDEBUG using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; using Cosmos.Common.Extensions; using Cosmos.Core; using Cosmos.HAL.BlockDevice; using Cosmos.System.FileSystem.FAT.Listing; using Cosmos.System.FileSystem.Listing; [assembly: InternalsVisibleTo("Cosmos.System.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")] namespace Cosmos.System.FileSystem.FAT { /// <summary> /// FatFileSystem class. /// </summary> internal class FatFileSystem : FileSystem { /// <summary> /// FAT class. Used to manage individual FAT entry. /// </summary> internal class Fat { private readonly FatFileSystem mFileSystem; private readonly ulong mFatSector; /// <summary> /// Initializes a new instance of the <see cref="Fat"/> class. /// </summary> /// <param name="aFileSystem">The file system.</param> /// <param name="aFatSector">The first sector of the FAT table.</param> /// <exception cref="ArgumentNullException">Thrown when aFileSystem is null.</exception> public Fat(FatFileSystem aFileSystem, ulong aFatSector) { if (aFileSystem == null) { throw new ArgumentNullException(nameof(aFileSystem)); } mFileSystem = aFileSystem; mFatSector = aFatSector; } /// <summary> /// Gets the size of a FAT entry in bytes. /// </summary> /// <returns>The size of a FAT entry in bytes.</returns> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> private uint GetFatEntrySizeInBytes() { switch (mFileSystem.mFatType) { case FatTypeEnum.Fat32: return 4; case FatTypeEnum.Fat16: return 2; case FatTypeEnum.Fat12: // TODO: break; } throw new NotSupportedException("Can not get the FAT entry size for an unknown FAT type."); } /// <summary> /// Gets the FAT chain. /// </summary> /// <param name="aFirstEntry">The first entry.</param> /// <param name="aDataSize">Size of a data to be stored in bytes.</param> /// <returns>An array of cluster numbers for the FAT chain.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown when the size of the chain is less then zero. (Never thrown)</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown on out of memory.</item> /// <item>data size invalid.</item> /// <item>unknown file system type</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentException">Thrown when bad aFirstEntry passed.</exception> /// <exception cref="ArgumentNullException">Thrown on fatal error (contact support).</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public uint[] GetFatChain(uint aFirstEntry, long aDataSize = 0) { Global.mFileSystemDebugger.SendInternal("-- Fat.GetFatChain --"); Global.mFileSystemDebugger.SendInternal("aFirstEntry ="); Global.mFileSystemDebugger.SendInternal(aFirstEntry); Global.mFileSystemDebugger.SendInternal("aDataSize ="); Global.mFileSystemDebugger.SendInternal(aDataSize); var xReturn = new uint[0]; uint xCurrentEntry = aFirstEntry; uint xValue; long xEntriesRequired = aDataSize / mFileSystem.BytesPerCluster; if (aDataSize % mFileSystem.BytesPerCluster != 0) { xEntriesRequired++; } GetFatEntry(xCurrentEntry, out xValue); Array.Resize(ref xReturn, xReturn.Length + 1); xReturn[xReturn.Length - 1] = xCurrentEntry; Global.mFileSystemDebugger.SendInternal("xEntriesRequired ="); Global.mFileSystemDebugger.SendInternal(xEntriesRequired); Global.mFileSystemDebugger.SendInternal("xCurrentEntry ="); Global.mFileSystemDebugger.SendInternal(xCurrentEntry); Global.mFileSystemDebugger.SendInternal("xReturn.Length ="); Global.mFileSystemDebugger.SendInternal(xReturn.Length); if (xEntriesRequired > 0) { while (!FatEntryIsEof(xValue)) { xCurrentEntry = xValue; GetFatEntry(xCurrentEntry, out xValue); Array.Resize(ref xReturn, xReturn.Length + 1); xReturn[xReturn.Length - 1] = xCurrentEntry; Global.mFileSystemDebugger.SendInternal("xCurrentEntry ="); Global.mFileSystemDebugger.SendInternal(xCurrentEntry); Global.mFileSystemDebugger.SendInternal("xReturn.Length ="); Global.mFileSystemDebugger.SendInternal(xReturn.Length); } if (xEntriesRequired > xReturn.Length) { long xNewClusters = xEntriesRequired - xReturn.Length; for (int i = 0; i < xNewClusters; i++) { xCurrentEntry = GetNextUnallocatedFatEntry(); mFileSystem.Write(xCurrentEntry, new byte[mFileSystem.BytesPerCluster]); uint xLastFatEntry = xReturn[xReturn.Length - 1]; SetFatEntry(xLastFatEntry, xCurrentEntry); SetFatEntry(xCurrentEntry, FatEntryEofValue()); Array.Resize(ref xReturn, xReturn.Length + 1); xReturn[xReturn.Length - 1] = xCurrentEntry; } } } string xChain = ""; for (int i = 0; i < xReturn.Length; i++) { xChain += xReturn[i]; if (i > 0 || i < xReturn.Length - 1) { xChain += "->"; } } Global.mFileSystemDebugger.SendInternal("Fat xChain:"); Global.mFileSystemDebugger.SendInternal(xChain); SetFatEntry(xCurrentEntry, FatEntryEofValue()); return xReturn; } /// <summary> /// Gets the next unallocated FAT entry. /// </summary> /// <returns>The index of the next unallocated FAT entry.</returns> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid / Failed to find an unallocated FAT entry.</exception> /// <exception cref="ArgumentException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArgumentNullException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public uint GetNextUnallocatedFatEntry() { Global.mFileSystemDebugger.SendInternal("-- Fat.GetNextUnallocatedFatEntry --"); uint xTotalEntries = mFileSystem.FatSectorCount * mFileSystem.BytesPerSector / GetFatEntrySizeInBytes(); for (uint i = mFileSystem.RootCluster + 1; i < xTotalEntries; i++) { GetFatEntry(i, out uint xEntryValue); if (xEntryValue == 0) // check if fat entry is free { Global.mFileSystemDebugger.SendInternal("i =" + i); Global.mFileSystemDebugger.SendInternal("-- ------------------------------ --"); return i; } } throw new Exception("Failed to find an unallocated FAT entry."); } /// <summary> /// Clears a FAT entry. /// </summary> /// <param name="aEntryNumber">The entry number.</param> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentNullException">Thrown when FAT sector data is null.</exception> public void ClearFatEntry(ulong aEntryNumber) { SetFatEntry(aEntryNumber, 0); } /// <summary> /// Set a value in aData corresponding to the type of Fat Filesystem currently in use /// </summary> /// <param name="aEntryNumber">A entry number to set.</param> /// <param name="aValue">A value to set.</param> /// <param name="aData">A data array in which the value should be set</param> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> private void SetValueInFat(ulong aEntryNumber, ulong aValue, byte[] aData) { uint xEntrySize = GetFatEntrySizeInBytes(); ulong xEntryOffset = aEntryNumber * xEntrySize; switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: aData.SetUInt16(xEntryOffset, (ushort)aValue); break; case FatTypeEnum.Fat16: aData.SetUInt16(xEntryOffset, (ushort)aValue); break; case FatTypeEnum.Fat32: aData.SetUInt32(xEntryOffset, (uint)aValue); break; default: throw new NotSupportedException("Unknown FAT type."); } } /// <summary> /// Clears all the FAT sectors. /// </summary> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid / Unknown file system type.</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when entrys aData is null.</item> /// <item>Out of memory.</item> /// </list> /// </exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>Entrys matadata offset value is invalid.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Data length is 0.</item> /// </list> /// </exception> public void ClearAllFat() { //byte[] xFatTable = new byte[4096]; // TODO find where '4096' is defined byte[] xFatTable = mFileSystem.NewBlockArray(); //var xFatTableSize = mFileSystem.FatSectorCount * mFileSystem.BytesPerSector / GetFatEntrySizeInBytes(); Global.mFileSystemDebugger.SendInternal($"FatSector is {mFatSector}"); Global.mFileSystemDebugger.SendInternal($"RootCluster is {mFileSystem.RootCluster}"); Global.mFileSystemDebugger.SendInternal("Clearing all Fat Table"); byte[] xFatTableFirstSector; ReadFatSector(0, out xFatTableFirstSector); /* Change 3rd entry (RootDirectory) to be EOC */ SetValueInFat(2, FatEntryEofValue(), xFatTableFirstSector); /* Copy first three elements on xFatTable */ Array.Copy(xFatTableFirstSector, xFatTable, 12); Global.mFileSystemDebugger.SendInternal($"Clearing First sector..."); /* The rest of 'xFatTable' should be all 0s as new does this internally */ WriteFatSector(0, xFatTable); Global.mFileSystemDebugger.SendInternal($"First sector cleared"); /* Restore the Array will all 0s as it is this we have to write in the other sectors */ //Array.Clear(xFatTable, 0, 12); /* Array.Clear() not work: stack overflow! */ for (int i = 0; i < 11; i++) { xFatTable[i] = 0; } for (ulong sector = 1; sector < mFileSystem.FatSectorCount; sector++) { if (sector % 100 == 0) { Global.mFileSystemDebugger.SendInternal($"Clearing sector {sector}"); } WriteFatSector(sector, xFatTable); } } /// <summary> /// Read FAT sector. /// </summary> /// <param name="aSector">A sector to read from.</param> /// <param name="aData">Output data byte.</param> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> private void ReadFatSector(ulong aSector, out byte[] aData) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.ReadFatSector --"); aData = mFileSystem.NewBlockArray(); ulong xSector = mFatSector + aSector; Global.mFileSystemDebugger.SendInternal("xSector =" + xSector); mFileSystem.Device.ReadBlock(xSector, mFileSystem.SectorsPerCluster, ref aData); Global.mFileSystemDebugger.SendInternal("-- --------------------------- --"); } /// <summary> /// Write FAT sector. /// </summary> /// <param name="aSector">A sector to write to.</param> /// <param name="aData">A data to write.</param> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentNullException">Thrown when aData is null.</exception> private void WriteFatSector(ulong aSector, byte[] aData) { if (aData == null) { throw new ArgumentNullException(nameof(aData)); } var xSector = mFatSector + aSector; mFileSystem.Device.WriteBlock(xSector, mFileSystem.SectorsPerCluster, ref aData); } /// <summary> /// Gets a FAT entry. /// </summary> /// <param name="aEntryNumber">The entry number.</param> /// <param name="aValue">The entry value.</param> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentException">Thrown when bad aEntryNumber passed.</exception> /// <exception cref="ArgumentNullException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when bad aEntryNumber passed.</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> internal void GetFatEntry(uint aEntryNumber, out uint aValue) { Global.mFileSystemDebugger.SendInternal("-- Fat.GetFatEntry --"); Global.mFileSystemDebugger.SendInternal("aEntryNumber = " + aEntryNumber); uint xEntrySize = GetFatEntrySizeInBytes(); ulong xEntryOffset = aEntryNumber * xEntrySize; Global.mFileSystemDebugger.SendInternal("xEntrySize = " + xEntrySize); Global.mFileSystemDebugger.SendInternal("xEntryOffset = " + xEntryOffset); ulong xSector = xEntryOffset / mFileSystem.BytesPerSector; Global.mFileSystemDebugger.SendInternal("xSector = " + xSector); ReadFatSector(xSector, out byte[] xData); switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: // We now access the FAT entry as a WORD just as we do for FAT16, but if the cluster number is // EVEN, we only want the low 12-bits of the 16-bits we fetch. If the cluster number is ODD // we want the high 12-bits of the 16-bits we fetch. uint xResult = BitConverter.ToUInt16(xData, (int)xEntryOffset); if ((aEntryNumber & 0x01) == 0) { aValue = xResult & 0x0FFF; // Even } else { aValue = xResult >> 4; // Odd } break; case FatTypeEnum.Fat16: aValue = BitConverter.ToUInt16(xData, (int)xEntryOffset); break; case FatTypeEnum.Fat32: aValue = BitConverter.ToUInt32(xData, (int)xEntryOffset) & 0x0FFFFFFF; break; default: throw new NotSupportedException("Unknown FAT type."); } Global.mFileSystemDebugger.SendInternal("aValue =" + aValue); Global.mFileSystemDebugger.SendInternal("-- --------------- --"); } /// <summary> /// Sets value in a FAT entry. /// </summary> /// <param name="aEntryNumber">The entry number.</param> /// <param name="aValue">The value.</param> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentNullException">Thrown when FAT sector data is null.</exception> internal void SetFatEntry(ulong aEntryNumber, ulong aValue) { Global.mFileSystemDebugger.SendInternal("--- Fat.SetFatEntry ---"); Global.mFileSystemDebugger.SendInternal("aEntryNumber ="); Global.mFileSystemDebugger.SendInternal(aEntryNumber); uint xEntrySize = GetFatEntrySizeInBytes(); ulong xEntryOffset = aEntryNumber * xEntrySize; ulong xSector = xEntryOffset / mFileSystem.BytesPerSector; //ulong xSectorOffset = (xSector * mFileSystem.BytesPerSector) - xEntryOffset; byte[] xData; ReadFatSector(xSector, out xData); switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: xData.SetUInt16(xEntryOffset, (ushort)aValue); break; case FatTypeEnum.Fat16: xData.SetUInt16(xEntryOffset, (ushort)aValue); break; case FatTypeEnum.Fat32: xData.SetUInt32(xEntryOffset, (uint)aValue); break; default: throw new NotSupportedException("Unknown FAT type."); } WriteFatSector(xSector, xData); Global.mFileSystemDebugger.SendInternal("Returning from --- Fat.SetFatEntry ---"); } /// <summary> /// Sets an array of values in a FAT entry. /// </summary> /// <param name="aEntryNumber">The entry number.</param> /// <param name="aData">The value.</param> /// <param name="aOffset">The offset in the sector to write the value to</param> /// <param name="aLength">The length of data to write</param> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentNullException">Thrown when FAT sector data is null.</exception> internal void SetFatEntry(ulong aEntryNumber, byte[] aData, uint aOffset, uint aLength) { Global.mFileSystemDebugger.SendInternal("--- Fat.SetFatEntry ---"); Global.mFileSystemDebugger.SendInternal("aEntryNumber ="); Global.mFileSystemDebugger.SendInternal(aEntryNumber); uint xEntrySize = GetFatEntrySizeInBytes(); ulong xEntryOffset = aEntryNumber * xEntrySize; ulong xSector = xEntryOffset / mFileSystem.BytesPerSector; ulong xSectorOffset = (xSector * mFileSystem.BytesPerSector) - xEntryOffset; byte[] xData; ReadFatSector(xSectorOffset, out xData); switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: case FatTypeEnum.Fat16: case FatTypeEnum.Fat32: Array.Copy(aData, 0, xData, aOffset, aLength); break; default: throw new NotSupportedException("Unknown FAT type."); } WriteFatSector(xSectorOffset, xData); } /// <summary> /// Check if EOF to FAT entry. /// </summary> /// <param name="aValue">A value to check if is EOF.</param> /// <returns>bool value.</returns> /// <exception cref="ArgumentException">Thrown when FAT type is unknown.</exception> internal bool FatEntryIsEof(uint aValue) { switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: return (aValue & 0x0FFF) >= 0x0FF8; case FatTypeEnum.Fat16: return (aValue & 0xFFFF) >= 0xFFF8; case FatTypeEnum.Fat32: return (aValue & 0x0FFFFFF8) >= 0x0FFFFFF8; default: throw new ArgumentException("Unknown FAT type"); } } /// <summary> /// Check if FAT entry is bad. /// </summary> /// <param name="aValue">A value to check0</param> /// <returns>bool value.</returns> /// <exception cref="ArgumentException">Thrown when FAT type is unknown.</exception> internal bool FatEntryIsBad(uint aValue) { switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: return (aValue & 0x0FFF) == 0x0FF7; case FatTypeEnum.Fat16: return (aValue & 0xFFFF) == 0xFFF7; case FatTypeEnum.Fat32: return (aValue & 0x0FFFFFF8) == 0x0FFFFFF7; default: throw new ArgumentException("Unknown FAT type"); } } /// <summary> /// The the EOF value for a specific FAT type. /// </summary> /// <returns>The EOF value.</returns> /// <exception cref="Exception">Unknown file system type.</exception> internal ulong FatEntryEofValue() { switch (mFileSystem.mFatType) { case FatTypeEnum.Fat12: return 0x0FFF; case FatTypeEnum.Fat16: return 0xFFFF; case FatTypeEnum.Fat32: return 0x0FFFFFFF; default: throw new Exception("Unknown file system type."); } } } /// <summary> /// Number of bytes per cluster. /// </summary> public uint BytesPerCluster { get; private set; } /// <summary> /// Number of bytes per sector. /// </summary> public uint BytesPerSector { get; private set; } /// <summary> /// Number of clusters. /// </summary> public uint ClusterCount { get; private set; } /// <summary> /// First data sector. /// </summary> public uint DataSector { get; private set; } // First Data Sector /// <summary> /// Number of data sectors. /// </summary> public uint DataSectorCount { get; private set; } /// <summary> /// Number of FAT sectors. /// </summary> public uint FatSectorCount { get; private set; } /// <summary> /// FAT type. /// <para> /// possible types: /// <list type="bullet"> /// <item>Unknown.</item> /// <item>Fat12.</item> /// <item>Fat16.</item> /// <item>Fat32.</item> /// </list> /// </para> /// </summary> public FatTypeEnum mFatType { get; private set; } /// <summary> /// Nuber of FATs in the filesystem. /// </summary> public uint NumberOfFATs { get; private set; } /// <summary> /// Number of reserved sectors. /// </summary> public uint ReservedSectorCount { get; private set; } /// <summary> /// FAT32 root cluster. /// </summary> public uint RootCluster { get; private set; } // FAT32 /// <summary> /// Number of root entrys. /// </summary> public uint RootEntryCount { get; private set; } /// <summary> /// FAT12/16 root sector. /// </summary> public uint RootSector { get; private set; } // FAT12/16 /// <summary> /// Number of root sectors. /// <para> /// For FAT12/16. In FAT32 this field remains 0. /// </para> /// </summary> public uint RootSectorCount { get; private set; } // FAT12/16, FAT32 remains 0 /// <summary> /// Number of sectors per cluster. /// </summary> public uint SectorsPerCluster { get; private set; } /// <summary> /// Total number of sectors. /// </summary> public uint TotalSectorCount { get; private set; } /// <summary> /// FATs array. /// </summary> private Fat[] mFats { get; set; } /// <summary> /// FileSystem exits. /// </summary> public bool FileSystemExists { get; private set; } /// <summary> /// Get FAT type. /// <para> /// possible types: /// <list type="bullet"> /// <item>Unknown.</item> /// <item>Fat12.</item> /// <item>Fat16.</item> /// <item>Fat32.</item> /// </list> /// </para> /// </summary> public override string Type { get { switch (mFatType) { case FatTypeEnum.Fat12: return "FAT12"; case FatTypeEnum.Fat16: return "FAT16"; case FatTypeEnum.Fat32: return "FAT32"; default: throw new Exception("Unknown FAT file system type."); } } } /// <summary> /// Initializes a new instance of the <see cref="FatFileSystem"/> class. /// </summary> /// <param name="aDevice">The partition.</param> /// <param name="aRootPath">The root path.</param> /// <param name="aSize">The partition size.</param> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aDevice is null.</item> /// <item>Thrown when FatFileSystem is null.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when aRootPath is null.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown on fatal error (contact support).</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown on fatal error (contact support).</item> /// <item>>FAT signature not found.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> public FatFileSystem(Partition aDevice, string aRootPath, long aSize, bool fileSystemExists = true) : base(aDevice, aRootPath, aSize) { if (aDevice == null) { throw new ArgumentNullException(nameof(aDevice)); } if (String.IsNullOrEmpty(aRootPath)) { throw new ArgumentException("Argument is null or empty", nameof(aRootPath)); } FileSystemExists = fileSystemExists; if (FileSystemExists) { ReadBootSector(); } } /// <summary> /// Initializes a new instance of the <see cref="FatFileSystem"/> class, then format the partition into a new FAT filesystem. /// </summary> /// <param name="aDevice">The partition.</param> /// <param name="aRootPath">The root path.</param> /// <param name="aSize">The partition size.</param> /// <param name="aDriveFormat">The drive format.</param> /// <returns>Fat FileSystem.</returns> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aDevice is null.</item> /// <item>Thrown when FatFileSystem is null.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when aRootPath is null.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown on fatal error (contact support).</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown on fatal error (contact support).</item> /// <item>>FAT signature not found.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> public static FatFileSystem CreateFatFileSystem(Partition aDevice, string aRootPath, long aSize, string aDriveFormat) { if (aDevice == null) { throw new ArgumentNullException(nameof(aDevice)); } if (String.IsNullOrEmpty(aRootPath)) { throw new ArgumentException("Argument is null or empty", nameof(aRootPath)); } Global.mFileSystemDebugger.SendInternal("Creating a new " + aDriveFormat + " FileSystem."); var fs = new FatFileSystem(aDevice, aRootPath, aSize, false); fs.Format(aDriveFormat, true); return fs; } /// <summary> /// Parse BPB /// </summary> /// <exception cref="OverflowException">Thrown on fatal error (contact support).</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown on fatal error (contact support).</item> /// <item>>FAT signature not found.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> internal void ReadBootSector() { var xBPB = Device.NewBlockArray(1); Device.ReadBlock(0UL, 1U, ref xBPB); ushort xSig = BitConverter.ToUInt16(xBPB, 510); if (xSig != 0xAA55) { throw new Exception("FAT signature not found."); } BytesPerSector = BitConverter.ToUInt16(xBPB, 11); SectorsPerCluster = xBPB[13]; BytesPerCluster = BytesPerSector * SectorsPerCluster; ReservedSectorCount = BitConverter.ToUInt16(xBPB, 14); NumberOfFATs = xBPB[16]; RootEntryCount = BitConverter.ToUInt16(xBPB, 17); TotalSectorCount = BitConverter.ToUInt16(xBPB, 19); if (TotalSectorCount == 0) { TotalSectorCount = BitConverter.ToUInt32(xBPB, 32); } // FATSz FatSectorCount = BitConverter.ToUInt16(xBPB, 22); if (FatSectorCount == 0) { FatSectorCount = BitConverter.ToUInt32(xBPB, 36); } DataSectorCount = TotalSectorCount - (ReservedSectorCount + NumberOfFATs * FatSectorCount + ReservedSectorCount); // Computation rounds down. ClusterCount = DataSectorCount / SectorsPerCluster; // Determine the FAT type. Do not use another method - this IS the official and // proper way to determine FAT type. // Comparisons are purposefully < and not <= // FAT16 starts at 4085, FAT32 starts at 65525 if (ClusterCount < 4085) { mFatType = FatTypeEnum.Fat12; } else if (ClusterCount < 65525) { mFatType = FatTypeEnum.Fat16; } else { mFatType = FatTypeEnum.Fat32; } if (mFatType == FatTypeEnum.Fat32) { RootCluster = BitConverter.ToUInt32(xBPB, 44); } else { RootSector = ReservedSectorCount + NumberOfFATs * FatSectorCount; RootSectorCount = (RootEntryCount * 32 + (BytesPerSector - 1)) / BytesPerSector; } DataSector = ReservedSectorCount + NumberOfFATs * FatSectorCount + RootSectorCount; mFats = new Fat[NumberOfFATs]; for (ulong i = 0; i < NumberOfFATs; i++) { mFats[i] = new Fat(this, (ReservedSectorCount + i * FatSectorCount)); } } /// <summary> /// Get FAT. /// </summary> /// <param name="aTableNumber">A table number to get.</param> /// <returns>FAT type.</returns> /// <exception cref="Exception">Thrown when FAT table number doesn't exist.</exception> internal Fat GetFat(int aTableNumber) { if (mFats.Length > aTableNumber) { return mFats[aTableNumber]; } throw new Exception("The fat table number doesn't exist."); } /// <summary> /// Create new block array. /// </summary> /// <returns>Byte array.</returns> internal byte[] NewBlockArray() { return new byte[BytesPerCluster]; } /// <summary> /// Read data from cluster. /// </summary> /// <param name="aCluster">A cluster to read from.</param> /// <param name="aData">A data array to write the output to.</param> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> internal void Read(long aCluster, out byte[] aData) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.Read --"); Global.mFileSystemDebugger.SendInternal($"aCluster = {aCluster}"); if (mFatType == FatTypeEnum.Fat32) { aData = NewBlockArray(); long xSector = DataSector + (aCluster - RootCluster) * SectorsPerCluster; Global.mFileSystemDebugger.SendInternal($"xSector = {xSector}"); Device.ReadBlock((ulong)xSector, SectorsPerCluster, ref aData); } else { Global.mFileSystemDebugger.SendInternal("aCluster: " + aCluster); aData = Device.NewBlockArray(1); Device.ReadBlock((ulong)aCluster, RootSectorCount, ref aData); } Global.mFileSystemDebugger.SendInternal($"aData.Length = {aData.Length}"); Global.mFileSystemDebugger.SendInternal("-- ------------------ --"); } /// <summary> /// Write data to cluster. /// </summary> /// <param name="aCluster">A cluster to write to.</param> /// <param name="aData">A data to write.</param> /// <param name="aSize">prob. unused.</param> /// <param name="aOffset">The offset to write from.</param> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when entrys aData is null.</item> /// <item>Out of memory.</item> /// </list> /// </exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>Entrys matadata offset value is invalid.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>aData length is 0.</item> /// </list> /// </exception> internal void Write(long aCluster, byte[] aData, long aSize = 0, long aOffset = 0) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.Write --"); if (aData == null) { throw new ArgumentNullException(nameof(aData)); } if (aSize == 0) { aSize = BytesPerCluster; } byte[] xData; Read(aCluster, out xData); Array.Copy(aData, 0, xData, aOffset, aSize); if (mFatType == FatTypeEnum.Fat32) { long xSector = DataSector + (aCluster - RootCluster) * SectorsPerCluster; Device.WriteBlock((ulong)xSector, SectorsPerCluster, ref xData); } else { Device.WriteBlock((ulong)aCluster, RootSectorCount, ref xData); } } /// <summary> /// Print filesystem info. /// </summary> /// <exception cref="IOException">Thrown on I/O error.</exception> public override void DisplayFileSystemInfo() { global::System.Console.WriteLine("-------File System--------"); global::System.Console.WriteLine("Bytes per Cluster = " + BytesPerCluster); global::System.Console.WriteLine("Bytes per Sector = " + BytesPerSector); global::System.Console.WriteLine("Cluster Count = " + ClusterCount); global::System.Console.WriteLine("Data Sector = " + DataSector); global::System.Console.WriteLine("Data Sector Count = " + DataSectorCount); global::System.Console.WriteLine("FAT Sector Count = " + FatSectorCount); global::System.Console.WriteLine("FAT Type = " + (uint)mFatType); global::System.Console.WriteLine("Number of FATS = " + NumberOfFATs); global::System.Console.WriteLine("Reserved Sector Count = " + ReservedSectorCount); global::System.Console.WriteLine("Root Cluster = " + RootCluster); global::System.Console.WriteLine("Root Entry Count = " + RootEntryCount); global::System.Console.WriteLine("Root Sector = " + RootSector); global::System.Console.WriteLine("Root Sector Count = " + RootSectorCount); global::System.Console.WriteLine("Sectors per Cluster = " + SectorsPerCluster); global::System.Console.WriteLine("Total Sector Count = " + TotalSectorCount); Global.mFileSystemDebugger.SendInternal("Bytes per Cluster ="); Global.mFileSystemDebugger.SendInternal(BytesPerCluster); Global.mFileSystemDebugger.SendInternal("Bytes per Sector ="); Global.mFileSystemDebugger.SendInternal(BytesPerSector); Global.mFileSystemDebugger.SendInternal("Cluster Count ="); Global.mFileSystemDebugger.SendInternal(ClusterCount); Global.mFileSystemDebugger.SendInternal("Data Sector ="); Global.mFileSystemDebugger.SendInternal(DataSector); Global.mFileSystemDebugger.SendInternal("Data Sector Count ="); Global.mFileSystemDebugger.SendInternal(DataSectorCount); Global.mFileSystemDebugger.SendInternal("FAT Sector Count ="); Global.mFileSystemDebugger.SendInternal(FatSectorCount); Global.mFileSystemDebugger.SendInternal("FAT Type ="); Global.mFileSystemDebugger.SendInternal((uint)mFatType); Global.mFileSystemDebugger.SendInternal("Number of FATS ="); Global.mFileSystemDebugger.SendInternal(NumberOfFATs); Global.mFileSystemDebugger.SendInternal("Reserved Sector Count ="); Global.mFileSystemDebugger.SendInternal(ReservedSectorCount); Global.mFileSystemDebugger.SendInternal("Root Cluster ="); Global.mFileSystemDebugger.SendInternal(RootCluster); Global.mFileSystemDebugger.SendInternal("Root Entry Count ="); Global.mFileSystemDebugger.SendInternal(RootEntryCount); Global.mFileSystemDebugger.SendInternal("Root Sector ="); Global.mFileSystemDebugger.SendInternal(RootSector); Global.mFileSystemDebugger.SendInternal("Root Sector Count ="); Global.mFileSystemDebugger.SendInternal(RootSectorCount); Global.mFileSystemDebugger.SendInternal("Sectors per Cluster ="); Global.mFileSystemDebugger.SendInternal(SectorsPerCluster); Global.mFileSystemDebugger.SendInternal("Total Sector Count ="); Global.mFileSystemDebugger.SendInternal(TotalSectorCount); } /// <summary> /// Get list of entries of a directory. /// </summary> /// <param name="aBaseDirectory">A base directory.</param> /// <returns>DirectoryEntry list.</returns> /// <exception cref="ArgumentNullException">Thrown when baseDirectory is null / memory error.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid / invalid directory entry type.</exception> /// <exception cref="ArgumentException">Thrown on memory error.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on memory error.</exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> public override List<DirectoryEntry> GetDirectoryListing(DirectoryEntry aBaseDirectory) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.GetDirectoryListing --"); Global.mFileSystemDebugger.SendInternal("aBaseDirectory: " + aBaseDirectory.mFullPath); if (aBaseDirectory == null) { throw new ArgumentNullException(nameof(aBaseDirectory)); } var result = new List<DirectoryEntry>(); var xEntry = (FatDirectoryEntry)aBaseDirectory; var fatListing = xEntry.ReadDirectoryContents(); for (int i = 0; i < fatListing.Count; i++) { result.Add(fatListing[i]); } Global.mFileSystemDebugger.SendInternal("-- --------------------------------- --"); return result; } /// <summary> /// Get root directory. /// </summary> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentOutOfRangeException">Thrown when root directory address is smaller then root directory address.</exception> /// <exception cref="ArgumentNullException">Thrown when filesystem is null.</exception> /// <exception cref="ArgumentException">Thrown when root path is null or empty.</exception> public override DirectoryEntry GetRootDirectory() { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.GetRootDirectory --"); var xRootEntry = new FatDirectoryEntry(this, null, RootPath, RootPath, Size, RootCluster); return xRootEntry; } /// <summary> /// Create directory. /// </summary> /// <param name="aParentDirectory">A parent directory.</param> /// <param name="aNewDirectory">A new directory name.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aParentDirectory is null.</item> /// <item>aNewDirectory is null or empty.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on memory error / unknown directory entry type.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid / invalid directory entry type / memory error.</exception> /// <exception cref="ArgumentException">Thrown on memory error.</exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown on memory error.</exception> public override DirectoryEntry CreateDirectory(DirectoryEntry aParentDirectory, string aNewDirectory) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.CreateDirectory --"); Global.mFileSystemDebugger.SendInternal("aParentDirectory.Name = " + aParentDirectory?.mName); Global.mFileSystemDebugger.SendInternal("aNewDirectory = " + aNewDirectory); if (aParentDirectory == null) { throw new ArgumentNullException(nameof(aParentDirectory)); } if (string.IsNullOrEmpty(aNewDirectory)) { throw new ArgumentNullException(nameof(aNewDirectory)); } var xParentDirectory = (FatDirectoryEntry)aParentDirectory; var xDirectoryEntryToAdd = xParentDirectory.AddDirectoryEntry(aNewDirectory, DirectoryEntryTypeEnum.Directory); Global.mFileSystemDebugger.SendInternal("-- ----------------------------- --"); return xDirectoryEntryToAdd; } /// <summary> /// Create file. /// </summary> /// <param name="aParentDirectory">A parent directory.</param> /// <param name="aNewFile">A new file name.</param> /// <returns>DirectoryEntry value.</returns> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aParentDirectory is null.</item> /// <item>aNewFile is null or empty.</item> /// <item>memory error.</item> /// </list> /// </exception> /// <exception cref="ArgumentOutOfRangeException">Thrown on memory error / unknown directory entry type.</exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid / invalid directory entry type / memory error.</exception> /// <exception cref="ArgumentException">Thrown on memory error.</exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown on memory error.</exception> public override DirectoryEntry CreateFile(DirectoryEntry aParentDirectory, string aNewFile) { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.CreateFile --"); Global.mFileSystemDebugger.SendInternal("aParentDirectory.Name = " + aParentDirectory?.mName); Global.mFileSystemDebugger.SendInternal("aNewFile =" + aNewFile); if (aParentDirectory == null) { throw new ArgumentNullException(nameof(aParentDirectory)); } if (string.IsNullOrEmpty(aNewFile)) { throw new ArgumentNullException(nameof(aNewFile)); } var xParentDirectory = (FatDirectoryEntry)aParentDirectory; var xDirectoryEntryToAdd = xParentDirectory.AddDirectoryEntry(aNewFile, DirectoryEntryTypeEnum.File); return xDirectoryEntryToAdd; } /// <summary> /// Delete directory. /// </summary> /// <param name="aDirectoryEntry">A directory entry to delete.</param> /// <exception cref="NotImplementedException">Thrown when given entry type is unknown.</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when tring to delete root directory.</item> /// <item>directory entry type is invalid.</item> /// <item>data size invalid.</item> /// <item>FAT table not found.</item> /// <item>out of memory.</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aDirectoryEntry is null.</item> /// <item>aData is null.</item> /// <item>Out of memory.</item> /// </list> /// </exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>Entrys matadata offset value is invalid.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>aData length is 0.</item> /// </list> /// </exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public override void DeleteDirectory(DirectoryEntry aDirectoryEntry) { if (aDirectoryEntry == null) { throw new ArgumentNullException(nameof(aDirectoryEntry)); } var xDirectoryEntry = (FatDirectoryEntry)aDirectoryEntry; xDirectoryEntry.DeleteDirectoryEntry(); } /// <summary> /// Delete file. /// </summary> /// <param name="aDirectoryEntry">A directory entry to delete.</param> /// <exception cref="NotImplementedException">Thrown when given entry type is unknown.</exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when tring to delete root directory.</item> /// <item>directory entry type is invalid.</item> /// <item>data size invalid.</item> /// <item>FAT table not found.</item> /// <item>out of memory.</item> /// </list> /// </exception> /// <exception cref="OverflowException"> /// <list type="bullet"> /// <item>Thrown when data lenght is greater then Int32.MaxValue.</item> /// <item>The number of clusters in the FAT entry is greater than Int32.MaxValue.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>Thrown when aDirectoryEntry is null.</item> /// <item>aData is null.</item> /// <item>Out of memory.</item> /// </list> /// </exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>The size of the chain is less then zero.</item> /// <item>Entrys matadata offset value is invalid.</item> /// </list> /// </exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when FAT type is unknown.</item> /// <item>aData length is 0.</item> /// </list> /// </exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public override void DeleteFile(DirectoryEntry aDirectoryEntry) { if (aDirectoryEntry == null) { throw new ArgumentNullException(nameof(aDirectoryEntry)); } var xDirectoryEntry = (FatDirectoryEntry)aDirectoryEntry; var entries = xDirectoryEntry.GetFatTable(); foreach (var entry in entries) { GetFat(0).ClearFatEntry(entry); } xDirectoryEntry.DeleteDirectoryEntry(); } /// <summary> /// Get and set the root directory label. /// </summary> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>(get) Thrown when root path is null or empty.</item> /// <item>(set) Thrown when label is null or empty string.</item> /// <item>(set) aData length is 0.</item> /// <item>(get / set) memory error.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>(get) Thrown when trying to access VolumeId out of Root Directory.</item> /// <item>(set) Thrown when entry metadata could not be changed.</item> /// <item>(get / set) Invalid entry type.</item> /// <item>(get / set) Invalid entry data size.</item> /// <item>(get / set) Invalid directory entry type.</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException"> /// <list type="bullet"> /// <item>(get) Thrown when filesystem is null.</item> /// <item>(set) Thrown when entrys aValue is null.</item> /// <item>(set) Thrown when entrys aData is null.</item> /// <item>(get / set) Out of memory.</item> /// </list> /// </exception> /// <exception cref="EncoderFallbackException">Thrown when encoder fallback operation on aValue fails / memory error.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aValue is corrupted.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>(get) Thrown when root directory address is smaller then root directory address.</item> /// <item>(get) memory error.</item> /// <item>(set) Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>(set) Entrys matadata offset value is invalid.</item> /// </list> /// </exception> public override string Label { /* * In the FAT filesystem the name field of RootDirectory is - in reality - the Volume Label */ get { Global.mFileSystemDebugger.SendInternal("-- FatFileSystem.mLabel --"); var RootDirectory = (FatDirectoryEntry)GetRootDirectory(); var VolumeId = RootDirectory.FindVolumeId(); if (VolumeId == null) { Global.mFileSystemDebugger.SendInternal("No VolumeID, returning drive name"); return RootDirectory.mName; } Global.mFileSystemDebugger.SendInternal($"Volume label is |{VolumeId.mName.TrimEnd()}|"); return VolumeId.mName.TrimEnd(); } set { Global.mFileSystemDebugger.SendInternal($"FatFileSystem - Setting Volume label to |{value}|"); var RootDirectory = (FatDirectoryEntry)GetRootDirectory(); var VolumeId = RootDirectory.FindVolumeId(); if (VolumeId != null) { VolumeId.SetName(value); return; } Global.mFileSystemDebugger.SendInternal("No VolumeID found, let's create it!"); VolumeId = RootDirectory.CreateVolumeId(value); } } /// <summary> /// Get size of free space available. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArgumentNullException">Thrown when filesystem is null.</exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when root path is null or empty.</item> /// <item>root directory entry data corrupted.</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> public override long AvailableFreeSpace { get { var RootDirectory = (FatDirectoryEntry)GetRootDirectory(); // We do not support "user quotas" for now so this is effectively the same then mTotalFreeSpace /* mSize is expressed in MegaByte */ var TotalSizeInBytes = Size * 1024 * 1024; var UsedSpace = RootDirectory.GetUsedSpace(); Global.mFileSystemDebugger.SendInternal($"TotalSizeInBytes {TotalSizeInBytes} UsedSpace {UsedSpace}"); return TotalSizeInBytes - UsedSpace; //return (mSize * 1024 * 1024) - RootDirectory.GetUsedSpace(); } } /// <summary> /// Get total free space. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArgumentNullException">Thrown when filesystem is null.</exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Thrown when root path is null or empty.</item> /// <item>root directory entry data corrupted.</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="Exception">Thrown when data size invalid.</exception> public override long TotalFreeSpace { get { var RootDirectory = (FatDirectoryEntry)GetRootDirectory(); /* mSize is expressed in MegaByte */ var TotalSizeInBytes = Size * 1024 * 1024; var UsedSpace = RootDirectory.GetUsedSpace(); Global.mFileSystemDebugger.SendInternal($"TotalSizeInBytes {TotalSizeInBytes} UsedSpace {UsedSpace}"); return TotalSizeInBytes - UsedSpace; //return (mSize * 1024 * 1024) - RootDirectory.GetUsedSpace(); } } /// <summary> /// FAT types. /// </summary> internal enum FatTypeEnum { Unknown, Fat12, Fat16, Fat32 } /// <summary> /// Format drive. (delete all) /// </summary> /// <param name="aDriveFormat">FAT Format.</param> /// <param name="aQuick">unused.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <list type = "bullet" > /// <item>Thrown when the data length is 0 or greater then Int32.MaxValue.</item> /// <item>Entrys matadata offset value is invalid.</item> /// <item>Fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="ArgumentNullException">Thrown when filesystem is null / memory error.</exception> /// <exception cref="ArgumentException"> /// <list type="bullet"> /// <item>Data length is 0.</item> /// <item>Root path is null or empty.</item> /// <item>Memory error.</item> /// </list> /// </exception> /// <exception cref="Exception"> /// <list type="bullet"> /// <item>Thrown when data size invalid.</item> /// <item>Thrown on unknown file system type.</item> /// <item>Thrown on fatal error (contact support).</item> /// </list> /// </exception> /// <exception cref="OverflowException">Thrown when data lenght is greater then Int32.MaxValue.</exception> /// <exception cref="DecoderFallbackException">Thrown on memory error.</exception> /// <exception cref="NotImplementedException">Thrown when FAT type is unknown.</exception> /// <exception cref="RankException">Thrown on fatal error (contact support).</exception> /// <exception cref="ArrayTypeMismatchException">Thrown on fatal error (contact support).</exception> /// <exception cref="InvalidCastException">Thrown when the data in aData is corrupted.</exception> /// <exception cref="NotSupportedException">Thrown when FAT type is unknown.</exception> public override void Format(string aDriveFormat, bool aQuick) { /* Parmaters check */ if (Device == null) { throw new ArgumentNullException(nameof(Device)); } if (aDriveFormat == "FAT32") { mFatType = FatTypeEnum.Fat32; } else if (aDriveFormat == "FAT16") { throw new NotImplementedException("FAT16 formatting not supported yet."); } else if (aDriveFormat == "FAT12") { throw new NotImplementedException("FAT12 formatting not supported yet."); } else { throw new Exception("Unknown FAT type."); } /* FAT Configuration */ BytesPerSector = (uint)Device.BlockSize; NumberOfFATs = 2; TotalSectorCount = (uint)Device.BlockCount; if (mFatType == FatTypeEnum.Fat32) { if (TotalSectorCount < 66600) { SectorsPerCluster = 0; } else if (TotalSectorCount < 532480) { SectorsPerCluster = 1; } else if (TotalSectorCount < 16777216) { SectorsPerCluster = 8; } else if (TotalSectorCount < 33554432) { SectorsPerCluster = 16; } else if (TotalSectorCount < 67108864) { SectorsPerCluster = 32; } else { SectorsPerCluster = 64; } } else { throw new NotImplementedException("Unknown FAT type."); } if (SectorsPerCluster == 0) { throw new Exception("FAT32 must have at least 65536 clusters."); } if (mFatType == FatTypeEnum.Fat32) { ReservedSectorCount = 32; RootEntryCount = 0; } else { throw new NotImplementedException("Unknown FAT type."); } FatSectorCount = (uint)GetFatSizeSectors(); /* Create BPB (BIOS Parameter Block) Structure */ var xBPB = new ManagedMemoryBlock(BytesPerSector); xBPB.Fill(0); xBPB.Write8(0, 0xEB); xBPB.Write8(1, 0xFE); xBPB.Write8(2, 0x90); xBPB.WriteString(3, "MSWIN4.1"); xBPB.Write16(0x0B, (ushort)BytesPerSector); xBPB.Write8(0x0D, (byte)SectorsPerCluster); xBPB.Write16(0x0E, (ushort)ReservedSectorCount); xBPB.Write8(0x10, (byte)NumberOfFATs); xBPB.Write16(0x11, (ushort)RootEntryCount); xBPB.Write16(0x1FE, 0xAA55); if (TotalSectorCount > 0xFFFF) { xBPB.Write16(0x13, 0); xBPB.Write32(0x20, TotalSectorCount); } else { xBPB.Write16(0x13, (ushort)TotalSectorCount); xBPB.Write32(0x20, 0); } xBPB.Write8(0x15, 0xF8); // Media type -> 0xF8 is Hard disk /* Create Extended Boot Record Structure */ if (mFatType == FatTypeEnum.Fat32) { xBPB.Write32(0x24, FatSectorCount); xBPB.Write8(0x28, 0); xBPB.Write16(0x2A, 0); //fat version xBPB.Write16(0x2B, 0); xBPB.Write32(0x2C, 2); //cluster number of root directory xBPB.Write16(0x30, 1); //sector # of fsinfo struct xBPB.Write16(0x32, 6); //backup boot sector # xBPB.Write8(0x34, 0); //reserved xBPB.Write8(0x40, 0x80); //drive number. 0x00 = floppy disk, 0x80 = hard disk xBPB.Write8(0x42, 0x29); //signature var SerialID = new byte[4] { 0x01, 0x02, 0x03, 0x04 }; var VolumeLabel = "COSMOSDISK"; xBPB.Copy(0x43, SerialID, 0, SerialID.Length); xBPB.WriteString(0x47, " "); xBPB.WriteString(0x47, VolumeLabel); xBPB.WriteString(0x52, "FAT32 "); //TODO: OS Boot Code } else { throw new NotImplementedException("Unknown FAT type."); } /* Create FSInfo Structure */ var infoSector = new ManagedMemoryBlock(BytesPerSector); infoSector.Fill(0); if (mFatType == FatTypeEnum.Fat32) { infoSector.Write32(0x00, 0x41615252); infoSector.Write32(484, 0x61417272); infoSector.Write32(488, 0xFFFFFFFF); infoSector.Write32(492, 0xFFFFFFFF); infoSector.Write32(508, 0xAA550000); infoSector.Write16(510, 0xAA55); } /* Create first FAT block */ var firstFat = new ManagedMemoryBlock(BytesPerSector); firstFat.Fill(0); if (mFatType == FatTypeEnum.Fat32) { firstFat.Write32(0, 0x0FFFFFFF); // Reserved cluster 1 firstFat.Write32(4, 0x0FFFFFFF); // Reserved cluster 2 firstFat.Write32(8, 0x0FFFFFFF); // mark end for 2nd cluster (root directory) } else { throw new NotImplementedException("Unknown FAT type."); } firstFat.Write8(0, 0xF8); //hard disk (0xF0 is floppy) /* Clean sectors */ if (FileSystemExists) { var emptySector = new ManagedMemoryBlock(BytesPerSector); emptySector.Fill(0); var emptyFat = new ManagedMemoryBlock(FatSectorCount * BytesPerSector); emptyFat.Fill(0); //Clean FATs for (uint fat = 0; fat < NumberOfFATs; fat++) { Device.WriteBlock((ulong)ReservedSectorCount + (FatSectorCount * fat), FatSectorCount, ref emptyFat.memory); } //Clear out root cluster to remove old data for (uint sector = 0; sector < SectorsPerCluster; sector++) { Device.WriteBlock((ulong)DataSector + sector, 1, ref emptySector.memory); } } /* Write structures */ Device.WriteBlock(0, 1, ref xBPB.memory); //Write BIOS Parameter Block to partition Device.WriteBlock(6, 1, ref xBPB.memory); //Write backup Device.WriteBlock(1, 1, ref infoSector.memory); Device.WriteBlock(7, 1, ref infoSector.memory); /* Write FAT sectors */ for (uint i = 0; i < NumberOfFATs; i++) { Device.WriteBlock(ReservedSectorCount + (i * FatSectorCount), 1, ref firstFat.memory); } FileSystemExists = true; ReadBootSector(); DisplayFileSystemInfo(); } /// <summary> /// Computation of FAT size. /// </summary> /// <returns>FAT size.</returns> private ulong GetFatSizeSectors() { ulong FatElementSize = 4; ulong ReservedClusCnt = 2; ulong Numerator = TotalSectorCount - ReservedSectorCount + ReservedClusCnt * SectorsPerCluster; ulong Denominator = SectorsPerCluster * BytesPerSector / FatElementSize + NumberOfFATs; return Numerator / Denominator + 1; } } }
44.122413
385
0.554677
[ "BSD-3-Clause" ]
BlitzWolfMatthew/Cosmos
source/Cosmos.System2/FileSystem/FAT/FatFileSystem.cs
74,613
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Content.Workflow { using System.Collections.Generic; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Content.Workflow.Entities; using DotNetNuke.Entities.Content.Workflow.Exceptions; using DotNetNuke.Entities.Content.Workflow.Repositories; using DotNetNuke.Framework; using DotNetNuke.Services.Localization; public class WorkflowManager : ServiceLocator<IWorkflowManager, WorkflowManager>, IWorkflowManager { private readonly DataProvider _dataProvider; private readonly IWorkflowRepository _workflowRepository; private readonly IWorkflowStateRepository _workflowStateRepository; private readonly ISystemWorkflowManager _systemWorkflowManager; public WorkflowManager() { this._dataProvider = DataProvider.Instance(); this._workflowRepository = WorkflowRepository.Instance; this._workflowStateRepository = WorkflowStateRepository.Instance; this._systemWorkflowManager = SystemWorkflowManager.Instance; } public void DeleteWorkflow(Entities.Workflow workflow) { var workflowToDelete = this._workflowRepository.GetWorkflow(workflow.WorkflowID); if (workflowToDelete == null) { return; } if (workflowToDelete.IsSystem) { throw new WorkflowInvalidOperationException(Localization.GetString("SystemWorkflowDeletionException", Localization.ExceptionsResourceFile)); } var usageCount = this.GetWorkflowUsageCount(workflowToDelete.WorkflowID); if (usageCount > 0) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowInUsageException", Localization.ExceptionsResourceFile)); } this._workflowRepository.DeleteWorkflow(workflowToDelete); } public Entities.Workflow GetWorkflow(int workflowId) { return this._workflowRepository.GetWorkflow(workflowId); } public Entities.Workflow GetWorkflow(ContentItem contentItem) { if (contentItem.StateID == Null.NullInteger) { return null; } var state = WorkflowStateRepository.Instance.GetWorkflowStateByID(contentItem.StateID); return state == null ? null : this.GetWorkflow(state.WorkflowID); } public IEnumerable<Entities.Workflow> GetWorkflows(int portalId) { return this._workflowRepository.GetWorkflows(portalId); } public void AddWorkflow(Entities.Workflow workflow) { this._workflowRepository.AddWorkflow(workflow); var firstDefaultState = this._systemWorkflowManager.GetDraftStateDefinition(1); var lastDefaultState = this._systemWorkflowManager.GetPublishedStateDefinition(2); firstDefaultState.WorkflowID = workflow.WorkflowID; lastDefaultState.WorkflowID = workflow.WorkflowID; this._workflowStateRepository.AddWorkflowState(firstDefaultState); this._workflowStateRepository.AddWorkflowState(lastDefaultState); workflow.States = new List<WorkflowState> { firstDefaultState, lastDefaultState, }; } public void UpdateWorkflow(Entities.Workflow workflow) { this._workflowRepository.UpdateWorkflow(workflow); } public IEnumerable<WorkflowUsageItem> GetWorkflowUsage(int workflowId, int pageIndex, int pageSize) { return CBO.FillCollection<WorkflowUsageItem>(this._dataProvider.GetContentWorkflowUsage(workflowId, pageIndex, pageSize)); } public int GetWorkflowUsageCount(int workflowId) { return this._dataProvider.GetContentWorkflowUsageCount(workflowId); } protected override System.Func<IWorkflowManager> GetFactory() { return () => new WorkflowManager(); } } }
38.353448
156
0.663745
[ "MIT" ]
EPTamminga/Dnn.Platform
DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs
4,451
C#
using Microsoft.AspNetCore.Mvc; namespace Eventnet.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
29.375
106
0.635106
[ "Apache-2.0" ]
HardSign-Team/EventsMap
Eventnet/Eventnet.Api/Controllers/WeatherForecastController.cs
940
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApplication1 { class Professor { private int codigo, salario, cargaHoraria, contacto; private string nome, nivelAcademico, estadoCivil, sexo; public Professor() { } public Professor(int codigo , string nome, int contacto, string nivelAcademico, int salario, int cargaHoraria, string sexo, string estadoCivil) { this.codigo = codigo; this.salario = salario; this.cargaHoraria = cargaHoraria; this.nome = nome; this.contacto = contacto; this.nivelAcademico = nivelAcademico; this.estadoCivil = estadoCivil; this.sexo = sexo; } public int GetCodigo() { return codigo; } public int GetSalario() { return salario; } public int GetCargaHoraria() { return cargaHoraria; } public string GetNome() { return nome; } public int GetContacto() { return contacto; } public string GetNivelAcademico() { return nivelAcademico; } public string GetEstadoCivil() { return estadoCivil; } public string GetSexo() { return sexo; } } }
21.388889
151
0.529221
[ "MIT" ]
Fenias-Manhenge/Crud-C-sharp-
WindowsFormsApplication1/Professor.cs
1,542
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Backend.Data { public static class Guard { public static void IsNotNull(object target, string nameOrDescription) { if (target == null) { throw new CheckInputException(nameOrDescription); } } public static void IsNotNull(object target) { if (target == null) { throw new CheckInputException(); } } } }
21.178571
77
0.554806
[ "MIT" ]
DennisKae/besuchernachweis
backend/Backend.Data/Guard.cs
595
C#
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. //------------------------------------------------------------------------------ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using System.Globalization; using Microsoft.CodeTalk.LanguageService.Entities.UDT; namespace Microsoft.CodeTalk.LanguageService { internal static class CSharpEntityCreationHelper { internal static UserDefinedType CreateClass(BaseTypeDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { UserDefinedType typeObj = new ClassDefinition(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, currentCodeFile); processModifiers(typeObj, node.Modifiers); typeObj.AccessSpecifiers = typeObj.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Internal : typeObj.AccessSpecifiers; typeObj.AssociatedComment = GetComment(typeObj, node, tree, currentCodeFile); return typeObj; } internal static UserDefinedType CreateStruct(BaseTypeDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { UserDefinedType typeObj = new StructDefinition(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, currentCodeFile); processModifiers(typeObj, node.Modifiers); typeObj.AccessSpecifiers = typeObj.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Internal : typeObj.AccessSpecifiers; typeObj.AssociatedComment = GetComment(typeObj, node, tree, currentCodeFile); return typeObj; } internal static UserDefinedType CreateEnum(BaseTypeDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { UserDefinedType typeObj = new Entities.UDT.EnumDefinition(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, currentCodeFile); processModifiers(typeObj, node.Modifiers); typeObj.AccessSpecifiers = typeObj.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Internal : typeObj.AccessSpecifiers; typeObj.AssociatedComment = GetComment(typeObj, node, tree, currentCodeFile); return typeObj; } internal static UserDefinedType CreateInterface(BaseTypeDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { UserDefinedType typeObj = new InterfaceDefinition(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, currentCodeFile); processModifiers(typeObj, node.Modifiers); typeObj.AccessSpecifiers = typeObj.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Internal : typeObj.AccessSpecifiers; typeObj.AssociatedComment = GetComment(typeObj, node, tree, currentCodeFile); return typeObj; } #region PROCESS FUNCTIONS internal static FunctionDefinition CreateMethod(MethodDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Identifier.Text, tree.GetLineSpan(node.Span), node.Modifiers, parent, currentCodeFile); func.ReturnType = node.ReturnType.ToString(); func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return func; } internal static FunctionDefinition CreateMethod(ConstructorDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Identifier.Text, tree.GetLineSpan(node.Span), node.Modifiers, parent, currentCodeFile); func.TypeOfFunction = FunctionTypes.Constructor; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return func; } internal static FunctionDefinition CreateMethod(DestructorDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Identifier.Text, tree.GetLineSpan(node.Span), node.Modifiers, parent, currentCodeFile); func.TypeOfFunction = FunctionTypes.Destructor; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return func; } internal static FunctionDefinition CreateMethod(LambdaExpressionSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject("", tree.GetLineSpan(node.Span), new SyntaxTokenList(), parent, currentCodeFile); func.TypeOfFunction = FunctionTypes.AnonymousFunction; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return func; } internal static FunctionDefinition CreateMethod(DelegateDeclarationSyntax node, ISyntaxEntity parent, CodeFile currentCodeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Identifier != null ? node.Identifier.Text : String.Empty, tree.GetLineSpan(node.Span), node.Modifiers, parent, currentCodeFile); func.TypeOfFunction = String.IsNullOrWhiteSpace(func.Name) ? FunctionTypes.AnonymousDelegate : FunctionTypes.Delegate; func.AssociatedComment = GetComment(func, node, tree, currentCodeFile); return func; } internal static FunctionDefinition CreateMethod(AnonymousMethodExpressionSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(String.Empty, tree.GetLineSpan(node.Span), new SyntaxTokenList(), parent, codeFile); func.TypeOfFunction = FunctionTypes.AnonymousDelegate; func.AssociatedComment = GetComment(func, node, tree, codeFile); return func; } internal static FunctionDefinition CreateMethod(OperatorDeclarationSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.OperatorToken.Text, tree.GetLineSpan(node.Span), node.Modifiers, parent, codeFile); func.TypeOfFunction = FunctionTypes.Operator; func.AssociatedComment = GetComment(func, node, tree, codeFile); return func; } internal static FunctionDefinition CreateMethod(ConversionOperatorDeclarationSyntax node, ISyntaxEntity parent, CodeFile codefile, SyntaxTree tree) { FunctionDefinition func = createFunctionObject(node.Type.ToString(), tree.GetLineSpan(node.Span), node.Modifiers, parent, codefile); func.TypeOfFunction = FunctionTypes.ConversionOperator; func.AssociatedComment = GetComment(func, node, tree, codefile); return func; } private static FunctionDefinition createFunctionObject(string nodeName, FileLinePositionSpan span, SyntaxTokenList modifiers, ISyntaxEntity parent, CodeFile currentCodeFile) { FunctionDefinition func = new FunctionDefinition(nodeName, new FileSpan(span), parent, currentCodeFile); if (modifiers != null) //modifiers are null for anonymous functions. { processModifiers(func, modifiers); } foreach (var modifier in modifiers) { if (modifier.Kind() == SyntaxKind.OverrideKeyword) { func.IsOverride = true; } if (modifier.Kind() == SyntaxKind.AsyncKeyword) { func.IsAsync = true; } if (modifier.Kind() == SyntaxKind.ExternKeyword) { func.IsExtern = true; func.StorageSpecifiers |= StorageSpecifiers.Extern; } if (modifier.Kind() == SyntaxKind.VirtualKeyword) { func.IsVirtual = true; } } if (parent.Kind == SyntaxEntityKind.Class || parent.Kind == SyntaxEntityKind.Interface || parent.Kind == SyntaxEntityKind.Interface) { if (func.IsExtern) { func.TypeOfFunction = FunctionTypes.External; // Defined externally. } else { func.TypeOfFunction = FunctionTypes.MemberFunction; } } else if (parent.Kind == SyntaxEntityKind.Function) { func.TypeOfFunction = FunctionTypes.AnonymousFunction; } else { func.TypeOfFunction = FunctionTypes.GlobalFunction; } func.AccessSpecifiers = func.AccessSpecifiers == AccessSpecifiers.None ? AccessSpecifiers.Private : func.AccessSpecifiers; return func; } private static void processModifiers(AbstractAddressableEntity classMethodOrVariable, SyntaxTokenList modifiers) { classMethodOrVariable.StorageSpecifiers = StorageSpecifiers.Instance; //default. classMethodOrVariable.AccessSpecifiers = AccessSpecifiers.None; //can do this becase we know it's C# foreach (var modifier in modifiers) { switch (modifier.Kind()) { case SyntaxKind.AbstractKeyword: classMethodOrVariable.IsAbstract = true; break; case SyntaxKind.StaticKeyword: classMethodOrVariable.StorageSpecifiers |= StorageSpecifiers.Static; break; case SyntaxKind.PublicKeyword: classMethodOrVariable.AccessSpecifiers = AccessSpecifiers.Public; break; case SyntaxKind.PrivateKeyword: classMethodOrVariable.AccessSpecifiers = AccessSpecifiers.Private; break; case SyntaxKind.InternalKeyword: classMethodOrVariable.AccessSpecifiers = processInternalAndProtected(classMethodOrVariable.AccessSpecifiers, AccessSpecifiers.Internal); break; case SyntaxKind.ProtectedKeyword: classMethodOrVariable.AccessSpecifiers = processInternalAndProtected(classMethodOrVariable.AccessSpecifiers, AccessSpecifiers.Protected); break; case SyntaxKind.OverrideKeyword: //We cannot handle this for both classes and methods, so we let methods handle it separately. break; case SyntaxKind.AsyncKeyword: break; case SyntaxKind.PartialKeyword: break; case SyntaxKind.AliasKeyword: break; case SyntaxKind.AssemblyKeyword: break; case SyntaxKind.BaseKeyword: break; case SyntaxKind.SealedKeyword: break; case SyntaxKind.DefaultKeyword: break; case SyntaxKind.ExplicitKeyword: break; case SyntaxKind.ExternKeyword: break; case SyntaxKind.VirtualKeyword: break; case SyntaxKind.UnsafeKeyword: break; case SyntaxKind.NewKeyword: break; default: throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, "Keyword {0} is not supported", modifier.Text)); } } } #endregion #region PROCESS PROPERTIES internal static MemberProperty CreateProperty(PropertyDeclarationSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { MemberProperty p = new MemberProperty(node.Identifier.Text, new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); p.PropertyType = node.Type.ToString(); p.AssociatedComment = GetComment(p, node, tree, codeFile); return p; } internal static MemberProperty CreateProperty(IndexerDeclarationSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { MemberProperty p = new MemberProperty("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); p.PropertyType = node.Type.ToString(); p.IsIndexer = true; p.AssociatedComment = GetComment(p, node, tree, codeFile); return p; } #endregion #region PROCESS BLOCKS internal static TryBlock CreateTryBlock(TryStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { var tryBlock = new TryBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); return tryBlock; } internal static CatchBlock CreateCatchBlock(CatchClauseSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new CatchBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile) { CatchType = node.Declaration.Type.ToString(), CatchFilterClause = (null == node.Filter) ? string.Empty : node.Filter.FilterExpression.ToString() }; } internal static IfBlock CreateIfBlock(IfStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new IfBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); } internal static ElseBlock CreateElseBlock(ElseClauseSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new ElseBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); } internal static ForBlock CreateForBlock(ForStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new ForBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); } internal static ForEachBlock CreateForEachBlock(ForEachStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new ForEachBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); } internal static WhileBlock CreateWhileBlock(WhileStatementSyntax node, ISyntaxEntity parent, CodeFile codeFile, SyntaxTree tree) { return new WhileBlock("", new FileSpan(tree.GetLineSpan(node.Span)), parent, codeFile); } #endregion internal static FormalParameter CreateFormalParameter(ParameterSyntax node) { FormalParameter fp = new FormalParameter(node.Type != null ? node.Type.ToFullString().Trim() : String.Empty, node.Identifier.Text); foreach (var modifier in node.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.InKeyword: fp.Modifiers |= ParameterModifiers.In; break; case SyntaxKind.OutKeyword: fp.Modifiers |= ParameterModifiers.Out; break; case SyntaxKind.RefKeyword: fp.Modifiers |= ParameterModifiers.Ref; break; case SyntaxKind.ParamsKeyword: fp.Modifiers |= ParameterModifiers.Params; break; case SyntaxKind.ThisKeyword: fp.Modifiers |= ParameterModifiers.This; break; default: throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, "Unable to process keyword {0} in parameter declaration {1}", modifier, node.ToString())); } } if (node.Default != null) { fp.DefaultValue = node.Default.Value.ToString(); } return fp; } private static AccessSpecifiers processInternalAndProtected(AccessSpecifiers current, AccessSpecifiers newAccessSpecifier) { if (current == AccessSpecifiers.None) { return AccessSpecifiers.Internal; } else if (current == AccessSpecifiers.Protected) { return current | newAccessSpecifier; } else if (current == AccessSpecifiers.Internal) { return current | newAccessSpecifier; } else { string msg = String.Format(CultureInfo.InvariantCulture, "Cannot specify {0} and {1} together.", current, newAccessSpecifier); throw new InvalidProgramException(msg); } } internal static Comment GetComment(ISyntaxEntity owner, CSharpSyntaxNode node, SyntaxTree tree, CodeFile currentCodeFile) { var trivias = node.GetLeadingTrivia().Where(t => t.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || t.Kind() == SyntaxKind.MultiLineCommentTrivia || t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || t.Kind() == SyntaxKind.SingleLineCommentTrivia); if (trivias.Any()) { string commentText = String.Empty; FileSpan overallSpan = null; foreach (var trivia in trivias) { if (trivia != null && trivia.Token.Value != null) { overallSpan = processSpan(overallSpan, tree.GetLineSpan(trivia.Span)); if (trivia.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || trivia.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia) { var xml = trivia.GetStructure(); commentText += String.Join(Environment.NewLine, xml.GetText().Lines); } else { commentText += trivia.ToFullString(); } } } var comment = new Comment(commentText, overallSpan, owner, currentCodeFile); comment.Parent = owner; currentCodeFile.AddComment(comment); return comment; } else { return null; } } private static FileSpan processSpan(FileSpan current, FileLinePositionSpan toCombine) { if (current == null) { return new FileSpan(toCombine); } else { return FileSpan.Combine(current, new FileSpan(toCombine)); } } } }
47.225653
192
0.609395
[ "MIT" ]
Bhaskers-Blu-Org2/CodeTalk
src/VisualStudio/CodeTalk.LanguageService/Languages/CSharpEntityCreationHelper.cs
19,884
C#
using Apocalypse.Any.Core.Model; using Apocalypse.Any.Domain.Common.Model.Network; using Apocalypse.Any.Domain.Common.Model.RPG; using System; using System.Collections.Generic; using System.Text; namespace Apocalypse.Any.Domain.Common.Model { public class DialogNode : IIdentifiableModel { public string Id { get; set; } public string Content { get; set; } //public int FontSize { get; set; } public List<Tuple<string,string>> DialogIdContent { get; set; } public CharacterSheet Requirement { get; set; } public ImageData Portrait { get; set; } public string DynamicRelationId { get; set; } } }
31.666667
71
0.687218
[ "MIT" ]
inidibininging/apocalypse_netcore
Apocalypse.Any.Domain.Common.Model/DialogNode.cs
667
C#
// ----------------------------------------------------------------------- // <copyright file="Futures.cs" company="Asynkron AB"> // Copyright (C) 2015-2020 Asynkron AB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; using Proto.Metrics; namespace Proto.Future { public interface IFuture : IDisposable { public PID Pid { get; } public Task<object> Task { get; } public Task<object> GetTask(CancellationToken cancellationToken); } public sealed class FutureFactory { private ActorSystem System { get; } private readonly SharedFutureProcess? _sharedFutureProcess; public FutureFactory(ActorSystem system, bool useSharedFutures, int sharedFutureSize) { System = system; _sharedFutureProcess = useSharedFutures ? new SharedFutureProcess(system, sharedFutureSize) : null; } public IFuture Get() => _sharedFutureProcess?.TryCreateHandle() ?? SingleProcessHandle(); private IFuture SingleProcessHandle() => new FutureProcess(System); } public sealed class FutureProcess : Process, IFuture { private readonly TaskCompletionSource<object> _tcs; private readonly ActorMetrics? _metrics; internal FutureProcess(ActorSystem system) : base(system) { if (!system.Metrics.IsNoop) { _metrics = system.Metrics.Get<ActorMetrics>(); _metrics.FuturesStartedCount.Inc(new[] {system.Id, system.Address}); } _tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously); var name = System.ProcessRegistry.NextId(); var (pid, absent) = System.ProcessRegistry.TryAdd(name, this); if (!absent) throw new ProcessNameExistException(name, pid); pid.RequestId = 1; Pid = pid; } public PID Pid { get; } public Task<object> Task => _tcs.Task; public async Task<object> GetTask(CancellationToken cancellationToken) { try { if (cancellationToken == default) { return await _tcs.Task; } await using (cancellationToken.Register(() => _tcs.TrySetCanceled())) { return await _tcs.Task; } } catch { if (!System.Metrics.IsNoop) { _metrics!.FuturesTimedOutCount.Inc(new[] {System.Id, System.Address}); } Stop(Pid); throw new TimeoutException("Request didn't receive any Response within the expected time."); } } protected internal override void SendUserMessage(PID pid, object message) { try { _tcs.TrySetResult(message); } finally { _metrics?.FuturesCompletedCount.Inc(new[] {System.Id, System.Address}); Stop(Pid); } } protected internal override void SendSystemMessage(PID pid, object message) { if (message is Stop) { Dispose(); return; } _tcs.TrySetResult(default!); if (!System.Metrics.IsNoop) { _metrics!.FuturesCompletedCount.Inc(new[] {System.Id, System.Address}); } Stop(pid); } public void Dispose() => System.ProcessRegistry.Remove(Pid); } }
30.36
111
0.534387
[ "Apache-2.0" ]
AsynkronIT/protoactor-dotnet
src/Proto.Actor/Future/Futures.cs
3,797
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using ARCX.Core.Writers; using System.IO; using System.Linq; using System.Text; using ARCX.Core.Archive; namespace ARCX.Core.Tests.Writers { [TestClass] public class ArcXWriterTests { public byte[] TestData = Encoding.ASCII.GetBytes("testdata".PadRight(512, 'X')); [TestMethod] public void WriteTest() { var writer = new ArcXWriter(); writer.AddFile(new ArcXWriterFile("dir/testfilename", () => new MemoryStream(TestData))); using (MemoryStream ms = new MemoryStream()) { writer.Write(ms, true); ms.Position = 0; ArcXContainer container = new ArcXContainer(ms); container.Files.First().GetStream(); using (Stream fs = container.Files.First().GetStream()) { Assert.AreEqual(TestData.Length, fs.Length); byte[] buffer = new byte[TestData.Length]; fs.Read(buffer, 0, TestData.Length); for (int i = 0; i < TestData.Length; i++) { if (buffer[i] != TestData[i]) { Assert.Fail("Incorrect data read from file."); } } } container.Files.First().GetStream(); } } [TestMethod] public void WriteMultipleChunkTest() { var writer = new ArcXWriter(new ArcXWriterSettings { TargetChunkSize = 512 }); writer.AddFile(new ArcXWriterFile("dir/testfilename", () => new MemoryStream(TestData))); writer.AddFile(new ArcXWriterFile("dir/testfilename2", () => new MemoryStream(TestData))); using (MemoryStream ms = new MemoryStream()) { writer.Write(ms, true); ms.Position = 0; ArcXContainer container = new ArcXContainer(ms); Assert.AreEqual(2, container.Chunks.Count()); } writer = new ArcXWriter(new ArcXWriterSettings { TargetChunkSize = 1024 }); writer.AddFile(new ArcXWriterFile("dir/testfilename", () => new MemoryStream(TestData))); writer.AddFile(new ArcXWriterFile("dir/testfilename2", () => new MemoryStream(TestData))); using (MemoryStream ms = new MemoryStream()) { writer.Write(ms, true); ms.Position = 0; ArcXContainer container = new ArcXContainer(ms); Assert.AreEqual(1, container.Chunks.Count()); } writer = new ArcXWriter(new ArcXWriterSettings { ChunkingEnabled = false }); writer.AddFile(new ArcXWriterFile("dir/testfilename", () => new MemoryStream(TestData))); writer.AddFile(new ArcXWriterFile("dir/testfilename2", () => new MemoryStream(TestData))); using (MemoryStream ms = new MemoryStream()) { writer.Write(ms, true); ms.Position = 0; ArcXContainer container = new ArcXContainer(ms); Assert.AreEqual(2, container.Chunks.Count()); } } } }
23.042735
93
0.662092
[ "MIT" ]
NeighTools/ARCX
ARCX.Core.Tests/Writers/ArcXWriterTests.cs
2,698
C#
using System; //09. Longer Line namespace LongerLine { class LongerLine { static void Main(string[] args) { double x1 = double.Parse(Console.ReadLine()); double y1 = double.Parse(Console.ReadLine()); double x2 = double.Parse(Console.ReadLine()); double y2 = double.Parse(Console.ReadLine()); double x3 = double.Parse(Console.ReadLine()); double y3 = double.Parse(Console.ReadLine()); double x4 = double.Parse(Console.ReadLine()); double y4 = double.Parse(Console.ReadLine()); double lengthOfFirstPair = LineLength(x1, y1, x2, y2); double lengthOfSecondPair = LineLength(x3, y3, x4, y4); string result = ""; if (lengthOfFirstPair >= lengthOfSecondPair) { result = closestPointToCenter(x1, y1, x2, y2); Console.WriteLine(result); } else { result = closestPointToCenter(x3, y3, x4, y4); Console.WriteLine(result); } } static double LineLength(double x1, double y1, double x2, double y2) { double differenceBetwenX = Math.Abs(x1 - x2); double differenceBetwenY = Math.Abs(y1 - y2); double line = Math.Sqrt(Math.Pow(differenceBetwenX,2)+ Math.Pow(differenceBetwenY,2)); return line; } static string closestPointToCenter(double x1, double y1, double x2, double y2) { string coordinates = ""; if (Math.Pow(x1, 2) + Math.Pow(y1, 2) <= Math.Pow(x2, 2) + Math.Pow(y2, 2)) { coordinates = $"({x1}, {y1})({x2}, {y2})"; } else { coordinates = $"({x2}, {y2})({x1}, {y1})"; } return coordinates; } } }
33.684211
98
0.511979
[ "MIT" ]
AquaRush/SoftwareUniversity
Programming-Fundamentals-Extended-May-2017/Methods-Debugging-Exercises/LongerLine/LongerLine.cs
1,922
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.DBFS.Model.V20200418 { public class CreateSnapshotResponse : AcsResponse { private string requestId; private string snapshotId; public string RequestId { get { return requestId; } set { requestId = value; } } public string SnapshotId { get { return snapshotId; } set { snapshotId = value; } } } }
22.701754
63
0.690881
[ "Apache-2.0" ]
aliyun/aliyun-openapi-net-sdk
aliyun-net-sdk-dbfs/DBFS/Model/V20200418/CreateSnapshotResponse.cs
1,294
C#
namespace MpcNET.Test { using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; public class MpdMock : IDisposable { public void Start() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { this.SendCommand("/usr/bin/pkill mpd"); } MpdConf.Create(Path.Combine(AppContext.BaseDirectory, "Server")); var server = this.GetServer(); this.Process = new Process { StartInfo = new ProcessStartInfo { FileName = server.FileName, WorkingDirectory = server.WorkingDirectory, Arguments = server.Arguments, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, } }; TestOutput.WriteLine($"Starting Server: {this.Process.StartInfo.FileName} {this.Process.StartInfo.Arguments}"); this.Process.Start(); TestOutput.WriteLine($"Output: {this.Process.StandardOutput.ReadToEnd()}"); TestOutput.WriteLine($"Error: {this.Process.StandardError.ReadToEnd()}"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { this.SendCommand("/bin/netstat -ntpl"); } } public Process Process { get; private set; } private Server GetServer() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return Server.Linux; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return Server.Windows; } throw new NotSupportedException("OS not supported"); } private void SendCommand(string command) { var netcat = new Process { StartInfo = new ProcessStartInfo { FileName = "/bin/bash", WorkingDirectory = "/bin/", Arguments = $"-c \"sudo {command}\"", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, } }; netcat.Start(); netcat.WaitForExit(); TestOutput.WriteLine(command); TestOutput.WriteLine($"Output: {netcat.StandardOutput.ReadToEnd()}"); TestOutput.WriteLine($"Error: {netcat.StandardError.ReadToEnd()}"); } public void Dispose() { this.Process?.Kill(); this.Process?.Dispose(); TestOutput.WriteLine("Server Stopped."); } private class Server { public static Server Linux = new Server( fileName: "/bin/bash", workingDirectory: "/bin/", arguments: $"-c \"sudo /usr/bin/mpd {Path.Combine(AppContext.BaseDirectory, "Server", "mpd.conf")} -v\""); public static Server Windows = new Server( fileName: Path.Combine(AppContext.BaseDirectory, "Server", "mpd.exe"), workingDirectory: Path.Combine(AppContext.BaseDirectory, "Server"), arguments: $"{Path.Combine(AppContext.BaseDirectory, "Server", "mpd.conf")} -v"); private Server(string fileName, string workingDirectory, string arguments) { this.FileName = fileName; this.WorkingDirectory = workingDirectory; this.Arguments = arguments; } public string FileName { get; } public string WorkingDirectory { get; } public string Arguments { get; } } } }
33.487395
123
0.523714
[ "MIT" ]
Difegue/MpcNET
Sources/MpcNET.Test/MpdMock.cs
3,985
C#
using FirstRealize.App.WebRedirects.Core.Models.Redirects; using FirstRealize.App.WebRedirects.Core.Models.Urls; using System.Collections.Generic; namespace FirstRealize.App.WebRedirects.Core.Exporters { public class Rewrite { public string Id { get; set; } public string Key { get; set; } public string Name { get; set; } public RedirectType RedirectType { get; set; } public bool OldUrlHasRootPath { get; set; } public bool OldUrlHasHost { get; set; } public bool NewUrlHasHost { get; set; } public IParsedUrl OldUrl { get; set; } public IParsedUrl NewUrl { get; set; } public IList<Rewrite> RelatedRewrites { get; set; } public Rewrite() { RelatedRewrites = new List<Rewrite>(); } } }
33.68
60
0.617577
[ "MIT" ]
henrikstengaard/FirstRealize.App.WebRedirects
src/FirstRealize.App.WebRedirects.Core/Exporters/Rewrite.cs
844
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Au.Models.Common; using KeyPayV2.Au.Enums; namespace KeyPayV2.Au.Models.PayRun { public class AuDeductionModel { public string DeductionCategoryId { get; set; } public string DeductionCategoryName { get; set; } public decimal Amount { get; set; } public string Notes { get; set; } public string PaymentReference { get; set; } public string Note { get; set; } public string PayToBankAccountBSB { get; set; } public string PayToBankAccountNumber { get; set; } public string PayToSuperFundName { get; set; } public string PayToSuperFundMemberNumber { get; set; } public string PayTo { get; set; } public int? AdditionalData { get; set; } public int Id { get; set; } public string ExternalId { get; set; } public string LocationId { get; set; } public string LocationName { get; set; } public string EmployeeId { get; set; } public string EmployeeName { get; set; } public string EmployeeExternalId { get; set; } } }
37.59375
63
0.628429
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Au/Models/PayRun/AuDeductionModel.cs
1,203
C#
/* Copyright © 2021 by Biblica, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using Microsoft.VisualStudio.TestTools.UnitTesting; using PpmMain.LocalInstaller; using PpmMain.Models; using System.Collections.Generic; using System.IO; using System.IO.Compression; namespace PpmUnitTests { [TestClass()] public class LocalInstallerServiceTests { [TestMethod()] public void GetInstalledPluginsTest() { /// Set up data string name = "gipt"; string shortName1 = $"{name}1"; string shortName2 = $"{name}2"; string json1 = $@"{{'name': 'Get Installed Plugins Test 1','shortName': '{shortName1}','ptVersions': ['8','9']}}"; string json2 = $@"{{'name': 'Get Installed Plugins Test 1','shortName': '{shortName2}','ptVersions': ['8','9']}}"; string basePath = System.IO.Path.GetTempPath(); string testDirectoryPath = Path.Combine(basePath, name); string directoryPath1 = Path.Combine(testDirectoryPath, shortName1.ToUpper()); string directoryPath2 = Path.Combine(testDirectoryPath, shortName2.ToUpper()); /// Create assets if (!Directory.Exists(testDirectoryPath)) Directory.CreateDirectory(testDirectoryPath); if (!Directory.Exists(directoryPath1)) Directory.CreateDirectory(directoryPath1); File.WriteAllText(Path.Combine(directoryPath1, "file.json"), json1); if (!Directory.Exists(directoryPath2)) Directory.CreateDirectory(directoryPath2); File.WriteAllText(Path.Combine(directoryPath2, "file.json"), json2); // Assert expectations IInstallerService localInstaller = new LocalInstallerService(testDirectoryPath); List<PluginDescription> plugins = localInstaller.GetInstalledPlugins(); Assert.IsTrue(plugins.Exists(plugin => plugin.ShortName == shortName1)); Assert.IsTrue(plugins.Exists(plugin => plugin.ShortName == shortName2)); // Cleanup Directory.Delete(testDirectoryPath, true); } [TestMethod()] public void InstallPluginTest() { // Set up names and text string shortName = "ipt"; string json = $"{{'shortName': '{shortName}'}}"; string name = "installTest"; string text = $"{name} file text"; string directory = name; string filename = $"{name}.txt"; string archiveName = $"{name}.zip"; string jsonName = $"{name}.json"; /// Set up paths string basePath = System.IO.Path.GetTempPath(); string installedPath = Path.Combine(basePath, shortName.ToUpper()); string directoryPath = Path.Combine(basePath, directory); string filePath = Path.Combine(directoryPath, filename); string archivePath = Path.Combine(basePath, archiveName); string jsonPath = Path.Combine(basePath, jsonName); /// Delete the assets if they already exist if (File.Exists(filePath)) File.Delete(filePath); if (File.Exists(archivePath)) File.Delete(archivePath); if (File.Exists(jsonPath)) File.Delete(jsonPath); /// Create the test assets if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); File.WriteAllText(filePath, text); ZipFile.CreateFromDirectory(directoryPath, archivePath); File.WriteAllText(jsonPath, json); /// Run the installer IInstallerService localInstaller = new LocalInstallerService(basePath); localInstaller.InstallPlugin(new FileInfo(archivePath)); /// Assert expectations Assert.IsTrue(Directory.Exists(installedPath)); Assert.IsTrue(File.Exists(Path.Combine(installedPath, jsonName))); Assert.IsTrue(File.Exists(Path.Combine(installedPath, filename))); Assert.IsFalse(File.Exists(Path.Combine(basePath, jsonName))); Assert.IsFalse(File.Exists(Path.Combine(basePath, archiveName))); /// Cleanup Directory.Delete(installedPath, true); File.Delete(filePath); File.Delete(archivePath); } [TestMethod()] public void UninstallPluginTest() { /// Set up data PluginDescription plugin = new PluginDescription() { Name = "Uninstall Plugin Test", ShortName = "upt" }; string basePath = System.IO.Path.GetTempPath(); string directoryPath = Path.Combine(basePath, plugin.ShortName.ToUpper()); /// Create assets if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); File.WriteAllText(Path.Combine(directoryPath, "file.txt"), "text"); /// Run the uninstaller IInstallerService localInstaller = new LocalInstallerService(System.IO.Path.GetTempPath()); localInstaller.UninstallPlugin(plugin); /// Assert expectations Assert.IsFalse(Directory.Exists(directoryPath)); } } }
48.529851
461
0.622174
[ "MIT" ]
biblica/tools-paratext-plugin-manager
PpmUnitTests/LocalInstallerService/LocalInstallerServiceTests.cs
6,373
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Distributed; using Serilog; using Microsoft.IdentityModel.Clients.ActiveDirectory; using System.Security.Claims; using System.Threading.Tasks; namespace Microsoft.Azure.IIoT.OpcUa.Services.Vault.App.TokenStorage { public class DistributedTokenCacheService : TokenCacheService { private IHttpContextAccessor _contextAccessor; private IDataProtectionProvider _dataProtectionProvider; private IDistributedCache _distributedCache; /// <summary> /// Initializes a new instance of <see cref="Tailspin.Surveys.TokenStorage.DistributedTokenCacheService"/> /// </summary> /// <param name="contextAccessor">An instance of <see cref="Microsoft.AspNetCore.Http.IHttpContextAccessor"/> used to get access to the current HTTP context.</param> /// <param name="logger">A <see cref="Serilog.ILogger"/> instance.</param> /// <param name="dataProtectionProvider">An <see cref="Microsoft.AspNetCore.DataProtection.IDataProtectionProvider"/> for creating a data protector.</param> public DistributedTokenCacheService( IDistributedCache distributedCache, IHttpContextAccessor contextAccessor, ILogger logger, IDataProtectionProvider dataProtectionProvider) : base(logger) { _distributedCache = distributedCache; _contextAccessor = contextAccessor; _dataProtectionProvider = dataProtectionProvider; } /// <summary> /// Returns an instance of <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache"/>. /// </summary> /// <param name="claimsPrincipal">Current user's <see cref="System.Security.Claims.ClaimsPrincipal"/>.</param> /// <returns>An instance of <see cref="Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache"/>.</returns> public override Task<TokenCache> GetCacheAsync(ClaimsPrincipal claimsPrincipal) { if (_cache == null) { _cache = new DistributedTokenCache(claimsPrincipal, _distributedCache, _logger, _dataProtectionProvider); } return Task.FromResult(_cache); } } }
45.309091
173
0.700241
[ "MIT" ]
Azure/azure-iiot-opc-vault-service
app/TokenStorage/DistributedTokenCacheService.cs
2,492
C#