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
/* Copyright 2017 James Craig 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 Inflatable.Aspect.Interfaces; using Inflatable.Interfaces; using System; using System.Linq; using System.Reflection; using System.Text; namespace Inflatable.Aspect.StartMethod { /// <summary> /// Map start method /// </summary> /// <seealso cref="IStartMethodHelper"/> public class MapStartMethod : IStartMethodHelper { /// <summary> /// Sets up the specified method. /// </summary> /// <param name="method">The method.</param> /// <param name="mapping">The mapping.</param> /// <param name="builder">The builder.</param> public void Setup(MethodInfo method, IMapping mapping, StringBuilder builder) { if (mapping is null || builder is null) return; var Property = mapping.MapProperties.Find(x => x.Name == method.Name.Replace("set_", string.Empty, StringComparison.Ordinal)); if (Property is null) return; builder.Append(Property.InternalFieldName).AppendLine(" = value;") .Append(Property.InternalFieldName).AppendLine("Loaded = true;") .Append("NotifyPropertyChanged0(\"").Append(Property.Name).AppendLine("\");"); } } }
36.333333
139
0.647598
[ "Apache-2.0" ]
cjwang/Inflatable
src/Inflatable/Aspect/StartMethod/MapStartMethod.cs
1,855
C#
// Copyright 2007-2014 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.Tests { using System; using System.Threading.Tasks; using NUnit.Framework; using Shouldly; using TestFramework; using TestFramework.Messages; [TestFixture] public class Sending_a_message_to_a_queue : InMemoryTestFixture { [Test] public async Task Should_have_an_empty_fault_address() { ConsumeContext<PingMessage> ping = await _ping; ping.FaultAddress.ShouldBe(null); } [Test] public async Task Should_have_an_empty_response_address() { ConsumeContext<PingMessage> ping = await _ping; ping.ResponseAddress.ShouldBe(null); } [Test] public async Task Should_include_the_correlation_id() { ConsumeContext<PingMessage> ping = await _ping; ping.CorrelationId.ShouldBe(_correlationId); } [Test] public async Task Should_include_the_destination_address() { ConsumeContext<PingMessage> ping = await _ping; ping.DestinationAddress.ShouldBe(InputQueueAddress); } [Test] public async Task Should_include_the_header() { ConsumeContext<PingMessage> ping = await _ping; object header; ping.Headers.TryGetHeader("One", out header); header.ShouldBe("1"); } [Test] public async Task Should_include_the_source_address() { ConsumeContext<PingMessage> ping = await _ping; ping.SourceAddress.ShouldBe(BusAddress); } Task<ConsumeContext<PingMessage>> _ping; Guid _correlationId; [TestFixtureSetUp] public void Setup() { _correlationId = Guid.NewGuid(); InputQueueSendEndpoint.Send(new PingMessage(), Pipe.New<SendContext<PingMessage>>(x => x.UseExecute(context => { context.CorrelationId = _correlationId; context.Headers.Set("One", "1"); }))) .Wait(TestCancellationToken); } protected override void ConfigureInputQueueEndpoint(IReceiveEndpointConfigurator configurator) { _ping = Handled<PingMessage>(configurator); } } [TestFixture] public class Sending_a_request_to_a_queue : InMemoryTestFixture { [Test] public async Task Should_have_received_the_response_on_the_handler() { PongMessage message = await _response; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_have_the_matching_correlation_id() { ConsumeContext<PongMessage> context = await _responseHandler; context.Message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_include_the_destination_address() { ConsumeContext<PingMessage> ping = await _ping; ping.DestinationAddress.ShouldBe(InputQueueAddress); } [Test] public async Task Should_include_the_response_address() { ConsumeContext<PingMessage> ping = await _ping; ping.ResponseAddress.ShouldBe(BusAddress); } [Test] public async Task Should_include_the_source_address() { ConsumeContext<PingMessage> ping = await _ping; ping.SourceAddress.ShouldBe(BusAddress); } [Test] public async Task Should_receive_the_response() { ConsumeContext<PongMessage> context = await _responseHandler; context.ConversationId.ShouldBe(_conversationId); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Guid? _conversationId; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _conversationId = NewId.NextGuid(); _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { x.ConversationId = _conversationId; _response = x.Handle<PongMessage>(async context => { Console.WriteLine("Response received"); }); x.Timeout = TestTimeout; }); } protected override void ConfigureInputQueueEndpoint(IReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PongMessage(x.Message.CorrelationId))); } } [TestFixture] public class Sending_a_request_with_two_handlers : InMemoryTestFixture { [Test] public async Task Should_have_received_the_actual_response() { PingNotSupported message = await _notSupported; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } [Test] public async Task Should_not_complete_the_handler() { await _notSupported; await BusSendEndpoint.Send(new PongMessage((await _ping).Message.CorrelationId)); Assert.Throws<TaskCanceledException>(async () => { await _response; }); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Task<PingNotSupported> _notSupported; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { _response = x.Handle<PongMessage>(async _ => { }); _notSupported = x.Handle<PingNotSupported>(async _ => { }); }); } protected override void ConfigureInputQueueEndpoint(IReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PingNotSupported(x.Message.CorrelationId))); } } [TestFixture] public class Publishing_a_request: InMemoryTestFixture { [Test] public async Task Should_have_received_the_response_on_the_handler() { PongMessage message = await _response; message.CorrelationId.ShouldBe(_ping.Result.Message.CorrelationId); } Task<ConsumeContext<PingMessage>> _ping; Task<ConsumeContext<PongMessage>> _responseHandler; Task<Request<PingMessage>> _request; Task<PongMessage> _response; Task<PingNotSupported> _notSupported; [TestFixtureSetUp] public void Setup() { _responseHandler = SubscribeHandler<PongMessage>(); _request = Bus.PublishRequest(new PingMessage(), x => { _response = x.Handle<PongMessage>(async _ => { }); }); } protected override void ConfigureInputQueueEndpoint(IReceiveEndpointConfigurator configurator) { _ping = Handler<PingMessage>(configurator, async x => await x.RespondAsync(new PongMessage(x.Message.CorrelationId))); } } [TestFixture] public class Sending_a_request_with_no_handler : InMemoryTestFixture { [Test] public async Task Should_receive_a_request_timeout_exception_on_the_handler() { Assert.Throws<RequestTimeoutException>(async () => await _response); } [Test] public async Task Should_receive_a_request_timeout_exception_on_the_request() { Assert.Throws<RequestTimeoutException>(async () => { Request<PingMessage> request = await _request; await request.Task; }); } Task<Request<PingMessage>> _request; Task<PongMessage> _response; [TestFixtureSetUp] public void Setup() { _request = Bus.Request(InputQueueAddress, new PingMessage(), x => { x.Timeout = TimeSpan.FromSeconds(1); _response = x.Handle<PongMessage>(async _ => { }); }); } } }
31
136
0.58518
[ "Apache-2.0" ]
lsfera/MassTransit
src/MassTransit.Tests/MessageContext_Specs.cs
9,703
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "ConsumableItem", menuName = "Create Item/Item Type/Consumable", order = 0)] public class ConsumableType : ScriptableObject { public bool Cookable, Raw; public float GiveHealthAmount; public float GiveCaloriesAmount; public float GiveHydrationAmount; public void EatFood(float playerHealth, float playerCalories, float playerHydration) { playerHealth += GiveHealthAmount; playerCalories += GiveCaloriesAmount; playerHydration += GiveHydrationAmount; } }
29.380952
104
0.747164
[ "MIT" ]
ddark1990/FPS
Assets/Scripts/PlayerScripts/PlayerInventory/ItemScripts/ConsumableType.cs
619
C#
public enum ColorEnum { DEFAULT,RED,GREEN,YELLOW }
13.75
28
0.727273
[ "MIT" ]
NenoTech-Gaming/Push_Me_all
Assets/Projects/scripts/ColorEnum.cs
55
C#
using System; using ASTRA.EMSG.Business.Interlis.Parser.AutoGen; namespace ASTRA.EMSG.Business.Interlis.Parser { /// <summary> /// Description of AxisReaderDataHandler. /// </summary> public interface IAxisReaderDataHandler { void EmitXMLFragment(string xml); void ReceivedAxis(IImportedAchse axis); void ReceivedAxissegment(IImportedSegment axisSegment); void ReceivedSector(IImportedSektor axisSektor); void Finished(); } }
21.090909
57
0.74569
[ "BSD-3-Clause" ]
astra-emsg/ASTRA.EMSG
Master/ASTRA.EMSG.Business/Interlis/Parser/IAxisReaderDataHandler.cs
466
C#
using VGAudio.Codecs.Atrac9; using Xunit; namespace VGAudio.Tests.Formats.Atrac9 { public class PackedTableTests { [Fact] public void UnpackedSfWeightsIsCorrect() { Assert.Equal(UnpackedTables.SfWeights, Tables.ScaleFactorWeights); } [Fact] public void UnpackedBexMode0Bands3IsCorrect() { Assert.Equal(UnpackedTables.BexMode0Bands3, Tables.BexMode0Bands3); } [Fact] public void UnpackedBexMode0Bands4IsCorrect() { Assert.Equal(UnpackedTables.BexMode0Bands4, Tables.BexMode0Bands4); } [Fact] public void UnpackedBexMode0Bands5IsCorrect() { Assert.Equal(UnpackedTables.BexMode0Bands5, Tables.BexMode0Bands5); } [Fact] public void UnpackedBexMode2MultIsCorrect() { Assert.Equal(UnpackedTables.BexMode2Scale, Tables.BexMode2Scale); } [Fact] public void UnpackedBexMode3SeedIsCorrect() { Assert.Equal(UnpackedTables.BexMode3Initial, Tables.BexMode3Initial); } [Fact] public void UnpackedBexMode3MultIsCorrect() { Assert.Equal(UnpackedTables.BexMode3Rate, Tables.BexMode3Rate); } [Fact] public void UnpackedBexMode4MultIsCorrect() { Assert.Equal(UnpackedTables.BexMode4Multiplier, Tables.BexMode4Multiplier); } } }
26.982456
88
0.596229
[ "MIT" ]
ActualMandM/VGAudio
src/VGAudio.Tests/Formats/Atrac9/PackedTableTests.cs
1,484
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Management; using System.Diagnostics; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Devices.Bluetooth.Advertisement; using Windows.Storage.Streams; using System.Reflection; using System.Threading; using Microsoft.Win32; using System.IO; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using IWshRuntimeLibrary; using AutoUpdaterDotNET; using System.Runtime.Serialization; using System.Timers; using System.ServiceProcess; using File = System.IO.File; using System.Text; using Microsoft.Toolkit.Uwp.Notifications; using System.IO.Packaging; using NUnit.Framework; using System.Globalization; namespace BSManager { public enum MsgSeverity { INFO, WARNING, ERROR } public partial class Form1 : Form { readonly ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1)); static int bsCount = 0; static List<string> bsSerials = new List<string>(); static List<string> sbsSerials = new List<string>(); static List<string> pbsSerials = new List<string>(); static IEnumerable<JToken> bsTokens; // Current data format static DataFormat _dataFormat = DataFormat.Hex; static string _versionInfo; static TimeSpan _timeout = TimeSpan.FromSeconds(5); static string steamvr_lhjson; static string pimax_lhjson; static bool slhfound = false; static bool plhfound = false; private HashSet<Lighthouse> _lighthouses = new HashSet<Lighthouse>(); private BluetoothLEAdvertisementWatcher watcher; private ManagementEventWatcher insertWatcher; private ManagementEventWatcher removeWatcher; private int _delayCmd = 500; private const string v2_ON = "01"; private const string v2_OFF = "00"; private readonly Guid v2_powerGuid = Guid.Parse("00001523-1212-efde-1523-785feabcd124"); private readonly Guid v2_powerCharacteristic = Guid.Parse("00001525-1212-efde-1523-785feabcd124"); private const string v1_ON = "12 00 00 28 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00"; private const string v1_OFF = "12 01 00 28 FF FF FF FF 00 00 00 00 00 00 00 00 00 00 00 00"; private readonly Guid v1_powerGuid = Guid.Parse("0000cb00-0000-1000-8000-00805f9b34fb"); private readonly Guid v1_powerCharacteristic = Guid.Parse("0000cb01-0000-1000-8000-00805f9b34fb"); private int _V2DoubleCheckMin = 5; private bool V2BaseStations = false; private bool V2BaseStationsVive = false; public bool HeadSetState = false; private static int processingCmdSync = 0; private static int processingLHSync = 0; private int ProcessLHtimerCycle = 1000; public Thread thrUSBDiscovery; public Thread thrProcessLH; private DateTime LastCmdStamp; private LastCmd LastCmdSent; System.Timers.Timer ProcessLHtimer = new System.Timers.Timer(); private static TextWriterTraceListener traceEx = new TextWriterTraceListener("BSManager_exceptions.log", "BSManagerEx"); private static TextWriterTraceListener traceDbg = new TextWriterTraceListener("BSManager.log", "BSManagerDbg"); private readonly string fnKillList = "BSManager.kill.txt"; private readonly string fnGraceList = "BSManager.grace.txt"; private string[] kill_list = new string[] { }; private string[] graceful_list = new string[] { "vrmonitor", "vrdashboard", "ReviveOverlay", "vrmonitor" }; private string[] cleanup_pilist = new string[] { "pi_server", "piservice", "pitool" }; private static bool debugLog = false; private static bool ManageRuntime = false; private static string RuntimePath = ""; private static bool LastManage = false; private static bool ShowProgressToast = true; private static bool SetProgressToast = true; protected List<Windows.UI.Notifications.ToastNotification> ptoastNotificationList = new List<Windows.UI.Notifications.ToastNotification>(); [System.Runtime.InteropServices.DllImportAttribute("user32.dll")] public static extern bool PostMessage(IntPtr handleWnd, UInt32 Msg, Int32 wParam, UInt32 lParam); const int WM_QUERYENDSESSION = 0x0011, WM_ENDSESSION = 0x0016, WM_TRUE = 0x1, WM_FALSE = 0x0; [System.Runtime.InteropServices.DllImportAttribute("user32.dll", EntryPoint = "FindWindowEx")] public static extern int FindWindowEx(int hwndParent, int hwndEnfant, int lpClasse, string lpTitre); [System.Runtime.InteropServices.DllImportAttribute("user32.dll")] static extern int GetWindowThreadProcessId(IntPtr hWnd, out int processId); [System.Runtime.InteropServices.DllImportAttribute("user32.dll")] public static extern IntPtr FindWindowEx(IntPtr parentWindow, IntPtr previousChildWindow, string windowClass, string windowTitle); public Form1() { LogLine($"[BSMANAGER] FORM INIT "); InitializeComponent(); Application.ApplicationExit += delegate { notifyIcon1.Dispose(); }; } private void Form1_Load(object sender, EventArgs e) { try { Trace.AutoFlush = true; this.Hide(); var name = Assembly.GetExecutingAssembly().GetName(); _versionInfo = string.Format($"{name.Version.Major:0}.{name.Version.Minor:0}.{name.Version.Build:0}"); LogLine($"[BSMANAGER] STARTED "); LogLine($"[BSMANAGER] Version: {_versionInfo}"); FindRuntime(); using (RegistryKey registrySettingsCheck = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true)) { RegistryKey registrySettings; if (registrySettingsCheck == null) { registrySettings = Registry.CurrentUser.CreateSubKey ("SOFTWARE\\ManniX\\BSManager"); } registrySettings = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true); if (registrySettings.GetValue("DebugLog") == null) { toolStripDebugLog.Checked = false; debugLog = false; LogLine($"[BSMANAGER] Debug Log disabled"); } else { toolStripDebugLog.Checked = true; debugLog = true; LogLine($"[BSMANAGER] Debug Log enabled"); } if (registrySettings.GetValue("ManageRuntime") == null) { RuntimeToolStripMenuItem.Checked = false; ManageRuntime = false; LogLine($"[BSMANAGER] Manage Runtime disabled"); } else { RuntimeToolStripMenuItem.Checked = true; ManageRuntime = true; LogLine($"[BSMANAGER] Manage Runtime enabled"); } if (registrySettings.GetValue("ShowProgressToast") == null) { disableProgressToastToolStripMenuItem.Checked = true; SetProgressToast = false; ShowProgressToast = false; LogLine($"[BSMANAGER] Progress Toast disabled"); } else { disableProgressToastToolStripMenuItem.Checked = false; SetProgressToast = true; ShowProgressToast = true; LogLine($"[BSMANAGER] Progress Toast enabled"); } } AutoUpdater.ReportErrors = false; AutoUpdater.InstalledVersion = new Version(_versionInfo); AutoUpdater.DownloadPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); AutoUpdater.RunUpdateAsAdmin = false; AutoUpdater.Synchronous = true; AutoUpdater.ParseUpdateInfoEvent += AutoUpdaterOnParseUpdateInfoEvent; AutoUpdater.Start("https://raw.githubusercontent.com/mann1x/BSManager/master/BSManager/AutoUpdaterBSManager.json"); bSManagerVersionToolStripMenuItem.Text = "BSManager Version " + _versionInfo; using (RegistryKey registryStart = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { string _curpath = registryStart.GetValue("BSManager").ToString(); if (_curpath == null) { toolStripRunAtStartup.Checked = false; } else { if (_curpath != MyExecutableWithPath) registryStart.SetValue("BSManager", MyExecutableWithPath); toolStripRunAtStartup.Checked = true; } } string [] _glist = null; string [] _klist = null; _glist = ProcListLoad(fnGraceList, "graceful"); _klist = ProcListLoad(fnKillList, "immediate"); if (_glist != null) graceful_list = _glist; if (_klist != null) kill_list = _klist; _glist = null; _klist = null; slhfound = Read_SteamVR_config(); if (!slhfound) { SteamVR_DB_ToolStripMenuItem.Text = "SteamVR DB not found in registry"; } else { slhfound = Load_LH_DB("SteamVR" ); if (!slhfound) { SteamVR_DB_ToolStripMenuItem.Text = "SteamVR DB file parse error"; } else { SteamVR_DB_ToolStripMenuItem.Text = "Serials:"; foreach (string bs in sbsSerials) { SteamVR_LH_ToolStripMenuItem.DropDownItems.Add(bs); } } } plhfound = Read_Pimax_config(); if (!plhfound) { Pimax_DB_ToolStripMenuItem.Text = "Pimax DB not found"; } else { plhfound = Load_LH_DB("Pimax"); if (!plhfound) { Pimax_DB_ToolStripMenuItem.Text = "Pimax DB file parse error"; } else { Pimax_DB_ToolStripMenuItem.Text = "Serials:"; foreach (string bs in pbsSerials) { Pimax_LH_ToolStripMenuItem.DropDownItems.Add(bs); } } } WqlEventQuery insertQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); insertWatcher = new ManagementEventWatcher(insertQuery); insertWatcher.EventArrived += new EventArrivedEventHandler(DeviceInsertedEvent); insertWatcher.Start(); WqlEventQuery removeQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'"); removeWatcher = new ManagementEventWatcher(removeQuery); removeWatcher.EventArrived += new EventArrivedEventHandler(DeviceRemovedEvent); removeWatcher.Start(); watcher = new BluetoothLEAdvertisementWatcher(); watcher.Received += AdvertisementWatcher_Received; thrUSBDiscovery = new Thread(RunUSBDiscovery); thrUSBDiscovery.Start(); thrProcessLH = new Thread(RunProcessLH); while (true) { if (!thrUSBDiscovery.IsAlive) { LogLine("[LightHouse] Starting LightHouse Thread"); thrProcessLH.Start(); break; } } const string scheme = "pack"; if (!UriParser.IsKnownScheme(scheme)) { Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme)); } // Listen to notification activation ToastNotificationManagerCompat.OnActivated += toastArgs => { // Obtain the arguments from the notification ToastArguments args = ToastArguments.Parse(toastArgs.Argument); // Clear the Toast Progress List if (args["conversationId"] == "9113") ptoastNotificationList.Clear(); }; } catch (Exception ex) { HandleEx(ex); } } private void HandleEx(Exception ex) { try { string _msg = ex.Message; if (ex.Source != string.Empty && ex.Source != null) _msg = $"{_msg} Source: {ex.Source}"; new ToastContentBuilder() .AddHeader("6789", "Exception raised", "") .AddText(_msg) .AddText(ex.StackTrace) .Show(toast => { toast.ExpirationTime = DateTime.Now.AddSeconds(360); }); LogLine($"{ex}"); traceEx.WriteLine($"[{DateTime.Now}] {ex}"); traceEx.Flush(); } catch (Exception e) { LogLine($"[HANDLEEX] Exception: {e}"); } } public static void LogLine(string msg) { Trace.WriteLine($"{msg}"); if (debugLog) { traceDbg.WriteLine($"[{DateTime.Now}] {msg}"); traceDbg.Flush(); } } public void BalloonMsg(string msg, string header = "BSManager") { try { new ToastContentBuilder() .AddText(header) .AddText(msg) .Show(toast => { toast.ExpirationTime = DateTime.Now.AddSeconds(120); }); Trace.WriteLine($"{msg}"); if (debugLog) { traceDbg.WriteLine($"[{DateTime.Now}] {msg}"); traceDbg.Flush(); } } catch (Exception e) { LogLine($"[BALLOONMSG] Exception: {e}"); } } private void timerManageRuntime() { Task.Delay(TimeSpan.FromMilliseconds(15000)) .ContinueWith(task => doManageRuntime()); } private IntPtr[] GetProcessWindows(int process) { IntPtr[] apRet = (new IntPtr[256]); int iCount = 0; IntPtr pLast = IntPtr.Zero; do { pLast = FindWindowEx(IntPtr.Zero, pLast, null, null); int iProcess_; GetWindowThreadProcessId(pLast, out iProcess_); if (iProcess_ == process) apRet[iCount++] = pLast; } while (pLast != IntPtr.Zero); System.Array.Resize(ref apRet, iCount); return apRet; } private void doManageRuntime() { try { void _pKill(Process _p2kill) { try { _p2kill.Kill(); } catch (InvalidOperationException) { LogLine($"[Manage Runtime] {_p2kill.ProcessName} has probably already exited"); } catch (AggregateException) { LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: not all processes in the tree can be killed"); } catch (NotSupportedException) { LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: operation not supported"); } catch (Win32Exception) { LogLine($"[Manage Runtime] {_p2kill.ProcessName} can't be killed: not enogh privileges or already exiting"); } } void _pClose(Process _p2close) { try { _p2close.CloseMainWindow(); } catch (InvalidOperationException) { string ProcessName = _p2close.ProcessName; LogLine($"[Manage Runtime] {ProcessName} has probably already exited"); } } void loopKill(string[] procnames, bool graceful) { foreach (string procname in procnames) { Process[] ProcsArray = Process.GetProcessesByName(procname); if (ProcsArray.Count() > 0) { foreach (Process Proc2Kill in ProcsArray) { string ProcessName = Proc2Kill.ProcessName; LogLine($"[Manage Runtime] Closing {ProcessName} with PID={Proc2Kill.Id}"); if (graceful) { _pClose(Proc2Kill); } else { _pKill(Proc2Kill); } for (int i = 0; i < 20; i++) { if (!Proc2Kill.HasExited) { Thread.Sleep(250); Proc2Kill.Refresh(); Thread.Sleep(250); } else { break; } } if (!Proc2Kill.HasExited) { _pKill(Proc2Kill); Thread.Sleep(250); Proc2Kill.Refresh(); Thread.Sleep(250); if (!Proc2Kill.HasExited) { IntPtr[] wnd = GetProcessWindows(Int32.Parse((Proc2Kill.Id).ToString())); var wm_ret = PostMessage(wnd[0], WM_ENDSESSION, WM_TRUE, 0x80000000); Thread.Sleep(1000); if (!Proc2Kill.HasExited) { LogLine($"[Manage Runtime] {ProcessName} can't be killed, still running"); } } else { LogLine($"[Manage Runtime] {ProcessName} killed"); Proc2Kill.Close(); Proc2Kill.Dispose(); } } else { LogLine($"[Manage Runtime] {ProcessName} killed"); Proc2Kill.Close(); Proc2Kill.Dispose(); } } } else { LogLine($"[Manage Runtime] {procname} can't be killed: not found"); } ProcsArray = null; } } if (ManageRuntime) { if (!HeadSetState && LastManage) { #if DEBUG Process[] localAll = Process.GetProcesses(); foreach (Process processo in localAll) { LogLine($"[PROCESSES] Active: {processo.ProcessName} PID={processo.Id}"); } #endif ServiceController sc = new ServiceController("PiServiceLauncher"); LogLine($"[Manage Runtime] PiService is currently: {sc.Status}"); if ((sc.Status.Equals(ServiceControllerStatus.Running)) || (sc.Status.Equals(ServiceControllerStatus.StartPending))) { LogLine($"[Manage Runtime] Stopping PiService"); sc.Stop(); sc.Refresh(); LogLine($"[Manage Runtime] PiService is now: {sc.Status}"); } loopKill(cleanup_pilist, false); if (graceful_list.Length > 0) loopKill(graceful_list, true); if (kill_list.Length > 0) loopKill(kill_list, false); LastManage = false; } else if (HeadSetState && !LastManage) { Process[] PiToolArray = Process.GetProcessesByName("Pitool"); LogLine($"[Manage Runtime] Found {PiToolArray.Count()} PiTool running"); if (PiToolArray.Count() == 0) { ProcessStartInfo startInfo = new ProcessStartInfo(RuntimePath + "\\Pitool.exe", "hide"); startInfo.WindowStyle = ProcessWindowStyle.Minimized; Process PiTool = Process.Start(startInfo); LogLine($"[Manage Runtime] Started PiTool ({RuntimePath + "\\Pitool.exe"}) with PID={PiTool.Id}"); } LastManage = true; } } } catch (Exception e) when (e is Win32Exception || e is FileNotFoundException) { LogLine($"[Manage Runtime] The following exception was raised: {e}"); } } private void USBDiscovery() { try { ManagementObjectCollection collection; using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) collection = searcher.Get(); foreach (var device in collection) { string did = (string)device.GetPropertyValue("DeviceID"); LogLine($"[USB Discovery] DID={did}"); CheckHMDOn(did); } collection.Dispose(); return; } catch (Exception ex) { HandleEx(ex); } } private void CheckHMDOn(string did) { try { string _hmd = ""; string action = "ON"; if (did.Contains("VID_0483&PID_0101")) _hmd = "PIMAX HMD"; if (did.Contains("VID_2996&PID_0309")) _hmd = "VIVE PRO HMD"; if (_hmd.Length > 0) { if (SetProgressToast) ShowProgressToast = true; LogLine($"[HMD] ## {_hmd} {action} "); ChangeHMDStrip($" {_hmd} {action} ", true); this.notifyIcon1.Icon = BSManagerRes.bsmanager_on; HeadSetState = true; Task.Delay(TimeSpan.FromMilliseconds(5000)) .ContinueWith(task => checkLHState(lh => !lh.PoweredOn, true)); LogLine($"[HMD] Runtime {action}: ManageRuntime is {ManageRuntime}"); timerManageRuntime(); } } catch (Exception ex) { HandleEx(ex); } } private void checkLHState(Func<Lighthouse, bool> lighthousePredicate, bool hs_state) { if (HeadSetState == hs_state) { var results = _lighthouses.Where(lighthousePredicate); if (results.Any()) { foreach (Lighthouse lh in _lighthouses) { lh.ProcessDone = false; } } } } private void CheckHMDOff(string did) { try { string _hmd = ""; string action = "OFF"; if (did.Contains("VID_0483&PID_0101")) _hmd = "PIMAX HMD"; if (did.Contains("VID_2996&PID_0309")) _hmd = "VIVE PRO HMD"; if (_hmd.Length > 0) { if (SetProgressToast) ShowProgressToast = true; LogLine($"[HMD] ## {_hmd} {action} "); ChangeHMDStrip($" {_hmd} {action} ", false); this.notifyIcon1.Icon = BSManagerRes.bsmanager_off; HeadSetState = false; Task.Delay(TimeSpan.FromMilliseconds(5000)) .ContinueWith(task => checkLHState(lh => lh.PoweredOn, false)); LogLine($"[HMD] Runtime {action}: ManageRuntime is {ManageRuntime}"); timerManageRuntime(); } } catch (Exception ex) { HandleEx(ex); } } private void DeviceInsertedEvent(object sender, EventArrivedEventArgs e) { try { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { if (property.Name == "PNPDeviceID") { CheckHMDOn(property.Value.ToString()); } //LogLine($" INSERTED " + property.Name + " = " + property.Value); } e.NewEvent.Dispose(); } catch (Exception ex) { HandleEx(ex); } } private void DeviceRemovedEvent(object sender, EventArrivedEventArgs e) { try { ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"]; foreach (var property in instance.Properties) { if (property.Name == "PNPDeviceID") { CheckHMDOff(property.Value.ToString()); } //LogLine($" REMOVED " + property.Name + " = " + property.Value); } e.NewEvent.Dispose(); } catch (Exception ex) { HandleEx(ex); } } private void ProcessLH_ElapsedEventHandler(object sender, ElapsedEventArgs e) { int sync = Interlocked.CompareExchange(ref processingLHSync, 1, 0); if (sync == 0) { OnProcessLH(sender, e); processingLHSync = 0; } } public void ProcessWatcher(bool start) { if (start) { if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Stopped || watcher.Status == BluetoothLEAdvertisementWatcherStatus.Created) { ptoastNotificationList.Clear(); LogLine($"[LightHouse] Starting BLE Watcher Status: {watcher.Status}"); watcher.Start(); Thread.Sleep(250); LogLine($"[LightHouse] Started BLE Watcher Status: {watcher.Status}"); } } else { if (watcher.Status == BluetoothLEAdvertisementWatcherStatus.Started && watcher.Status != BluetoothLEAdvertisementWatcherStatus.Stopping) { LogLine($"[LightHouse] Stopping BLE Watcher Status: {watcher.Status}"); watcher.Stop(); Thread.Sleep(250); LogLine($"[LightHouse] Stopped BLE Watcher Status: {watcher.Status}"); ptoastNotificationList.Clear(); } } } public void OnProcessLH(object sender, ElapsedEventArgs args) { try { bool _done = true; if (V2BaseStationsVive && LastCmdSent == LastCmd.SLEEP && !HeadSetState) { TimeSpan _delta = DateTime.Now - LastCmdStamp; //LogLine($"LastCmdSent {LastCmdSent} _delta {_delta}"); if (_delta.Minutes >= _V2DoubleCheckMin) { ShowProgressToast = false; foreach (Lighthouse lh in _lighthouses) { lh.ProcessDone = false; } } } foreach (Lighthouse _lh in _lighthouses) { if (_lh.ProcessDone == false) _done = false; } if (_lighthouses.Count == 0 || _lighthouses.Count < bsCount) { ProcessWatcher(true); } else if (_done) { ProcessWatcher(false); } else { ProcessWatcher(true); } Thread.Sleep(ProcessLHtimerCycle); } catch (Exception ex) { HandleEx(ex); } } void RunUSBDiscovery() { USBDiscovery(); } void RunProcessLH() { ProcessLHtimer.Interval = ProcessLHtimerCycle; ProcessLHtimer.Elapsed += new ElapsedEventHandler(ProcessLH_ElapsedEventHandler); ProcessLHtimer.Start(); } private void AutoUpdaterOnParseUpdateInfoEvent(ParseUpdateInfoEventArgs args) { dynamic json = JsonConvert.DeserializeObject(args.RemoteData); args.UpdateInfo = new UpdateInfoEventArgs { CurrentVersion = json.version, ChangelogURL = json.changelog, DownloadURL = json.url, Mandatory = new Mandatory { Value = json.mandatory.value, UpdateMode = json.mandatory.mode, MinimumVersion = json.mandatory.minVersion }, CheckSum = new CheckSum { Value = json.checksum.value, HashingAlgorithm = json.checksum.hashingAlgorithm } }; } private void ChangeHMDStrip(string label, bool _checked) { try { BeginInvoke((MethodInvoker)delegate { ToolStripMenuItemHmd.Text = label; ToolStripMenuItemHmd.Checked = _checked; }); } catch (Exception ex) { HandleEx(ex); } } private void ChangeDiscoMsg(string count, string nameBS) { try { BeginInvoke((MethodInvoker)delegate { ToolStripMenuItemDisco.Text = $"Discovered: {count}/{bsCount}"; toolStripMenuItemBS.DropDownItems.Add(nameBS); }); } catch (Exception ex) { HandleEx(ex); } } private void ChangeBSMsg(string _name, bool _poweredOn, LastCmd _lastCmd, Action _action) { try { string _cmdStatus = ""; string _actionStatus = ""; switch (_lastCmd) { case LastCmd.ERROR: _cmdStatus = "[ERROR] "; break; default: _cmdStatus = ""; break; } switch (_action) { case Action.WAKEUP: _actionStatus = " - Going to Wakeup"; break; case Action.SLEEP: _actionStatus = " - Going to Standby"; break; default: _actionStatus = ""; break; } BeginInvoke((MethodInvoker)delegate { foreach (ToolStripMenuItem item in toolStripMenuItemBS.DropDownItems) { if (item.Text.StartsWith(_name)) { if (_poweredOn) item.Image = BSManagerRes.bsmanager_on.ToBitmap(); if (!_poweredOn) item.Image = null; item.Text = $"{_name} {_cmdStatus}{_actionStatus}"; } } }); } catch (Exception ex) { HandleEx(ex); } } private bool Read_SteamVR_config() { try { steamvr_lhjson = string.Empty; using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\WOW6432Node\\Valve\\Steam")) { if (key != null) { Object o = key.GetValue("InstallPath"); if (o != null) { steamvr_lhjson = o.ToString() + "\\config\\lighthouse\\lighthousedb.json"; if (File.Exists(steamvr_lhjson)) { LogLine($"[CONFIG] Found SteamVR LH DB at Path={steamvr_lhjson}"); return true; } else { LogLine($"[CONFIG] Not found SteamVR LH DB at Path={steamvr_lhjson}"); return false; } } } return false; } } catch (Exception ex) { HandleEx(ex); return false; } } private bool Read_Pimax_config() { try { pimax_lhjson = string.Empty; string ProgramDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); pimax_lhjson = ProgramDataFolder + "\\pimax\\runtime\\config\\lighthouse\\lighthousedb.json"; if (File.Exists(pimax_lhjson)) { LogLine($"[CONFIG] Found Pimax LH DB at Path={pimax_lhjson}"); return true; } else { LogLine($"[CONFIG] Not found Pimax LH DB at Path={pimax_lhjson}"); return false; } } catch (Exception ex) { HandleEx(ex); return false; } } private bool Load_LH_DB(string db_name) { try { string _lhjson = string.Empty; if (db_name == "Pimax") { _lhjson = pimax_lhjson; } else { _lhjson = steamvr_lhjson; } using (StreamReader r = new StreamReader(_lhjson)) { string json = r.ReadToEnd(); LogLine($"[CONFIG] SteamDB JSON Length={json.Length}"); JObject o = JObject.Parse(json); LogLine($"[CONFIG] SteamDB JSON Parsed"); bsTokens = o.SelectTokens("$..base_serial_number"); int _maxbs = 6; int _curbs = 1; int _bsCount = 0; foreach (JToken bsitem in bsTokens) { if (!bsSerials.Contains(bsitem.ToString())) bsSerials.Add(bsitem.ToString()); if (db_name == "Pimax") { if (!pbsSerials.Contains(bsitem.ToString())) pbsSerials.Add(bsitem.ToString()); _bsCount = pbsSerials.Count; } else { if (!sbsSerials.Contains(bsitem.ToString())) sbsSerials.Add(bsitem.ToString()); _bsCount = sbsSerials.Count; } LogLine($"[CONFIG] {db_name} DB Base Station Serial={bsitem}"); _curbs++; if (_curbs > _maxbs) break; } LogLine($"[CONFIG] {db_name} DB Base Stations List=" + string.Join(", ", bsSerials)); bsCount = bsSerials.Count(); LogLine($"[CONFIG] {db_name} DB Base Stations count: {_bsCount}"); return true; } } catch (Exception ex) { HandleEx(ex); return false; } } private void AdvertisementWatcher_Received(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args) { try { //Trace.WriteLine($"Advertisment: {args.Advertisement.LocalName}"); if (!args.Advertisement.LocalName.StartsWith("LHB-") && !args.Advertisement.LocalName.StartsWith("HTC BS ")) { return; } //Trace.WriteLine($"Advertisment: {args.Advertisement.LocalName}"); var existing = _lighthouses.SingleOrDefault(lh => lh.Address == args.BluetoothAddress); if (existing == null) { LogLine($"[LightHouse] Found lighthouse {args.Advertisement.LocalName}"); existing = new Lighthouse(args.Advertisement.LocalName, args.BluetoothAddress); _lighthouses.Add(existing); ChangeDiscoMsg(_lighthouses.Count.ToString(), existing.Name); } int intpstate = 0; if (args.Advertisement.LocalName.StartsWith("LHB-")) { var valveData = args.Advertisement.GetManufacturerDataByCompanyId(0x055D); var htcData = args.Advertisement.GetManufacturerDataByCompanyId(0x02ED); if (valveData.Count > 0) { existing.Manufacturer = BSManufacturer.VIVE; var valveDataSingle = valveData.Single(); var data = new byte[valveDataSingle.Data.Length]; using (var reader = DataReader.FromBuffer(valveDataSingle.Data)) { reader.ReadBytes(data); } if (!string.IsNullOrEmpty(data[4].ToString())) { intpstate = Int32.Parse(data[4].ToString()); existing.V2PoweredOn = intpstate > 0; //existing.PoweredOn = data[4] == 0x03; //LogLine($"{existing.Name} power status {intpstate} last {existing.lastPowerState} PoweredOn={existing.PoweredOn}"); } V2BaseStationsVive = true; } else if (htcData.Count > 0) { var htcDataSingle = htcData.Single(); var data = new byte[htcDataSingle.Data.Length]; using (var reader = DataReader.FromBuffer(htcDataSingle.Data)) { reader.ReadBytes(data); } if (!string.IsNullOrEmpty(data[4].ToString())) { intpstate = Int32.Parse(data[4].ToString()); existing.V2PoweredOn = intpstate > 0; //existing.PoweredOn = data[4] == 0x03; //LogLine($"{existing.Name} power status {intpstate} last {existing.lastPowerState} PoweredOn={existing.PoweredOn}"); } } V2BaseStations = true; existing.V2 = true; if (existing.V2PoweredOn && existing.LastCmd == LastCmd.SLEEP && !HeadSetState && existing.Manufacturer == BSManufacturer.VIVE) { TimeSpan _delta = DateTime.Now - existing.LastCmdStamp; if (_delta.Minutes >= _V2DoubleCheckMin) { if (0 == Interlocked.Exchange(ref processingCmdSync, 1)) { ShowProgressToast = false; LogLine($"[LightHouse] Processing SLEEP check {_V2DoubleCheckMin} minutes still ON for: {existing.Name}"); ProcessLighthouseAsync(existing, "SLEEP"); existing.ProcessDone = true; } } else { existing.ProcessDone = true; } } } else { existing.V2 = false; } if (HeadSetState) { if (existing.V2 && (existing.LastCmd == LastCmd.NONE) && existing.PoweredOn) { ChangeBSMsg(existing.Name, true, LastCmd.WAKEUP, Action.NONE); return; } if (existing.LastCmd != LastCmd.WAKEUP) { if (0 == Interlocked.Exchange(ref processingCmdSync, 1)) { ProcessLighthouseAsync(existing, "WAKEUP"); } } } else { if (existing.V2 && (existing.LastCmd == LastCmd.NONE) && !existing.PoweredOn) { ChangeBSMsg(existing.Name, false, LastCmd.SLEEP, Action.NONE); return; } if (existing.LastCmd != LastCmd.SLEEP) { if (0 == Interlocked.Exchange(ref processingCmdSync, 1)) { ProcessLighthouseAsync(existing, "SLEEP"); } } } Thread.Sleep(100); } catch (Exception ex) { HandleEx(ex); } } private void ProcessLighthouseAsync(Lighthouse lh, string command) { try { void exitProcess(string msg) { throw new ProcessError($"{msg}"); } var progressdec = CultureInfo.InvariantCulture.Clone() as CultureInfo; progressdec.NumberFormat.NumberDecimalSeparator = "."; string _toastAction = (command == "WAKEUP") ? "Waking up" : "Set to sleep"; uint pidx = 1; string ptag = "LHProcess"; string pgroup = "LHProcess"; int _leftDone = 0; foreach (Lighthouse lhDone in _lighthouses) { if (lhDone.ProcessDone) _leftDone++; } lh.OpsTotal++; int _doneCount=_leftDone+1; var pcontent = new ToastContentBuilder() .AddArgument("action", "viewConversation") .AddArgument("conversationId", 9113) .AddText("Commandeering the Base Stations...") .AddAudio(null,null,true) .AddVisualChild(new AdaptiveProgressBar() { Title = new BindableString("title"), Value = new BindableProgressBarValue("progressValue"), ValueStringOverride = new BindableString("pregressCount"), Status = new BindableString("progressStatus") }).GetToastContent(); int eRate = (int)Math.Round((double)(100 * lh.ErrorTotal) / lh.OpsTotal); bool showeRate = (eRate > 10) ? true : false; string bsmanuf = ""; if (V2BaseStations) bsmanuf = (lh.Manufacturer == BSManufacturer.HTC) ? " (by HTC)" : " (by VIVE)"; var ptoast = new Windows.UI.Notifications.ToastNotification(pcontent.GetXml()); if (ptoastNotificationList.Count == 0) { ptoast.Tag = ptag; ptoast.Group = pgroup; ptoast.Data = new Windows.UI.Notifications.NotificationData(); ptoast.Data.Values["title"] = $"BS {lh.Name}{bsmanuf}"; ptoast.Data.Values["progressValue"] = "0"; ptoast.Data.Values["pregressCount"] = $"{_doneCount}/{bsCount}"; ptoast.Data.Values["progressStatus"] = $"{_toastAction}... (0%)"; ptoast.Data.SequenceNumber = pidx; ptoast.ExpirationTime = DateTime.Now.AddSeconds(120); ptoastNotificationList.Add(ptoast); if (ShowProgressToast) ToastNotificationManagerCompat.CreateToastNotifier().Show(ptoast); } else { ptoast = ptoastNotificationList[0]; var initdata = new Windows.UI.Notifications.NotificationData { SequenceNumber = pidx++ }; initdata.Values["title"] = $"BS {lh.Name}{bsmanuf}"; initdata.Values["progressValue"] = $"0"; initdata.Values["pregressCount"] = $"{_doneCount}/{bsCount}"; initdata.Values["progressStatus"] = $"{_toastAction}... (0%)"; if (ShowProgressToast) ToastNotificationManagerCompat.CreateToastNotifier().Update(initdata, ptag, pgroup); } void updateProgress(double percentage, string _msg = "Commandeering") { string _ptag = "LHProcess"; string _pgroup = "LHProcess"; var data = new Windows.UI.Notifications.NotificationData { SequenceNumber = pidx++ }; double _p = percentage / 100; string _status = $"{_toastAction}... ({percentage}%)"; if (showeRate) _status += $" [Errors {eRate}%]"; data.Values["title"] = $"BS {lh.Name}{bsmanuf}"; data.Values["progressValue"] = $"{_p.ToString(progressdec)}"; data.Values["pregressCount"] = $"{_doneCount}/{bsCount}"; data.Values["progressStatus"] = _status; if (ShowProgressToast) ToastNotificationManagerCompat.CreateToastNotifier().Update(data, _ptag, _pgroup); } LogLine($"[{lh.Name}] START Processing command: {command}"); lh.Action = (command == "WAKEUP") ? Action.WAKEUP : Action.SLEEP; ChangeBSMsg(lh.Name, lh.PoweredOn, lh.LastCmd, lh.Action); Guid _powerServGuid = v1_powerGuid; Guid _powerCharGuid = v1_powerCharacteristic; if (lh.V2) { _powerServGuid = v2_powerGuid; _powerCharGuid = v2_powerCharacteristic; } //https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-client var potentialLighthouseTask = BluetoothLEDevice.FromBluetoothAddressAsync(lh.Address).AsTask(); potentialLighthouseTask.Wait(); if (ShowProgressToast) updateProgress(10); Thread.Sleep(_delayCmd); if (!potentialLighthouseTask.IsCompletedSuccessfully || potentialLighthouseTask.Result == null) exitProcess($"Could not connect to lighthouse"); using var btDevice = potentialLighthouseTask.Result; if (ShowProgressToast) updateProgress(20); Thread.Sleep(_delayCmd); var gattServicesTask = btDevice.GetGattServicesAsync(BluetoothCacheMode.Uncached).AsTask(); gattServicesTask.Wait(); if (ShowProgressToast) updateProgress(30); Thread.Sleep(_delayCmd); if (!gattServicesTask.IsCompletedSuccessfully || gattServicesTask.Result.Status != GattCommunicationStatus.Success) exitProcess($"Failed to get services"); LogLine($"[{lh.Name}] Got services: {gattServicesTask.Result.Services.Count}"); foreach (var _serv in gattServicesTask.Result.Services.ToArray()) { LogLine($"[{lh.Name}] Service Attr: {_serv.AttributeHandle} Uuid: {_serv.Uuid}"); } using var service = gattServicesTask.Result.Services.SingleOrDefault(s => s.Uuid == _powerServGuid); if (ShowProgressToast) updateProgress(40); Thread.Sleep(_delayCmd); if (service == null) exitProcess($"Could not find power service"); LogLine($"[{lh.Name}] Found power service"); var powerCharacteristicsTask = service.GetCharacteristicsAsync(BluetoothCacheMode.Uncached).AsTask(); powerCharacteristicsTask.Wait(); if (ShowProgressToast) updateProgress(50); Thread.Sleep(_delayCmd); if (!powerCharacteristicsTask.IsCompletedSuccessfully || powerCharacteristicsTask.Result.Status != GattCommunicationStatus.Success) exitProcess($"Could not get power service characteristics"); var powerChar = powerCharacteristicsTask.Result.Characteristics.SingleOrDefault(c => c.Uuid == _powerCharGuid); if (ShowProgressToast) updateProgress(60); Thread.Sleep(_delayCmd); if (powerChar == null) exitProcess($"Could not get power characteristic"); if (ShowProgressToast) updateProgress(70); Thread.Sleep(_delayCmd); LogLine($"[{lh.Name}] Found power characteristic"); if (ShowProgressToast) updateProgress(80); string data = v1_OFF; if (command == "WAKEUP") data = v1_ON; if (lh.V2) { data = v2_OFF; if (command == "WAKEUP") data = v2_ON; } string[] values = data.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); byte[] bytes = new byte[values.Length]; for (int i = 0; i < values.Length; i++) bytes[i] = Convert.ToByte(values[i], (_dataFormat == DataFormat.Dec ? 10 : (_dataFormat == DataFormat.Hex ? 16 : 2))); var writer = new DataWriter(); writer.ByteOrder = ByteOrder.LittleEndian; writer.WriteBytes(bytes); var buff = writer.DetachBuffer(); LogLine($"[{lh.Name}] Sending {command} command to {lh.Name}"); var writeResultTask = powerChar.WriteValueAsync(buff).AsTask(); writeResultTask.Wait(); if (ShowProgressToast) updateProgress(95); Thread.Sleep(_delayCmd); if (!writeResultTask.IsCompletedSuccessfully || writeResultTask.Result != GattCommunicationStatus.Success) exitProcess($"Failed to write {command} command"); lh.LastCmd = (command == "WAKEUP") ? LastCmd.WAKEUP : LastCmd.SLEEP; lh.PoweredOn = (command == "WAKEUP") ? true : false; btDevice.Dispose(); LogLine($"[{lh.Name}] SUCCESS command {command}"); if (ShowProgressToast) updateProgress(100, "Command received!"); Thread.Sleep(_delayCmd); LastCmdSent = lh.LastCmd; LastCmdStamp = DateTime.Now; lh.Action = Action.NONE; lh.ProcessDone = true; ChangeBSMsg(lh.Name, lh.PoweredOn, lh.LastCmd, lh.Action); lh.TooManyErrors = true; Interlocked.Exchange(ref processingCmdSync, 0); LogLine($"[{lh.Name}] END Processing"); } catch (ProcessError ex) { LogLine($"[{lh.Name}] ERROR Processing ({lh.HowManyErrors}): {ex}"); lh.ErrorStrings = lh.ErrorStrings.Insert(0, $"{ex.Message}\n"); if (lh.TooManyErrors) BalloonMsg($"{lh.ErrorStrings}", $"[{lh.Name}] LAST ERRORS:"); lh.LastCmd = LastCmd.ERROR; ChangeBSMsg(lh.Name, lh.PoweredOn, lh.LastCmd, lh.Action); Interlocked.Exchange(ref processingCmdSync, 0); } catch (Exception ex) { LogLine($"[{lh.Name}] ERROR Exception Processing ({lh.HowManyErrors}): {ex}"); lh.LastCmd = LastCmd.ERROR; lh.ErrorStrings = lh.ErrorStrings.Insert(0, $"{ex.Message}\n"); if (lh.TooManyErrors) BalloonMsg($"{lh.ErrorStrings}", $"[{lh.Name}] LAST ERRORS:"); ChangeBSMsg(lh.Name, lh.PoweredOn, lh.LastCmd, lh.Action); Interlocked.Exchange(ref processingCmdSync, 0); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { while (true) { if (0 == Interlocked.Exchange(ref processingCmdSync, 1)) break; Thread.Sleep(100); } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { traceDbg.Close(); traceEx.Close(); } private void quitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void createDesktopShortcutToolStripMenuItem_Click(object sender, EventArgs e) { try { object shDesktop = (object)"Desktop"; WshShell shell = new WshShell(); string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\BSManager.lnk"; IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress); shortcut.Description = "Open BSManager"; shortcut.Hotkey = ""; shortcut.TargetPath = MyExecutableWithPath; shortcut.Save(); } catch (Exception ex) { HandleEx(ex); } } private void licenseToolStripMenuItem_Click(object sender, EventArgs e) { openlink("https://github.com/mann1x/BSManager/LICENSE"); } private void documentationToolStripMenuItem_Click(object sender, EventArgs e) { openlink("https://github.com/mann1x/BSManager/"); } private void toolStripRunAtStartup_Click(object sender, EventArgs e) { using (RegistryKey registryStart = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true)) { if (!toolStripRunAtStartup.Checked) { registryStart.SetValue("BSManager", MyExecutableWithPath); toolStripRunAtStartup.Checked = true; } else { registryStart.DeleteValue("BSManager", false); toolStripRunAtStartup.Checked = false; } } } private void openlink(string uri) { var psi = new ProcessStartInfo(); psi.UseShellExecute = true; psi.FileName = uri; Process.Start(psi); } private string MyExecutableWithPath { get { string filepath = Process.GetCurrentProcess().MainModule.FileName; string extension = Path.GetExtension(filepath).ToLower(); if (String.Equals(extension, ".dll")) { string folder = Path.GetDirectoryName(filepath); string fileName = Path.GetFileNameWithoutExtension(filepath); fileName = String.Concat(fileName, ".exe"); filepath = Path.Combine(folder, fileName); } return filepath; } } private string[] ProcListLoad(string _filename, string friendlyListName) { try { string[] _list = null; if (File.Exists(_filename)) { _list = File.ReadLines(_filename).ToArray(); LogLine($"[CONFIG] Loaded custom processes list for {friendlyListName} killing: {string.Join(", ", _list)}"); } return _list; } catch (Exception ex) { HandleEx(ex); return null; } } private void FindRuntime() { try { using (RegistryKey registryManage = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true)) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service"); var collection = searcher.Get().Cast<ManagementBaseObject>() .Where(mbo => (string)mbo.GetPropertyValue("Name") == "PiServiceLauncher") .Select(mbo => (string)mbo.GetPropertyValue("PathName")); if (collection.Any()) { RuntimePath = Path.GetDirectoryName(collection.First()); LogLine($"[CONFIG] Found Runtime={RuntimePath}"); registryManage.SetValue("ManageRuntimePath", RuntimePath); } else { BalloonMsg($"[CONFIG] Pimax Runtime not found"); LogLine($"[CONFIG] Pimax Runtime not found"); } } } catch (Exception ex) { HandleEx(ex); } } private void toolStripDebugLog_Click(object sender, EventArgs e) { using (RegistryKey registryDebug = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true)) { if (!toolStripDebugLog.Checked) { registryDebug.SetValue("DebugLog", "1"); toolStripDebugLog.Checked = true; } else { registryDebug.DeleteValue("DebugLog", false); toolStripDebugLog.Checked = false; } } } private void disableProgressToastToolStripMenuItem_Click(object sender, EventArgs e) { try { using (RegistryKey registryManage = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true)) { if (!disableProgressToastToolStripMenuItem.Checked) { SetProgressToast = false; ShowProgressToast = false; registryManage.DeleteValue("ShowProgressToast", false); disableProgressToastToolStripMenuItem.Checked = true; } else { SetProgressToast = true; ShowProgressToast = true; registryManage.SetValue("ShowProgressToast", "1"); disableProgressToastToolStripMenuItem.Checked = false; } } } catch (Exception ex) { HandleEx(ex); } } private void RuntimeToolStripMenuItem_Click(object sender, EventArgs e) { try { using (RegistryKey registryManage = Registry.CurrentUser.OpenSubKey("SOFTWARE\\ManniX\\BSManager", true)) { if (!RuntimeToolStripMenuItem.Checked) { ManageRuntime = true; registryManage.SetValue("ManageRuntime", "1"); RuntimeToolStripMenuItem.Checked = true; } else { ManageRuntime = false; registryManage.DeleteValue("ManageRuntime", false); RuntimeToolStripMenuItem.Checked = false; } } } catch (Exception ex) { HandleEx(ex); } } public new void Dispose() { ProcessLHtimer.Enabled = false; ProcessLHtimer.Stop(); removeWatcher.Stop(); insertWatcher.Stop(); watcher.Stop(); Dispose(true); } } public class ProcessError : Exception { public ProcessError() { } public ProcessError(string message) : base(message) { } public ProcessError(string message, Exception innerException) : base(message, innerException) { } protected ProcessError(SerializationInfo info, StreamingContext context) : base(info, context) { } ProcessError(int severity, string message) : base(message) { } } }
37.850668
173
0.47256
[ "MIT" ]
drowhunter/BSManager
BSManagerMain.cs
65,143
C#
using CadEditor; using System; //css_include shared_settings/BlockUtils.cs; //css_include shared_settings/SharedUtils.cs; public class Data { public OffsetRec getScreensOffset() { return new OffsetRec(0xf610, 4, 16*16, 16, 16); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk(new[] {"chr3-2.bin"}); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0xfa10, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksFromAlignedArrays;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksToAlignedArrays;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal3-2.bin"}); } public SetPalFunc setPalFunc() { return null;} }
49.259259
113
0.706015
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/final_fight_3_unl/Settings_FinalFight3_NES-3-2.cs
1,330
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Net; namespace NFMessageLogViewer { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void openToolStripMenuItem_Click(object sender, EventArgs e) { } private void listView1_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files.Length == 0) return; if(files[0].EndsWith(".nlog")) { ReadMsgLogFile(files[0]); } else { MessageBox.Show("请托入nlog 日志文件格式"); } } private void listView1_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, true) == true) { //允许拖放 e.Effect = DragDropEffects.All; } } private void ReadMsgLogFile(string path) { FileStream f = System.IO.File.OpenRead(path); byte[] buffer = new byte[f.Length]; f.Read(buffer, 0, buffer.Length); f.Close(); _CurrentFileMS = new MemoryStream(buffer, 0, buffer.Length, false, true); _ProtoList = new List<ProtoListItem>(); byte[] twoBytes = new byte[2]; byte[] fourBytes = new byte[4]; while (_CurrentFileMS.Position < _CurrentFileMS.Length) { _CurrentFileMS.Read(twoBytes, 0, 2); ushort protoID = (ushort)IPAddress.NetworkToHostOrder((short)BitConverter.ToUInt16(twoBytes, 0)); _CurrentFileMS.Read(fourBytes, 0, 4); uint protoLen = (uint)IPAddress.NetworkToHostOrder((int)BitConverter.ToUInt32(fourBytes, 0)); _CurrentFileMS.Position += protoLen-6; var item = new ProtoListItem(); item.proto_id = protoID; item.buffer_offset = (uint)_CurrentFileMS.Position; item.data_length = protoLen; _ProtoList.Add(item); } listView1.View = View.Details; for(int i=0;i < _ProtoList.Count;++i) { var protoItem = _ProtoList[i]; ListViewItem item = new ListViewItem(new string[] { ((NFMsg.EGameMsgID)protoItem.proto_id).ToString(), protoItem.proto_id.ToString(), protoItem.buffer_offset.ToString(), protoItem.data_length.ToString() }); listView1.Items.Add(item); } } private MemoryStream _CurrentFileMS; private List<ProtoListItem> _ProtoList; class ProtoListItem { public ushort proto_id; public uint buffer_offset; public uint data_length; } } }
29.096491
114
0.526681
[ "Apache-2.0" ]
guoliulong/NoahGameFrame
NFTools/NFMessageLogViewer/Form1.cs
3,345
C#
using System.IO; namespace System { public static class Logger { static string logPath = "d:\\"; static Logger() { if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } } public static void Info(string fileName, string content) { string logFullName = Path.Combine(logPath, fileName); content = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffffff")} {content}\r\n"; File.AppendAllText(logFullName, content); } } }
23.68
93
0.537162
[ "MIT" ]
GavinYao2018/WinServiceShell
Src/MethodTest/Logger.cs
594
C#
using System.Drawing; using System.Runtime.Serialization; namespace MSI_LED_Tool { [DataContract] public class LedSettings { private const int MinimumTemperature = 0; private const int MaximumTemperature = 100; private int temperatureLowerLimit; private int temperatureUpperLimit; /// <summary> /// Default constructor with default values. /// </summary> public LedSettings() { R = 255; G = 0; B = 0; AnimationType = AnimationType.NoAnimation; TemperatureUpperLimit = 85; TemperatureLowerLimit = 45; OverwriteSecurityChecks = false; } [DataMember] public AnimationType AnimationType { get; set; } [DataMember] public int R { get; set; } [DataMember] public int G { get; set; } [DataMember] public int B { get; set; } [DataMember] public int TemperatureUpperLimit { get { return temperatureUpperLimit; } set { temperatureUpperLimit = AdjustTemperatureWithinBounds(value); AdjustTemperatureRange(); } } [DataMember] public int TemperatureLowerLimit { get { return temperatureLowerLimit; } set { temperatureLowerLimit = AdjustTemperatureWithinBounds(value); AdjustTemperatureRange(); } } [DataMember] public bool OverwriteSecurityChecks { get; set; } /// <summary> /// Accessor to modify RGB values through <see cref="System.Drawing.Color"/> object. /// </summary> public Color Color { get { return Color.FromArgb(255, R, G, B); } set { R = value.R; G = value.G; B = value.B; } } public static LedSettings CopyFrom(LedSettings ledSettings) { return new LedSettings() { AnimationType = ledSettings.AnimationType, Color = ledSettings.Color, OverwriteSecurityChecks = ledSettings.OverwriteSecurityChecks, TemperatureLowerLimit = ledSettings.TemperatureLowerLimit, TemperatureUpperLimit = ledSettings.TemperatureUpperLimit }; } /// <summary> /// Cap the temperature value within acceptable bounds. /// </summary> /// <param name="input">The value to adjust</param> /// <returns>An adjusted value.</returns> private int AdjustTemperatureWithinBounds(int input) { if (input > MaximumTemperature) { input = MaximumTemperature; } if (input < MinimumTemperature) { input = MinimumTemperature; } return input; } /// <summary> /// Adjust lower and upper limit with respect to each other and bounds. /// </summary> private void AdjustTemperatureRange() { if (temperatureUpperLimit <= temperatureLowerLimit) { if (temperatureLowerLimit >= MaximumTemperature) { temperatureLowerLimit = MaximumTemperature - 1; } temperatureUpperLimit = temperatureLowerLimit + 1; } } } }
26.319149
92
0.506871
[ "MIT" ]
SIZMW/MSI-LED-Tool
MSI LED Tool/Model/LedSettings.cs
3,713
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.DotNet.Interactive.CSharpProject.Protocol { public class CompletionItem { public string DisplayText { get; } public string Kind { get; } public string FilterText { get; } public string SortText { get; } public string InsertText { get; } public MarkdownString Documentation { get; set; } public Uri AcceptanceUri { get; } public CompletionItem(string displayText, string kind, string filterText = null, string sortText = null, string insertText = null, MarkdownString documentation = null, Uri acceptanceUri = null) { DisplayText = displayText ?? throw new ArgumentNullException(nameof(displayText)); Kind = kind ?? throw new ArgumentException(nameof(kind)); FilterText = filterText; SortText = sortText; InsertText = insertText; Documentation = documentation; AcceptanceUri = acceptanceUri; } public override string ToString() => DisplayText; } }
41.032258
202
0.647799
[ "MIT" ]
alireza-rezaee/interactive
src/Microsoft.DotNet.Interactive.CSharpProject/CompletionItem.cs
1,272
C#
using System.Collections.Generic; using SimpleLang.Visitors; namespace ProgramTree { public enum AssignType { Assign, AssignPlus, AssignMinus, AssignMult, AssignDivide }; public abstract class Node // базовый класс для всех узлов { public abstract void Visit(Visitor v); } public abstract class ExprNode : Node // базовый класс для всех выражений { } public class IdNode : ExprNode { public string Name { get; set; } public IdNode(string name) { Name = name; } public override void Visit(Visitor v) { v.VisitIdNode(this); } } public class IntNumNode : ExprNode { public int Num { get; set; } public IntNumNode(int num) { Num = num; } public override void Visit(Visitor v) { v.VisitIntNumNode(this); } } public class BinOpNode : ExprNode { public ExprNode Left { get; set; } public ExprNode Right { get; set; } public char Op { get; set; } public BinOpNode(ExprNode Left, ExprNode Right, char op) { this.Left = Left; this.Right = Right; this.Op = op; } public override void Visit(Visitor v) { v.VisitBinOpNode(this); } } public abstract class StatementNode : Node // базовый класс для всех операторов { } public class AssignNode : StatementNode { public IdNode Id { get; set; } public ExprNode Expr { get; set; } public AssignType AssOp { get; set; } public AssignNode(IdNode id, ExprNode expr, AssignType assop = AssignType.Assign) { Id = id; Expr = expr; AssOp = assop; } public override void Visit(Visitor v) { v.VisitAssignNode(this); } } public class CycleNode : StatementNode { public ExprNode Expr { get; set; } public StatementNode Stat { get; set; } public CycleNode(ExprNode expr, StatementNode stat) { Expr = expr; Stat = stat; } public override void Visit(Visitor v) { v.VisitCycleNode(this); } } public class ForNode : StatementNode { public AssignNode Assign { get; set; } public ExprNode Expr { get; set; } public StatementNode Stat { get; set; } public ForNode(AssignNode assign,ExprNode expr, StatementNode stat) { Assign = assign; Expr = expr; Stat = stat; } public override void Visit(Visitor v) { v.VisitForNode(this); } } public class BlockNode : StatementNode { public List<StatementNode> StList = new List<StatementNode>(); public BlockNode(StatementNode stat) { Add(stat); } public void Add(StatementNode stat) { StList.Add(stat); } public override void Visit(Visitor v) { v.VisitBlockNode(this); } } public class WriteNode : StatementNode { public ExprNode Expr { get; set; } public WriteNode(ExprNode Expr) { this.Expr = Expr; } public override void Visit(Visitor v) { v.VisitWriteNode(this); } } public class EmptyNode : StatementNode { public override void Visit(Visitor v) { v.VisitEmptyNode(this); } } public class VarDefNode : StatementNode { public List<IdNode> vars = new List<IdNode>(); public VarDefNode(IdNode id) { Add(id); } public void Add(IdNode id) { vars.Add(id); } public override void Visit(Visitor v) { v.VisitVarDefNode(this); } } public class IfNode : StatementNode { public ExprNode expr; public StatementNode ifTrue, ifFalse; public IfNode(ExprNode expr, StatementNode ifTrue, StatementNode ifFalse = null) { this.expr = expr; this.ifTrue = ifTrue; this.ifFalse = ifFalse; } public override void Visit(Visitor v) { v.VisitIfNode(this); } } }
24.100559
89
0.548215
[ "MIT" ]
midikko/MMCS_CS311
Module8/ProgramTree.cs
4,397
C#
using System.Collections.Generic; using System.Diagnostics; namespace Speiser.Masterthesis.SourceCodeService.Contracts.Syntax { [DebuggerDisplay("class {Identifier}")] public class CodeClass { public IEnumerable<CodeAttribute> Attributes { get; set; } public string Identifier { get; set; } public IEnumerable<string> Base { get; set; } public IEnumerable<CodeMethod> Methods { get; set; } } }
29.6
66
0.693694
[ "MIT" ]
Speiser/masterthesis-computerscience
code/Speiser.Masterthesis.SourceCodeService/Contracts/Syntax/CodeClass.cs
446
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Frs.V2.Model { /// <summary> /// Request Object /// </summary> public class DetectLiveByFileRequest { /// <summary> /// /// </summary> [SDKProperty("body", IsBody = true)] [JsonProperty("body", NullValueHandling = NullValueHandling.Ignore)] public DetectLiveByFileRequestBody Body { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DetectLiveByFileRequest {\n"); sb.Append(" body: ").Append(Body).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as DetectLiveByFileRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(DetectLiveByFileRequest input) { if (input == null) return false; return ( this.Body == input.Body || (this.Body != null && this.Body.Equals(input.Body)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Body != null) hashCode = hashCode * 59 + this.Body.GetHashCode(); return hashCode; } } } }
26.246753
76
0.505195
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Frs/V2/Model/DetectLiveByFileRequest.cs
2,021
C#
using HomematicIp.Data.Enums; using Newtonsoft.Json; namespace HomematicIp.Data.HomematicIpObjects.Channels { [EnumMap(FunctionalChannelType.MULTI_MODE_INPUT_DIMMER_CHANNEL)] public class MultiModeInputDimmerChannel : Channel { [JsonProperty(PropertyName = "dimLevel")] public double? DimLevel { get; set; } [JsonProperty(PropertyName = "on")] public bool? IsOn { get; set; } public string ProfileMode { get; set; } public string UserDesiredProfileMode { get; set; } public MultiModeInputMode? MultiModeInputMode { get; set; } public BinaryBehaviorType? BinaryBehaviorType { get; set; } } }
32.142857
68
0.691852
[ "MIT" ]
DevEddy/HomematicIp
src/HomematicIp/Data/HomematicIpObjects/Channels/MultiModeInputDimmerChannel.cs
677
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Bedrock.DomainBuilder.Enumerations; namespace Bedrock.DomainBuilder { public class BuildSettings { #region Fields private eDomain? _domain; private string _connectionString; private string _domainPath; private string _namespaceEntity; private string _namespaceShared; private eEntityType? _entityType; private ePrimaryKeyType? _primaryKeyType; private string _fileExtension; private bool? _isValidatable; private bool? _isIncludeSpatialType; private bool? _isIncludeCrud; private bool? _isIncludeCrudEntity; private bool? _isRecursiveCrud; private bool? _isIncludePrimaryKey; private bool? _isIncludeAuditFields; private bool? _isIncludeDeletableFields; private bool? _isIncludeProperties; private bool? _isCleanPath; private bool? _isNetCore; private List<eBuilder> _activeBuilders; private string _namespaceContext; private eContextType? _contextType; private string _namespaceMapping; private string _commonKey; private bool? _isUseCommonKey; private string _namespaceService; private eServiceType? _serviceType; private string _namespaceEnumeration; private bool? _isOpenFolder; private bool? _isCascadeOnDelete; private bool? _isIgnoreRootChildren; private string _namespaceDomain; private List<string> _entityExclusions; private List<string> _propertyInclusions; private string _namespaceContract; private string _contractName; private eContractType? _contractType; private string _namespaceAppService; private eAppServiceType? _appServiceType; private string _namespaceControllerApi; private eControllerApiType? _controllerApiType; private string _namespaceControllerMvc; private eControllerMvcType? _controllerMvcType; private string _storeSchemaNamespace; private bool? _isUsePropertyInclusions; private bool? _isTracked; private string _namespaceInfrastructure; #endregion #region Constructors private BuildSettings() { StoreSchemaNamespace = "dbo"; } #endregion #region Properties public string Delimeter { get { return ","; } } public eDomain Domain { get { return _domain.Value; } set { _domain = value; Reset(); } } public string ConnectionString { get { if (string.IsNullOrEmpty(_connectionString)) { var key = string.Concat("Bedrock.ConnectionString.", Domain.ToString()); _connectionString = ConfigurationManager.ConnectionStrings[key].ConnectionString; } return _connectionString; } set { _connectionString = value; } } public string ProviderInvariantName { get { return "System.Data.SqlClient"; } } public string StoreSchemaNamespace { get { return _storeSchemaNamespace; } set { _storeSchemaNamespace = value; } } public string DomainPath { get { if (string.IsNullOrEmpty(_domainPath)) { var key = "Bedrock.Domain.Path"; _domainPath = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _domainPath; } set { _domainPath = value; } } public string EntityPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Entity\\Model\\"); } } public string EntityPathPartial { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Entity\\"); } } public string ContextPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Context\\"); } } public string MappingPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Mapping\\"); } } public string ServicePath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Service\\"); } } public string ServiceInterfacePath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Service\\Interface\\"); } } public string EnumerationPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Enumeration\\"); } } public string AppContextPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\AppContext\\"); } } public string ContractPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\Contract\\"); } } public string AppServicePath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\AppService\\"); } } public string AppServiceInterfacePath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\AppService\\Interface\\"); } } public string ControllerApiPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\ControllerApi\\"); } } public string ControllerMvcPath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\ControllerMvc\\"); } } public string AutoMapperProfilePath { get { return string.Concat(DomainPath, StoreSchemaNamespace, "\\AutoMapperProfile\\"); } } public string NamespaceEntity { get { if (string.IsNullOrEmpty(_namespaceEntity)) { var key = "Bedrock.Entity.Namespace"; _namespaceEntity = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceEntity; } set { _namespaceEntity = value; } } public string NamespaceShared { get { if (string.IsNullOrEmpty(_namespaceShared)) { var key = "Bedrock.Domain.Namespace.Shared"; _namespaceShared = ConfigurationManager.AppSettings[key]; } return _namespaceShared; } set { _namespaceShared = value; } } public string NamespaceDomain { get { if (string.IsNullOrEmpty(_namespaceDomain)) { var key = "Bedrock.Domain.Namespace"; _namespaceDomain = string.Format(ConfigurationManager.AppSettings[key], Domain); } return _namespaceDomain; } set { _namespaceDomain = value; } } public eEntityType EntityType { get { if (!_entityType.HasValue) { var key = "Bedrock.Entity.Type"; var value = ConfigurationManager.AppSettings[key]; _entityType = (eEntityType)Enum.Parse(typeof(eEntityType), value, true); } return _entityType.Value; } set { _entityType = value; } } public ePrimaryKeyType PrimaryKeyType { get { if (!_primaryKeyType.HasValue) { var key = "Bedrock.Entity.PrimaryKeyType"; var value = ConfigurationManager.AppSettings[key]; _primaryKeyType = (ePrimaryKeyType)Enum.Parse(typeof(ePrimaryKeyType), value, true); } return _primaryKeyType.Value; } set { _primaryKeyType = value; } } public string FileExtension { get { if (string.IsNullOrEmpty(_fileExtension)) { var key = "Bedrock.Domain.File.Extension"; _fileExtension = ConfigurationManager.AppSettings[key]; } return _fileExtension; } set { _fileExtension = value; } } public bool IsValidatable { get { if (!_isValidatable.HasValue) { var key = "Bedrock.Entity.IsValidatable"; var value = ConfigurationManager.AppSettings[key]; _isValidatable = bool.Parse(value); } return _isValidatable.Value; } set { _isValidatable = value; } } public bool IsIncludeSpatialType { get { if (!_isIncludeSpatialType.HasValue) { var key = "Bedrock.Entity.IsIncludeSpatialType"; var value = ConfigurationManager.AppSettings[key]; _isIncludeSpatialType = bool.Parse(value); } return _isIncludeSpatialType.Value; } set { _isIncludeSpatialType = value; } } public bool IsIncludeCrud { get { if (!_isIncludeCrud.HasValue) { var key = "Bedrock.Domain.IsIncludeCrud"; var value = ConfigurationManager.AppSettings[key]; _isIncludeCrud = bool.Parse(value); } return _isIncludeCrud.Value; } set { _isIncludeCrud = value; } } public bool IsIncludeCrudEntity { get { if (!_isIncludeCrudEntity.HasValue) { var key = "Bedrock.Entity.IsIncludeCrud"; var value = ConfigurationManager.AppSettings[key]; _isIncludeCrudEntity = bool.Parse(value); } return _isIncludeCrudEntity.Value; } set { _isIncludeCrudEntity = value; } } public bool IsRecursiveCrud { get { if (!_isRecursiveCrud.HasValue) { var key = "Bedrock.Domain.IsRecursiveCrud"; var value = ConfigurationManager.AppSettings[key]; _isRecursiveCrud = bool.Parse(value); } return _isRecursiveCrud.Value; } set { _isRecursiveCrud = value; } } public bool IsIncludePrimaryKey { get { if (!_isIncludePrimaryKey.HasValue) { var key = "Bedrock.Entity.IsIncludePrimaryKey"; var value = ConfigurationManager.AppSettings[key]; _isIncludePrimaryKey = bool.Parse(value); } return _isIncludePrimaryKey.Value; } set { _isIncludePrimaryKey = value; } } public bool IsIncludeAuditFields { get { if (!_isIncludeAuditFields.HasValue) { var key = "Bedrock.Entity.IsIncludeAuditFields"; var value = ConfigurationManager.AppSettings[key]; _isIncludeAuditFields = bool.Parse(value); } return _isIncludeAuditFields.Value; } set { _isIncludeAuditFields = value; } } public bool IsIncludeDeletableFields { get { if (!_isIncludeDeletableFields.HasValue) { var key = "Bedrock.Entity.IsIncludeDeletableFields"; var value = ConfigurationManager.AppSettings[key]; _isIncludeDeletableFields = bool.Parse(value); } return _isIncludeDeletableFields.Value; } set { _isIncludeDeletableFields = value; } } public bool IsIncludeProperties { get { if (!_isIncludeProperties.HasValue) { var key = "Bedrock.Entity.IsIncludeProperties"; var value = ConfigurationManager.AppSettings[key]; _isIncludeProperties = bool.Parse(value); } return _isIncludeProperties.Value; } set { _isIncludeProperties = value; } } public bool IsCleanPath { get { if (!_isCleanPath.HasValue) { var key = "Bedrock.Domain.IsCleanPath"; var value = ConfigurationManager.AppSettings[key]; _isCleanPath = bool.Parse(value); } return _isCleanPath.Value; } set { _isCleanPath = value; } } public bool IsNetCore { get { if (!_isNetCore.HasValue) { var key = "Bedrock.Domain.IsNetCore"; var value = ConfigurationManager.AppSettings[key]; _isNetCore = bool.Parse(value); } return _isNetCore.Value; } set { _isNetCore = value; } } public List<eBuilder> ActiveBuilders { get { if (_activeBuilders == null) { var configBuilders = ConfigurationManager .AppSettings["Bedrock.Domain.ActiveBuilders"] .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(b => (eBuilder)Enum.Parse(typeof(eBuilder), b, true)); _activeBuilders = new List<eBuilder>(configBuilders); } return _activeBuilders; } } public string NamespaceContext { get { if (string.IsNullOrEmpty(_namespaceContext)) { var key = "Bedrock.Context.Namespace"; _namespaceContext = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceContext; } set { _namespaceContext = value; } } public eContextType ContextType { get { if (!_contextType.HasValue) { var key = "Bedrock.Context.Type"; var value = ConfigurationManager.AppSettings[key]; _contextType = (eContextType)Enum.Parse(typeof(eContextType), value, true); } return _contextType.Value; } set { _contextType = value; } } public string NamespaceMapping { get { if (string.IsNullOrEmpty(_namespaceMapping)) { var key = "Bedrock.Mapping.Namespace"; _namespaceMapping = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceMapping; } set { _namespaceMapping = value; } } public string CommonKey { get { if (string.IsNullOrEmpty(_commonKey)) { _commonKey = ConfigurationManager.AppSettings["Bedrock.Domain.CommonKey"]; } return _commonKey; } set { _commonKey = value; } } public bool IsUseCommonKey { get { if (!_isUseCommonKey.HasValue) { var key = "Bedrock.Domain.IsUseCommonKey"; var value = ConfigurationManager.AppSettings[key]; _isUseCommonKey = bool.Parse(value); } return _isUseCommonKey.Value; } set { _isUseCommonKey = value; } } public string NamespaceService { get { if (string.IsNullOrEmpty(_namespaceService)) { var key = "Bedrock.Service.Namespace"; _namespaceService = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceService; } set { _namespaceService = value; } } public eServiceType ServiceType { get { if (!_serviceType.HasValue) { var key = "Bedrock.Service.Type"; var value = ConfigurationManager.AppSettings[key]; _serviceType = (eServiceType)Enum.Parse(typeof(eServiceType), value, true); } return _serviceType.Value; } set { _serviceType = value; } } public string NamespaceEnumeration { get { if (string.IsNullOrEmpty(_namespaceEnumeration)) { var key = "Bedrock.Enumeration.Namespace"; _namespaceEnumeration = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceEnumeration; } set { _namespaceEnumeration = value; } } public bool IsOpenFolder { get { if (!_isOpenFolder.HasValue) { var key = "Bedrock.Domain.IsOpenFolder"; var value = ConfigurationManager.AppSettings[key]; _isOpenFolder = bool.Parse(value); } return _isOpenFolder.Value; } set { _isOpenFolder = value; } } public bool IsCascadeOnDelete { get { if (!_isCascadeOnDelete.HasValue) { var key = "Bedrock.Domain.IsCascadeOnDelete"; var value = ConfigurationManager.AppSettings[key]; _isCascadeOnDelete = bool.Parse(value); } return _isCascadeOnDelete.Value; } set { _isCascadeOnDelete = value; } } public bool IsIgnoreRootChildren { get { if (!_isIgnoreRootChildren.HasValue) { var key = "Bedrock.Domain.IsIgnoreRootChildren"; var value = ConfigurationManager.AppSettings[key]; _isIgnoreRootChildren = bool.Parse(value); } return _isIgnoreRootChildren.Value; } set { _isIgnoreRootChildren = value; } } public List<string> EntityExclusions { get { if (_entityExclusions == null) { var key = string.Format("Bedrock.Domain.EntityExclusions.{0}", Domain.ToString()); var entityExclusions = ConfigurationManager .AppSettings[key] .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); _entityExclusions = new List<string>(entityExclusions); } return _entityExclusions; } } public List<string> PropertyInclusions { get { if (_propertyInclusions == null) { var key = string.Format("Bedrock.Domain.PropertyInclusions.{0}", Domain.ToString()); var propertyInclusions = ConfigurationManager .AppSettings[key] .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); _propertyInclusions = new List<string>(propertyInclusions); } return _propertyInclusions; } } public string NamespaceContract { get { if (string.IsNullOrEmpty(_namespaceContract)) { var key = "Bedrock.Contract.Namespace"; _namespaceContract = string.Format(ConfigurationManager.AppSettings[key], Domain); } return _namespaceContract; } set { _namespaceContract = value; } } public string ContractName { get { if (string.IsNullOrEmpty(_contractName)) _contractName = ConfigurationManager.AppSettings["Bedrock.Contract.Name"]; return _contractName; } set { _contractName = value; } } public eContractType ContractType { get { if (!_contractType.HasValue) { var key = "Bedrock.Contract.Type"; var value = ConfigurationManager.AppSettings[key]; _contractType = (eContractType)Enum.Parse(typeof(eContractType), value, true); } return _contractType.Value; } set { _contractType = value; } } public string NamespaceAppService { get { if (string.IsNullOrEmpty(_namespaceAppService)) { var key = "Bedrock.AppService.Namespace"; _namespaceAppService = string.Format(ConfigurationManager.AppSettings[key], Domain); } return _namespaceAppService; } set { _namespaceAppService = value; } } public eAppServiceType AppServiceType { get { if (!_appServiceType.HasValue) { var key = "Bedrock.AppService.Type"; var value = ConfigurationManager.AppSettings[key]; _appServiceType = (eAppServiceType)Enum.Parse(typeof(eAppServiceType), value, true); } return _appServiceType.Value; } set { _appServiceType = value; } } public string NamespaceControllerApi { get { if (string.IsNullOrEmpty(_namespaceControllerApi)) { var key = "Bedrock.ControllerApi.Namespace"; _namespaceControllerApi = string.Format(ConfigurationManager.AppSettings[key], Domain); } return _namespaceControllerApi; } set { _namespaceControllerApi = value; } } public eControllerApiType ControllerApiType { get { if (!_controllerApiType.HasValue) { var key = "Bedrock.ControllerApi.Type"; var value = ConfigurationManager.AppSettings[key]; _controllerApiType = (eControllerApiType)Enum.Parse(typeof(eControllerApiType), value, true); } return _controllerApiType.Value; } set { _controllerApiType = value; } } public string NamespaceControllerMvc { get { if (string.IsNullOrEmpty(_namespaceControllerMvc)) { var key = "Bedrock.ControllerMvc.Namespace"; _namespaceControllerMvc = string.Format(ConfigurationManager.AppSettings[key], Domain); } return _namespaceControllerMvc; } set { _namespaceControllerMvc = value; } } public eControllerMvcType ControllerMvcType { get { if (!_controllerMvcType.HasValue) { var key = "Bedrock.ControllerMvc.Type"; var value = ConfigurationManager.AppSettings[key]; _controllerMvcType = (eControllerMvcType)Enum.Parse(typeof(eControllerMvcType), value, true); } return _controllerMvcType.Value; } set { _controllerMvcType = value; } } public bool IsUsePropertyInclusions { get { if (!_isUsePropertyInclusions.HasValue) { var key = "Bedrock.Domain.IsUsePropertyInclusions"; var value = ConfigurationManager.AppSettings[key]; _isUsePropertyInclusions = bool.Parse(value); } return _isUsePropertyInclusions.Value; } set { _isUsePropertyInclusions = value; } } public bool IsTracked { get { if (!_isTracked.HasValue) { var key = "Bedrock.Domain.IsTracked"; var value = ConfigurationManager.AppSettings[key]; _isTracked = bool.Parse(value); } return _isTracked.Value; } set { _isTracked = value; } } public string NamespaceInfrastructure { get { if (string.IsNullOrEmpty(_namespaceInfrastructure)) { var key = "Bedrock.Infrastructure.Namespace"; _namespaceInfrastructure = string.Format(ConfigurationManager.AppSettings[key], Domain.ToString()); } return _namespaceInfrastructure; } set { _namespaceInfrastructure = value; } } #endregion #region Public Methods public static BuildSettings Create() { return new BuildSettings(); } public static BuildSettings Create(eDomain domain) { return new BuildSettings { Domain = domain }; } public static BuildSettings Create(eDomain domain, eEntityType entityType) { return new BuildSettings { Domain = domain, EntityType = entityType }; } public void Verify() { VerifyConnectionString(); VerifyDomainPath(); VerifyNamespaceEntity(); VerifyNamespaceShared(); } public string GetBuilderPath(eBuilder builder) { switch (builder) { case eBuilder.Entity: return EntityPath; case eBuilder.EntityPartial: return EntityPathPartial; case eBuilder.Mapping: return MappingPath; case eBuilder.Context: return ContextPath; case eBuilder.Service: return ServicePath; case eBuilder.ServiceInterface: return ServiceInterfacePath; case eBuilder.Enumeration: return EnumerationPath; case eBuilder.AppContext: return AppContextPath; case eBuilder.Contract: return ContractPath; case eBuilder.AppService: return AppServicePath; case eBuilder.AppServiceInterface: return AppServiceInterfacePath; case eBuilder.ControllerApi: return ControllerApiPath; case eBuilder.ControllerMvc: return ControllerMvcPath; case eBuilder.AutoMapperProfile: return AutoMapperProfilePath; default: throw new NotSupportedException(string.Concat("Unsupported builder: ", builder.ToString())); } } #endregion #region Public Methods (Verify) public void VerifyConnectionString() { try { new SqlConnectionStringBuilder(ConnectionString); } catch (Exception ex) { var newLine = Environment.NewLine; throw new ArgumentException(string.Concat("Connection string invalid.", newLine, newLine, ex.Message)); } } public void VerifyDomainPath() { try { if (!DomainPath.EndsWith("\\")) DomainPath += "\\"; Path.GetFullPath(DomainPath); } catch (Exception ex) { var newLine = Environment.NewLine; throw new ArgumentException(string.Concat("Domain Path invalid.", newLine, newLine, ex.Message)); } } public void VerifyNamespaceEntity() { if (!GetNamespaceExpression().IsMatch(NamespaceEntity)) throw new ArgumentException("Entity Namespace invalid."); } public void VerifyNamespaceShared() { if (!GetNamespaceExpression().IsMatch(NamespaceShared)) throw new ArgumentException("Shared Namespace invalid."); } #endregion #region Private Methods private void Reset() { _connectionString = null; _domainPath = null; _namespaceEntity = null; _namespaceContext = null; _namespaceMapping = null; _namespaceService = null; _namespaceEnumeration = null; _namespaceContract = null; _namespaceAppService = null; _namespaceControllerApi = null; _namespaceControllerMvc = null; _entityExclusions = null; _propertyInclusions = null; } private Regex GetNamespaceExpression() { var pattern = @"(@?[a-z_A-Z]\w+(?:\.@?[a-z_A-Z]\w+)*)$"; return new Regex(pattern, RegexOptions.IgnoreCase); } #endregion } }
30.53913
119
0.499272
[ "MIT" ]
BedrockNet/Bedrock.DomainBuilder
Bedrock.DomainBuilder/BuildSettings.cs
31,610
C#
/* -------------------------------------------------------------------------- * Copyrights * * Portions created by or assigned to Cursive Systems, Inc. are * Copyright (c) 2002-2008 Cursive Systems, Inc. All Rights Reserved. Contact * information for Cursive Systems, Inc. is available at * http://www.cursive.net/. * * License * * Jabber-Net can be used under either JOSL or the GPL. * See LICENSE.txt for details. * --------------------------------------------------------------------------*/ using System; namespace stringprep.unicode { /// <summary> /// Combining classes for Unicode characters. /// </summary> public class Combining { /// <summary> /// What is the combining class for the given character? /// </summary> /// <param name="c">Character to look up</param> /// <returns>Combining class for this character</returns> public static int Class(char c) { int page = c >> 8; if (CombiningData.Pages[page] == 255) return 0; else return CombiningData.Classes[CombiningData.Pages[page], c & 0xff]; } } }
30.358974
82
0.519426
[ "MIT" ]
JustOxlamon/TwoRatChat
JabberNet-2.1.0.710/stringprep/unicode/Combining.cs
1,184
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic.DocumentationCommentFormatting; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.DocCommentFormatting { public class DocCommentFormattingTests { private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string xmlFragment, string expectedCSharp, string expectedVB) { var csharpFormattedText = _csharpService.Format(xmlFragment); var vbFormattedText = _vbService.Format(xmlFragment); Assert.Equal(expectedCSharp, csharpFormattedText); Assert.Equal(expectedVB, vbFormattedText); } private void TestFormat(string xmlFragment, string expected) { TestFormat(xmlFragment, expected, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void CTag() { var comment = "Class <c>Point</c> models a point in a two-dimensional plane."; var expected = "Class Point models a point in a two-dimensional plane."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ExampleAndCodeTags() { var comment = @"This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example>"; var expected = "This method changes the point's location by the given x- and y-offsets. For example: Point p = new Point(3,5); p.Translate(-1,3); results in p's having the value (2,8)."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ListTag() { var comment = @"Here is an example of a bulleted list: <list type=""bullet""> <item> <description>Item 1.</description> </item> <item> <description>Item 2.</description> </item> </list>"; var expected = @"Here is an example of a bulleted list: Item 1. Item 2."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ParaTag() { var comment = @"This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class.</para>"; var expected = @"This is the entry point of the Point class testing program. This program tests each method and operator, and is intended to be run after any non-trivial maintenance has been performed on the Point class."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestPermissionTag() { var comment = @"<permission cref=""System.Security.PermissionSet"">Everyone can access this method.</permission>"; var expected = @"Everyone can access this method."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeTag() { var comment = @"<see cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlsoTag() { var comment = @"<seealso cref=""AnotherFunction""/>"; var expected = @"AnotherFunction"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void ValueTag() { var comment = @"<value>Property <c>X</c> represents the point's x-coordinate.</value>"; var expected = @"Property X represents the point's x-coordinate."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestParamRefTag() { var comment = @"This constructor initializes the new Point to (<paramref name=""xor""/>,<paramref name=""yor""/>)."; var expected = "This constructor initializes the new Point to (xor,yor)."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void TestTypeParamRefTag() { var comment = @"This method fetches data and returns a list of <typeparamref name=""Z""/>."; var expected = @"This method fetches data and returns a list of Z."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace1() { var comment = " This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace2() { var comment = @" This has extra whitespace. "; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Whitespace3() { var comment = "This has extra whitespace."; var expected = "This has extra whitespace."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs1() { var comment = @" <para>This is part of a paragraph.</para> "; var expected = "This is part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs2() { var comment = @" <para>This is part of a paragraph.</para> <para>This is also part of a paragraph.</para> "; var expected = @"This is part of a paragraph. This is also part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs3() { var comment = @" This is a summary. <para>This is part of a paragraph.</para> "; var expected = @"This is a summary. This is part of a paragraph."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void Paragraphs4() { var comment = @" <para>This is part of a paragraph.</para> This is part of the summary, too. "; var expected = @"This is part of a paragraph. This is part of the summary, too."; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See1() { var comment = @"See <see cref=""T:System.Object"" />"; var expected = "See System.Object"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void See2() { var comment = @"See <see />"; var expected = @"See"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso1() { var comment = @"See also <seealso cref=""T:System.Object"" />"; var expected = @"See also System.Object"; TestFormat(comment, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.DocCommentFormatting)] public void SeeAlso2() { var comment = @"See also <seealso />"; var expected = @"See also"; TestFormat(comment, expected); } } }
31.496528
198
0.610848
[ "Apache-2.0" ]
0x53A/roslyn
src/EditorFeatures/Test/DocCommentFormatting/DocCommentFormattingTests.cs
9,071
C#
using System.Linq.Expressions; using Core.IRepository; using System.Linq; using Microsoft.EntityFrameworkCore; namespace Core.Repository.Base { public class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class, new() { private readonly DbContext _context; private readonly DbSet<TEntity> _entities; public BaseRepository(DbContext context) { _context = context; _entities = _context.Set<TEntity>(); } #region 新增 public TEntity Add(TEntity entity, bool isSave = true) { _context.Set<TEntity>().Add(entity); if (isSave && SaveChanges() > 0) { return entity; } return null; } public async Task<TEntity> AddAsync(TEntity entity, bool isSave = true) { try { await _context.Set<TEntity>().AddAsync(entity); if (isSave && await SaveChangesAsync() > 0) { return entity; } return null; } catch (Exception ex) { throw ex; } } #endregion 新增 #region 更新 public bool Update(TEntity entity, bool isSave = true) { _context.Set<TEntity>().Update(entity); if (isSave && SaveChanges() > 0) { return true; } return false; } #endregion 更新 #region 删除 public bool Remove(TEntity entity, bool isSave = true) { _context.Set<TEntity>().Remove(entity); if (isSave && SaveChanges() > 0) { return true; } return false; } public bool RemoveById(int id, bool isSave = true) { TEntity entity = FindById(id); _entities.Remove(entity); if (isSave && SaveChanges() > 0) { return true; } return false; } #endregion 删除 #region 查询 public List<TEntity> FindAll() { return _entities.ToList(); } public TEntity FindById(int id) { return _entities.Find(id); } public List<TEntity> Query(Expression<Func<TEntity, bool>> expression) { return _entities.Where(expression).ToList(); } public List<TEntity> QueryByPage(Expression<Func<TEntity, bool>> expression = null, int start = 0, int end = 10) { if (expression == null) { return _entities.Skip(start).Take(end - start).ToList(); } return _entities.Where(expression).Skip(start).Take(end - start).ToList(); } public int GetCount(Expression<Func<TEntity, bool>> expression = null) { if (expression is null) { return _entities.Count(); } return _entities.Where(expression).Count(); } #endregion 查询 #region SaveChanges public int SaveChanges() { return _context.SaveChanges(); } public async Task<int> SaveChangesAsync() { return await _context.SaveChangesAsync(); } public async Task<TEntity> FindByIdAsync(int id) { return await _entities.FindAsync(id); } #endregion SaveChanges } }
24.398649
120
0.495154
[ "Apache-2.0" ]
chenyanbo1024/Core.Simple
Core.Repository/Base/BaseRepository.cs
3,645
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ad_jwt_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>(); } }
24.24
76
0.693069
[ "MIT" ]
pablospizzamiglio/ad-jwt-api
Program.cs
608
C#
using Dms.Integration.Infrastructure.Document; using Dms.Integration.Infrastructure.Extensions; using Dms.Integration.Infrastructure.Models; using System.Text; namespace Dms.Integration.Infrastructure.DocumentServices; public abstract class DocumentInfo { public DocumentBase Document { get; set; } public Dictionary<string, string> DocumentParameters { get; set; } //[RotaDMS].[dbo].[DocumentTag].TagId altinda bunlar public string OwnerName { get; set; } public string OwnerSurname { get; set; } public string ChannelReferenceId { get; set; } public string DmsPrefix { get; set; } protected DocumentInfo(DocumentBase document, string ownerName, string ownerSurName, string channelReferenceId = null) { Document = document; OwnerName = ownerName; OwnerSurname = ownerSurName; DocumentParameters = new Dictionary<string, string>(); ChannelReferenceId = channelReferenceId; DmsPrefix = "DijitalBaşvuru"; } public virtual DocumentContent Content { get { var content = Document.Contents.FirstOrDefault(x => x.MimeType == MimeTypeExtensions.PdfMimeType); if (content == null) { content = Document.Contents.FirstOrDefault(x => x.MimeType == MimeTypeExtensions.HtmlMimeType); } if (content == null) { content = Document.Contents.FirstOrDefault(); } //Throw.If<CoreSystemException>(content == null, $"DYS'ye boş dosya kaydı yapılamaz ({Document.Definition.Key.GetAttributeDescription()} dokümanı)."); return content; } } public virtual string FileName { get { return $"{OwnerName}{OwnerSurname}-{Document.Definition.Key.ToString()}-{Guid.NewGuid()}." + Content.MimeType.Split("/")[1]; } } public virtual string DocumentTypeDMSReferenceId { get { return Document.Definition.DmsReferenceId; } } public virtual string Description { get { if (Document.OwnerActionType.HasValue && Document.OwnerActionType.Value != DocumentActionType.None) { return $"{DmsPrefix} - {Document.Definition.Key.GetAttributeDescription()} - {Document.OwnerActionType.GetAttributeDescription()}"; } return $"{DmsPrefix} - { Document.Definition.Key.GetAttributeDescription()} "; } } public string ConstructDocumentTags() { var tags = new StringBuilder(); foreach (var item in DocumentParameters) { tags = tags.AppendLine($"<{item.Key}>{item.Value}</{item.Key}>"); } return $"{tags}"; } } /// <summary> /// BhsDocument /// </summary> public class BhsDocument : DocumentInfo { public BhsDocument(DocumentBase document, DmsPerson owner, string channelReferenceId, int customerNo, string citizenshipNumber, string branchCode, string bhsOrderNo, string version) : base(document, owner.FirstName, owner.LastName, channelReferenceId) { //<M375><Field19SubeKodu>9620</Field19SubeKodu> //<Field01MusteriNo>151933</Field01MusteriNo> //<Field08TCKimlik>67174055724</Field08TCKimlik> //<Field09VergiNo>4930036169</Field09VergiNo></M375> DocumentParameters.Add("Field19SubeKodu", branchCode); DocumentParameters.Add("Field01MusteriNo", customerNo.ToString()); DocumentParameters.Add("Field08TCKimlik", citizenshipNumber); DocumentParameters.Add("BHSVersion", version); DocumentParameters.Add("BHSOrder", bhsOrderNo); } }
35.692308
185
0.646552
[ "MIT" ]
hub-burgan-com-tr/bbt.endorsement
dms/Dms.Integration.Infrastructure/DocumentServices/DocumentInfo.cs
3,720
C#
namespace Orleans.Serialization.Invocation { public interface IResponseCompletionSource { /// <summary> /// Sets the result. /// </summary> /// <param name="value">The result value.</param> void Complete(Response value); void Complete(); } }
23.307692
57
0.580858
[ "MIT" ]
AmedeoV/orleans
src/Orleans.Serialization/Invocation/IResponseCompletionSource.cs
303
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Encodings.Web; using Foundation; using Microsoft.AspNetCore.Components.Web; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using UIKit; using WebKit; namespace Microsoft.AspNetCore.Components.WebView.Maui { /// <summary> /// An implementation of <see cref="WebViewManager"/> that uses the <see cref="WKWebView"/> browser control /// to render web content. /// </summary> internal class IOSWebViewManager : WebViewManager { private readonly BlazorWebViewHandler _blazorMauiWebViewHandler; private readonly WKWebView _webview; private readonly string _contentRootRelativeToAppRoot; /// <summary> /// Initializes a new instance of <see cref="IOSWebViewManager"/> /// </summary> /// <param name="blazorMauiWebViewHandler">The <see cref="BlazorWebViewHandler"/>.</param> /// <param name="webview">The <see cref="WKWebView"/> to render web content in.</param> /// <param name="provider">The <see cref="IServiceProvider"/> for the application.</param> /// <param name="dispatcher">A <see cref="Dispatcher"/> instance instance that can marshal calls to the required thread or sync context.</param> /// <param name="fileProvider">Provides static content to the webview.</param> /// <param name="jsComponents">Describes configuration for adding, removing, and updating root components from JavaScript code.</param> /// <param name="contentRootRelativeToAppRoot">Path to the directory containing application content files.</param> /// <param name="hostPageRelativePath">Path to the host page within the fileProvider.</param> public IOSWebViewManager(BlazorWebViewHandler blazorMauiWebViewHandler!!, WKWebView webview!!, IServiceProvider provider, Dispatcher dispatcher, IFileProvider fileProvider, JSComponentConfigurationStore jsComponents, string contentRootRelativeToAppRoot, string hostPageRelativePath) : base(provider, dispatcher, BlazorWebViewHandler.AppOriginUri, fileProvider, jsComponents, hostPageRelativePath) { if (provider.GetService<MauiBlazorMarkerService>() is null) { throw new InvalidOperationException( "Unable to find the required services. " + $"Please add all the required services by calling '{nameof(IServiceCollection)}.{nameof(BlazorWebViewServiceCollectionExtensions.AddMauiBlazorWebView)}' in the application startup code."); } _blazorMauiWebViewHandler = blazorMauiWebViewHandler; _webview = webview; _contentRootRelativeToAppRoot = contentRootRelativeToAppRoot; InitializeWebView(); } /// <inheritdoc /> protected override void NavigateCore(Uri absoluteUri) { using var nsUrl = new NSUrl(absoluteUri.ToString()); using var request = new NSUrlRequest(nsUrl); _webview.LoadRequest(request); } internal bool TryGetResponseContentInternal(string uri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out IDictionary<string, string> headers) { var defaultResult = TryGetResponseContent(uri, allowFallbackOnHostPage, out statusCode, out statusMessage, out content, out headers); var hotReloadedResult = StaticContentHotReloadManager.TryReplaceResponseContent(_contentRootRelativeToAppRoot, uri, ref statusCode, ref content, headers); return defaultResult || hotReloadedResult; } /// <inheritdoc /> protected override void SendMessage(string message) { var messageJSStringLiteral = JavaScriptEncoder.Default.Encode(message); _webview.EvaluateJavaScript( javascript: $"__dispatchMessageCallback(\"{messageJSStringLiteral}\")", completionHandler: (NSObject result, NSError error) => { }); } internal void MessageReceivedInternal(Uri uri, string message) { MessageReceived(uri, message); } private void InitializeWebView() { _webview.NavigationDelegate = new WebViewNavigationDelegate(_blazorMauiWebViewHandler); _webview.UIDelegate = new WebViewUIDelegate(_blazorMauiWebViewHandler); } internal sealed class WebViewUIDelegate : WKUIDelegate { private static readonly string LocalOK = NSBundle.FromIdentifier("com.apple.UIKit").GetLocalizedString("OK"); private static readonly string LocalCancel = NSBundle.FromIdentifier("com.apple.UIKit").GetLocalizedString("Cancel"); private readonly BlazorWebViewHandler _webView; public WebViewUIDelegate(BlazorWebViewHandler webView) { _webView = webView ?? throw new ArgumentNullException(nameof(webView)); } public override void RunJavaScriptAlertPanel(WKWebView webView, string message, WKFrameInfo frame, Action completionHandler) { PresentAlertController( webView, message, okAction: _ => completionHandler() ); } public override void RunJavaScriptConfirmPanel(WKWebView webView, string message, WKFrameInfo frame, Action<bool> completionHandler) { PresentAlertController( webView, message, okAction: _ => completionHandler(true), cancelAction: _ => completionHandler(false) ); } public override void RunJavaScriptTextInputPanel( WKWebView webView, string prompt, string? defaultText, WKFrameInfo frame, Action<string> completionHandler) { PresentAlertController( webView, prompt, defaultText: defaultText, okAction: x => completionHandler(x.TextFields[0].Text!), cancelAction: _ => completionHandler(null!) ); } private static string GetJsAlertTitle(WKWebView webView) { // Emulate the behavior of UIWebView dialogs. // The scheme and host are used unless local html content is what the webview is displaying, // in which case the bundle file name is used. if (webView.Url != null && webView.Url.AbsoluteString != $"file://{NSBundle.MainBundle.BundlePath}/") return $"{webView.Url.Scheme}://{webView.Url.Host}"; return new NSString(NSBundle.MainBundle.BundlePath).LastPathComponent; } private static UIAlertAction AddOkAction(UIAlertController controller, Action handler) { var action = UIAlertAction.Create(LocalOK, UIAlertActionStyle.Default, (_) => handler()); controller.AddAction(action); controller.PreferredAction = action; return action; } private static UIAlertAction AddCancelAction(UIAlertController controller, Action handler) { var action = UIAlertAction.Create(LocalCancel, UIAlertActionStyle.Cancel, (_) => handler()); controller.AddAction(action); return action; } private static void PresentAlertController( WKWebView webView, string message, string? defaultText = null, Action<UIAlertController>? okAction = null, Action<UIAlertController>? cancelAction = null) { var controller = UIAlertController.Create(GetJsAlertTitle(webView), message, UIAlertControllerStyle.Alert); if (defaultText != null) controller.AddTextField((textField) => textField.Text = defaultText); if (okAction != null) AddOkAction(controller, () => okAction(controller)); if (cancelAction != null) AddCancelAction(controller, () => cancelAction(controller)); #pragma warning disable CA1416 // TODO: 'UIApplication.Windows' is unsupported on: 'ios' 15.0 and later GetTopViewController(UIApplication.SharedApplication.Windows.FirstOrDefault(m => m.IsKeyWindow)?.RootViewController)? .PresentViewController(controller, true, null); #pragma warning restore CA1416 } private static UIViewController? GetTopViewController(UIViewController? viewController) { if (viewController is UINavigationController navigationController) return GetTopViewController(navigationController.VisibleViewController); if (viewController is UITabBarController tabBarController) return GetTopViewController(tabBarController.SelectedViewController!); if (viewController?.PresentedViewController != null) return GetTopViewController(viewController.PresentedViewController); return viewController; } } internal class WebViewNavigationDelegate : WKNavigationDelegate { private readonly BlazorWebViewHandler _webView; private WKNavigation? _currentNavigation; private Uri? _currentUri; public WebViewNavigationDelegate(BlazorWebViewHandler webView) { _webView = webView ?? throw new ArgumentNullException(nameof(webView)); } public override void DidStartProvisionalNavigation(WKWebView webView, WKNavigation navigation) { _currentNavigation = navigation; } public override void DecidePolicy(WKWebView webView, WKNavigationAction navigationAction, Action<WKNavigationActionPolicy> decisionHandler) { var requestUrl = navigationAction.Request.Url; UrlLoadingStrategy strategy; // TargetFrame is null for navigation to a new window (`_blank`) if (navigationAction.TargetFrame is null) { // Open in a new browser window regardless of UrlLoadingStrategy strategy = UrlLoadingStrategy.OpenExternally; } else { // Invoke the UrlLoading event to allow overriding the default link handling behavior var uri = new Uri(requestUrl.ToString()); var callbackArgs = UrlLoadingEventArgs.CreateWithDefaultLoadingStrategy(uri, BlazorWebViewHandler.AppOriginUri); _webView.UrlLoading(callbackArgs); strategy = callbackArgs.UrlLoadingStrategy; } if (strategy == UrlLoadingStrategy.OpenExternally) { #pragma warning disable CA1416 // TODO: OpenUrl(...) has [UnsupportedOSPlatform("ios10.0")] UIApplication.SharedApplication.OpenUrl(requestUrl); #pragma warning restore CA1416 } if (strategy != UrlLoadingStrategy.OpenInWebView) { // Cancel any further navigation as we've either opened the link in the external browser // or canceled the underlying navigation action. decisionHandler(WKNavigationActionPolicy.Cancel); return; } if (navigationAction.TargetFrame!.MainFrame) { _currentUri = requestUrl; } decisionHandler(WKNavigationActionPolicy.Allow); } public override void DidReceiveServerRedirectForProvisionalNavigation(WKWebView webView, WKNavigation navigation) { // We need to intercept the redirects to the app scheme because Safari will block them. // We will handle these redirects through the Navigation Manager. if (_currentUri?.Host == BlazorWebView.AppHostAddress) { var uri = _currentUri; _currentUri = null; _currentNavigation = null; var request = new NSUrlRequest(uri); webView.LoadRequest(request); } } public override void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error) { _currentUri = null; _currentNavigation = null; } public override void DidFailProvisionalNavigation(WKWebView webView, WKNavigation navigation, NSError error) { _currentUri = null; _currentNavigation = null; } public override void DidCommitNavigation(WKWebView webView, WKNavigation navigation) { if (_currentUri != null && _currentNavigation == navigation) { // TODO: Determine whether this is needed //_webView.HandleNavigationStarting(_currentUri); } } public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation) { if (_currentUri != null && _currentNavigation == navigation) { // TODO: Determine whether this is needed //_webView.HandleNavigationFinished(_currentUri); _currentUri = null; _currentNavigation = null; } } } } }
37.839344
284
0.750801
[ "MIT" ]
Axemasta/maui
src/BlazorWebView/src/Maui/iOS/IOSWebViewManager.cs
11,541
C#
using System; using System.Collections.Generic; using System.Linq; using Parser; namespace Semantics { public class GetClass { private static MMethod MethodFromDefinition(ConcreteMethodDeclarationSyntaxNode methodDefinition) { var name = methodDefinition.Name.Text; var description = ""; description += string.Join("", methodDefinition.LeadingTrivia.Select(x => x.FullText)); if (methodDefinition.Body == null) { description += string.Join("", methodDefinition.EndKeyword.LeadingTrivia.Select(x => x.FullText)); } else { description += string.Join("", methodDefinition.Body.LeadingTrivia.Select(x => x.FullText)); } return new MMethod(name, description); } private static MMethod MethodFromDeclaration(AbstractMethodDeclarationSyntaxNode methodDeclaration) { var name = methodDeclaration.Name.Text; var description = ""; description += string.Join("", methodDeclaration.LeadingTrivia.Select(x => x.FullText)); return new MMethod(name, description); } private static List<MMethod> MethodsFromList(MethodsListSyntaxNode methodsList) { var result = new List<MMethod>(); foreach (var method in methodsList.Methods) { if (method.IsToken) { continue; } if (method.AsNode() is ConcreteMethodDeclarationSyntaxNode methodDefinition) { result.Add(MethodFromDefinition(methodDefinition)); } if (method.AsNode() is AbstractMethodDeclarationSyntaxNode methodDeclaration) { result.Add(MethodFromDeclaration(methodDeclaration)); } } return result; } public static MClass FromTree(FileSyntaxNode tree, string fileName) { var classDeclaration = tree.Body.Statements[0].AsNode() as ClassDeclarationSyntaxNode; if (classDeclaration == null) { return null; } var name = classDeclaration.ClassName.Text; var methods = new List<MMethod>(); foreach (var s in classDeclaration.Nodes) { if (s.IsToken) { continue; } if (s.AsNode() is MethodsListSyntaxNode methodsList) { methods.AddRange(MethodsFromList(methodsList)); } } return new MClass(tree, name, fileName, methods); } } }
34.512195
114
0.54311
[ "MIT" ]
mahalex/MParser
Semantics/GetClass.cs
2,832
C#
using System; using System.Collections.Generic; namespace Alica { /// <summary> /// A capability definition set holds all defined capabilities. /// </summary> public class CapabilityDefinitionSet : PlanElement { public CapabilityDefinitionSet() { this.Capabilities = new List<Capability>(); } public List<Capability> Capabilities {get; private set;} } /// <summary> /// A capability is used to match agents to roles. /// </summary> public class Capability : PlanElement { protected List<CapValue> values; /// <summary> /// Gets the List of possible values for this capability /// </summary> /// <value> /// The cap values. /// </value> public List<CapValue> CapValues { get{ return this.values;} } public Capability() { this.values = new List<CapValue>(); } /// <summary> /// Computes the similarity between two capability values. /// </summary> /// <returns> /// The value, ranges between 0 and 1. /// </returns> /// <param name='roleVal'> /// Role value. /// </param> /// <param name='robotVal'> /// Robot value. /// </param> public double SimilarityValue(CapValue roleVal, CapValue robotVal) { int rlIndex = this.CapValues.IndexOf(roleVal); int rbIndex = this.CapValues.IndexOf(robotVal); double[,] sTable; SimilarityTable( out sTable ); return sTable[rlIndex,rbIndex]; } private void SimilarityTable( out double[,] sTable ) { int nCount = this.CapValues.Count; sTable = new double[nCount, nCount]; for(int i = 0; i < nCount; i++) { double k; for(int j = 0; j < nCount; j++) { k = nCount - Math.Abs(i-j)- 1; sTable[i,j] = k/(nCount-1); //s = s + sTable[i,j] + " "; } //Console.WriteLine(s); } } } /// <summary> /// A value for a <see cref="Capability"/>. /// </summary> public class CapValue : PlanElement { } }
20.978261
68
0.606736
[ "BSD-3-Clause-Clear" ]
RedundantEntry/cn-alica-ros-pkg
AlicaEngine/src/Engine/Model/CapabilityDefinitionSet.cs
1,930
C#
using UnityEngine.Events; namespace Console { [System.Serializable] public class CommandEvent : UnityEvent<string[]> { } public abstract class AbstractCommand : ICommand { public abstract string name {get; protected set;} public abstract string command {get; protected set;} public abstract string description {get; protected set;} public abstract string help {get; protected set;} public CommandEvent process { get; } public abstract bool OnCommand(string[] args); public AbstractCommand() { if (process == null) process = new CommandEvent(); process.AddListener((args) => { if (!OnCommand(args)) { GlobalConsole.Error($"Usage: {help}"); } }); } } }
31.111111
64
0.580952
[ "Apache-2.0" ]
lampask/steampunk-samurai
Assets/Scripts/Console/AbstractCommand.cs
842
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; #nullable enable namespace UnitsNet.NumberExtensions.NumberToElectricResistance { /// <summary> /// A number to ElectricResistance Extensions /// </summary> public static class NumberToElectricResistanceExtensions { /// <inheritdoc cref="ElectricResistance.FromGigaohms(UnitsNet.QuantityValue)" /> public static ElectricResistance Gigaohms<T>(this T value) => ElectricResistance.FromGigaohms(Convert.ToDouble(value)); /// <inheritdoc cref="ElectricResistance.FromKiloohms(UnitsNet.QuantityValue)" /> public static ElectricResistance Kiloohms<T>(this T value) => ElectricResistance.FromKiloohms(Convert.ToDouble(value)); /// <inheritdoc cref="ElectricResistance.FromMegaohms(UnitsNet.QuantityValue)" /> public static ElectricResistance Megaohms<T>(this T value) => ElectricResistance.FromMegaohms(Convert.ToDouble(value)); /// <inheritdoc cref="ElectricResistance.FromMicroohms(UnitsNet.QuantityValue)" /> public static ElectricResistance Microohms<T>(this T value) => ElectricResistance.FromMicroohms(Convert.ToDouble(value)); /// <inheritdoc cref="ElectricResistance.FromMilliohms(UnitsNet.QuantityValue)" /> public static ElectricResistance Milliohms<T>(this T value) => ElectricResistance.FromMilliohms(Convert.ToDouble(value)); /// <inheritdoc cref="ElectricResistance.FromOhms(UnitsNet.QuantityValue)" /> public static ElectricResistance Ohms<T>(this T value) => ElectricResistance.FromOhms(Convert.ToDouble(value)); } }
45.929825
125
0.674561
[ "MIT-feh" ]
AIKICo/UnitsNet
UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistanceExtensions.g.cs
2,618
C#
using System.Threading.Tasks; using Android.App; using Android.Content.PM; using Android.OS; using Android.Runtime; using Android.Support.V7.App; using WorldOfEnglishWord.BisnessLogic; using WorldOfEnglishWord.Translator; namespace WorldOfEnglishWord.Controllers { [Activity(ScreenOrientation = ScreenOrientation.Portrait, Label = "@string/app_name", Icon = "@drawable/ic_launcher", Theme = "@style/AppTheme", MainLauncher = true, NoHistory = true)] public class SplashScreenActivity : AppCompatActivity { private int counter; private bool isContinue; private Task sleeper; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); counter = 1; WordsLogic.GetInstance(); Task.Run(() => TranslatorApi.ZeroRequest()); SetContentView(Resource.Layout.splash_screen_view); } protected override void OnResume() { isContinue = true; base.OnResume(); sleeper = new Task(WaitingAsync); sleeper.Start(); } protected override void OnSaveInstanceState(Bundle outState) { base.OnSaveInstanceState(outState); outState.PutInt("counter", counter); } protected override void OnRestoreInstanceState(Bundle savedInstanceState) { base.OnRestoreInstanceState(savedInstanceState); counter = savedInstanceState.GetInt("counter"); } protected override void OnStop() { base.OnStop(); isContinue = false; } async void WaitingAsync() { while (counter < 928) { if (isContinue) { await Task.Delay(1); counter++; } } StartActivity(typeof(MainAppActivity)); Finish(); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
30.987342
188
0.612337
[ "MIT" ]
Bezuglyash/WorldOfEnglishWords
WorldOfEnglishWord/Controllers/SplashScreenActivity.cs
2,450
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ClosedXML.Excel; namespace ExcelView.Data { public class ExcelObj { //private XLWorkbook ImportWb; //private string ImportFileName; } }
17.866667
40
0.716418
[ "MIT" ]
ymd65536/ExcelView
Data/ExcelObj.cs
268
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.InterfaceCommander; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Timers; using System.Xml; using System.Xml.Serialization; namespace OpenSim.Region.OptionalModules.World.TreePopulator { /// <summary> /// Version 2.02 - Still hacky /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "TreePopulatorModule")] public class TreePopulatorModule : INonSharedRegionModule, ICommandableModule, IVegetationModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Commander m_commander = new Commander("tree"); private Scene m_scene; [XmlRootAttribute(ElementName = "Copse", IsNullable = false)] public class Copse { public string m_name; public Boolean m_frozen; public Tree m_tree_type; public int m_tree_quantity; public float m_treeline_low; public float m_treeline_high; public Vector3 m_seed_point; public double m_range; public Vector3 m_initial_scale; public Vector3 m_maximum_scale; public Vector3 m_rate; [XmlIgnore] public Boolean m_planted; [XmlIgnore] public List<UUID> m_trees; public Copse() { } public Copse(string fileName, Boolean planted) { Copse cp = (Copse)DeserializeObject(fileName); this.m_name = cp.m_name; this.m_frozen = cp.m_frozen; this.m_tree_quantity = cp.m_tree_quantity; this.m_treeline_high = cp.m_treeline_high; this.m_treeline_low = cp.m_treeline_low; this.m_range = cp.m_range; this.m_tree_type = cp.m_tree_type; this.m_seed_point = cp.m_seed_point; this.m_initial_scale = cp.m_initial_scale; this.m_maximum_scale = cp.m_maximum_scale; this.m_initial_scale = cp.m_initial_scale; this.m_rate = cp.m_rate; this.m_planted = planted; this.m_trees = new List<UUID>(); } public Copse(string copsedef) { char[] delimiterChars = {':', ';'}; string[] field = copsedef.Split(delimiterChars); this.m_name = field[1].Trim(); this.m_frozen = (copsedef[0] == 'F'); this.m_tree_quantity = int.Parse(field[2]); this.m_treeline_high = float.Parse(field[3], Culture.NumberFormatInfo); this.m_treeline_low = float.Parse(field[4], Culture.NumberFormatInfo); this.m_range = double.Parse(field[5], Culture.NumberFormatInfo); this.m_tree_type = (Tree) Enum.Parse(typeof(Tree),field[6]); this.m_seed_point = Vector3.Parse(field[7]); this.m_initial_scale = Vector3.Parse(field[8]); this.m_maximum_scale = Vector3.Parse(field[9]); this.m_rate = Vector3.Parse(field[10]); this.m_planted = true; this.m_trees = new List<UUID>(); } public Copse(string name, int quantity, float high, float low, double range, Vector3 point, Tree type, Vector3 scale, Vector3 max_scale, Vector3 rate, List<UUID> trees) { this.m_name = name; this.m_frozen = false; this.m_tree_quantity = quantity; this.m_treeline_high = high; this.m_treeline_low = low; this.m_range = range; this.m_tree_type = type; this.m_seed_point = point; this.m_initial_scale = scale; this.m_maximum_scale = max_scale; this.m_rate = rate; this.m_planted = false; this.m_trees = trees; } public override string ToString() { string frozen = (this.m_frozen ? "F" : "A"); return string.Format("{0}TPM: {1}; {2}; {3:0.0}; {4:0.0}; {5:0.0}; {6}; {7:0.0}; {8:0.0}; {9:0.0}; {10:0.00};", frozen, this.m_name, this.m_tree_quantity, this.m_treeline_high, this.m_treeline_low, this.m_range, this.m_tree_type, this.m_seed_point.ToString(), this.m_initial_scale.ToString(), this.m_maximum_scale.ToString(), this.m_rate.ToString()); } } private List<Copse> m_copse; private double m_update_ms = 1000.0; // msec between updates private bool m_active_trees = false; Timer CalculateTrees; #region ICommandableModule Members public ICommander CommandInterface { get { return m_commander; } } #endregion #region Region Module interface public void Initialise(IConfigSource config) { // ini file settings try { m_active_trees = config.Configs["Trees"].GetBoolean("active_trees", m_active_trees); } catch (Exception) { m_log.Debug("[TREES]: ini failure for active_trees - using default"); } try { m_update_ms = config.Configs["Trees"].GetDouble("update_rate", m_update_ms); } catch (Exception) { m_log.Debug("[TREES]: ini failure for update_rate - using default"); } InstallCommands(); m_log.Debug("[TREES]: Initialised tree module"); } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleCommander(m_commander); m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { ReloadCopse(); if (m_copse.Count > 0) m_log.Info("[TREES]: Copse load complete"); if (m_active_trees) activeizeTreeze(true); } public void Close() { } public string Name { get { return "TreePopulatorModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion //-------------------------------------------------------------- #region ICommandableModule Members private void HandleTreeActive(Object[] args) { if ((Boolean)args[0] && !m_active_trees) { m_log.InfoFormat("[TREES]: Activating Trees"); m_active_trees = true; activeizeTreeze(m_active_trees); } else if (!(Boolean)args[0] && m_active_trees) { m_log.InfoFormat("[TREES]: Trees module is no longer active"); m_active_trees = false; activeizeTreeze(m_active_trees); } else { m_log.InfoFormat("[TREES]: Trees module is already in the required state"); } } private void HandleTreeFreeze(Object[] args) { string copsename = ((string)args[0]).Trim(); Boolean freezeState = (Boolean) args[1]; foreach (Copse cp in m_copse) { if (cp.m_name == copsename && (!cp.m_frozen && freezeState || cp.m_frozen && !freezeState)) { cp.m_frozen = freezeState; foreach (UUID tree in cp.m_trees) { SceneObjectPart sop = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; sop.Name = (freezeState ? sop.Name.Replace("ATPM", "FTPM") : sop.Name.Replace("FTPM", "ATPM")); sop.ParentGroup.HasGroupChanged = true; } m_log.InfoFormat("[TREES]: Activity for copse {0} is frozen {1}", copsename, freezeState); return; } else if (cp.m_name == copsename && (cp.m_frozen && freezeState || !cp.m_frozen && !freezeState)) { m_log.InfoFormat("[TREES]: Copse {0} is already in the requested freeze state", copsename); return; } } m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename); } private void HandleTreeLoad(Object[] args) { Copse copse; m_log.InfoFormat("[TREES]: Loading copse definition...."); copse = new Copse(((string)args[0]), false); foreach (Copse cp in m_copse) { if (cp.m_name == copse.m_name) { m_log.InfoFormat("[TREES]: Copse: {0} is already defined - command failed", copse.m_name); return; } } m_copse.Add(copse); m_log.InfoFormat("[TREES]: Loaded copse: {0}", copse.ToString()); } private void HandleTreePlant(Object[] args) { string copsename = ((string)args[0]).Trim(); m_log.InfoFormat("[TREES]: New tree planting for copse {0}", copsename); UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; foreach (Copse copse in m_copse) { if (copse.m_name == copsename) { if (!copse.m_planted) { // The first tree for a copse is created here CreateTree(uuid, copse, copse.m_seed_point); copse.m_planted = true; return; } else { m_log.InfoFormat("[TREES]: Copse {0} has already been planted", copsename); } } } m_log.InfoFormat("[TREES]: Copse {0} not found for planting", copsename); } private void HandleTreeRate(Object[] args) { m_update_ms = (double)args[0]; if (m_update_ms >= 1000.0) { if (m_active_trees) { activeizeTreeze(false); activeizeTreeze(true); } m_log.InfoFormat("[TREES]: Update rate set to {0} mSec", m_update_ms); } else { m_log.InfoFormat("[TREES]: minimum rate is 1000.0 mSec - command failed"); } } private void HandleTreeReload(Object[] args) { if (m_active_trees) { CalculateTrees.Stop(); } ReloadCopse(); if (m_active_trees) { CalculateTrees.Start(); } } private void HandleTreeRemove(Object[] args) { string copsename = ((string)args[0]).Trim(); Copse copseIdentity = null; foreach (Copse cp in m_copse) { if (cp.m_name == copsename) { copseIdentity = cp; } } if (copseIdentity != null) { foreach (UUID tree in copseIdentity.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; // Delete tree and alert clients (not silent) m_scene.DeleteSceneObject(selectedTree.ParentGroup, false); } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } copseIdentity.m_trees = new List<UUID>(); m_copse.Remove(copseIdentity); m_log.InfoFormat("[TREES]: Copse {0} has been removed", copsename); } else { m_log.InfoFormat("[TREES]: Copse {0} was not found - command failed", copsename); } } private void HandleTreeStatistics(Object[] args) { m_log.InfoFormat("[TREES]: Activity State: {0}; Update Rate: {1}", m_active_trees, m_update_ms); foreach (Copse cp in m_copse) { m_log.InfoFormat("[TREES]: Copse {0}; {1} trees; frozen {2}", cp.m_name, cp.m_trees.Count, cp.m_frozen); } } private void InstallCommands() { Command treeActiveCommand = new Command("active", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeActive, "Change activity state for the trees module"); treeActiveCommand.AddArgument("activeTF", "The required activity state", "Boolean"); Command treeFreezeCommand = new Command("freeze", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeFreeze, "Freeze/Unfreeze activity for a defined copse"); treeFreezeCommand.AddArgument("copse", "The required copse", "String"); treeFreezeCommand.AddArgument("freezeTF", "The required freeze state", "Boolean"); Command treeLoadCommand = new Command("load", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeLoad, "Load a copse definition from an xml file"); treeLoadCommand.AddArgument("filename", "The (xml) file you wish to load", "String"); Command treePlantCommand = new Command("plant", CommandIntentions.COMMAND_HAZARDOUS, HandleTreePlant, "Start the planting on a copse"); treePlantCommand.AddArgument("copse", "The required copse", "String"); Command treeRateCommand = new Command("rate", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRate, "Reset the tree update rate (mSec)"); treeRateCommand.AddArgument("updateRate", "The required update rate (minimum 1000.0)", "Double"); Command treeReloadCommand = new Command("reload", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeReload, "Reload copse definitions from the in-scene trees"); Command treeRemoveCommand = new Command("remove", CommandIntentions.COMMAND_HAZARDOUS, HandleTreeRemove, "Remove a copse definition and all its in-scene trees"); treeRemoveCommand.AddArgument("copse", "The required copse", "String"); Command treeStatisticsCommand = new Command("statistics", CommandIntentions.COMMAND_STATISTICAL, HandleTreeStatistics, "Log statistics about the trees"); m_commander.RegisterCommand("active", treeActiveCommand); m_commander.RegisterCommand("freeze", treeFreezeCommand); m_commander.RegisterCommand("load", treeLoadCommand); m_commander.RegisterCommand("plant", treePlantCommand); m_commander.RegisterCommand("rate", treeRateCommand); m_commander.RegisterCommand("reload", treeReloadCommand); m_commander.RegisterCommand("remove", treeRemoveCommand); m_commander.RegisterCommand("statistics", treeStatisticsCommand); } /// <summary> /// Processes commandline input. Do not call directly. /// </summary> /// <param name="args">Commandline arguments</param> private void EventManager_OnPluginConsole(string[] args) { if (args[0] == "tree") { if (args.Length == 1) { m_commander.ProcessConsoleCommand("help", new string[0]); return; } string[] tmpArgs = new string[args.Length - 2]; int i; for (i = 2; i < args.Length; i++) { tmpArgs[i - 2] = args[i]; } m_commander.ProcessConsoleCommand(args[1], tmpArgs); } } #endregion #region IVegetationModule Members public SceneObjectGroup AddTree( UUID uuid, UUID groupID, Vector3 scale, Quaternion rotation, Vector3 position, Tree treeType, bool newTree) { PrimitiveBaseShape treeShape = new PrimitiveBaseShape(); treeShape.PathCurve = 16; treeShape.PathEnd = 49900; treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree; treeShape.Scale = scale; treeShape.State = (byte)treeType; return m_scene.AddNewPrim(uuid, groupID, position, rotation, treeShape); } #endregion #region IEntityCreator Members protected static readonly PCode[] creationCapabilities = new PCode[] { PCode.NewTree, PCode.Tree }; public PCode[] CreationCapabilities { get { return creationCapabilities; } } public SceneObjectGroup CreateEntity( UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape) { if (Array.IndexOf(creationCapabilities, (PCode)shape.PCode) < 0) { m_log.DebugFormat("[VEGETATION]: PCode {0} not handled by {1}", shape.PCode, Name); return null; } SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape); SceneObjectPart rootPart = sceneObject.GetPart(sceneObject.UUID); rootPart.AddFlag(PrimFlags.Phantom); m_scene.AddNewSceneObject(sceneObject, true); sceneObject.SetGroup(groupID, null); return sceneObject; } #endregion //-------------------------------------------------------------- #region Tree Utilities static public void SerializeObject(string fileName, Object obj) { try { XmlSerializer xs = new XmlSerializer(typeof(Copse)); using (XmlTextWriter writer = new XmlTextWriter(fileName, Util.UTF8)) { writer.Formatting = Formatting.Indented; xs.Serialize(writer, obj); } } catch (SystemException ex) { throw new ApplicationException("Unexpected failure in Tree serialization", ex); } } static public object DeserializeObject(string fileName) { try { XmlSerializer xs = new XmlSerializer(typeof(Copse)); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) return xs.Deserialize(fs); } catch (SystemException ex) { throw new ApplicationException("Unexpected failure in Tree de-serialization", ex); } } private void ReloadCopse() { m_copse = new List<Copse>(); EntityBase[] objs = m_scene.GetEntities(); foreach (EntityBase obj in objs) { if (obj is SceneObjectGroup) { SceneObjectGroup grp = (SceneObjectGroup)obj; if (grp.Name.Length > 5 && (grp.Name.Substring(0, 5) == "ATPM:" || grp.Name.Substring(0, 5) == "FTPM:")) { // Create a new copse definition or add uuid to an existing definition try { Boolean copsefound = false; Copse copse = new Copse(grp.Name); foreach (Copse cp in m_copse) { if (cp.m_name == copse.m_name) { copsefound = true; cp.m_trees.Add(grp.UUID); //m_log.DebugFormat("[TREES]: Found tree {0}", grp.UUID); } } if (!copsefound) { m_log.InfoFormat("[TREES]: Found copse {0}", grp.Name); m_copse.Add(copse); copse.m_trees.Add(grp.UUID); } } catch { m_log.InfoFormat("[TREES]: Ill formed copse definition {0} - ignoring", grp.Name); } } } } } #endregion private void activeizeTreeze(bool activeYN) { if (activeYN) { CalculateTrees = new Timer(m_update_ms); CalculateTrees.Elapsed += CalculateTrees_Elapsed; CalculateTrees.Start(); } else { CalculateTrees.Stop(); } } private void growTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen) { foreach (UUID tree in copse.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; if (s_tree.Scale.X < copse.m_maximum_scale.X && s_tree.Scale.Y < copse.m_maximum_scale.Y && s_tree.Scale.Z < copse.m_maximum_scale.Z) { s_tree.Scale += copse.m_rate; s_tree.ParentGroup.HasGroupChanged = true; s_tree.ScheduleFullUpdate(); } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void seedTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen) { foreach (UUID tree in copse.m_trees) { if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart s_tree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; if (copse.m_trees.Count < copse.m_tree_quantity) { // Tree has grown enough to seed if it has grown by at least 25% of seeded to full grown height if (s_tree.Scale.Z > copse.m_initial_scale.Z + (copse.m_maximum_scale.Z - copse.m_initial_scale.Z) / 4.0) { if (Util.RandomClass.NextDouble() > 0.75) { SpawnChild(copse, s_tree); } } } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void killTrees() { foreach (Copse copse in m_copse) { if (!copse.m_frozen && copse.m_trees.Count >= copse.m_tree_quantity) { foreach (UUID tree in copse.m_trees) { double killLikelyhood = 0.0; if (m_scene.Entities.ContainsKey(tree)) { SceneObjectPart selectedTree = ((SceneObjectGroup)m_scene.Entities[tree]).RootPart; double selectedTreeScale = Math.Sqrt(Math.Pow(selectedTree.Scale.X, 2) + Math.Pow(selectedTree.Scale.Y, 2) + Math.Pow(selectedTree.Scale.Z, 2)); foreach (UUID picktree in copse.m_trees) { if (picktree != tree) { SceneObjectPart pickedTree = ((SceneObjectGroup)m_scene.Entities[picktree]).RootPart; double pickedTreeScale = Math.Sqrt(Math.Pow(pickedTree.Scale.X, 2) + Math.Pow(pickedTree.Scale.Y, 2) + Math.Pow(pickedTree.Scale.Z, 2)); double pickedTreeDistance = Vector3.Distance(pickedTree.AbsolutePosition, selectedTree.AbsolutePosition); killLikelyhood += (selectedTreeScale / (pickedTreeScale * pickedTreeDistance)) * 0.1; } } if (Util.RandomClass.NextDouble() < killLikelyhood) { // Delete tree and alert clients (not silent) m_scene.DeleteSceneObject(selectedTree.ParentGroup, false); copse.m_trees.Remove(selectedTree.ParentGroup.UUID); break; } } else { m_log.DebugFormat("[TREES]: Tree not in scene {0}", tree); } } } } } private void SpawnChild(Copse copse, SceneObjectPart s_tree) { Vector3 position = new Vector3(); double randX = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); double randY = ((Util.RandomClass.NextDouble() * 2.0) - 1.0) * (s_tree.Scale.X * 3); position.X = s_tree.AbsolutePosition.X + (float)randX; position.Y = s_tree.AbsolutePosition.Y + (float)randY; if (position.X <= (m_scene.RegionInfo.RegionSizeX - 1) && position.X >= 0 && position.Y <= (m_scene.RegionInfo.RegionSizeY - 1) && position.Y >= 0 && Util.GetDistanceTo(position, copse.m_seed_point) <= copse.m_range) { UUID uuid = m_scene.RegionInfo.EstateSettings.EstateOwner; CreateTree(uuid, copse, position); } } private void CreateTree(UUID uuid, Copse copse, Vector3 position) { position.Z = (float)m_scene.Heightmap[(int)position.X, (int)position.Y]; if (position.Z >= copse.m_treeline_low && position.Z <= copse.m_treeline_high) { SceneObjectGroup tree = AddTree(uuid, UUID.Zero, copse.m_initial_scale, Quaternion.Identity, position, copse.m_tree_type, false); tree.Name = copse.ToString(); copse.m_trees.Add(tree.UUID); tree.SendGroupFullUpdate(); } } private void CalculateTrees_Elapsed(object sender, ElapsedEventArgs e) { growTrees(); seedTrees(); killTrees(); } } }
38.711367
180
0.50546
[ "BSD-3-Clause" ]
Michelle-Argus/ArribasimExtract
OpenSim/Region/OptionalModules/World/TreePopulator/TreePopulatorModule.cs
30,311
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TBD.Psi.Study.Analysis { class Program { static void Main(string[] args) { // SingleFileTestAsync.Run(); // SingleFileTest.Run(); Analysis2DToCSV.Run(); // InterpolationTest.Run(); } } }
19.95
41
0.591479
[ "MIT" ]
CMU-TBD/psi
TBD/TBD.Psi.Study.Analysis/Program.cs
401
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AdventOfCode2020.Star2 { public class Star2 { public static int GetMultiplyExpensesEqualsTo2020() { string pathExpenses = Environment.CurrentDirectory + @"\input.dat"; int result = 0; List<int> expenses = File.ReadAllLines(pathExpenses).Select(number => int.Parse(number)).ToList(); expenses.ForEach(expense1 => expenses.ForEach(expense2 => expenses.ForEach(expense3 => { if (expense1 + expense2 + expense3 == 2020) { result = expense1 * expense2 * expense3; } }))); return result; } } }
28.607143
111
0.548065
[ "MIT" ]
alan-garcia/advent-of-code-2020
AdventOfCode2020/Day1/Star2/Star2.cs
803
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using Newtonsoft.Json; namespace osu.Game.Rulesets.Mods { public interface IMod { /// <summary> /// The shortened name of this mod. /// </summary> [JsonProperty("acronym")] string Acronym { get; } } }
24.823529
93
0.597156
[ "MIT" ]
Dragicafit/osu
osu.Game/Rulesets/Mods/IMod.cs
408
C#
using System; namespace SolutionEleven { class Program { static void Main(string[] args) { int age = int.Parse(Console.ReadLine()); Console.WriteLine($"You look older than {age}"); } } }
17.785714
60
0.538153
[ "MIT" ]
georgidelchev/w3resource-solutions
01 - [CSharp Exercises]/01 - [C# Basic Exercises]/11 - [Taking Age And Prints Some Text]/Program.cs
251
C#
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_Collider2D : LuaObject { [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int constructor(IntPtr l) { try { UnityEngine.Collider2D o; o=new UnityEngine.Collider2D(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int IsTouching(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Collider2D a1; checkType(l,2,out a1); var ret=self.IsTouching(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int IsTouchingLayers(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==1){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); var ret=self.IsTouchingLayers(); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==2){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); var ret=self.IsTouchingLayers(a1); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int OverlapPoint(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); var ret=self.OverlapPoint(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Raycast(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==3){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); var ret=self.Raycast(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); var ret=self.Raycast(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==5){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); System.Int32 a4; checkType(l,5,out a4); var ret=self.Raycast(a1,a2,a3,a4); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==6){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); System.Int32 a4; checkType(l,5,out a4); System.Single a5; checkType(l,6,out a5); var ret=self.Raycast(a1,a2,a3,a4,a5); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==7){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); System.Int32 a4; checkType(l,5,out a4); System.Single a5; checkType(l,6,out a5); System.Single a6; checkType(l,7,out a6); var ret=self.Raycast(a1,a2,a3,a4,a5,a6); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int Cast(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if(argc==3){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); var ret=self.Cast(a1,a2); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==4){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); var ret=self.Cast(a1,a2,a3); pushValue(l,true); pushValue(l,ret); return 2; } else if(argc==5){ UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 a1; checkType(l,2,out a1); UnityEngine.RaycastHit2D[] a2; checkArray(l,3,out a2); System.Single a3; checkType(l,4,out a3); System.Boolean a4; checkType(l,5,out a4); var ret=self.Cast(a1,a2,a3,a4); pushValue(l,true); pushValue(l,ret); return 2; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function to call"); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_density(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.density); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_density(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); float v; checkType(l,2,out v); self.density=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_isTrigger(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.isTrigger); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_isTrigger(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); bool v; checkType(l,2,out v); self.isTrigger=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_usedByEffector(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.usedByEffector); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_usedByEffector(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); bool v; checkType(l,2,out v); self.usedByEffector=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_offset(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.offset); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_offset(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.Vector2 v; checkType(l,2,out v); self.offset=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_attachedRigidbody(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.attachedRigidbody); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_shapeCount(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.shapeCount); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_bounds(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.bounds); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int get_sharedMaterial(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); pushValue(l,true); pushValue(l,self.sharedMaterial); return 2; } catch(Exception e) { return error(l,e); } } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static public int set_sharedMaterial(IntPtr l) { try { UnityEngine.Collider2D self=(UnityEngine.Collider2D)checkSelf(l); UnityEngine.PhysicsMaterial2D v; checkType(l,2,out v); self.sharedMaterial=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } } static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.Collider2D"); addMember(l,IsTouching); addMember(l,IsTouchingLayers); addMember(l,OverlapPoint); addMember(l,Raycast); addMember(l,Cast); addMember(l,"density",get_density,set_density,true); addMember(l,"isTrigger",get_isTrigger,set_isTrigger,true); addMember(l,"usedByEffector",get_usedByEffector,set_usedByEffector,true); addMember(l,"offset",get_offset,set_offset,true); addMember(l,"attachedRigidbody",get_attachedRigidbody,null,true); addMember(l,"shapeCount",get_shapeCount,null,true); addMember(l,"bounds",get_bounds,null,true); addMember(l,"sharedMaterial",get_sharedMaterial,set_sharedMaterial,true); createTypeMetatable(l,constructor, typeof(UnityEngine.Collider2D),typeof(UnityEngine.Behaviour)); } }
26.318296
99
0.690791
[ "MIT" ]
zhangjie0072/FairyGUILearn
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_Collider2D.cs
10,503
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace DotNetify { public static class MixinsVM { public static void AcceptChangedProperties(this IBaseVM vm) { vm.ChangedProperties.Clear(); } public static void Ignore<T>(this IBaseVM vm, Expression<Func<T>> expression) { var propertyName = ((MemberExpression)expression.Body).Member.Name; if (!vm.IgnoredProperties.Contains(propertyName)) vm.IgnoredProperties.Add(propertyName); } } }
26.12
85
0.660031
[ "Apache-2.0" ]
lrhmx/dotNetify
DotNetifyLib.Core/MixinsVM.cs
655
C#
/* Copyright (C) 2020 Jean-Camille Tournier (mail@tournierjc.fr) This file is part of QLCore Project https://github.com/OpenDerivatives/QLCore QLCore is free software: you can redistribute it and/or modify it under the terms of the QLCore and QLNet license. You should have received a copy of the license along with this program; if not, license is available at https://github.com/OpenDerivatives/QLCore/LICENSE. QLCore is a forked of QLNet which is a based on QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ The QuantLib license is available online at http://quantlib.org/license.shtml and the QLNet license is available online at https://github.com/amaggiulli/QLNet/blob/develop/LICENSE. 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 PARTICAR PURPOSE. See the license for more details. */ using System; using System.Collections.Generic; using Xunit; using QLCore; namespace TestSuite { public class T_CapFlooredCoupon { private class CommonVars { // global data public Date today, settlement, startDate; public Calendar calendar; public double nominal; public List<double> nominals; public BusinessDayConvention convention; public Frequency frequency; public IborIndex index; public int settlementDays, fixingDays; public RelinkableHandle<YieldTermStructure> termStructure ; //public List<double> caps; //public List<double> floors; public int length; public double volatility; // cleanup public Settings settings; // setup public CommonVars() { termStructure = new RelinkableHandle<YieldTermStructure>(); settings = new Settings(); length = 20; //years volatility = 0.20; nominal = 100.0; nominals = new InitializedList<double>(length, nominal); frequency = Frequency.Annual; index = new Euribor1Y(settings, termStructure); calendar = index.fixingCalendar(); convention = BusinessDayConvention.ModifiedFollowing; today = calendar.adjust(Date.Today); settings.setEvaluationDate(today); settlementDays = 2; fixingDays = 2; settlement = calendar.advance(today, settlementDays, TimeUnit.Days); startDate = settlement; termStructure.linkTo(Utilities.flatRate(settings, settlement, 0.05, new ActualActual(ActualActual.Convention.ISDA))); } // utilities public List<CashFlow> makeFixedLeg(Date sDate, int len) { Date endDate = calendar.advance(sDate, len, TimeUnit.Years, convention); Schedule schedule = new Schedule(settings, sDate, endDate, new Period(frequency), calendar, convention, convention, DateGeneration.Rule.Forward, false); List<double> coupons = new InitializedList<double>(len, 0.0); return new FixedRateLeg(schedule) .withCouponRates(coupons, new Thirty360()) .withNotionals(nominals); } public List<CashFlow> makeFloatingLeg(Date sDate, int len, double gearing = 1.0, double spread = 0.0) { Date endDate = calendar.advance(sDate, len, TimeUnit.Years, convention); Schedule schedule = new Schedule(settings, sDate, endDate, new Period(frequency), calendar, convention, convention, DateGeneration.Rule.Forward, false); List<double> gearingVector = new InitializedList<double>(len, gearing); List<double> spreadVector = new InitializedList<double>(len, spread); return new IborLeg(schedule, index) .withPaymentDayCounter(index.dayCounter()) .withFixingDays(fixingDays) .withGearings(gearingVector) .withSpreads(spreadVector) .withNotionals(nominals) .withPaymentAdjustment(convention); } public List<CashFlow> makeCapFlooredLeg(Date sDate, int len, List < double? > caps, List < double? > floors, double volatility, double gearing = 1.0, double spread = 0.0) { Date endDate = calendar.advance(sDate, len, TimeUnit.Years, convention); Schedule schedule = new Schedule(settings, sDate, endDate, new Period(frequency), calendar, convention, convention, DateGeneration.Rule.Forward, false); Handle<OptionletVolatilityStructure> vol = new Handle<OptionletVolatilityStructure>(new ConstantOptionletVolatility(settings, 0, calendar, BusinessDayConvention.Following, volatility, new Actual365Fixed())); IborCouponPricer pricer = new BlackIborCouponPricer(vol); List<double> gearingVector = new InitializedList<double>(len, gearing); List<double> spreadVector = new InitializedList<double>(len, spread); List<CashFlow> iborLeg = new IborLeg(schedule, index) .withFloors(floors) .withPaymentDayCounter(index.dayCounter()) .withFixingDays(fixingDays) .withGearings(gearingVector) .withSpreads(spreadVector) .withCaps(caps) .withNotionals(nominals) .withPaymentAdjustment(convention); Utils.setCouponPricer(iborLeg, pricer); return iborLeg; } public IPricingEngine makeEngine(double vols) { Handle<Quote> vol = new Handle<Quote>(new SimpleQuote(vols)); return new BlackCapFloorEngine(termStructure, vol); } public CapFloor makeCapFloor(CapFloorType type, List<CashFlow> leg, double capStrike, double floorStrike, double vol) { CapFloor result = null; switch (type) { case CapFloorType.Cap: result = new Cap(settings, leg, new InitializedList<double>(1, capStrike)); break; case CapFloorType.Floor: result = new Floor(settings, leg, new InitializedList<double>(1, floorStrike)); break; case CapFloorType.Collar: result = new Collar(settings, leg, new InitializedList<double>(1, capStrike), new InitializedList<double>(1, floorStrike)); break; default: Utils.QL_FAIL("unknown cap/floor type"); break; } result.setPricingEngine(makeEngine(vol)); return result; } } [Fact] public void testLargeRates() { // Testing degenerate collared coupon CommonVars vars = new CommonVars(); /* A vanilla floating leg and a capped floating leg with strike equal to 100 and floor equal to 0 must have (about) the same NPV (depending on variance: option expiry and volatility) */ List < double? > caps = new InitializedList < double? >(vars.length, 100.0); List < double? > floors = new InitializedList < double? >(vars.length, 0.0); double tolerance = 1e-10; // fixed leg with zero rate List<CashFlow> fixedLeg = vars.makeFixedLeg(vars.startDate, vars.length); List<CashFlow> floatLeg = vars.makeFloatingLeg(vars.startDate, vars.length); List<CashFlow> collaredLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors, vars.volatility); IPricingEngine engine = new DiscountingSwapEngine(vars.termStructure); Swap vanillaLeg = new Swap(vars.settings, fixedLeg, floatLeg); Swap collarLeg = new Swap(vars.settings, fixedLeg, collaredLeg); vanillaLeg.setPricingEngine(engine); collarLeg.setPricingEngine(engine); double npvVanilla = vanillaLeg.NPV(); double npvCollar = collarLeg.NPV(); if (Math.Abs(npvVanilla - npvCollar) > tolerance) { QAssert.Fail("Lenght: " + vars.length + " y" + "\n" + "Volatility: " + vars.volatility * 100 + "%\n" + "Notional: " + vars.nominal + "\n" + "Vanilla floating leg NPV: " + vanillaLeg.NPV() + "\n" + "Collared floating leg NPV (strikes 0 and 100): " + collarLeg.NPV() + "\n" + "Diff: " + Math.Abs(vanillaLeg.NPV() - collarLeg.NPV())); } } [Fact] public void testDecomposition() { // Testing collared coupon against its decomposition CommonVars vars = new CommonVars(); double tolerance = 1e-12; double npvVanilla, npvCappedLeg, npvFlooredLeg, npvCollaredLeg, npvCap, npvFloor, npvCollar; double error; double floorstrike = 0.05; double capstrike = 0.10; List < double? > caps = new InitializedList < double? >(vars.length, capstrike); List < double? > caps0 = new List < double? >(); List < double? > floors = new InitializedList < double? >(vars.length, floorstrike); List < double? > floors0 = new List < double? >(); double gearing_p = 0.5; double spread_p = 0.002; double gearing_n = -1.5; double spread_n = 0.12; // fixed leg with zero rate List<CashFlow> fixedLeg = vars.makeFixedLeg(vars.startDate, vars.length); // floating leg with gearing=1 and spread=0 List<CashFlow> floatLeg = vars.makeFloatingLeg(vars.startDate, vars.length); // floating leg with positive gearing (gearing_p) and spread<>0 List<CashFlow> floatLeg_p = vars.makeFloatingLeg(vars.startDate, vars.length, gearing_p, spread_p); // floating leg with negative gearing (gearing_n) and spread<>0 List<CashFlow> floatLeg_n = vars.makeFloatingLeg(vars.startDate, vars.length, gearing_n, spread_n); // Swap with null fixed leg and floating leg with gearing=1 and spread=0 Swap vanillaLeg = new Swap(vars.settings, fixedLeg, floatLeg); // Swap with null fixed leg and floating leg with positive gearing and spread<>0 Swap vanillaLeg_p = new Swap(vars.settings, fixedLeg, floatLeg_p); // Swap with null fixed leg and floating leg with negative gearing and spread<>0 Swap vanillaLeg_n = new Swap(vars.settings, fixedLeg, floatLeg_n); IPricingEngine engine = new DiscountingSwapEngine(vars.termStructure); vanillaLeg.setPricingEngine(engine); vanillaLeg_p.setPricingEngine(engine); vanillaLeg_n.setPricingEngine(engine); /* CAPPED coupon - Decomposition of payoff Payoff = Nom * Min(rate,strike) * accrualperiod = = Nom * [rate + Min(0,strike-rate)] * accrualperiod = = Nom * rate * accrualperiod - Nom * Max(rate-strike,0) * accrualperiod = = VanillaFloatingLeg - Call */ // Case gearing = 1 and spread = 0 List<CashFlow> cappedLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0, vars.volatility); Swap capLeg = new Swap(vars.settings, fixedLeg, cappedLeg); capLeg.setPricingEngine(engine); Cap cap = new Cap(vars.settings, floatLeg, new InitializedList<double>(1, capstrike)); cap.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg.NPV(); npvCappedLeg = capLeg.NPV(); npvCap = cap.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla - npvCap)); if (error > tolerance) { QAssert.Fail("\nCapped Leg: gearing=1, spread=0%, strike=" + capstrike * 100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error); } /* gearing = 1 and spread = 0 FLOORED coupon - Decomposition of payoff Payoff = Nom * Max(rate,strike) * accrualperiod = = Nom * [rate + Max(0,strike-rate)] * accrualperiod = = Nom * rate * accrualperiod + Nom * Max(strike-rate,0) * accrualperiod = = VanillaFloatingLeg + Put */ List<CashFlow> flooredLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors, vars.volatility); Swap floorLeg = new Swap(vars.settings, fixedLeg, flooredLeg); floorLeg.setPricingEngine(engine); Floor floor = new Floor(vars.settings, floatLeg, new InitializedList<double>(1, floorstrike)); floor.setPricingEngine(vars.makeEngine(vars.volatility)); npvFlooredLeg = floorLeg.NPV(); npvFloor = floor.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor)); if (error > tolerance) { QAssert.Fail("Floored Leg: gearing=1, spread=0%, strike=" + floorstrike * 100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error); } /* gearing = 1 and spread = 0 COLLARED coupon - Decomposition of payoff Payoff = Nom * Min(strikem,Max(rate,strikeM)) * accrualperiod = = VanillaFloatingLeg - Collar */ List<CashFlow> collaredLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors, vars.volatility); Swap collarLeg = new Swap(vars.settings, fixedLeg, collaredLeg); collarLeg.setPricingEngine(engine); Collar collar = new Collar(vars.settings, floatLeg, new InitializedList<double>(1, capstrike), new InitializedList<double>(1, floorstrike)); collar.setPricingEngine(vars.makeEngine(vars.volatility)); npvCollaredLeg = collarLeg.NPV(); npvCollar = collar.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar)); if (error > tolerance) { QAssert.Fail("\nCollared Leg: gearing=1, spread=0%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error); } /* gearing = a and spread = b CAPPED coupon - Decomposition of payoff Payoff = Nom * Min(a*rate+b,strike) * accrualperiod = = Nom * [a*rate+b + Min(0,strike-a*rate-b)] * accrualperiod = = Nom * a*rate+b * accrualperiod + Nom * Min(strike-b-a*rate,0) * accrualperiod --> If a>0 (assuming positive effective strike): Payoff = VanillaFloatingLeg - Call(a*rate+b,strike) --> If a<0 (assuming positive effective strike): Payoff = VanillaFloatingLeg + Nom * Min(strike-b+|a|*rate+,0) * accrualperiod = = VanillaFloatingLeg + Put(|a|*rate+b,strike) */ // Positive gearing List<CashFlow> cappedLeg_p = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0, vars.volatility, gearing_p, spread_p); Swap capLeg_p = new Swap(vars.settings, fixedLeg, cappedLeg_p); capLeg_p.setPricingEngine(engine); Cap cap_p = new Cap(vars.settings, floatLeg_p, new InitializedList<double>(1, capstrike)); cap_p.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_p.NPV(); npvCappedLeg = capLeg_p.NPV(); npvCap = cap_p.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla - npvCap)); if (error > tolerance) { QAssert.Fail("\nCapped Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + capstrike * 100 + "%, " + "effective strike= " + (capstrike - spread_p) / gearing_p * 100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " Vanilla Leg NPV: " + npvVanilla + "\n" + " Cap NPV: " + npvCap + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" + " Diff: " + error); } // Negative gearing List<CashFlow> cappedLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0, vars.volatility, gearing_n, spread_n); Swap capLeg_n = new Swap(vars.settings, fixedLeg, cappedLeg_n); capLeg_n.setPricingEngine(engine); Floor floor_n = new Floor(vars.settings, floatLeg, new InitializedList<double>(1, (capstrike - spread_n) / gearing_n)); floor_n.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_n.NPV(); npvCappedLeg = capLeg_n.NPV(); npvFloor = floor_n.NPV(); error = Math.Abs(npvCappedLeg - (npvVanilla + gearing_n * npvFloor)); if (error > tolerance) { QAssert.Fail("\nCapped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + capstrike * 100 + "%, " + "effective strike= " + (capstrike - spread_n) / gearing_n * 100 + "%\n" + " Capped Floating Leg NPV: " + npvCappedLeg + "\n" + " npv Vanilla: " + npvVanilla + "\n" + " npvFloor: " + npvFloor + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla + gearing_n * npvFloor) + "\n" + " Diff: " + error); } /* gearing = a and spread = b FLOORED coupon - Decomposition of payoff Payoff = Nom * Max(a*rate+b,strike) * accrualperiod = = Nom * [a*rate+b + Max(0,strike-a*rate-b)] * accrualperiod = = Nom * a*rate+b * accrualperiod + Nom * Max(strike-b-a*rate,0) * accrualperiod --> If a>0 (assuming positive effective strike): Payoff = VanillaFloatingLeg + Put(a*rate+b,strike) --> If a<0 (assuming positive effective strike): Payoff = VanillaFloatingLeg + Nom * Max(strike-b+|a|*rate+,0) * accrualperiod = = VanillaFloatingLeg - Call(|a|*rate+b,strike) */ // Positive gearing List<CashFlow> flooredLeg_p1 = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors, vars.volatility, gearing_p, spread_p); Swap floorLeg_p1 = new Swap(vars.settings, fixedLeg, flooredLeg_p1); floorLeg_p1.setPricingEngine(engine); Floor floor_p1 = new Floor(vars.settings, floatLeg_p, new InitializedList<double>(1, floorstrike)); floor_p1.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_p.NPV(); npvFlooredLeg = floorLeg_p1.NPV(); npvFloor = floor_p1.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor)); if (error > tolerance) { QAssert.Fail("\nFloored Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + floorstrike * 100 + "%, " + "effective strike= " + (floorstrike - spread_p) / gearing_p * 100 + "%\n" + " Floored Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" + " Diff: " + error); } // Negative gearing List<CashFlow> flooredLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors, vars.volatility, gearing_n, spread_n); Swap floorLeg_n = new Swap(vars.settings, fixedLeg, flooredLeg_n); floorLeg_n.setPricingEngine(engine); Cap cap_n = new Cap(vars.settings, floatLeg, new InitializedList<double>(1, (floorstrike - spread_n) / gearing_n)); cap_n.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_n.NPV(); npvFlooredLeg = floorLeg_n.NPV(); npvCap = cap_n.NPV(); error = Math.Abs(npvFlooredLeg - (npvVanilla - gearing_n * npvCap)); if (error > tolerance) { QAssert.Fail("\nCapped Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + floorstrike * 100 + "%, " + "effective strike= " + (floorstrike - spread_n) / gearing_n * 100 + "%\n" + " Capped Floating Leg NPV: " + npvFlooredLeg + "\n" + " Floating Leg NPV - Cap NPV: " + (npvVanilla - gearing_n * npvCap) + "\n" + " Diff: " + error); } /* gearing = a and spread = b COLLARED coupon - Decomposition of payoff Payoff = Nom * Min(caprate,Max(a*rate+b,floorrate)) * accrualperiod --> If a>0 (assuming positive effective strike): Payoff = VanillaFloatingLeg - Collar(a*rate+b, floorrate, caprate) --> If a<0 (assuming positive effective strike): Payoff = VanillaFloatingLeg + Collar(|a|*rate+b, caprate, floorrate) */ // Positive gearing List<CashFlow> collaredLeg_p = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors, vars.volatility, gearing_p, spread_p); Swap collarLeg_p1 = new Swap(vars.settings, fixedLeg, collaredLeg_p); collarLeg_p1.setPricingEngine(engine); Collar collar_p = new Collar(vars.settings, floatLeg_p, new InitializedList<double>(1, capstrike), new InitializedList<double>(1, floorstrike)); collar_p.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_p.NPV(); npvCollaredLeg = collarLeg_p1.NPV(); npvCollar = collar_p.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar)); if (error > tolerance) { QAssert.Fail("\nCollared Leg: gearing=" + gearing_p + ", " + "spread= " + spread_p * 100 + "%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%, " + "effective strike=" + (floorstrike - spread_p) / gearing_p * 100 + "% and " + (capstrike - spread_p) / gearing_p * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" + " Diff: " + error); } // Negative gearing List<CashFlow> collaredLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors, vars.volatility, gearing_n, spread_n); Swap collarLeg_n1 = new Swap(vars.settings, fixedLeg, collaredLeg_n); collarLeg_n1.setPricingEngine(engine); Collar collar_n = new Collar(vars.settings, floatLeg, new InitializedList<double>(1, (floorstrike - spread_n) / gearing_n), new InitializedList<double>(1, (capstrike - spread_n) / gearing_n)); collar_n.setPricingEngine(vars.makeEngine(vars.volatility)); npvVanilla = vanillaLeg_n.NPV(); npvCollaredLeg = collarLeg_n1.NPV(); npvCollar = collar_n.NPV(); error = Math.Abs(npvCollaredLeg - (npvVanilla - gearing_n * npvCollar)); if (error > tolerance) { QAssert.Fail("\nCollared Leg: gearing=" + gearing_n + ", " + "spread= " + spread_n * 100 + "%, strike=" + floorstrike * 100 + "% and " + capstrike * 100 + "%, " + "effective strike=" + (floorstrike - spread_n) / gearing_n * 100 + "% and " + (capstrike - spread_n) / gearing_n * 100 + "%\n" + " Collared Floating Leg NPV: " + npvCollaredLeg + "\n" + " Floating Leg NPV - Collar NPV: " + (npvVanilla - gearing_n * npvCollar) + "\n" + " Diff: " + error); } } } }
51.808383
137
0.556442
[ "BSD-3-Clause" ]
OpenDerivatives/QLCore
QLCore.Tests/T_CapFlooredCoupon.cs
25,958
C#
using App.Core; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace XPaint { /// <summary> /// 工具类别 /// </summary> public enum ToolType { [UI("平移")] Hand, [UI("选择")] Select, [UI("自定义")] Custom, // [UI("文本")] Text, [UI("线段")] Line, [UI("箭头")] Arrow, [UI("矩形")] Rect, [UI("圆角矩形")] RoundedRect, [UI("椭圆")] Ellipse, // [UI("三角形")] Triangle, [UI("星形")] Star, [UI("多边线")] Polyline, [UI("多边形")] Polygon } /// <summary> /// 工具 /// </summary> public class XTool { public ToolType Type { get; set; } public Image Icon { get; set; } public override string ToString() { return this.Type.GetTitle(); } public XTool() { } public XTool(ToolType type, Image icon) { this.Type = type; this.Icon = icon; } // public static List<XTool> All = GetAll(); public static List<XTool> GetAll() { var items = new List<XTool>(); items.Add(new XTool(ToolType.Select, Properties.Resources.icon_cursor_2x)); //items.Add(new XTool(ToolType.Text, Properties.Resources.icon_text_2x)); items.Add(new XTool(ToolType.Rect, Properties.Resources.icon_rect_2x)); items.Add(new XTool(ToolType.RoundedRect, Properties.Resources.icon_round_rect_2x)); items.Add(new XTool(ToolType.Polyline, Properties.Resources.icon_polyline_2x)); //items.Add(new XTool(ToolType.Polygon, Properties.Resources.icon_polygon_2x)); //items.Add(new XTool(ToolType.Star, Properties.Resources.icon_star_2x)); items.Add(new XTool(ToolType.Arrow, Properties.Resources.icon_arrow_2x)); return items; } } }
27.479452
96
0.559322
[ "MIT" ]
surfsky/PaintX
XPaint/Components/XTool.cs
2,084
C#
using Abp.Authorization; using CovidCommunity.Api.Authorization.Roles; using CovidCommunity.Api.Authorization.Users; namespace CovidCommunity.Api.Authorization { public class PermissionChecker : PermissionChecker<Role, User> { public PermissionChecker(UserManager userManager) : base(userManager) { } } }
23.666667
66
0.712676
[ "Apache-2.0" ]
eventually-apps/covid-community
api/src/CovidCommunity.Api.Core/Authorization/PermissionChecker.cs
357
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.VMware.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Extensions; using System; /// <summary>Cancel a ScriptExecution in a private cloud</summary> /// <remarks> /// [OpenAPI] Delete=>DELETE:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/scriptExecutions/{scriptExecutionName}" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Remove, @"AzVMwareScriptExecution_Delete", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(bool))] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Description(@"Cancel a ScriptExecution in a private cloud")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Generated] public partial class RemoveAzVMwareScriptExecution_Delete : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.VMware.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>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.VMware Client => Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.VMware.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="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary>Backing field for <see cref="Name" /> property.</summary> private string _name; /// <summary>Name of the user-invoked script execution resource</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the user-invoked script execution resource")] [Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Info( Required = true, ReadOnly = false, Description = @"Name of the user-invoked script execution resource", SerializedName = @"scriptExecutionName", PossibleTypes = new [] { typeof(string) })] [global::System.Management.Automation.Alias("ScriptExecutionName")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)] public string Name { get => this._name; set => this._name = value; } /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary> /// When specified, forces the cmdlet return a 'bool' given that there isn't a return type by default. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Returns true when the command succeeds")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter PassThru { get; set; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>Backing field for <see cref="PrivateCloudName" /> property.</summary> private string _privateCloudName; /// <summary>Name of the private cloud</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the private cloud")] [Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Info( Required = true, ReadOnly = false, Description = @"Name of the private cloud", SerializedName = @"privateCloudName", PossibleTypes = new [] { typeof(string) })] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)] public string PrivateCloudName { get => this._privateCloudName; set => this._privateCloudName = value; } /// <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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.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.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.Info( Required = true, ReadOnly = false, Description = @"The ID of the target subscription.", SerializedName = @"subscriptionId", PossibleTypes = new [] { typeof(string) })] [Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.DefaultInfo( Name = @"", Description =@"", Script = @"(Get-AzContext).Subscription.Id")] [global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)] public string SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault 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.VMware.Models.Api20211201.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnNoContent</c> will be called before the regular onNoContent 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="returnNow">/// Determines if the rest of the onNoContent method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnNoContent(global::System.Net.Http.HttpResponseMessage responseMessage, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <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="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, 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() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of RemoveAzVMwareScriptExecution_Delete</returns> public Microsoft.Azure.PowerShell.Cmdlets.VMware.Cmdlets.RemoveAzVMwareScriptExecution_Delete Clone() { var clone = new RemoveAzVMwareScriptExecution_Delete(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.SubscriptionId = this.SubscriptionId; clone.ResourceGroupName = this.ResourceGroupName; clone.PrivateCloudName = this.PrivateCloudName; clone.Name = this.Name; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <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.VMware.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.VMware.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 ; } case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.VMware.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'ScriptExecutionsDelete' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.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.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.VMware.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await this.Client.ScriptExecutionsDelete(SubscriptionId, ResourceGroupName, PrivateCloudName, Name, onOk, onNoContent, onDefault, this, Pipeline); await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,PrivateCloudName=PrivateCloudName,Name=Name}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary> /// Intializes a new instance of the <see cref="RemoveAzVMwareScriptExecution_Delete" /> cmdlet class. /// </summary> public RemoveAzVMwareScriptExecution_Delete() { } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </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.VMware.Models.Api20211201.ICloudError" /// /> 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 onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20211201.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, PrivateCloudName=PrivateCloudName, Name=Name }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, PrivateCloudName=PrivateCloudName, Name=Name }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 204 (NoContent).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</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 onNoContent(global::System.Net.Http.HttpResponseMessage responseMessage) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnNoContent(responseMessage, ref _returnNow); // if overrideOnNoContent has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onNoContent - response for 204 / if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) { WriteObject(true); } } } /// <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> /// <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) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / if (true == MyInvocation?.BoundParameters?.ContainsKey("PassThru")) { WriteObject(true); } } } } }
69.667946
455
0.654903
[ "MIT" ]
Agazoth/azure-powershell
src/VMware/generated/cmdlets/RemoveAzVMwareScriptExecution_Delete.cs
35,777
C#
namespace SharpCompress.Compressor.Rar.decode { internal class AudioVariables { internal AudioVariables() { Dif = new int[11]; } internal int[] Dif { get; private set; } internal int ByteCount { get; set; } internal int D1 { get; set; } internal int D2 { get; set; } internal int D3 { get; set; } internal int D4 { get; set; } internal int K1 { get; set; } internal int K2 { get; set; } internal int K3 { get; set; } internal int K4 { get; set; } internal int K5 { get; set; } internal int LastChar { get; set; } internal int LastDelta { get; set; } } }
28.192308
49
0.51296
[ "MIT" ]
Gert-Jan/sharpcompress
SharpCompress/Compressor/Rar/Decode/AudioVariables.cs
733
C#
using System; using System.Collections.Generic; using System.Text; namespace PdfSharp.Xps.XpsModel { /// <summary> /// Pseudo element that represents an XML comment in an XPS file. /// </summary> class Comment : XpsElement { /// <summary> /// Gets or sets the comment text. /// </summary> public string Text { get; set; } } }
20.882353
67
0.64507
[ "MIT" ]
DHTMLX/grid-to-pdf-net
src/lib/PDFsharp/code/PdfSharp.Xps/PdfSharp.Xps.XpsModel/Comment.cs
357
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using FileParameter = Org.OpenAPITools.Client.FileParameter; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; namespace Org.OpenAPITools.Model { /// <summary> /// GmFruit /// </summary> [JsonConverter(typeof(GmFruitJsonConverter))] [DataContract(Name = "gmFruit")] public partial class GmFruit : AbstractOpenAPISchema, IEquatable<GmFruit>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="GmFruit" /> class /// with the <see cref="Apple" /> class /// </summary> /// <param name="actualInstance">An instance of Apple.</param> public GmFruit(Apple actualInstance) { this.IsNullable = false; this.SchemaType= "anyOf"; this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); } /// <summary> /// Initializes a new instance of the <see cref="GmFruit" /> class /// with the <see cref="Banana" /> class /// </summary> /// <param name="actualInstance">An instance of Banana.</param> public GmFruit(Banana actualInstance) { this.IsNullable = false; this.SchemaType= "anyOf"; this.ActualInstance = actualInstance ?? throw new ArgumentException("Invalid instance found. Must not be null."); } private Object _actualInstance; /// <summary> /// Gets or Sets ActualInstance /// </summary> public override Object ActualInstance { get { return _actualInstance; } set { if (value.GetType() == typeof(Apple)) { this._actualInstance = value; } else if (value.GetType() == typeof(Banana)) { this._actualInstance = value; } else { throw new ArgumentException("Invalid instance found. Must be the following types: Apple, Banana"); } } } /// <summary> /// Get the actual instance of `Apple`. If the actual instanct is not `Apple`, /// the InvalidClassException will be thrown /// </summary> /// <returns>An instance of Apple</returns> public Apple GetApple() { return (Apple)this.ActualInstance; } /// <summary> /// Get the actual instance of `Banana`. If the actual instanct is not `Banana`, /// the InvalidClassException will be thrown /// </summary> /// <returns>An instance of Banana</returns> public Banana GetBanana() { return (Banana)this.ActualInstance; } /// <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 GmFruit {\n"); sb.Append(" ActualInstance: ").Append(this.ActualInstance).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 override string ToJson() { return JsonConvert.SerializeObject(this.ActualInstance, GmFruit.SerializerSettings); } /// <summary> /// Converts the JSON string into an instance of GmFruit /// </summary> /// <param name="jsonString">JSON string</param> /// <returns>An instance of GmFruit</returns> public static GmFruit FromJson(string jsonString) { GmFruit newGmFruit = null; if (jsonString == null) { return newGmFruit; } try { newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Apple>(jsonString, GmFruit.SerializerSettings)); // deserialization is considered successful at this point if no exception has been thrown. return newGmFruit; } catch (Exception exception) { // deserialization failed, try the next one System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Apple: {1}", jsonString, exception.ToString())); } try { newGmFruit = new GmFruit(JsonConvert.DeserializeObject<Banana>(jsonString, GmFruit.SerializerSettings)); // deserialization is considered successful at this point if no exception has been thrown. return newGmFruit; } catch (Exception exception) { // deserialization failed, try the next one System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into Banana: {1}", jsonString, exception.ToString())); } // no match found, throw an exception throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); } /// <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 OpenAPIClientUtils.compareLogic.Compare(this, input as GmFruit).AreEqual; } /// <summary> /// Returns true if GmFruit instances are equal /// </summary> /// <param name="input">Instance of GmFruit to be compared</param> /// <returns>Boolean</returns> public bool Equals(GmFruit input) { return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; } /// <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.ActualInstance != null) hashCode = hashCode * 59 + this.ActualInstance.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; } } /// <summary> /// Custom JSON converter for GmFruit /// </summary> public class GmFruitJsonConverter : JsonConverter { /// <summary> /// To write the JSON string /// </summary> /// <param name="writer">JSON writer</param> /// <param name="value">Object to be converted into a JSON string</param> /// <param name="serializer">JSON Serializer</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteRawValue((string)(typeof(GmFruit).GetMethod("ToJson").Invoke(value, null))); } /// <summary> /// To convert a JSON string into an object /// </summary> /// <param name="reader">JSON reader</param> /// <param name="objectType">Object type</param> /// <param name="existingValue">Existing value</param> /// <param name="serializer">JSON Serializer</param> /// <returns>The object converted from the JSON string</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if(reader.TokenType != JsonToken.Null) { return GmFruit.FromJson(JObject.Load(reader).ToString(Formatting.None)); } return null; } /// <summary> /// Check if the object can be converted /// </summary> /// <param name="objectType">Object type</param> /// <returns>True if the object can be converted</returns> public override bool CanConvert(Type objectType) { return false; } } }
35.981132
159
0.579444
[ "Apache-2.0" ]
AYLIEN/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GmFruit.cs
9,535
C#
// Copyright (c) Dolittle. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dolittle.Runtime.Projections.Store; /// <summary> /// Defines a system for collecting metrics about the projection store. /// </summary> public interface IMetricsCollector { /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryGet"/>. /// </summary> void IncrementTotalGet(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryGet"/> that failed. /// </summary> void IncrementTotalFailedGet(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryGetAll"/>. /// </summary> void IncrementTotalGetAll(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryGetAll"/> that failed. /// </summary> void IncrementTotalFailedGetAll(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionPersister.TryReplace"/>. /// </summary> void IncrementTotalReplaceAttempts(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryReplace"/>. /// </summary> void IncrementTotalCopyStoreReplacements(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryReplace"/> that failed. /// </summary> void IncrementTotalFailedCopyStoreReplacements(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryReplace"/>. /// </summary> void IncrementTotalProjectionStoreReplacements(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryReplace"/> that failed. /// </summary> void IncrementTotalFailedProjectionStoreReplacements(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionPersister.TryRemove"/>. /// </summary> void IncrementTotalRemoveAttempts(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryRemove"/>. /// </summary> void IncrementTotalCopyStoreRemovals(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryRemove"/> that failed. /// </summary> void IncrementTotalFailedCopyStoreRemovals(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryRemove"/>. /// </summary> void IncrementTotalProjectionStoreRemovals(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryRemove"/> that failed. /// </summary> void IncrementTotalFailedProjectionStoreRemovals(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionPersister.TryDrop"/>. /// </summary> void IncrementTotalDropAttempts(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryDrop"/>. /// </summary> void IncrementTotalCopyStoreDrops(); /// <summary> /// Increments the total number of writes to copy stores from calls to <see cref="IProjectionPersister.TryDrop"/> that failed. /// </summary> void IncrementTotalFailedCopyStoreDrops(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryDrop"/>. /// </summary> void IncrementTotalProjectionStoreDrops(); /// <summary> /// Increments the total number of calls to <see cref="IProjectionStore.TryDrop"/> that failed. /// </summary> void IncrementTotalFailedProjectionStoreDrops(); }
37.056604
133
0.684827
[ "MIT" ]
dolittle-runtime/Runtime
Source/Projections.Store/IMetricsCollector.cs
3,928
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum SeedType { LIGHTGRASS = 1, PUREGRASS = 2, BOUNCEMUSH = 3, BLOCKTREE = 4, WEED = 5 } abstract public class StartPoint : MonoBehaviour { public bool isActivate = false; public WaterColor color; public Vector3 centerPointOffset; public GameObject activatedGrass; public GameObject deactivatedGrass; public GameObject offGrass; public SeedType seedType; private LevelGrid grid; private Vector3 hitPoint; private bool needVisualUpdate = true; protected void InitializeGrid() { int layerMask = 1 << 9; RaycastHit hit; if (Physics.Raycast(transform.position + transform.TransformVector(centerPointOffset) + transform.TransformDirection(Vector3.up) * 0.5f, transform.TransformDirection(Vector3.down), out hit, 1.2f, layerMask)) { hitPoint = hit.point; grid = hit.collider.GetComponent<GridSplitter>().GetGridAtPosition(hit.point); grid.type = GridType.SEED; grid.groundColor = color; grid.state = 2; grid.seed = this; grid.grassStates[(int)seedType - 1] = 1; } GameManager.AddStartPoint(this); } abstract public void Activate(); abstract public void Deactivate(); private void OnDrawGizmos() { Gizmos.color = Color.black; Gizmos.DrawLine(transform.position + transform.TransformVector(centerPointOffset) + transform.TransformDirection(Vector3.up) * 0.5f, hitPoint); } protected bool ChangeModel(bool b) { if(isActivate != b) { isActivate = b; return true; } else { return false; } } public void VisualUpdateRequest() { needVisualUpdate = true; } protected void UpdateNewVisual() { if (needVisualUpdate) { activatedGrass.SetActive(false); deactivatedGrass.SetActive(false); offGrass.SetActive(false); GetNewVisual().SetActive(true); needVisualUpdate = false; } } private GameObject GetNewVisual() { if(grid.state == 2) { for(int i = 1; i <= 4; i++) { LevelGrid tmp = grid.GetNearGrid((NearGridDirection)i); if(tmp.state == 2 && color == tmp.groundColor) { return deactivatedGrass; } } return offGrass; } else { return activatedGrass; } } }
25.40566
215
0.577423
[ "MIT" ]
YumiiK/Regrass
Assets/Resources/Scripts/Seeds/StartPoint.cs
2,695
C#
/**** * Created by: Ben Jenkins * Date Created: April 20,2022 * * Last Edited by: NA * Last Edited: NA * * Description: Controls the halo when a card is hovered ****/ using UnityEngine; public class HoverScript : MonoBehaviour { [HideInInspector] public GameObject thisCubeSlot; [HideInInspector] public GameObject HoverSpot; [HideInInspector] private bool hover; private bool inInventory = false; private GameManager GM; private void Awake() { GM = GameManager.GM; } // Start is called before the first frame update void Start() { thisCubeSlot = this.gameObject; HoverSpot = thisCubeSlot.transform.Find("HaloHolder").gameObject; HoverSpot.SetActive(false); } private void OnMouseEnter() { this.HoverSpot.SetActive(true); hover = true; } private void OnMouseExit() { this.HoverSpot.SetActive(false); hover = false; } private void OnMouseDown() { if (hover && GM.playerTurn == 1) { if (inInventory && this.gameObject.CompareTag("Bundle")) { this.gameObject.GetComponent<BundleCards>().CompleteBundle(); return; } else if(inInventory && this.gameObject.CompareTag("Card")) { GM.player.GetComponent<Inventory>().RemoveCard(this.gameObject); Destroy(this.gameObject); GM.NextTurn(); return; } if (this.gameObject.GetComponent<CardData>()) { inInventory = true; GM.player.GetComponent<PlayerScript>().cardsTakenByPlayer += 1; TakeCard(GM.player); } else { inInventory = true; TakeBundle(GM.player); GM.board.GetComponent<DrawArea>().bundleTaken = true; GM.NextTurn(); } } } public void TakeCard(GameObject source) { Debug.LogWarning(source); source.GetComponent<Inventory>().AddCard(this.gameObject); GM.board.GetComponent<DrawArea>().RemoveCardFromBoard(this.gameObject); } public void TakeBundle(GameObject source) { source.GetComponent<Inventory>().AddBundle(this.gameObject); } }
26.197802
80
0.567953
[ "MIT" ]
Doggitoz/Rename
Oppozootion Unity/Assets/Scripts/Cards/HoverScript.cs
2,384
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Problem 3. Min, Max, Sum and Average of N Numbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem 3. Min, Max, Sum and Average of N Numbers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2dd480e3-8d27-4873-a82b-940e1df6e486")] // 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")]
40.72973
85
0.723955
[ "MIT" ]
Telerik-Homework-ValentinRangelov/Homework
C#/C# 1/Homework Loops/Problem 3. Min, Max, Sum and Average of N Numbers/Properties/AssemblyInfo.cs
1,510
C#
using System; using Xunit; namespace Typesafe.Mailgun.Tests { [Trait("Category", TestCategory.Integration)] public class When_sending_an_email_message_for_a_non_existing_domain { [Fact] public void an_invalid_operation_exception_should_be_thrown() { Assert.Throws<InvalidOperationException>(() => MailgunClientBuilder.GetClient("foobar.com") .SendMail(MailMessageBuilder.CreateMailWithoutAttachments())); } } }
24.222222
69
0.784404
[ "Apache-2.0" ]
astiskala/mnailgun
src/Typesafe.Mailgun.Tests/When_sending_an_email_message_for_a_non_existing_domain.cs
436
C#
/*********************************************************************** * Project: CoreCms * ProjectName: 核心内容管理系统 * Web: https://www.corecms.net * Author: 大灰灰 * Email: jianweie@163.com * CreateTime: 2021/1/31 21:45:10 * Description: 暂无 ***********************************************************************/ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; using CoreCms.Net.Configuration; using CoreCms.Net.Model.Entities; using CoreCms.Net.Model.ViewModels.Basics; using CoreCms.Net.IRepository; using CoreCms.Net.IRepository.UnitOfWork; using CoreCms.Net.Model.ViewModels.DTO.Agent; using CoreCms.Net.Model.ViewModels.DTO.Distribution; using SqlSugar; namespace CoreCms.Net.Repository { /// <summary> /// 分销商表 接口实现 /// </summary> public class CoreCmsDistributionRepository : BaseRepository<CoreCmsDistribution>, ICoreCmsDistributionRepository { public CoreCmsDistributionRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { } #region 根据条件查询分页数据 /// <summary> /// 根据条件查询分页数据 /// </summary> /// <param name="userId"></param> /// <param name="pageIndex">当前页面索引</param> /// <param name="pageSize">分布大小</param> /// <param name="typeId">类型</param> /// <returns></returns> public async Task<IPageList<CoreCmsDistributionOrder>> QueryOrderPageAsync(int userId, int pageIndex = 1, int pageSize = 20, int typeId = 0) { RefAsync<int> totalCount = 0; var page = await DbClient.Queryable<CoreCmsDistributionOrder, CoreCmsOrder, CoreCmsUser>((dOrder, cOrder, userInfo) => new object[] { JoinType.Inner,dOrder.orderId==cOrder.orderId,JoinType.Inner,dOrder.buyUserId==userInfo.id }) .Where((dOrder, cOrder, userInfo) => dOrder.userId == userId) .Select((dOrder, cOrder, userInfo) => new CoreCmsDistributionOrder() { id = dOrder.id, userId = dOrder.userId, buyUserId = dOrder.buyUserId, orderId = dOrder.orderId, amount = dOrder.amount, isSettlement = dOrder.isSettlement, level = dOrder.level, createTime = dOrder.createTime, updateTime = dOrder.updateTime, isDelete = dOrder.isDelete, buyUserNickName = userInfo.nickName }) .With(SqlWith.NoLock) .MergeTable() .WhereIF(typeId > 0, p => p.isSettlement == typeId) .OrderBy(dOrder => dOrder.id, OrderByType.Desc) .ToPageListAsync(pageIndex, pageSize, totalCount); var list = new PageList<CoreCmsDistributionOrder>(page, pageIndex, pageSize, totalCount); return list; } #endregion #region 获取代理商排行 /// <summary> /// 获取代理商排行 /// </summary> /// <param name="pageIndex">当前页面索引</param> /// <param name="pageSize">分布大小</param> /// <returns></returns> public async Task<IPageList<DistributionRankingDTO>> QueryRankingPageAsync(int pageIndex = 1, int pageSize = 20) { RefAsync<int> totalCount = 0; var page = await DbClient.Queryable<CoreCmsDistribution>() .Select(p => new DistributionRankingDTO() { id = p.userId, nickname = p.name, createtime = p.createTime, totalInCome = SqlFunc.Subqueryable<CoreCmsDistributionOrder>().Where(o => o.userId == p.userId && p.isDelete == false && p.verifyStatus == (int)GlobalEnumVars.DistributionOrderSettlementStatus.SettlementYes).Sum(o => o.amount), orderCount = SqlFunc.Subqueryable<CoreCmsDistributionOrder>().Where(o => o.userId == p.userId && p.isDelete == false && p.verifyStatus == (int)GlobalEnumVars.DistributionOrderSettlementStatus.SettlementYes).Count() }) .With(SqlWith.NoLock) .MergeTable() .OrderBy(dOrder => dOrder.totalInCome, OrderByType.Desc) .WithCache() .ToPageListAsync(pageIndex, pageSize, totalCount); var list = new PageList<DistributionRankingDTO>(page, pageIndex, pageSize, totalCount); return list; } #endregion } }
41.12931
247
0.548103
[ "Apache-2.0" ]
CoreUnion/CoreShop
CoreCms.Net.Repository/Distribution/CoreCmsDistributionRepository.cs
4,925
C#
using System; namespace SpecFlow.VisualStudio.Common; public class DeveroomConfigurationException : Exception { public DeveroomConfigurationException() { } public DeveroomConfigurationException(string message) : base(message) { } public DeveroomConfigurationException(string message, Exception innerException) : base(message, innerException) { } }
20.473684
115
0.742931
[ "MIT" ]
SpecFlowOSS/SpecFlow.VS
SpecFlow.VisualStudio.Common/DeveroomConfigurationException.cs
391
C#
// Copyright (c) Six Labors and contributors. // Licensed under the GNU Affero General Public License, Version 3. using System; using System.Buffers; using System.Numerics; using System.Runtime.CompilerServices; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.PixelFormats; namespace SixLabors.ImageSharp.Processing.Processors.Overlays { /// <summary> /// An <see cref="IImageProcessor{TPixel}"/> that applies a radial glow effect an <see cref="Image{TPixel}"/>. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> internal class GlowProcessor<TPixel> : ImageProcessor<TPixel> where TPixel : unmanaged, IPixel<TPixel> { private readonly PixelBlender<TPixel> blender; private readonly GlowProcessor definition; /// <summary> /// Initializes a new instance of the <see cref="GlowProcessor{TPixel}"/> class. /// </summary> /// <param name="configuration">The configuration which allows altering default behaviour or extending the library.</param> /// <param name="definition">The <see cref="GlowProcessor"/> defining the processor parameters.</param> /// <param name="source">The source <see cref="Image{TPixel}"/> for the current processor instance.</param> /// <param name="sourceRectangle">The source area to process for the current processor instance.</param> public GlowProcessor(Configuration configuration, GlowProcessor definition, Image<TPixel> source, Rectangle sourceRectangle) : base(configuration, source, sourceRectangle) { this.definition = definition; this.blender = PixelOperations<TPixel>.Instance.GetPixelBlender(definition.GraphicsOptions); } /// <inheritdoc/> protected override void OnFrameApply(ImageFrame<TPixel> source) { TPixel glowColor = this.definition.GlowColor.ToPixel<TPixel>(); float blendPercent = this.definition.GraphicsOptions.BlendPercentage; var interest = Rectangle.Intersect(this.SourceRectangle, source.Bounds()); Vector2 center = Rectangle.Center(interest); float finalRadius = this.definition.Radius.Calculate(interest.Size); float maxDistance = finalRadius > 0 ? MathF.Min(finalRadius, interest.Width * .5F) : interest.Width * .5F; Configuration configuration = this.Configuration; MemoryAllocator allocator = configuration.MemoryAllocator; using IMemoryOwner<TPixel> rowColors = allocator.Allocate<TPixel>(interest.Width); rowColors.GetSpan().Fill(glowColor); var operation = new RowOperation(configuration, interest, rowColors, this.blender, center, maxDistance, blendPercent, source); ParallelRowIterator.IterateRows<RowOperation, float>( configuration, interest, in operation); } private readonly struct RowOperation : IRowOperation<float> { private readonly Configuration configuration; private readonly Rectangle bounds; private readonly PixelBlender<TPixel> blender; private readonly Vector2 center; private readonly float maxDistance; private readonly float blendPercent; private readonly IMemoryOwner<TPixel> colors; private readonly ImageFrame<TPixel> source; [MethodImpl(InliningOptions.ShortMethod)] public RowOperation( Configuration configuration, Rectangle bounds, IMemoryOwner<TPixel> colors, PixelBlender<TPixel> blender, Vector2 center, float maxDistance, float blendPercent, ImageFrame<TPixel> source) { this.configuration = configuration; this.bounds = bounds; this.colors = colors; this.blender = blender; this.center = center; this.maxDistance = maxDistance; this.blendPercent = blendPercent; this.source = source; } [MethodImpl(InliningOptions.ShortMethod)] public void Invoke(int y, Span<float> span) { Span<TPixel> colorSpan = this.colors.GetSpan(); for (int i = 0; i < this.bounds.Width; i++) { float distance = Vector2.Distance(this.center, new Vector2(i + this.bounds.X, y)); span[i] = (this.blendPercent * (1 - (.95F * (distance / this.maxDistance)))).Clamp(0, 1); } Span<TPixel> destination = this.source.GetPixelRowSpan(y).Slice(this.bounds.X, this.bounds.Width); this.blender.Blend( this.configuration, destination, destination, colorSpan, span); } } } }
42.908333
138
0.613129
[ "Apache-2.0" ]
fahadabdulaziz/ImageSharp
src/ImageSharp/Processing/Processors/Overlays/GlowProcessor{TPixel}.cs
5,149
C#
// <auto-generated /> using System; using EFCoreMigration; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace EFCoreMigration.DataAccess.Migrations { [DbContext(typeof(CertificationContext))] [Migration("20210318045309_AddLocation")] partial class AddLocation { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.4") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.Certificate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("LocationId") .HasColumnType("int"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("LocationId"); b.ToTable("Certificate"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.CertificateLocation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("CertificateLocation"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.Employee", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Employee"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.EmployeeCertificate", b => { b.Property<int>("EmployeeId") .HasColumnType("int"); b.Property<int>("CertificateId") .HasColumnType("int"); b.HasKey("EmployeeId", "CertificateId"); b.HasIndex("CertificateId"); b.ToTable("EmployeeCertificate"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.Certificate", b => { b.HasOne("EFCoreMigration.DataAccess.Entities.CertificateLocation", "Location") .WithMany("Certificates") .HasForeignKey("LocationId"); b.Navigation("Location"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.EmployeeCertificate", b => { b.HasOne("EFCoreMigration.DataAccess.Entities.Certificate", "Certificate") .WithMany("EmployeeCertificates") .HasForeignKey("CertificateId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("EFCoreMigration.DataAccess.Entities.Employee", "Employee") .WithMany("EmployeeCertificates") .HasForeignKey("EmployeeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Certificate"); b.Navigation("Employee"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.Certificate", b => { b.Navigation("EmployeeCertificates"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.CertificateLocation", b => { b.Navigation("Certificates"); }); modelBuilder.Entity("EFCoreMigration.DataAccess.Entities.Employee", b => { b.Navigation("EmployeeCertificates"); }); #pragma warning restore 612, 618 } } }
37.607407
125
0.530431
[ "MIT" ]
nghianguyendev/EFCoreMigration
EFCoreMigration/Migrations/20210318045309_AddLocation.Designer.cs
5,079
C#
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authentication; using MyBlog.Engine.Data.Models; using Newtonsoft.Json; using System; using System.Security.Claims; namespace MyBlog.Engine.Services { public class UserService { #region Declarations private const String UserProfileSessionKey = "UserProfile"; private readonly DataService _dataService; private readonly IHttpContextAccessor _httpContextAccessor; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="dataService"></param> public UserService(DataService dataService, IHttpContextAccessor httpContextAccessor) { _dataService = dataService; _httpContextAccessor = httpContextAccessor; } #endregion #region Properties #endregion #region Methods /// <summary> /// Get user from claims /// </summary> /// <param name="principal"></param> /// <returns></returns> public UserProfile GetFromClaims(ClaimsPrincipal principal ) { if (principal == null) { principal = _httpContextAccessor.HttpContext.User; } if (principal == null) return null; // Get Identifier Claim nameIdentifierClaim = principal.FindFirst(ClaimTypes.NameIdentifier); // Get name Claim nameClaim = principal.FindFirst(ClaimTypes.Name); // Add mail Claim mailClaim = principal.FindFirst(ClaimTypes.Email); // Test nameIdentifier if (nameIdentifierClaim == null) return null; // Get values String issuer = nameIdentifierClaim.Issuer; String nameIdentifier = nameIdentifierClaim.Value; // Try to get User from database // Try to get user from database UserProfile user = _dataService.GetUser(issuer, nameIdentifier); // Test user if (user == null) { user = new UserProfile { Issuer = issuer, NameIdentifier = nameIdentifier, Name = nameClaim?.Value, Email = mailClaim?.Value, EmailValidate = false }; } // Return the user return user; } /// <summary> /// Get user from session /// </summary> /// <returns></returns> public UserProfile Get() { // Try to get user from session UserProfile user = GetFromSession(); // Try to get user from claims if (user == null && _httpContextAccessor.HttpContext.User != null) { user = GetFromClaims(null); Set(user); } // return user return user; } /// <summary> /// Get fresh useer updated from dataBase for edition /// </summary> /// <returns></returns> public UserProfile GetFreshUseerUpdatedFromDataBase() { // Try know user id from session UserProfile user = GetFromSession(); // Try to get user from claims if (user == null && _httpContextAccessor.HttpContext.User != null) { user = GetFromClaims(null); } if (user == null) return null; // Get fresh data from data base if user is not new if (user.Id != 0) { user = _dataService.GetUser(user.Id); } // return user return user; } /// <summary> /// Get usedr from session /// </summary> /// <returns></returns> private UserProfile GetFromSession() { // Try know user id from session String value = _httpContextAccessor.HttpContext.Session.GetString(UserProfileSessionKey); if (String.IsNullOrWhiteSpace(value)) return null; return JsonConvert.DeserializeObject<UserProfile>(value); } /// <summary> /// Set user in session /// </summary> /// <param name="user"></param> public void Set(UserProfile user) { String value = JsonConvert.SerializeObject(user); _httpContextAccessor.HttpContext.Session.SetString(UserProfileSessionKey, value); } /// <summary> /// Set user in session /// </summary> /// <param name="user"></param> public void Clear() { _httpContextAccessor.HttpContext.Session.SetString(UserProfileSessionKey, String.Empty); } #endregion } }
29.218935
101
0.535844
[ "MIT" ]
JeremyJeanson/MyBlog.netcore
Sources/MyBlog.Engine/Services/UserService.cs
4,940
C#
using System; using Microsoft.Extensions.DependencyInjection; using Orleans; using Orleans.Runtime; using Orleans.Runtime.Placement; using UnitTests.GrainInterfaces; using Orleans.Hosting; using Orleans.TestingHost; using UnitTests.Grains; namespace TestVersionGrains { public class VersionGrainsSiloBuilderConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder .ConfigureServices(this.ConfigureServices) .ConfigureApplicationParts(parts => parts.AddFromAppDomain().AddFromApplicationBaseDirectory()); } private void ConfigureServices(IServiceCollection services) { services.AddSingletonNamedService<PlacementStrategy, VersionAwarePlacementStrategy>(nameof(VersionAwarePlacementStrategy)); services.AddSingletonKeyedService<Type, IPlacementDirector, VersionAwarePlacementDirector>(typeof(VersionAwarePlacementStrategy)); } } }
34.827586
142
0.755446
[ "MIT" ]
eckerdj7/orleans
test/Versions/TestVersionGrains/VersionGrainsSiloBuilderfactory.cs
1,010
C#
using System; using ActiproSoftware.Text; using ActiproSoftware.Text.Lexing; using ActiproSoftware.Windows.Controls.SyntaxEditor.Outlining; using ActiproSoftware.Windows.Controls.SyntaxEditor.Outlining.Implementation; namespace ActiproSoftware.ProductSamples.SyntaxEditorSamples.QuickStart.CodeOutliningCollapsedText { /// <summary> /// Implements a multi-line comment <see cref="IOutliningNodeDefinition"/> that renders some of /// a collapsed node's inner text. /// </summary> public class MultiLineCommentNodeDefinition : OutliningNodeDefinition { ///////////////////////////////////////////////////////////////////////////////////////////////////// // OBJECT ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Initializes a new instance of the <c>MultiLineCommentNodeDefinition</c> class. /// </summary> public MultiLineCommentNodeDefinition() : base("MultiLineComment") { this.DefaultCollapsedContent = "/**/"; this.IsDefaultCollapsed = true; this.IsImplementation = true; } ///////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC PROCEDURES ///////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Returns the content that should be displayed when the outlining node is collapsed. /// </summary> /// <param name="node">The <see cref="IOutliningNode"/>, based on this definition, for which content is requested.</param> /// <returns>The content that should be displayed when the outlining node is collapsed.</returns> /// <remarks> /// Only string-based content is currently supported. /// The default implementation of this method returns the value of the <see cref="DefaultCollapsedContent"/> property. /// This method can be overridden to generate unique collapsed content for a particular node. /// </remarks> public override object GetCollapsedContent(IOutliningNode node) { // Get the node's snapshot range TextSnapshotRange snapshotRange = node.SnapshotRange; // If the comment is over multiple lines... if (snapshotRange.StartPosition.Line < snapshotRange.EndPosition.Line) { // Use the text in the first line int lineEndOffset = snapshotRange.StartLine.EndOffset; return snapshotRange.Snapshot.GetSubstring(new TextRange(snapshotRange.StartOffset, lineEndOffset)) + "..."; } else { // On a single line... use default collapsed content return this.DefaultCollapsedContent; } } } }
42.655738
124
0.623367
[ "MIT" ]
Actipro/WPF-Controls
Samples/SampleBrowser/ProductSamples/SyntaxEditorSamples/QuickStart/CodeOutliningCollapsedText/MultiLineCommentNodeDefinition.cs
2,604
C#
using FriendyFy.Data; using FriendyFy.Services.Contracts; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ViewModels; using ViewModels.ViewModels; namespace FriendyFy.Controllers { [Route("post")] [ApiController] public class PostController : BaseController { private readonly IPostService postService; private readonly IEventService eventService; public PostController(IPostService postService, IEventService eventService) { this.postService = postService; this.eventService = eventService; } [HttpPost("make")] public async Task<IActionResult> MakePost(MakePostDto makePostDto) { var user = this.GetUserByToken(); if (user == null) { return Unauthorized("You are not signed in!"); } else if (string.IsNullOrWhiteSpace(makePostDto.Image) && string.IsNullOrWhiteSpace(makePostDto.PostMessage)) { return BadRequest("Something went wrong, try again!"); } return Json(new { success = await postService.CreatePostAsync(makePostDto, user.Id) }); } [HttpGet("getPosts")] public IActionResult GetPosts() { var user = this.GetUserByToken(); if (user == null) { return Unauthorized("You are not signed in!"); } return Json(this.postService.GetAllPosts(user.Id)); } [HttpPost("likePost")] public async Task<IActionResult> LikePost(LikePostDto likePostDto) { var user = this.GetUserByToken(); if (user == null) { return Unauthorized("You are not signed in!"); } int? likes; try { likes = await this.postService.LikePostAsync(likePostDto.PostId, user); } catch (Exception) { return BadRequest("There was an error saving your like!"); } if (likes != null) { return Ok(likes); } else { return BadRequest(); } } [HttpPost("getLikes")] public IActionResult GetLikes(GetPostLikesCount dto) { var parsed = Enum.TryParse(dto.PostType, out PostType postType); if (!parsed) { return BadRequest(); } if (postType == PostType.Post) { return Ok(this.postService.GetPeopleLikes(dto.PostId, dto.Take, dto.Skip)); } else { return Ok(this.eventService.GetPeopleLikes(dto.PostId, dto.Take, dto.Skip)); } } [HttpPost("getReposts")] public IActionResult GetReposts(GetPostLikesCount dto) { var parsed = Enum.TryParse(dto.PostType, out PostType postType); if (!parsed) { return BadRequest(); } if (postType == PostType.Post) { return Ok(this.postService.GetPeopleReposts(dto.PostId, dto.Take, dto.Skip)); } else { return Ok(this.eventService.GetPostReposts(dto.PostId, dto.Take, dto.Skip)); } } [HttpPost("getTaggedPeople")] public List<PersonListPopupViewModel> GetTaggedPeople(GetPostLikesCount dto) { return this.postService.GetTaggedPeople(dto.PostId, dto.Take, dto.Skip); } [HttpPost("getByImageId")] public IActionResult GetPostByImageId(GetByImageIdDto dto) { var user = this.GetUserByToken(); var post = this.postService.GetPostByImageId(dto.ImageId, user != null ? user.Id : null); if (post == null) { return BadRequest(); } return Ok(post); } [HttpPost("repost")] public async Task<IActionResult> Repost(RepostDto dto) { var parsed = Enum.TryParse(dto.Type, out PostType postType); if (!parsed) { return BadRequest("There was something wrong with the request!"); } var user = this.GetUserByToken(); if (user == null) { return Unauthorized("You are not logged in!"); } if (postType == PostType.Event) { var result = await this.eventService.RepostEventAsync(dto.PostId, dto.Text, user.Id); if (result > 0) { return Ok(new { reposts = result }); } } else if (postType == PostType.Post) { var result = await this.postService.RepostAsync(dto.PostId, dto.Text, user.Id); if (result > 0) { return Ok(new { reposts = result }); } } return BadRequest(); } [HttpPost("deletePost")] public async Task<IActionResult> DeletePost(DeletePostDto dto) { var parsed = Enum.TryParse(dto.PostType, out PostType postType); if (!parsed) { return BadRequest("There was something wrong with the request!"); } var user = this.GetUserByToken(); if (user == null) { return Unauthorized("You are not logged in!"); } bool deleted = false; if (postType == PostType.Post) { deleted = await this.postService.DeletePostAsync(dto.PostId, user.Id); } else if (postType == PostType.Event) { deleted = await this.eventService.DeleteEventPostAsync(dto.PostId, user.Id); } if (deleted) return Ok(deleted); return BadRequest(); } [HttpPost("getFeedPosts")] public IActionResult GetFeedPosts(GetFeedData dto) { var user = this.GetUserByToken(); var data = new List<PostDetailsViewModel>(); var events = new List<PostDetailsViewModel>(); var posts = new List<PostDetailsViewModel>(); var toTake = dto.Take / 2; if (dto.FeedType != "posts") { if (dto.HasEvents) { events = this.eventService.GetFeedEvents(user, dto.isProfile, dto.Username, toTake, dto.EventIds.Count(), dto.EventIds); } } if (dto.FeedType != "events") { if (dto.HasPosts) { posts = this.postService.GetFeedPosts(user, dto.isProfile, dto.Username, toTake, dto.PostIds.Count(), dto.PostIds); } } bool hasPosts = false, hasEvents = false; if (events.Count() == toTake) { hasEvents = true; } if (posts.Count() == toTake) { hasPosts = true; } data.AddRange(events); data.AddRange(posts); if (!dto.isProfile) { data = data.OrderBy(x => Guid.NewGuid()).ToList(); } else { data = data.OrderBy(x => x.CreatedAgo).ToList(); } return Ok(new FeedViewModel() { Posts = data, HasEvents = hasEvents, HasPosts = hasPosts }); } } }
30.744186
140
0.497226
[ "MIT" ]
thunder913/FriendyFy
FriendyFy/Controllers/PostController.cs
7,934
C#
namespace Cosmos.Workflow { /// <summary> /// Dynamic Forms Interface<br /> /// 动态表单接口<br /> /// 本接口用于 Cosmos.Walker 与 Cosmos.Flower /// </summary> public interface IDynamicForms { /// <summary> /// Dynamic Forms Design<br /> /// 动态表单设计稿 /// </summary> IDynamicFormsDesign Design { get; } /// <summary> /// Title<br /> /// 动态表单标题 /// </summary> string Title { get; } } }
22
43
0.487603
[ "MIT" ]
alexinea/Cosmos.Standard
src/Cosmos.Abstractions/Cosmos/Workflow/IDynamicForms.cs
536
C#
using System.Text.Json.Serialization; namespace EzrealClient.Serialization.JsonConverters { /// <summary> /// 提供一些类型的兼容性的json转换器 /// </summary> public static class JsonCompatibleConverter { /// <summary> /// 获取Enum类型反序列化兼容的转换器 /// </summary> public static JsonConverter EnumReader { get; } = new JsonStringEnumConverter(); /// <summary> /// 获取DateTime类型反序列化兼容的转换器 /// </summary> public static JsonConverter DateTimeReader { get; } = new JsonDateTimeConverter("O"); } }
27.95
93
0.627907
[ "MIT" ]
EzrealJ/EzrealClient
src/EzrealClient.Abstractions/Serialization/JsonConverters/JsonCompatibleConverter.cs
645
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataObjects { public class Project { public string ProjectID { get; set; } public string Name { get; set; } public string Description { get; set; } public DateTime PurchaseDate { get; set; } public int WorkStation { get; set; } public string ProjectTypeID { get; set; } public string PhaseID { get; set; } public int ClientID { get; set; } public bool Active { get; set; } } }
21.571429
50
0.612583
[ "MIT" ]
pythoncoder999/TekCafe
src/DataObjects/Project.cs
606
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. #nullable enable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.LiveShare.CustomProtocol; using Microsoft.VisualStudio.LiveShare.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.LiveShare { [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentCompletionName)] internal class TypeScriptCompletionHandlerShim : AbstractLiveShareHandlerShim<CompletionParams, object> { [ImportingConstructor] public TypeScriptCompletionHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentCompletionName) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentCompletionResolveName)] internal class TypeScriptCompletionResolverHandlerShim : AbstractLiveShareHandlerShim<CompletionItem, CompletionItem> { [ImportingConstructor] public TypeScriptCompletionResolverHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentCompletionResolveName) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentDocumentHighlightName)] internal class TypeScriptDocumentHighlightHandlerShim : AbstractLiveShareHandlerShim<TextDocumentPositionParams, DocumentHighlight[]> { [ImportingConstructor] public TypeScriptDocumentHighlightHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentDocumentHighlightName) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentDocumentSymbolName)] internal class TypeScriptDocumentSymbolsHandlerShim : AbstractLiveShareHandlerShim<DocumentSymbolParams, SymbolInformation[]> { [ImportingConstructor] public TypeScriptDocumentSymbolsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentDocumentSymbolName) { } public override async Task<SymbolInformation[]> HandleAsync(DocumentSymbolParams param, RequestContext<Solution> requestContext, CancellationToken cancellationToken) { var clientCapabilities = requestContext.ClientCapabilities?.ToObject<VSClientCapabilities>(); if (clientCapabilities?.TextDocument?.DocumentSymbol?.HierarchicalDocumentSymbolSupport == true) { // If the value is true, set it to false. Liveshare does not support hierarchical document symbols. clientCapabilities.TextDocument.DocumentSymbol.HierarchicalDocumentSymbolSupport = false; } var handler = (IRequestHandler<DocumentSymbolParams, object[]>)LazyRequestHandler.Value; var response = await handler.HandleRequestAsync(requestContext.Context, param, clientCapabilities, cancellationToken).ConfigureAwait(false); // Since hierarchicalSupport will never be true, it is safe to cast the response to SymbolInformation[] return response.Cast<SymbolInformation>().ToArray(); } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentFormattingName)] internal class TypeScriptFormatDocumentHandlerShim : FormatDocumentHandler, ILspRequestHandler<DocumentFormattingParams, TextEdit[], Solution> { private readonly IThreadingContext _threadingContext; [ImportingConstructor] public TypeScriptFormatDocumentHandlerShim(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public Task<TextEdit[]> HandleAsync(DocumentFormattingParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => base.HandleRequestAsync(requestContext.Context, request, requestContext.ClientCapabilities?.ToObject<ClientCapabilities>(), cancellationToken); protected override async Task<IList<TextChange>> GetFormattingChangesAsync(IEditorFormattingService formattingService, Document document, TextSpan? textSpan, CancellationToken cancellationToken) { // TypeScript expects to be called on the UI thread to get the formatting options. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return await base.GetFormattingChangesAsync(formattingService, document, textSpan, cancellationToken).ConfigureAwait(false); } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentRangeFormattingName)] internal class TypeScriptFormatDocumentRangeHandlerShim : FormatDocumentRangeHandler, ILspRequestHandler<DocumentRangeFormattingParams, TextEdit[], Solution> { private readonly IThreadingContext _threadingContext; [ImportingConstructor] public TypeScriptFormatDocumentRangeHandlerShim(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public Task<TextEdit[]> HandleAsync(DocumentRangeFormattingParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => base.HandleRequestAsync(requestContext.Context, request, requestContext.ClientCapabilities?.ToObject<ClientCapabilities>(), cancellationToken); protected override async Task<IList<TextChange>> GetFormattingChangesAsync(IEditorFormattingService formattingService, Document document, TextSpan? textSpan, CancellationToken cancellationToken) { // TypeScript expects to be called on the UI thread to get the formatting options. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return await base.GetFormattingChangesAsync(formattingService, document, textSpan, cancellationToken).ConfigureAwait(false); } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentOnTypeFormattingName)] internal class TypeScriptFormatDocumentOnTypeHandlerShim : FormatDocumentOnTypeHandler, ILspRequestHandler<DocumentOnTypeFormattingParams, TextEdit[], Solution> { private readonly IThreadingContext _threadingContext; [ImportingConstructor] public TypeScriptFormatDocumentOnTypeHandlerShim(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public Task<TextEdit[]> HandleAsync(DocumentOnTypeFormattingParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => base.HandleRequestAsync(requestContext.Context, request, requestContext?.ClientCapabilities?.ToObject<ClientCapabilities>(), cancellationToken); protected override async Task<IList<TextChange>?> GetFormattingChangesAsync(IEditorFormattingService formattingService, Document document, char typedChar, int position, CancellationToken cancellationToken) { // TypeScript expects to be called on the UI thread to get the formatting options. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return await base.GetFormattingChangesAsync(formattingService, document, typedChar, position, cancellationToken).ConfigureAwait(false); } protected override async Task<IList<TextChange>?> GetFormattingChangesOnReturnAsync(IEditorFormattingService formattingService, Document document, int position, CancellationToken cancellationToken) { // TypeScript expects to be called on the UI thread to get the formatting options. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); return await base.GetFormattingChangesOnReturnAsync(formattingService, document, position, cancellationToken).ConfigureAwait(false); } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentImplementationName)] internal class TypeScriptFindImplementationsHandlerShim : FindImplementationsHandler, ILspRequestHandler<TextDocumentPositionParams, object, Solution> { private readonly IThreadingContext _threadingContext; [ImportingConstructor] public TypeScriptFindImplementationsHandlerShim(IThreadingContext threadingContext) { _threadingContext = threadingContext; } public Task<object> HandleAsync(TextDocumentPositionParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken) => base.HandleRequestAsync(requestContext.Context, request, requestContext.ClientCapabilities?.ToObject<ClientCapabilities>(), cancellationToken); protected override async Task FindImplementationsAsync(IFindUsagesService findUsagesService, Document document, int position, SimpleFindUsagesContext context) { // TypeScript expects to be called on the UI to get implementations. await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(context.CancellationToken); await base.FindImplementationsAsync(findUsagesService, document, position, context).ConfigureAwait(false); } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.InitializeName)] internal class TypeScriptInitializeHandlerShim : AbstractLiveShareHandlerShim<InitializeParams, InitializeResult> { [ImportingConstructor] public TypeScriptInitializeHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.InitializeName) { } public override async Task<InitializeResult> HandleAsync(InitializeParams param, RequestContext<Solution> requestContext, CancellationToken cancellationToken) { var initializeResult = await base.HandleAsync(param, requestContext, cancellationToken).ConfigureAwait(false); initializeResult.Capabilities.Experimental = new RoslynExperimentalCapabilities { SyntacticLspProvider = true }; return initializeResult; } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentSignatureHelpName)] internal class TypeScriptSignatureHelpHandlerShim : AbstractLiveShareHandlerShim<TextDocumentPositionParams, SignatureHelp> { [ImportingConstructor] public TypeScriptSignatureHelpHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentSignatureHelpName) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.TextDocumentRenameName)] internal class TypeScriptRenameHandlerShim : AbstractLiveShareHandlerShim<RenameParams, WorkspaceEdit> { [ImportingConstructor] public TypeScriptRenameHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.TextDocumentRenameName) { } } [ExportLspRequestHandler(LiveShareConstants.TypeScriptContractName, Methods.WorkspaceSymbolName)] internal class TypeScriptWorkspaceSymbolsHandlerShim : AbstractLiveShareHandlerShim<WorkspaceSymbolParams, SymbolInformation[]> { [ImportingConstructor] public TypeScriptWorkspaceSymbolsHandlerShim([ImportMany] IEnumerable<Lazy<IRequestHandler, IRequestHandlerMetadata>> requestHandlers) : base(requestHandlers, Methods.WorkspaceSymbolName) { } } }
56.946188
213
0.776439
[ "MIT" ]
missymessa/roslyn
src/VisualStudio/LiveShare/Impl/Shims/TypeScriptHandlerShims.cs
12,701
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediaconnect-2018-11-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.MediaConnect.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.MediaConnect.Model.Internal.MarshallTransformations { /// <summary> /// AddFlowOutputs Request Marshaller /// </summary> public class AddFlowOutputsRequestMarshaller : IMarshaller<IRequest, AddFlowOutputsRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((AddFlowOutputsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(AddFlowOutputsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.MediaConnect"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-11-14"; request.HttpMethod = "POST"; string uriResourcePath = "/v1/flows/{flowArn}/outputs"; if (!publicRequest.IsSetFlowArn()) throw new AmazonMediaConnectException("Request object does not have required field FlowArn set"); uriResourcePath = uriResourcePath.Replace("{flowArn}", StringUtils.FromStringWithSlashEncoding(publicRequest.FlowArn)); request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetOutputs()) { context.Writer.WritePropertyName("outputs"); context.Writer.WriteArrayStart(); foreach(var publicRequestOutputsListValue in publicRequest.Outputs) { context.Writer.WriteObjectStart(); var marshaller = AddOutputRequestMarshaller.Instance; marshaller.Marshall(publicRequestOutputsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static AddFlowOutputsRequestMarshaller _instance = new AddFlowOutputsRequestMarshaller(); internal static AddFlowOutputsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static AddFlowOutputsRequestMarshaller Instance { get { return _instance; } } } }
37.491379
143
0.626351
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/MediaConnect/Generated/Model/Internal/MarshallTransformations/AddFlowOutputsRequestMarshaller.cs
4,349
C#
namespace _06.Heists { using System; using System.Linq; public class Heists { public static void Main() { var prices = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int jewelsPrice = prices[0]; int goldPrice = prices[1]; string input; int jewelCounter = 0; int goldCounter = 0; long totalExpenses = 0; while ((input=Console.ReadLine())!="Jail Time") { var lootAndExpenses = input.Split(' '); string loot = lootAndExpenses[0]; int expenses = int.Parse(lootAndExpenses[1]); totalExpenses += expenses; for (int i = 0; i < loot.Length; i++) { if (loot[i]=='%') { jewelCounter++; } if (loot[i] == '$') { goldCounter++; } } } long netEarnings = jewelCounter * jewelsPrice + goldCounter * goldPrice - totalExpenses; if (netEarnings>=0) { Console.WriteLine($"Heists will continue. Total earnings: {netEarnings}."); } else { Console.WriteLine($"Have to find another job. Lost: {Math.Abs(netEarnings)}."); } } } }
29.7
100
0.428283
[ "MIT" ]
MihailDobrev/SoftUni
Tech Module/Programming Fundamentals/13. Arrays and Methods - More Exercises/06. Heists/Heists.cs
1,487
C#
using System; using System.Collections.Generic; using System.Text; namespace COASqlQuery { public class COASqlData<T> { public string SqlQuery { get; set; } public int Lenght { get; set; } public string TableName { get; set; } public COADataBaseTypes DataBaseType { get; set; } public string PrimaryKeyName { get; set; } public List<string> SelectedColumns { get; set; } = new List<string>(); public string OrderQuery { get; set; } public string WhereQuery { get; set; } } }
27.47619
80
0.604853
[ "MIT" ]
cemozguraA/COASqlQuery
COASqlQuery/COASqlData.cs
579
C#
// <copyright file="BoxResampler.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageProcessorCore { /// <summary> /// The function implements the box algorithm. Similar to nearest neighbour when upscaling. /// When downscaling the pixels will average, merging together. /// </summary> public class BoxResampler : IResampler { /// <inheritdoc/> public float Radius => 0.5F; /// <inheritdoc/> public float GetValue(float x) { if (x > -0.5F && x <= 0.5F) { return 1; } return 0; } } }
25.758621
95
0.57162
[ "Apache-2.0" ]
ChaseFlorell/ImageProcessor
src/ImageProcessorCore/Samplers/Resamplers/BoxResampler.cs
749
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Live.V20180801.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class HttpStatusData : AbstractModel { /// <summary> /// 数据时间点, /// 格式:yyyy-mm-dd HH:MM:SS。 /// </summary> [JsonProperty("Time")] public string Time{ get; set; } /// <summary> /// 播放状态码详细信息。 /// </summary> [JsonProperty("HttpStatusInfoList")] public HttpStatusInfo[] HttpStatusInfoList{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "Time", this.Time); this.SetParamArrayObj(map, prefix + "HttpStatusInfoList.", this.HttpStatusInfoList); } } }
30.346154
96
0.637516
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Live/V20180801/Models/HttpStatusData.cs
1,618
C#
using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Rest; using Discord.WebSocket; using Modix.Common.Messaging; using Modix.Data.Models.Moderation; using Modix.Services.Core; using Modix.Services.Utilities; using Serilog; namespace Modix.Services.Moderation { /// <summary> /// Implements a handler that synchronizes infractions when applied manually through the Discord UI instead of through MODiX. /// </summary> public class InfractionSyncingHandler : INotificationHandler<UserBannedNotification> { private readonly IModerationService _moderationService; private readonly DiscordRestClient _restClient; private readonly IAuthorizationService _authorizationService; /// <summary> /// Constructs a new <see cref="InfractionSyncingHandler"/> object with the given injected dependencies. /// </summary> /// <param name="moderationService">A moderation service to interact with the infractions system.</param> /// <param name="restClient">A REST client to interact with the Discord API.</param> public InfractionSyncingHandler( IModerationService moderationService, IAuthorizationService authorizationService, DiscordRestClient restClient) { _moderationService = moderationService; _restClient = restClient; _authorizationService = authorizationService; } public Task HandleNotificationAsync(UserBannedNotification notification, CancellationToken cancellationToken) => TryCreateBanInfractionAsync(notification.User, notification.Guild); /// <summary> /// Creates a ban infraction for the user if they do not already have one. /// </summary> /// <param name="guild">The guild that the user was banned from.</param> /// <param name="user">The user who was banned.</param> /// <returns> /// A <see cref="Task"/> that will complete when the operation completes. /// </returns> private async Task TryCreateBanInfractionAsync(ISocketUser user, ISocketGuild guild) { if (await _moderationService.AnyInfractionsAsync(GetBanSearchCriteria(guild, user))) { return; } var restGuild = await _restClient.GetGuildAsync(guild.Id); var allAudits = await restGuild.GetAuditLogsAsync(10).FlattenAsync(); var banLog = allAudits .Where(x => x.Action == ActionType.Ban && x.Data is BanAuditLogData) .Select(x => (Entry: x, Data: (BanAuditLogData)x.Data)) .FirstOrDefault(x => x.Data.Target.Id == user.Id); // We're in a scenario in where the guild does not have a Discord audit of the // ban MODiX just received, if that's the case something has gone wrong and we // need to investigate. if(banLog.Data is null || banLog.Entry is null) { // Snapshot the most amount of information possible about this event // to log this incident and investigate further var mostRecentAudit = allAudits.OrderByDescending(x => x.CreatedAt).FirstOrDefault(); Log.Error("No ban audit found when handling {message} for user {userId}, in guild {guild} - " + "the most recent audit was created at {mostRecentAuditTime}: {mostRecentAuditAction} for user: {mostRecentAuditUserId}", nameof(UserBannedNotification), user.Id, guild.Id, mostRecentAudit?.CreatedAt, mostRecentAudit?.Action, mostRecentAudit?.User.Id); return; } var reason = string.IsNullOrWhiteSpace(banLog.Entry.Reason) ? $"Banned by {banLog.Entry.User.GetFullUsername()}." : banLog.Entry.Reason; var guildUser = guild.GetUser(banLog.Entry.User.Id); await _authorizationService.OnAuthenticatedAsync(guildUser.Id, guildUser.Guild.Id, guildUser.RoleIds.ToList()); await _moderationService.CreateInfractionAsync(guild.Id, banLog.Entry.User.Id, InfractionType.Ban, user.Id, reason, null); } private InfractionSearchCriteria GetBanSearchCriteria(IGuild guild, IUser user) => new InfractionSearchCriteria() { GuildId = guild.Id, SubjectId = user.Id, Types = new[] { InfractionType.Ban }, IsDeleted = false, IsRescinded = false, }; } }
42.927928
146
0.628122
[ "MIT" ]
CryoMyst/MODiX
Modix.Services/Moderation/InfractionSyncingHandler.cs
4,767
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.ComponentModel; using Pulumi; namespace Pulumi.AzureNextGen.Resources.V20190701 { /// <summary> /// The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources. /// </summary> [EnumType] public readonly struct DeploymentMode : IEquatable<DeploymentMode> { private readonly string _value; private DeploymentMode(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static DeploymentMode Incremental { get; } = new DeploymentMode("Incremental"); public static DeploymentMode Complete { get; } = new DeploymentMode("Complete"); public static bool operator ==(DeploymentMode left, DeploymentMode right) => left.Equals(right); public static bool operator !=(DeploymentMode left, DeploymentMode right) => !left.Equals(right); public static explicit operator string(DeploymentMode value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is DeploymentMode other && Equals(other); public bool Equals(DeploymentMode other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment. /// </summary> [EnumType] public readonly struct OnErrorDeploymentType : IEquatable<OnErrorDeploymentType> { private readonly string _value; private OnErrorDeploymentType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static OnErrorDeploymentType LastSuccessful { get; } = new OnErrorDeploymentType("LastSuccessful"); public static OnErrorDeploymentType SpecificDeployment { get; } = new OnErrorDeploymentType("SpecificDeployment"); public static bool operator ==(OnErrorDeploymentType left, OnErrorDeploymentType right) => left.Equals(right); public static bool operator !=(OnErrorDeploymentType left, OnErrorDeploymentType right) => !left.Equals(right); public static explicit operator string(OnErrorDeploymentType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is OnErrorDeploymentType other && Equals(other); public bool Equals(OnErrorDeploymentType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } /// <summary> /// The identity type. /// </summary> [EnumType] public readonly struct ResourceIdentityType : IEquatable<ResourceIdentityType> { private readonly string _value; private ResourceIdentityType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } public static ResourceIdentityType SystemAssigned { get; } = new ResourceIdentityType("SystemAssigned"); public static ResourceIdentityType UserAssigned { get; } = new ResourceIdentityType("UserAssigned"); public static ResourceIdentityType SystemAssigned_UserAssigned { get; } = new ResourceIdentityType("SystemAssigned, UserAssigned"); public static ResourceIdentityType None { get; } = new ResourceIdentityType("None"); public static bool operator ==(ResourceIdentityType left, ResourceIdentityType right) => left.Equals(right); public static bool operator !=(ResourceIdentityType left, ResourceIdentityType right) => !left.Equals(right); public static explicit operator string(ResourceIdentityType value) => value._value; [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => obj is ResourceIdentityType other && Equals(other); public bool Equals(ResourceIdentityType other) => string.Equals(_value, other._value, StringComparison.Ordinal); [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; public override string ToString() => _value; } }
48.142857
437
0.712957
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Resources/V20190701/Enums.cs
5,055
C#
namespace Azure { public abstract partial class AsyncPageable<T> : System.Collections.Generic.IAsyncEnumerable<T> where T : notnull { protected AsyncPageable() { } protected AsyncPageable(System.Threading.CancellationToken cancellationToken) { } protected virtual System.Threading.CancellationToken CancellationToken { get { throw null; } } public abstract System.Collections.Generic.IAsyncEnumerable<Azure.Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = default(int?)); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.AsyncPageable<T> FromPages(System.Collections.Generic.IEnumerable<Azure.Page<T>> pages) { throw null; } public virtual System.Collections.Generic.IAsyncEnumerator<T> GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public static partial class AzureCoreExtensions { public static System.Threading.Tasks.ValueTask<T?> ToObjectAsync<T>(this System.BinaryData data, Azure.Core.Serialization.ObjectSerializer serializer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static T? ToObject<T>(this System.BinaryData data, Azure.Core.Serialization.ObjectSerializer serializer, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class AzureKeyCredential { public AzureKeyCredential(string key) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string Key { get { throw null; } } public void Update(string key) { } } public partial class AzureNamedKeyCredential { public AzureNamedKeyCredential(string name, string key) { } public string Name { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Deconstruct(out string name, out string key) { throw null; } public void Update(string name, string key) { } } public partial class AzureSasCredential { public AzureSasCredential(string signature) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string Signature { get { throw null; } } public void Update(string signature) { } } [System.FlagsAttribute] public enum ErrorOptions { Default = 0, NoThrow = 1, } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ETag : System.IEquatable<Azure.ETag> { private readonly object _dummy; private readonly int _dummyPrimitive; public static readonly Azure.ETag All; public ETag(string etag) { throw null; } public bool Equals(Azure.ETag other) { throw null; } public override bool Equals(object? obj) { throw null; } public bool Equals(string? other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ETag left, Azure.ETag right) { throw null; } public static bool operator !=(Azure.ETag left, Azure.ETag right) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } public string ToString(string format) { throw null; } } public partial class HttpAuthorization { public HttpAuthorization(string scheme, string parameter) { } public string Parameter { get { throw null; } } public string Scheme { get { throw null; } } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HttpRange : System.IEquatable<Azure.HttpRange> { private readonly int _dummyPrimitive; public HttpRange(long offset = (long)0, long? length = default(long?)) { throw null; } public long? Length { get { throw null; } } public long Offset { get { throw null; } } public bool Equals(Azure.HttpRange other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.HttpRange left, Azure.HttpRange right) { throw null; } public static bool operator !=(Azure.HttpRange left, Azure.HttpRange right) { throw null; } public override string ToString() { throw null; } } public partial class JsonPatchDocument { public JsonPatchDocument() { } public JsonPatchDocument(Azure.Core.Serialization.ObjectSerializer serializer) { } public JsonPatchDocument(System.ReadOnlyMemory<byte> rawDocument) { } public JsonPatchDocument(System.ReadOnlyMemory<byte> rawDocument, Azure.Core.Serialization.ObjectSerializer serializer) { } public void AppendAddRaw(string path, string rawJsonValue) { } public void AppendAdd<T>(string path, T value) { } public void AppendCopy(string from, string path) { } public void AppendMove(string from, string path) { } public void AppendRemove(string path) { } public void AppendReplaceRaw(string path, string rawJsonValue) { } public void AppendReplace<T>(string path, T value) { } public void AppendTestRaw(string path, string rawJsonValue) { } public void AppendTest<T>(string path, T value) { } public System.ReadOnlyMemory<byte> ToBytes() { throw null; } public override string ToString() { throw null; } } public partial class MatchConditions { public MatchConditions() { } public Azure.ETag? IfMatch { get { throw null; } set { } } public Azure.ETag? IfNoneMatch { get { throw null; } set { } } } public abstract partial class Operation { protected Operation() { } public abstract bool HasCompleted { get; } public abstract string Id { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } public abstract Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public virtual Azure.Response WaitForCompletionResponse(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response WaitForCompletionResponse(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class Operation<T> : Azure.Operation where T : notnull { protected Operation() { } public abstract bool HasValue { get; } public abstract T Value { get; } public virtual Azure.Response<T> WaitForCompletion(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<T> WaitForCompletion(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Response<T>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.ValueTask<Azure.Response<T>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override System.Threading.Tasks.ValueTask<Azure.Response> WaitForCompletionResponseAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class PageableOperation<T> : Azure.Operation<Azure.AsyncPageable<T>> where T : notnull { protected PageableOperation() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override Azure.AsyncPageable<T> Value { get { throw null; } } public abstract Azure.Pageable<T> GetValues(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); public abstract Azure.AsyncPageable<T> GetValuesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public abstract partial class Pageable<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.IEnumerable where T : notnull { protected Pageable() { } protected Pageable(System.Threading.CancellationToken cancellationToken) { } protected virtual System.Threading.CancellationToken CancellationToken { get { throw null; } } public abstract System.Collections.Generic.IEnumerable<Azure.Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = default(int?)); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.Pageable<T> FromPages(System.Collections.Generic.IEnumerable<Azure.Page<T>> pages) { throw null; } public virtual System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public abstract partial class Page<T> { protected Page() { } public abstract string? ContinuationToken { get; } public abstract System.Collections.Generic.IReadOnlyList<T> Values { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } public static Azure.Page<T> FromValues(System.Collections.Generic.IReadOnlyList<T> values, string? continuationToken, Azure.Response response) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } public partial class RequestConditions : Azure.MatchConditions { public RequestConditions() { } public System.DateTimeOffset? IfModifiedSince { get { throw null; } set { } } public System.DateTimeOffset? IfUnmodifiedSince { get { throw null; } set { } } } public partial class RequestContext : Azure.RequestOptions { public RequestContext() { } public RequestContext(Azure.RequestOptions options) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } set { } } public static implicit operator Azure.RequestContext (Azure.ErrorOptions options) { throw null; } } public partial class RequestFailedException : System.Exception, System.Runtime.Serialization.ISerializable { public RequestFailedException(Azure.Response response) { } public RequestFailedException(int status, string message) { } public RequestFailedException(int status, string message, System.Exception? innerException) { } public RequestFailedException(int status, string message, string? errorCode, System.Exception? innerException) { } protected RequestFailedException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public RequestFailedException(string message) { } public RequestFailedException(string message, System.Exception? innerException) { } public string? ErrorCode { get { throw null; } } public int Status { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } public partial class RequestOptions { public RequestOptions() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] protected RequestOptions(Azure.RequestOptions options) { } public Azure.ErrorOptions ErrorOptions { get { throw null; } set { } } public void AddClassifier(Azure.Core.ResponseClassificationHandler classifier) { } public void AddClassifier(int statusCode, bool isError) { } public void AddPolicy(Azure.Core.Pipeline.HttpPipelinePolicy policy, Azure.Core.HttpPipelinePosition position) { } } public abstract partial class Response : System.IDisposable { protected Response() { } public abstract string ClientRequestId { get; set; } public virtual System.BinaryData Content { get { throw null; } } public abstract System.IO.Stream? ContentStream { get; set; } public virtual Azure.Core.ResponseHeaders Headers { get { throw null; } } public virtual bool IsError { get { throw null; } } public abstract string ReasonPhrase { get; } public abstract int Status { get; } protected internal abstract bool ContainsHeader(string name); public abstract void Dispose(); protected internal abstract System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader> EnumerateHeaders(); public static Azure.Response<T> FromValue<T>(T value, Azure.Response response) { throw null; } public override string ToString() { throw null; } protected internal abstract bool TryGetHeader(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value); protected internal abstract bool TryGetHeaderValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values); } public sealed partial class ResponseError { public ResponseError(string? code, string? message) { } public string? Code { get { throw null; } } public string? Message { get { throw null; } } public override string ToString() { throw null; } } public abstract partial class Response<T> { protected Response() { } public abstract T Value { get; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public abstract Azure.Response GetRawResponse(); public static implicit operator T (Azure.Response<T> response) { throw null; } public override string ToString() { throw null; } } public partial class SyncAsyncEventArgs : System.EventArgs { public SyncAsyncEventArgs(bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public bool IsRunningSynchronously { get { throw null; } } } } namespace Azure.Core { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct AccessToken { private object _dummy; private int _dummyPrimitive; public AccessToken(string accessToken, System.DateTimeOffset expiresOn) { throw null; } public System.DateTimeOffset ExpiresOn { get { throw null; } } public string Token { get { throw null; } } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct AzureLocation : System.IEquatable<Azure.Core.AzureLocation> { private readonly object _dummy; private readonly int _dummyPrimitive; public AzureLocation(string location) { throw null; } public AzureLocation(string name, string displayName) { throw null; } public static Azure.Core.AzureLocation AustraliaCentral { get { throw null; } } public static Azure.Core.AzureLocation AustraliaCentral2 { get { throw null; } } public static Azure.Core.AzureLocation AustraliaEast { get { throw null; } } public static Azure.Core.AzureLocation AustraliaSoutheast { get { throw null; } } public static Azure.Core.AzureLocation BrazilSouth { get { throw null; } } public static Azure.Core.AzureLocation BrazilSoutheast { get { throw null; } } public static Azure.Core.AzureLocation CanadaCentral { get { throw null; } } public static Azure.Core.AzureLocation CanadaEast { get { throw null; } } public static Azure.Core.AzureLocation CentralIndia { get { throw null; } } public static Azure.Core.AzureLocation CentralUS { get { throw null; } } public string? DisplayName { get { throw null; } } public static Azure.Core.AzureLocation EastAsia { get { throw null; } } public static Azure.Core.AzureLocation EastUS { get { throw null; } } public static Azure.Core.AzureLocation EastUS2 { get { throw null; } } public static Azure.Core.AzureLocation FranceCentral { get { throw null; } } public static Azure.Core.AzureLocation FranceSouth { get { throw null; } } public static Azure.Core.AzureLocation GermanyNorth { get { throw null; } } public static Azure.Core.AzureLocation GermanyWestCentral { get { throw null; } } public static Azure.Core.AzureLocation JapanEast { get { throw null; } } public static Azure.Core.AzureLocation JapanWest { get { throw null; } } public static Azure.Core.AzureLocation KoreaCentral { get { throw null; } } public static Azure.Core.AzureLocation KoreaSouth { get { throw null; } } public string Name { get { throw null; } } public static Azure.Core.AzureLocation NorthCentralUS { get { throw null; } } public static Azure.Core.AzureLocation NorthEurope { get { throw null; } } public static Azure.Core.AzureLocation NorwayWest { get { throw null; } } public static Azure.Core.AzureLocation SouthAfricaNorth { get { throw null; } } public static Azure.Core.AzureLocation SouthAfricaWest { get { throw null; } } public static Azure.Core.AzureLocation SouthCentralUS { get { throw null; } } public static Azure.Core.AzureLocation SoutheastAsia { get { throw null; } } public static Azure.Core.AzureLocation SouthIndia { get { throw null; } } public static Azure.Core.AzureLocation SwitzerlandNorth { get { throw null; } } public static Azure.Core.AzureLocation SwitzerlandWest { get { throw null; } } public static Azure.Core.AzureLocation UAECentral { get { throw null; } } public static Azure.Core.AzureLocation UAENorth { get { throw null; } } public static Azure.Core.AzureLocation UKSouth { get { throw null; } } public static Azure.Core.AzureLocation UKWest { get { throw null; } } public static Azure.Core.AzureLocation WestCentralUS { get { throw null; } } public static Azure.Core.AzureLocation WestEurope { get { throw null; } } public static Azure.Core.AzureLocation WestIndia { get { throw null; } } public static Azure.Core.AzureLocation WestUS { get { throw null; } } public static Azure.Core.AzureLocation WestUS2 { get { throw null; } } public bool Equals(Azure.Core.AzureLocation other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.AzureLocation left, Azure.Core.AzureLocation right) { throw null; } public static implicit operator string (Azure.Core.AzureLocation location) { throw null; } public static implicit operator Azure.Core.AzureLocation (string location) { throw null; } public static bool operator !=(Azure.Core.AzureLocation left, Azure.Core.AzureLocation right) { throw null; } public override string ToString() { throw null; } } public abstract partial class ClientOptions { protected ClientOptions() { } public static Azure.Core.ClientOptions Default { get { throw null; } } public Azure.Core.DiagnosticsOptions Diagnostics { get { throw null; } } public Azure.Core.RetryOptions Retry { get { throw null; } } public Azure.Core.Pipeline.HttpPipelineTransport Transport { get { throw null; } set { } } public void AddPolicy(Azure.Core.Pipeline.HttpPipelinePolicy policy, Azure.Core.HttpPipelinePosition position) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string? ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ContentType : System.IEquatable<Azure.Core.ContentType>, System.IEquatable<string> { private readonly object _dummy; private readonly int _dummyPrimitive; public ContentType(string contentType) { throw null; } public static Azure.Core.ContentType ApplicationJson { get { throw null; } } public static Azure.Core.ContentType ApplicationOctetStream { get { throw null; } } public static Azure.Core.ContentType TextPlain { get { throw null; } } public bool Equals(Azure.Core.ContentType other) { throw null; } public override bool Equals(object? obj) { throw null; } public bool Equals(string? other) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.ContentType left, Azure.Core.ContentType right) { throw null; } public static implicit operator Azure.Core.ContentType (string contentType) { throw null; } public static bool operator !=(Azure.Core.ContentType left, Azure.Core.ContentType right) { throw null; } public override string ToString() { throw null; } } public partial class CoreResponseClassifier : Azure.Core.ResponseClassifier { public CoreResponseClassifier(System.ReadOnlySpan<int> nonErrors) { } public override bool IsErrorResponse(Azure.Core.HttpMessage message) { throw null; } } public static partial class DelegatedTokenCredential { public static Azure.Core.TokenCredential Create(System.Func<Azure.Core.TokenRequestContext, System.Threading.CancellationToken, Azure.Core.AccessToken> getToken) { throw null; } public static Azure.Core.TokenCredential Create(System.Func<Azure.Core.TokenRequestContext, System.Threading.CancellationToken, Azure.Core.AccessToken> getToken, System.Func<Azure.Core.TokenRequestContext, System.Threading.CancellationToken, System.Threading.Tasks.ValueTask<Azure.Core.AccessToken>> getTokenAsync) { throw null; } } public partial class DiagnosticsOptions { internal DiagnosticsOptions() { } public string? ApplicationId { get { throw null; } set { } } public static string? DefaultApplicationId { get { throw null; } set { } } public bool IsDistributedTracingEnabled { get { throw null; } set { } } public bool IsLoggingContentEnabled { get { throw null; } set { } } public bool IsLoggingEnabled { get { throw null; } set { } } public bool IsTelemetryEnabled { get { throw null; } set { } } public int LoggedContentSizeLimit { get { throw null; } set { } } public System.Collections.Generic.IList<string> LoggedHeaderNames { get { throw null; } } public System.Collections.Generic.IList<string> LoggedQueryParameters { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct HttpHeader : System.IEquatable<Azure.Core.HttpHeader> { private readonly object _dummy; private readonly int _dummyPrimitive; public HttpHeader(string name, string value) { throw null; } public string Name { get { throw null; } } public string Value { get { throw null; } } public bool Equals(Azure.Core.HttpHeader other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } public static partial class Common { public static readonly Azure.Core.HttpHeader FormUrlEncodedContentType; public static readonly Azure.Core.HttpHeader JsonAccept; public static readonly Azure.Core.HttpHeader JsonContentType; public static readonly Azure.Core.HttpHeader OctetStreamContentType; } public static partial class Names { public static string Accept { get { throw null; } } public static string Authorization { get { throw null; } } public static string ContentDisposition { get { throw null; } } public static string ContentLength { get { throw null; } } public static string ContentType { get { throw null; } } public static string Date { get { throw null; } } public static string ETag { get { throw null; } } public static string Host { get { throw null; } } public static string IfMatch { get { throw null; } } public static string IfModifiedSince { get { throw null; } } public static string IfNoneMatch { get { throw null; } } public static string IfUnmodifiedSince { get { throw null; } } public static string Prefer { get { throw null; } } public static string Range { get { throw null; } } public static string Referer { get { throw null; } } public static string UserAgent { get { throw null; } } public static string WwwAuthenticate { get { throw null; } } public static string XMsDate { get { throw null; } } public static string XMsRange { get { throw null; } } public static string XMsRequestId { get { throw null; } } } } public sealed partial class HttpMessage : System.IDisposable { public HttpMessage(Azure.Core.Request request, Azure.Core.ResponseClassifier responseClassifier) { } public bool BufferResponse { get { throw null; } set { } } public System.Threading.CancellationToken CancellationToken { get { throw null; } } public bool HasResponse { get { throw null; } } public System.TimeSpan? NetworkTimeout { get { throw null; } set { } } public Azure.Core.Request Request { get { throw null; } } public Azure.Response Response { get { throw null; } set { } } public Azure.Core.ResponseClassifier ResponseClassifier { get { throw null; } set { } } public void Dispose() { } public System.IO.Stream? ExtractResponseContent() { throw null; } public void SetProperty(string name, object value) { } public bool TryGetProperty(string name, out object? value) { throw null; } } public enum HttpPipelinePosition { PerCall = 0, PerRetry = 1, BeforeTransport = 2, } public abstract partial class Request : System.IDisposable { protected Request() { } public abstract string ClientRequestId { get; set; } public virtual Azure.Core.RequestContent? Content { get { throw null; } set { } } public Azure.Core.RequestHeaders Headers { get { throw null; } } public virtual Azure.Core.RequestMethod Method { get { throw null; } set { } } public virtual Azure.Core.RequestUriBuilder Uri { get { throw null; } set { } } protected internal abstract void AddHeader(string name, string value); protected internal abstract bool ContainsHeader(string name); public abstract void Dispose(); protected internal abstract System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader> EnumerateHeaders(); protected internal abstract bool RemoveHeader(string name); protected internal virtual void SetHeader(string name, string value) { } protected internal abstract bool TryGetHeader(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value); protected internal abstract bool TryGetHeaderValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values); } public abstract partial class RequestContent : System.IDisposable { protected RequestContent() { } public static Azure.Core.RequestContent Create(System.BinaryData content) { throw null; } public static Azure.Core.RequestContent Create(System.Buffers.ReadOnlySequence<byte> bytes) { throw null; } public static Azure.Core.RequestContent Create(byte[] bytes) { throw null; } public static Azure.Core.RequestContent Create(byte[] bytes, int index, int length) { throw null; } public static Azure.Core.RequestContent Create(System.IO.Stream stream) { throw null; } public static Azure.Core.RequestContent Create(object serializable, Azure.Core.Serialization.ObjectSerializer? serializer = null) { throw null; } public static Azure.Core.RequestContent Create(System.ReadOnlyMemory<byte> bytes) { throw null; } public static Azure.Core.RequestContent Create(string content) { throw null; } public abstract void Dispose(); public static implicit operator Azure.Core.RequestContent (System.BinaryData content) { throw null; } public static implicit operator Azure.Core.RequestContent (string content) { throw null; } public abstract bool TryComputeLength(out long length); public abstract void WriteTo(System.IO.Stream stream, System.Threading.CancellationToken cancellation); public abstract System.Threading.Tasks.Task WriteToAsync(System.IO.Stream stream, System.Threading.CancellationToken cancellation); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RequestHeaders : System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader>, System.Collections.IEnumerable { private readonly object _dummy; private readonly int _dummyPrimitive; public void Add(Azure.Core.HttpHeader header) { } public void Add(string name, string value) { } public bool Contains(string name) { throw null; } public System.Collections.Generic.IEnumerator<Azure.Core.HttpHeader> GetEnumerator() { throw null; } public bool Remove(string name) { throw null; } public void SetValue(string name, string value) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value) { throw null; } public bool TryGetValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct RequestMethod : System.IEquatable<Azure.Core.RequestMethod> { private readonly object _dummy; private readonly int _dummyPrimitive; public RequestMethod(string method) { throw null; } public static Azure.Core.RequestMethod Delete { get { throw null; } } public static Azure.Core.RequestMethod Get { get { throw null; } } public static Azure.Core.RequestMethod Head { get { throw null; } } public string Method { get { throw null; } } public static Azure.Core.RequestMethod Options { get { throw null; } } public static Azure.Core.RequestMethod Patch { get { throw null; } } public static Azure.Core.RequestMethod Post { get { throw null; } } public static Azure.Core.RequestMethod Put { get { throw null; } } public static Azure.Core.RequestMethod Trace { get { throw null; } } public bool Equals(Azure.Core.RequestMethod other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.RequestMethod left, Azure.Core.RequestMethod right) { throw null; } public static bool operator !=(Azure.Core.RequestMethod left, Azure.Core.RequestMethod right) { throw null; } public static Azure.Core.RequestMethod Parse(string method) { throw null; } public override string ToString() { throw null; } } public partial class RequestUriBuilder { public RequestUriBuilder() { } public string? Host { get { throw null; } set { } } public string Path { get { throw null; } set { } } public string PathAndQuery { get { throw null; } } public int Port { get { throw null; } set { } } public string Query { get { throw null; } set { } } public string? Scheme { get { throw null; } set { } } public void AppendPath(string value) { } public void AppendPath(string value, bool escape) { } public void AppendQuery(string name, string value) { } public void AppendQuery(string name, string value, bool escapeValue) { } public void Reset(System.Uri value) { } public override string ToString() { throw null; } public System.Uri ToUri() { throw null; } } public sealed partial class ResourceIdentifier : System.IComparable<Azure.Core.ResourceIdentifier>, System.IEquatable<Azure.Core.ResourceIdentifier> { public static readonly Azure.Core.ResourceIdentifier Root; public ResourceIdentifier(string resourceId) { } public Azure.Core.AzureLocation? Location { get { throw null; } } public string Name { get { throw null; } } public Azure.Core.ResourceIdentifier? Parent { get { throw null; } } public string? Provider { get { throw null; } } public string? ResourceGroupName { get { throw null; } } public Azure.Core.ResourceType ResourceType { get { throw null; } } public string? SubscriptionId { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Azure.Core.ResourceIdentifier AppendChildResource(string childResourceType, string childResourceName) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Azure.Core.ResourceIdentifier AppendProviderResource(string providerNamespace, string resourceType, string resourceName) { throw null; } public int CompareTo(Azure.Core.ResourceIdentifier? other) { throw null; } public bool Equals(Azure.Core.ResourceIdentifier? other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public static bool operator >(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public static bool operator >=(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public static implicit operator string (Azure.Core.ResourceIdentifier id) { throw null; } public static bool operator !=(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public static bool operator <(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public static bool operator <=(Azure.Core.ResourceIdentifier left, Azure.Core.ResourceIdentifier right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ResourceType : System.IEquatable<Azure.Core.ResourceType> { private readonly object _dummy; private readonly int _dummyPrimitive; public ResourceType(string resourceType) { throw null; } public string Namespace { get { throw null; } } public string Type { get { throw null; } } public bool Equals(Azure.Core.ResourceType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object? other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string GetLastType() { throw null; } public static bool operator ==(Azure.Core.ResourceType left, Azure.Core.ResourceType right) { throw null; } public static implicit operator string (Azure.Core.ResourceType resourceType) { throw null; } public static implicit operator Azure.Core.ResourceType (string resourceType) { throw null; } public static bool operator !=(Azure.Core.ResourceType left, Azure.Core.ResourceType right) { throw null; } public override string ToString() { throw null; } } public abstract partial class ResponseClassificationHandler { protected ResponseClassificationHandler() { } public abstract bool TryClassify(Azure.Core.HttpMessage message, out bool isError); } public partial class ResponseClassifier { public ResponseClassifier() { } public virtual bool IsErrorResponse(Azure.Core.HttpMessage message) { throw null; } public virtual bool IsRetriable(Azure.Core.HttpMessage message, System.Exception exception) { throw null; } public virtual bool IsRetriableException(System.Exception exception) { throw null; } public virtual bool IsRetriableResponse(Azure.Core.HttpMessage message) { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ResponseHeaders : System.Collections.Generic.IEnumerable<Azure.Core.HttpHeader>, System.Collections.IEnumerable { private readonly object _dummy; private readonly int _dummyPrimitive; public int? ContentLength { get { throw null; } } public string? ContentType { get { throw null; } } public System.DateTimeOffset? Date { get { throw null; } } public Azure.ETag? ETag { get { throw null; } } public string? RequestId { get { throw null; } } public bool Contains(string name) { throw null; } public System.Collections.Generic.IEnumerator<Azure.Core.HttpHeader> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } public bool TryGetValue(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out string? value) { throw null; } public bool TryGetValues(string name, [System.Diagnostics.CodeAnalysis.NotNullWhenAttribute(true)] out System.Collections.Generic.IEnumerable<string>? values) { throw null; } } public enum RetryMode { Fixed = 0, Exponential = 1, } public partial class RetryOptions { internal RetryOptions() { } public System.TimeSpan Delay { get { throw null; } set { } } public System.TimeSpan MaxDelay { get { throw null; } set { } } public int MaxRetries { get { throw null; } set { } } public Azure.Core.RetryMode Mode { get { throw null; } set { } } public System.TimeSpan NetworkTimeout { get { throw null; } set { } } } public delegate System.Threading.Tasks.Task SyncAsyncEventHandler<T>(T e) where T : Azure.SyncAsyncEventArgs; public abstract partial class TokenCredential { protected TokenCredential() { } public abstract Azure.Core.AccessToken GetToken(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken); public abstract System.Threading.Tasks.ValueTask<Azure.Core.AccessToken> GetTokenAsync(Azure.Core.TokenRequestContext requestContext, System.Threading.CancellationToken cancellationToken); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct TokenRequestContext { private readonly object _dummy; private readonly int _dummyPrimitive; public TokenRequestContext(string[] scopes, string? parentRequestId) { throw null; } public TokenRequestContext(string[] scopes, string? parentRequestId, string? claims) { throw null; } public TokenRequestContext(string[] scopes, string? parentRequestId = null, string? claims = null, string? tenantId = null) { throw null; } public string? Claims { get { throw null; } } public string? ParentRequestId { get { throw null; } } public string[] Scopes { get { throw null; } } public string? TenantId { get { throw null; } } } } namespace Azure.Core.Cryptography { public partial interface IKeyEncryptionKey { string KeyId { get; } byte[] UnwrapKey(string algorithm, System.ReadOnlyMemory<byte> encryptedKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<byte[]> UnwrapKeyAsync(string algorithm, System.ReadOnlyMemory<byte> encryptedKey, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); byte[] WrapKey(string algorithm, System.ReadOnlyMemory<byte> key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<byte[]> WrapKeyAsync(string algorithm, System.ReadOnlyMemory<byte> key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } public partial interface IKeyEncryptionKeyResolver { Azure.Core.Cryptography.IKeyEncryptionKey Resolve(string keyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); System.Threading.Tasks.Task<Azure.Core.Cryptography.IKeyEncryptionKey> ResolveAsync(string keyId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } } namespace Azure.Core.Diagnostics { public partial class AzureEventSourceListener : System.Diagnostics.Tracing.EventListener { public const string TraitName = "AzureEventSource"; public const string TraitValue = "true"; public AzureEventSourceListener(System.Action<System.Diagnostics.Tracing.EventWrittenEventArgs, string> log, System.Diagnostics.Tracing.EventLevel level) { } public static Azure.Core.Diagnostics.AzureEventSourceListener CreateConsoleLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; } public static Azure.Core.Diagnostics.AzureEventSourceListener CreateTraceLogger(System.Diagnostics.Tracing.EventLevel level = System.Diagnostics.Tracing.EventLevel.Informational) { throw null; } protected sealed override void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { } protected sealed override void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { } } } namespace Azure.Core.Extensions { public partial interface IAzureClientBuilder<TClient, TOptions> where TOptions : class { } public partial interface IAzureClientFactoryBuilder { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(System.Func<TOptions, TClient> clientFactory) where TOptions : class; } public partial interface IAzureClientFactoryBuilderWithConfiguration<in TConfiguration> : Azure.Core.Extensions.IAzureClientFactoryBuilder { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(TConfiguration configuration) where TOptions : class; } public partial interface IAzureClientFactoryBuilderWithCredential { Azure.Core.Extensions.IAzureClientBuilder<TClient, TOptions> RegisterClientFactory<TClient, TOptions>(System.Func<TOptions, Azure.Core.TokenCredential, TClient> clientFactory, bool requiresCredential = true) where TOptions : class; } } namespace Azure.Core.GeoJson { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct GeoArray<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.Generic.IReadOnlyList<T>, System.Collections.IEnumerable { private readonly object _dummy; private readonly int _dummyPrimitive; public int Count { get { throw null; } } public T this[int index] { get { throw null; } } public Azure.Core.GeoJson.GeoArray<T>.Enumerator GetEnumerator() { throw null; } System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public partial struct Enumerator : System.Collections.Generic.IEnumerator<T>, System.Collections.IEnumerator, System.IDisposable { private object _dummy; private int _dummyPrimitive; public T Current { get { throw null; } } object System.Collections.IEnumerator.Current { get { throw null; } } public void Dispose() { } public bool MoveNext() { throw null; } public void Reset() { } } } public sealed partial class GeoBoundingBox : System.IEquatable<Azure.Core.GeoJson.GeoBoundingBox> { public GeoBoundingBox(double west, double south, double east, double north) { } public GeoBoundingBox(double west, double south, double east, double north, double? minAltitude, double? maxAltitude) { } public double East { get { throw null; } } public double this[int index] { get { throw null; } } public double? MaxAltitude { get { throw null; } } public double? MinAltitude { get { throw null; } } public double North { get { throw null; } } public double South { get { throw null; } } public double West { get { throw null; } } public bool Equals(Azure.Core.GeoJson.GeoBoundingBox? other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public override string ToString() { throw null; } } public sealed partial class GeoCollection : Azure.Core.GeoJson.GeoObject, System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoObject>, System.Collections.Generic.IReadOnlyCollection<Azure.Core.GeoJson.GeoObject>, System.Collections.Generic.IReadOnlyList<Azure.Core.GeoJson.GeoObject>, System.Collections.IEnumerable { public GeoCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoObject> geometries) { } public GeoCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoObject> geometries, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public int Count { get { throw null; } } public Azure.Core.GeoJson.GeoObject this[int index] { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } public System.Collections.Generic.IEnumerator<Azure.Core.GeoJson.GeoObject> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class GeoLinearRing { public GeoLinearRing(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPosition> coordinates) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition> Coordinates { get { throw null; } } } public sealed partial class GeoLineString : Azure.Core.GeoJson.GeoObject { public GeoLineString(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPosition> coordinates) { } public GeoLineString(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPosition> coordinates, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition> Coordinates { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } } public sealed partial class GeoLineStringCollection : Azure.Core.GeoJson.GeoObject, System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoLineString>, System.Collections.Generic.IReadOnlyCollection<Azure.Core.GeoJson.GeoLineString>, System.Collections.Generic.IReadOnlyList<Azure.Core.GeoJson.GeoLineString>, System.Collections.IEnumerable { public GeoLineStringCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoLineString> lines) { } public GeoLineStringCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoLineString> lines, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition>> Coordinates { get { throw null; } } public int Count { get { throw null; } } public Azure.Core.GeoJson.GeoLineString this[int index] { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } public System.Collections.Generic.IEnumerator<Azure.Core.GeoJson.GeoLineString> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public abstract partial class GeoObject { internal GeoObject() { } public Azure.Core.GeoJson.GeoBoundingBox? BoundingBox { get { throw null; } } public abstract Azure.Core.GeoJson.GeoObjectType Type { get; } public static Azure.Core.GeoJson.GeoObject Parse(string json) { throw null; } public override string ToString() { throw null; } public bool TryGetCustomProperty(string name, out object? value) { throw null; } } public enum GeoObjectType { Point = 0, MultiPoint = 1, Polygon = 2, MultiPolygon = 3, LineString = 4, MultiLineString = 5, GeometryCollection = 6, } public sealed partial class GeoPoint : Azure.Core.GeoJson.GeoObject { public GeoPoint(Azure.Core.GeoJson.GeoPosition position) { } public GeoPoint(Azure.Core.GeoJson.GeoPosition position, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public GeoPoint(double longitude, double latitude) { } public GeoPoint(double longitude, double latitude, double? altitude) { } public Azure.Core.GeoJson.GeoPosition Coordinates { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } } public sealed partial class GeoPointCollection : Azure.Core.GeoJson.GeoObject, System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPoint>, System.Collections.Generic.IReadOnlyCollection<Azure.Core.GeoJson.GeoPoint>, System.Collections.Generic.IReadOnlyList<Azure.Core.GeoJson.GeoPoint>, System.Collections.IEnumerable { public GeoPointCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPoint> points) { } public GeoPointCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPoint> points, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition> Coordinates { get { throw null; } } public int Count { get { throw null; } } public Azure.Core.GeoJson.GeoPoint this[int index] { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } public System.Collections.Generic.IEnumerator<Azure.Core.GeoJson.GeoPoint> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public sealed partial class GeoPolygon : Azure.Core.GeoJson.GeoObject { public GeoPolygon(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoLinearRing> rings) { } public GeoPolygon(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoLinearRing> rings, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public GeoPolygon(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPosition> positions) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition>> Coordinates { get { throw null; } } public Azure.Core.GeoJson.GeoLinearRing OuterRing { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.Core.GeoJson.GeoLinearRing> Rings { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } } public sealed partial class GeoPolygonCollection : Azure.Core.GeoJson.GeoObject, System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPolygon>, System.Collections.Generic.IReadOnlyCollection<Azure.Core.GeoJson.GeoPolygon>, System.Collections.Generic.IReadOnlyList<Azure.Core.GeoJson.GeoPolygon>, System.Collections.IEnumerable { public GeoPolygonCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPolygon> polygons) { } public GeoPolygonCollection(System.Collections.Generic.IEnumerable<Azure.Core.GeoJson.GeoPolygon> polygons, Azure.Core.GeoJson.GeoBoundingBox? boundingBox, System.Collections.Generic.IReadOnlyDictionary<string, object?> customProperties) { } public Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoArray<Azure.Core.GeoJson.GeoPosition>>> Coordinates { get { throw null; } } public int Count { get { throw null; } } public Azure.Core.GeoJson.GeoPolygon this[int index] { get { throw null; } } public override Azure.Core.GeoJson.GeoObjectType Type { get { throw null; } } public System.Collections.Generic.IEnumerator<Azure.Core.GeoJson.GeoPolygon> GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct GeoPosition : System.IEquatable<Azure.Core.GeoJson.GeoPosition> { private readonly int _dummyPrimitive; public GeoPosition(double longitude, double latitude) { throw null; } public GeoPosition(double longitude, double latitude, double? altitude) { throw null; } public double? Altitude { get { throw null; } } public int Count { get { throw null; } } public double this[int index] { get { throw null; } } public double Latitude { get { throw null; } } public double Longitude { get { throw null; } } public bool Equals(Azure.Core.GeoJson.GeoPosition other) { throw null; } public override bool Equals(object? obj) { throw null; } public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Core.GeoJson.GeoPosition left, Azure.Core.GeoJson.GeoPosition right) { throw null; } public static bool operator !=(Azure.Core.GeoJson.GeoPosition left, Azure.Core.GeoJson.GeoPosition right) { throw null; } public override string ToString() { throw null; } } } namespace Azure.Core.Pipeline { public partial class BearerTokenAuthenticationPolicy : Azure.Core.Pipeline.HttpPipelinePolicy { public BearerTokenAuthenticationPolicy(Azure.Core.TokenCredential credential, System.Collections.Generic.IEnumerable<string> scopes) { } public BearerTokenAuthenticationPolicy(Azure.Core.TokenCredential credential, string scope) { } protected void AuthenticateAndAuthorizeRequest(Azure.Core.HttpMessage message, Azure.Core.TokenRequestContext context) { } protected System.Threading.Tasks.ValueTask AuthenticateAndAuthorizeRequestAsync(Azure.Core.HttpMessage message, Azure.Core.TokenRequestContext context) { throw null; } protected virtual void AuthorizeRequest(Azure.Core.HttpMessage message) { } protected virtual System.Threading.Tasks.ValueTask AuthorizeRequestAsync(Azure.Core.HttpMessage message) { throw null; } protected virtual bool AuthorizeRequestOnChallenge(Azure.Core.HttpMessage message) { throw null; } protected virtual System.Threading.Tasks.ValueTask<bool> AuthorizeRequestOnChallengeAsync(Azure.Core.HttpMessage message) { throw null; } public override void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } public override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public sealed partial class DisposableHttpPipeline : Azure.Core.Pipeline.HttpPipeline, System.IDisposable { internal DisposableHttpPipeline() : base (default(Azure.Core.Pipeline.HttpPipelineTransport), default(Azure.Core.Pipeline.HttpPipelinePolicy[]), default(Azure.Core.ResponseClassifier)) { } public void Dispose() { } } public partial class HttpClientTransport : Azure.Core.Pipeline.HttpPipelineTransport, System.IDisposable { public static readonly Azure.Core.Pipeline.HttpClientTransport Shared; public HttpClientTransport() { } public HttpClientTransport(System.Net.Http.HttpClient client) { } public HttpClientTransport(System.Net.Http.HttpMessageHandler messageHandler) { } public sealed override Azure.Core.Request CreateRequest() { throw null; } public void Dispose() { } public override void Process(Azure.Core.HttpMessage message) { } public override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message) { throw null; } } public static partial class HttpMessageExtensions { public static void SetUserAgentString(this Azure.Core.HttpMessage message, Azure.Core.Pipeline.UserAgentValue userAgentValue) { } } public partial class HttpPipeline { public HttpPipeline(Azure.Core.Pipeline.HttpPipelineTransport transport, Azure.Core.Pipeline.HttpPipelinePolicy[]? policies = null, Azure.Core.ResponseClassifier? responseClassifier = null) { } public Azure.Core.ResponseClassifier ResponseClassifier { get { throw null; } } public static System.IDisposable CreateClientRequestIdScope(string? clientRequestId) { throw null; } public static System.IDisposable CreateHttpMessagePropertiesScope(System.Collections.Generic.IDictionary<string, object?> messageProperties) { throw null; } public Azure.Core.HttpMessage CreateMessage() { throw null; } public Azure.Core.HttpMessage CreateMessage(Azure.RequestContext? context) { throw null; } public Azure.Core.HttpMessage CreateMessage(Azure.RequestContext? context, Azure.Core.CoreResponseClassifier? classifier = null) { throw null; } public Azure.Core.Request CreateRequest() { throw null; } public void Send(Azure.Core.HttpMessage message, System.Threading.CancellationToken cancellationToken) { } public System.Threading.Tasks.ValueTask SendAsync(Azure.Core.HttpMessage message, System.Threading.CancellationToken cancellationToken) { throw null; } public Azure.Response SendRequest(Azure.Core.Request request, System.Threading.CancellationToken cancellationToken) { throw null; } public System.Threading.Tasks.ValueTask<Azure.Response> SendRequestAsync(Azure.Core.Request request, System.Threading.CancellationToken cancellationToken) { throw null; } } public static partial class HttpPipelineBuilder { public static Azure.Core.Pipeline.HttpPipeline Build(Azure.Core.ClientOptions options, params Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies) { throw null; } public static Azure.Core.Pipeline.DisposableHttpPipeline Build(Azure.Core.ClientOptions options, Azure.Core.Pipeline.HttpPipelinePolicy[] perCallPolicies, Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies, Azure.Core.Pipeline.HttpPipelineTransportOptions transportOptions, Azure.Core.ResponseClassifier? responseClassifier) { throw null; } public static Azure.Core.Pipeline.HttpPipeline Build(Azure.Core.ClientOptions options, Azure.Core.Pipeline.HttpPipelinePolicy[] perCallPolicies, Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies, Azure.Core.ResponseClassifier? responseClassifier) { throw null; } } public abstract partial class HttpPipelinePolicy { protected HttpPipelinePolicy() { } public abstract void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline); public abstract System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline); protected static void ProcessNext(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } protected static System.Threading.Tasks.ValueTask ProcessNextAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public abstract partial class HttpPipelineSynchronousPolicy : Azure.Core.Pipeline.HttpPipelinePolicy { protected HttpPipelineSynchronousPolicy() { } public virtual void OnReceivedResponse(Azure.Core.HttpMessage message) { } public virtual void OnSendingRequest(Azure.Core.HttpMessage message) { } public override void Process(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { } public override System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message, System.ReadOnlyMemory<Azure.Core.Pipeline.HttpPipelinePolicy> pipeline) { throw null; } } public abstract partial class HttpPipelineTransport { protected HttpPipelineTransport() { } public abstract Azure.Core.Request CreateRequest(); public abstract void Process(Azure.Core.HttpMessage message); public abstract System.Threading.Tasks.ValueTask ProcessAsync(Azure.Core.HttpMessage message); } public partial class HttpPipelineTransportOptions { public HttpPipelineTransportOptions() { } public System.Func<Azure.Core.Pipeline.ServerCertificateCustomValidationArgs, bool>? ServerCertificateCustomValidationCallback { get { throw null; } set { } } } public partial class ServerCertificateCustomValidationArgs { public ServerCertificateCustomValidationArgs(System.Security.Cryptography.X509Certificates.X509Certificate2? certificate, System.Security.Cryptography.X509Certificates.X509Chain? certificateAuthorityChain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { } public System.Security.Cryptography.X509Certificates.X509Certificate2? Certificate { get { throw null; } } public System.Security.Cryptography.X509Certificates.X509Chain? CertificateAuthorityChain { get { throw null; } } public System.Net.Security.SslPolicyErrors SslPolicyErrors { get { throw null; } } } public partial class UserAgentValue { public UserAgentValue(System.Type type, string? applicationId = null) { } public static Azure.Core.Pipeline.UserAgentValue FromType<T>(string? applicationId = null) { throw null; } public override string ToString() { throw null; } } } namespace Azure.Core.Serialization { public partial interface IMemberNameConverter { string? ConvertMemberName(System.Reflection.MemberInfo member); } public partial class JsonObjectSerializer : Azure.Core.Serialization.ObjectSerializer, Azure.Core.Serialization.IMemberNameConverter { public JsonObjectSerializer() { } public JsonObjectSerializer(System.Text.Json.JsonSerializerOptions options) { } public static Azure.Core.Serialization.JsonObjectSerializer Default { get { throw null; } } string? Azure.Core.Serialization.IMemberNameConverter.ConvertMemberName(System.Reflection.MemberInfo member) { throw null; } public override object? Deserialize(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken) { throw null; } public override void Serialize(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken) { } public override System.BinaryData Serialize(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask SerializeAsync(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken) { throw null; } public override System.Threading.Tasks.ValueTask<System.BinaryData> SerializeAsync(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public abstract partial class ObjectSerializer { protected ObjectSerializer() { } public abstract object? Deserialize(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken); public abstract System.Threading.Tasks.ValueTask<object?> DeserializeAsync(System.IO.Stream stream, System.Type returnType, System.Threading.CancellationToken cancellationToken); public abstract void Serialize(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken); public virtual System.BinaryData Serialize(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public abstract System.Threading.Tasks.ValueTask SerializeAsync(System.IO.Stream stream, object? value, System.Type inputType, System.Threading.CancellationToken cancellationToken); public virtual System.Threading.Tasks.ValueTask<System.BinaryData> SerializeAsync(object? value, System.Type? inputType = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } namespace Azure.Messaging { public partial class CloudEvent { public CloudEvent(string source, string type, System.BinaryData? data, string? dataContentType, Azure.Messaging.CloudEventDataFormat dataFormat = Azure.Messaging.CloudEventDataFormat.Binary) { } public CloudEvent(string source, string type, object? jsonSerializableData, System.Type? dataSerializationType = null) { } public System.BinaryData? Data { get { throw null; } set { } } public string? DataContentType { get { throw null; } set { } } public string? DataSchema { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, object> ExtensionAttributes { get { throw null; } } public string Id { get { throw null; } set { } } public string Source { get { throw null; } set { } } public string? Subject { get { throw null; } set { } } public System.DateTimeOffset? Time { get { throw null; } set { } } public string Type { get { throw null; } set { } } public static Azure.Messaging.CloudEvent? Parse(System.BinaryData json, bool skipValidation = false) { throw null; } public static Azure.Messaging.CloudEvent[] ParseMany(System.BinaryData json, bool skipValidation = false) { throw null; } } public enum CloudEventDataFormat { Binary = 0, Json = 1, } }
73.269951
355
0.729551
[ "MIT" ]
Kyle8329/azure-sdk-for-net
sdk/core/Azure.Core/api/Azure.Core.net5.0.cs
74,369
C#
using System; using System.IO; using GroupDocs.Conversion.Options.Convert; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert OTT file into DOC format. /// For more details about Open Document Template (.ott) to Microsoft Word Document (.doc) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-ott-to-doc /// </summary> internal static class ConvertOttToDoc { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "ott-converted-to.doc"); // Load the source OTT file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_OTT)) { WordProcessingConvertOptions options = new WordProcessingConvertOptions { Format = GroupDocs.Conversion.FileTypes.WordProcessingFileType.Doc }; // Save converted DOC file converter.Convert(outputFile, options); } Console.WriteLine("\nConversion to doc completed successfully. \nCheck output in {0}", outputFolder); } } }
41.129032
159
0.665098
[ "MIT" ]
groupdocs-conversion/GroupDocs.Conversion-for-.NET
Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToWordProcessing/ConvertToDoc/ConvertOttToDoc.cs
1,275
C#
using System; using masz.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace masz.Controllers { [ApiController] [Route("api/v1/meta/")] [Authorize] public class MetaController : ControllerBase { private readonly ILogger<MetaController> logger; private readonly IOptions<InternalConfig> config; public MetaController(ILogger<MetaController> logger, IOptions<InternalConfig> config) { this.logger = logger; this.config = config; } [HttpGet("clientid")] public IActionResult Status() { logger.LogInformation($"{HttpContext.Request.Method} {HttpContext.Request.Path} | Incoming request."); return Ok(new { clientid = config.Value.DiscordClientId }); } } }
29.129032
114
0.674419
[ "MIT" ]
matrix2113/discord-masz
backend/masz/Controllers/api/v1/MetaController.cs
903
C#
// MIT License // Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns // Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd. // 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.Collections.Generic; using Microsoft.Xna.Framework; using Steropes.UI.Components; namespace Steropes.UI.Widgets.Container { public enum DockPanelConstraint { Top = 0, Left = 1, Right = 3, Bottom = 4 } /// <summary> /// A dock-panel allows to attach child widgets to one of the edges of the dock-panel box. The last widget can be stretched to fill any remaining space. /// If the widgets contained in the dock-panel are larger than the available layout space for the dock-panel, the panel will overflow. /// </summary> public class DockPanel : WidgetContainer<DockPanelConstraint> { struct WidgetConstraintAndPosition { public int Position { get; } public IWidget Widget { get; } public DockPanelConstraint Constraint { get; } public WidgetConstraintAndPosition(int position, IWidget widget, DockPanelConstraint constraint) { Position = position; Widget = widget; Constraint = constraint; } } readonly WidgetSorter comparator; readonly List<WidgetConstraintAndPosition> sortedWidgets; bool lastChildFill; public DockPanel(IUIStyle style, bool lastChildFill) : this(style) { LastChildFill = lastChildFill; } public DockPanel(IUIStyle style) : base(style) { sortedWidgets = new List<WidgetConstraintAndPosition>(); comparator = new WidgetSorter(this); } public bool LastChildFill { get { return lastChildFill; } set { lastChildFill = value; OnPropertyChanged(); InvalidateLayout(); } } protected override Rectangle ArrangeOverride(Rectangle layoutSize) { var lastWidget = LastChildFill && Count > 0 ? FindLastVisibleWidget() : null; if (sortedWidgets.Count != Count) { // Sort order is "Top, Left, Right, Bottom". sortedWidgets.Clear(); var list = WidgetsWithConstraints; for (int idx = 0; idx < list.Count; idx += 1) { var widget = list[idx]; sortedWidgets.Add(new WidgetConstraintAndPosition(idx, widget.Widget, widget.Constraint)); } sortedWidgets.Sort(comparator); } var centerRect = ComputeCenterWidget(layoutSize); var xOffset = layoutSize.X; var yOffset = layoutSize.Y; var lastConstraint = DockPanelConstraint.Top; for (var index = 0; index < sortedWidgets.Count; index++) { var widgetAndConstraint = sortedWidgets[index]; var widget = widgetAndConstraint.Widget; if (widget == null) { continue; } if (widget.Visibility == Visibility.Collapsed) { continue; } if (ReferenceEquals(widget, lastWidget)) { widget.Arrange(widget.ArrangeChild(centerRect)); } else { switch (widgetAndConstraint.Constraint) { case DockPanelConstraint.Top: { widget.Arrange(widget.ArrangeChild(new Rectangle(layoutSize.X, yOffset, layoutSize.Width, widget.DesiredSize.HeightInt))); yOffset += widget.DesiredSize.HeightInt; break; } case DockPanelConstraint.Bottom: { if (lastConstraint != DockPanelConstraint.Bottom) { yOffset += centerRect.Height; } widget.Arrange(widget.ArrangeChild(new Rectangle(layoutSize.X, yOffset, layoutSize.Width, widget.DesiredSize.HeightInt))); yOffset += widget.DesiredSize.HeightInt; break; } case DockPanelConstraint.Left: { widget.Arrange(widget.ArrangeChild(new Rectangle(xOffset, yOffset, widget.DesiredSize.WidthInt, centerRect.Height))); xOffset += widget.DesiredSize.WidthInt; break; } case DockPanelConstraint.Right: { if (lastConstraint != DockPanelConstraint.Right) { xOffset += centerRect.Width; } widget.Arrange(widget.ArrangeChild(new Rectangle(xOffset, yOffset, widget.DesiredSize.WidthInt, centerRect.Height))); xOffset += widget.DesiredSize.WidthInt; break; } default: { throw new ArgumentOutOfRangeException(); } } lastConstraint = widgetAndConstraint.Constraint; } } return layoutSize; } protected Rectangle ComputeCenterWidget(Rectangle layoutSize) { var lastWidget = FindLastVisibleWidget(); var usedHeight = 0; var usedWidth = 0; var centerOffsetX = 0; var centerOffsetY = 0; var centerWidth = 0; var centerHeight = 0; for (var index = 0; index < sortedWidgets.Count; index++) { var widgetAndConstraint = sortedWidgets[index]; var widget = widgetAndConstraint.Widget; if (widget == null) { continue; } if (widget.Visibility == Visibility.Collapsed) { continue; } if (ReferenceEquals(widget, lastWidget)) { centerWidth = widget.DesiredSize.WidthInt; centerHeight = widget.DesiredSize.HeightInt; } else { switch (widgetAndConstraint.Constraint) { case DockPanelConstraint.Top: { usedHeight += widget.DesiredSize.HeightInt; centerOffsetY = usedHeight; break; } case DockPanelConstraint.Bottom: { usedHeight += widget.DesiredSize.HeightInt; break; } case DockPanelConstraint.Left: { usedWidth += widget.DesiredSize.WidthInt; centerOffsetX = usedWidth; break; } case DockPanelConstraint.Right: { usedWidth += widget.DesiredSize.WidthInt; break; } default: { throw new ArgumentOutOfRangeException(); } } } } centerWidth = Math.Max(centerWidth, layoutSize.Width - usedWidth); centerHeight = Math.Max(centerHeight, layoutSize.Height - usedHeight); return new Rectangle(layoutSize.X + centerOffsetX, layoutSize.Y + centerOffsetY, centerWidth, centerHeight); } protected override Size MeasureOverride(Size availableSize) { float horizontalWidgetWidth = 0; float horizontalWidgetHeight = 0; float verticalWidgetWidth = 0; float verticalWidgetHeight = 0; var widgetsAndConstraints = WidgetsWithConstraints; for (var index = 0; index < widgetsAndConstraints.Count; index++) { var widgetAndConstraint = widgetsAndConstraints[index]; var widget = widgetAndConstraint.Widget; if (widget == null) { continue; } if (widget.Visibility == Visibility.Collapsed) { continue; } switch (widgetAndConstraint.Constraint) { case DockPanelConstraint.Top: case DockPanelConstraint.Bottom: { widget.Measure(new Size(availableSize.Width, float.PositiveInfinity)); horizontalWidgetWidth = Math.Max(horizontalWidgetWidth, widget.DesiredSize.Width); horizontalWidgetHeight += widget.DesiredSize.Height; break; } case DockPanelConstraint.Left: case DockPanelConstraint.Right: { widget.Measure(new Size(float.PositiveInfinity, availableSize.Height)); verticalWidgetWidth += widget.DesiredSize.Width; verticalWidgetHeight = Math.Max(verticalWidgetHeight, widget.DesiredSize.Height); break; } default: { throw new ArgumentOutOfRangeException(); } } } return new Size(Math.Max(verticalWidgetWidth, horizontalWidgetWidth), verticalWidgetHeight + horizontalWidgetHeight); } protected override void OnChildAdded(IWidget w, int index, DockPanelConstraint constraint) { sortedWidgets.Clear(); base.OnChildAdded(w, index, constraint); } protected override void OnChildRemoved(IWidget w, int index, DockPanelConstraint constraint) { sortedWidgets.Clear(); base.OnChildRemoved(w, index, constraint); } IWidget FindLastVisibleWidget() { if (LastChildFill == false) { return null; } for (var i = Count - 1; i >= 0; i--) { var widget = this[i]; if (widget.Visibility != Visibility.Collapsed) { return widget; } } return null; } class WidgetSorter : IComparer<WidgetConstraintAndPosition> { readonly DockPanel parent; public WidgetSorter(DockPanel parent) { this.parent = parent; } public int Compare(WidgetConstraintAndPosition x, WidgetConstraintAndPosition y) { // this is safe as this code can only be called if there are two or more elements in the panel. var lastWidget = parent.FindLastVisibleWidget(); if (ReferenceEquals(x.Widget, lastWidget)) { return 1; } if (ReferenceEquals(y.Widget, lastWidget)) { return -1; } int order = x.Constraint.CompareTo(y.Constraint); if (order != 0) { return order; } return x.Position.CompareTo(y.Position); } } } }
31.525424
155
0.600986
[ "MIT" ]
RabbitStewDio/Steropes.UI
src/Steropes.UI/Widgets/Container/DockPanel.cs
11,163
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.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Internal.Cryptography; namespace System.Security.Cryptography.Pkcs { internal partial class CmsSignature { static partial void PrepareRegistrationDsa(Dictionary<string, CmsSignature> lookup) { if (Helpers.IsDSASupported) { lookup.Add(Oids.DsaWithSha1, new DSACmsSignature(Oids.DsaWithSha1, HashAlgorithmName.SHA1)); lookup.Add(Oids.DsaWithSha256, new DSACmsSignature(Oids.DsaWithSha256, HashAlgorithmName.SHA256)); lookup.Add(Oids.DsaWithSha384, new DSACmsSignature(Oids.DsaWithSha384, HashAlgorithmName.SHA384)); lookup.Add(Oids.DsaWithSha512, new DSACmsSignature(Oids.DsaWithSha512, HashAlgorithmName.SHA512)); lookup.Add(Oids.Dsa, new DSACmsSignature(null, default)); } } private sealed class DSACmsSignature : CmsSignature { private readonly HashAlgorithmName _expectedDigest; private readonly string? _signatureAlgorithm; internal override RSASignaturePadding? SignaturePadding => null; internal DSACmsSignature(string? signatureAlgorithm, HashAlgorithmName expectedDigest) { _signatureAlgorithm = signatureAlgorithm; _expectedDigest = expectedDigest; } protected override bool VerifyKeyType(AsymmetricAlgorithm key) { return (key as DSA) != null; } internal override bool VerifySignature( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> valueHash, ReadOnlyMemory<byte> signature, #else byte[] valueHash, byte[] signature, #endif string? digestAlgorithmOid, HashAlgorithmName digestAlgorithmName, ReadOnlyMemory<byte>? signatureParameters, X509Certificate2 certificate) { if (_expectedDigest != digestAlgorithmName) { throw new CryptographicException( SR.Format( SR.Cryptography_Cms_InvalidSignerHashForSignatureAlg, digestAlgorithmOid, _signatureAlgorithm)); } Debug.Assert(Helpers.IsDSASupported); DSA? dsa = certificate.GetDSAPublicKey(); if (dsa == null) { return false; } DSAParameters dsaParameters = dsa.ExportParameters(false); int bufSize = 2 * dsaParameters.Q!.Length; #if NETCOREAPP || NETSTANDARD2_1 byte[] rented = CryptoPool.Rent(bufSize); Span<byte> ieee = new Span<byte>(rented, 0, bufSize); try { #else byte[] ieee = new byte[bufSize]; #endif if (!DsaDerToIeee(signature, ieee)) { return false; } return dsa.VerifySignature(valueHash, ieee); #if NETCOREAPP || NETSTANDARD2_1 } finally { CryptoPool.Return(rented, bufSize); } #endif } protected override bool Sign( #if NETCOREAPP || NETSTANDARD2_1 ReadOnlySpan<byte> dataHash, #else byte[] dataHash, #endif HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm? key, bool silent, [NotNullWhen(true)] out string? signatureAlgorithm, [NotNullWhen(true)] out byte[]? signatureValue, out byte[]? signatureParameters) { Debug.Assert(Helpers.IsDSASupported); signatureParameters = null; // If there's no private key, fall back to the public key for a "no private key" exception. DSA? dsa = key as DSA ?? PkcsPal.Instance.GetPrivateKeyForSigning<DSA>(certificate, silent) ?? certificate.GetDSAPublicKey(); if (dsa == null) { signatureAlgorithm = null; signatureValue = null; return false; } string? oidValue = hashAlgorithmName == HashAlgorithmName.SHA1 ? Oids.DsaWithSha1 : hashAlgorithmName == HashAlgorithmName.SHA256 ? Oids.DsaWithSha256 : hashAlgorithmName == HashAlgorithmName.SHA384 ? Oids.DsaWithSha384 : hashAlgorithmName == HashAlgorithmName.SHA512 ? Oids.DsaWithSha512 : null; if (oidValue == null) { signatureAlgorithm = null; signatureValue = null; return false; } signatureAlgorithm = oidValue; #if NETCOREAPP || NETSTANDARD2_1 // The Q size cannot be bigger than the KeySize. byte[] rented = CryptoPool.Rent(dsa.KeySize / 8); int bytesWritten = 0; try { if (dsa.TryCreateSignature(dataHash, rented, out bytesWritten)) { var signature = new ReadOnlySpan<byte>(rented, 0, bytesWritten); if (key != null && !certificate.GetDSAPublicKey()!.VerifySignature(dataHash, signature)) { // key did not match certificate signatureValue = null; return false; } signatureValue = DsaIeeeToDer(signature); return true; } } finally { CryptoPool.Return(rented, bytesWritten); } signatureValue = null; return false; #else byte[] signature = dsa.CreateSignature(dataHash); signatureValue = DsaIeeeToDer(new ReadOnlySpan<byte>(signature)); return true; #endif } } } }
36.241935
114
0.529298
[ "MIT" ]
333fred/runtime
src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/CmsSignature.DSA.cs
6,741
C#
using System; using System.Collections.Generic; using System.Numerics; using System.Reflection; using Windows.UI; using Windows.UI.Composition; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; using Uno.Extensions; using Uno.Logging; #if NETCOREAPP using Microsoft.UI; #endif #if __IOS__ || __MACOS__ using CoreGraphics; #endif namespace Uno.UI.Toolkit { #if !NET6_0_OR_GREATER // Moved to the linker definition file #if __IOS__ [global::Foundation.PreserveAttribute(AllMembers = true)] #elif __ANDROID__ [Android.Runtime.PreserveAttribute(AllMembers = true)] #endif #endif public static class UIElementExtensions { #region Elevation public static void SetElevation(this UIElement element, double elevation) { element.SetValue(ElevationProperty, elevation); } public static double GetElevation(this UIElement element) { return (double)element.GetValue(ElevationProperty); } public static DependencyProperty ElevationProperty { get; } = DependencyProperty.RegisterAttached( "Elevation", typeof(double), typeof(UIElementExtensions), new PropertyMetadata(0, OnElevationChanged) ); private static readonly Color ElevationColor = Color.FromArgb(64, 0, 0, 0); private static void OnElevationChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args) { if (args.NewValue is double elevation) { SetElevationInternal(dependencyObject, elevation, ElevationColor); } } #if __IOS__ || __MACOS__ internal static void SetElevationInternal(this DependencyObject element, double elevation, Color shadowColor, CGPath path = null) #elif NETFX_CORE || NETCOREAPP internal static void SetElevationInternal(this DependencyObject element, double elevation, Color shadowColor, DependencyObject host = null, CornerRadius cornerRadius = default(CornerRadius)) #else internal static void SetElevationInternal(this DependencyObject element, double elevation, Color shadowColor) #endif { #if __ANDROID__ if (element is Android.Views.View view) { AndroidX.Core.View.ViewCompat.SetElevation(view, (float)Uno.UI.ViewHelper.LogicalToPhysicalPixels(elevation)); if(Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.P) { view.SetOutlineAmbientShadowColor(shadowColor); view.SetOutlineSpotShadowColor(shadowColor); } } #elif __IOS__ || __MACOS__ #if __MACOS__ if (element is AppKit.NSView view) #else if (element is UIKit.UIView view) #endif { if (elevation > 0) { // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator const float x = 0.25f; const float y = 0.92f * 0.5f; // Looks more accurate than the recommended 0.92f. const float blur = 0.5f; #if __MACOS__ view.WantsLayer = true; view.Shadow ??= new AppKit.NSShadow(); #endif view.Layer.MasksToBounds = false; view.Layer.ShadowOpacity = shadowColor.A / 255f; #if __MACOS__ view.Layer.ShadowColor = AppKit.NSColor.FromRgb(shadowColor.R, shadowColor.G, shadowColor.B).CGColor; #else view.Layer.ShadowColor = UIKit.UIColor.FromRGB(shadowColor.R, shadowColor.G, shadowColor.B).CGColor; #endif view.Layer.ShadowRadius = (nfloat)(blur * elevation); view.Layer.ShadowOffset = new CoreGraphics.CGSize(x * elevation, y * elevation); view.Layer.ShadowPath = path; } else if(view.Layer != null) { view.Layer.ShadowOpacity = 0; } } #elif __WASM__ if (element is UIElement uiElement) { if (elevation > 0) { // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator const double x = 0.25d; const double y = 0.92f * 0.5f; // Looks more accurate than the recommended 0.92f. const double blur = 0.5f; var color = Color.FromArgb((byte)(shadowColor.A * .35), shadowColor.R, shadowColor.G, shadowColor.B); var str = $"{(x * elevation).ToStringInvariant()}px {(y * elevation).ToStringInvariant()}px {(blur * elevation).ToStringInvariant()}px {color.ToCssString()}"; uiElement.SetStyle("box-shadow", str); uiElement.SetCssClasses("noclip"); } else { uiElement.ResetStyle("box-shadow"); uiElement.UnsetCssClasses("noclip"); } } #elif NETFX_CORE || NETCOREAPP if (element is UIElement uiElement) { var compositor = ElementCompositionPreview.GetElementVisual(uiElement).Compositor; var spriteVisual = compositor.CreateSpriteVisual(); var newSize = new Vector2(0, 0); if (uiElement is FrameworkElement contentFE) { newSize = new Vector2((float)contentFE.ActualWidth, (float)contentFE.ActualHeight); } if (!(host is Canvas uiHost) || newSize == default) { return; } spriteVisual.Size = newSize; if (elevation > 0) { // Values for 1dp elevation according to https://material.io/guidelines/resources/shadows.html#shadows-illustrator const float x = 0.25f; const float y = 0.92f * 0.5f; // Looks more accurate than the recommended 0.92f. const float blur = 0.5f; var shadow = compositor.CreateDropShadow(); shadow.Offset = new Vector3((float)elevation*x, (float)elevation*y, -(float)elevation); shadow.BlurRadius = (float)(blur * elevation); shadow.Mask = uiElement switch { // GetAlphaMask is only available for shapes, images, and textblocks Shape shape => shape.GetAlphaMask(), Image image => image.GetAlphaMask(), TextBlock tb => tb.GetAlphaMask(), _ => shadow.Mask }; if (!cornerRadius.Equals(default)) { var averageRadius = (cornerRadius.TopLeft + cornerRadius.TopRight + cornerRadius.BottomLeft + cornerRadius.BottomRight) / 4f; // Create a rectangle with similar corner radius (average for now) var rect = new Rectangle() { Fill = new SolidColorBrush(Colors.White), Width = newSize.X, Height = newSize.Y, RadiusX = averageRadius, RadiusY = averageRadius }; uiHost.Children.Add(rect); // The rect need to be in th VisualTree for .GetAlphaMask() to work shadow.Mask = rect.GetAlphaMask(); uiHost.Children.Remove(rect); // No need anymore, we can discard it. } shadow.Color = shadowColor; shadow.Opacity = shadowColor.A/255f; spriteVisual.Shadow = shadow; } ElementCompositionPreview.SetElementChildVisual(uiHost, spriteVisual); } #endif } #endregion internal static Thickness GetPadding(this UIElement uiElement) { if (uiElement is FrameworkElement fe && fe.TryGetPadding(out var padding)) { return padding; } var property = uiElement.FindDependencyPropertyUsingReflection<Thickness>("PaddingProperty"); return property != null && uiElement.GetValue(property) is Thickness t ? t : default; } internal static bool SetPadding(this UIElement uiElement, Thickness padding) { if (uiElement is FrameworkElement fe && fe.TrySetPadding(padding)) { return true; } var property = uiElement.FindDependencyPropertyUsingReflection<Thickness>("PaddingProperty"); if (property != null) { uiElement.SetValue(property, padding); return true; } return false; } internal static bool TryGetPadding(this FrameworkElement frameworkElement, out Thickness padding) { switch (frameworkElement) { case Grid g: padding = g.Padding; return true; case StackPanel sp: padding = sp.Padding; return true; case Control c: padding = c.Padding; return true; case ContentPresenter cp: padding = cp.Padding; return true; case Border b: padding = b.Padding; return true; } padding = default; return false; } internal static bool TrySetPadding(this FrameworkElement frameworkElement, Thickness padding) { switch (frameworkElement) { case Grid g: g.Padding = padding; return true; case StackPanel sp: sp.Padding = padding; return true; case Control c: c.Padding = padding; return true; case ContentPresenter cp: cp.Padding = padding; return true; case Border b: b.Padding = padding; return true; } return false; } private static Dictionary<(Type type, string property), DependencyProperty> _dependencyPropertyReflectionCache; internal static DependencyProperty FindDependencyPropertyUsingReflection<TProperty>(this UIElement uiElement, string propertyName) { var type = uiElement.GetType(); var propertyType = typeof(TProperty); var key = (ownerType: type, propertyName); _dependencyPropertyReflectionCache ??= new Dictionary<(Type, string), DependencyProperty>(2); if (_dependencyPropertyReflectionCache.TryGetValue(key, out var property)) { return property; } property = type .GetTypeInfo() .GetDeclaredProperty(propertyName) ?.GetValue(null) as DependencyProperty ?? type .GetTypeInfo() .GetDeclaredField(propertyName) ?.GetValue(null) as DependencyProperty; if (property == null) { uiElement.Log().Warn($"The {propertyName} dependency property does not exist on {type}"); } #if !NETFX_CORE && !NETCOREAPP else if (property.Type != propertyType) { uiElement.Log().Warn($"The {propertyName} dependency property {type} is not of the {propertyType} Type."); property = null; } #endif _dependencyPropertyReflectionCache[key] = property; return property; } } }
28.378299
192
0.699804
[ "Apache-2.0" ]
Arieldelossantos/uno
src/Uno.UI.Toolkit/UIElementExtensions.cs
9,677
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3d12video.h(237,9) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct D3D12_VIDEO_SIZE_RANGE { public uint MaxWidth; public uint MaxHeight; public uint MinWidth; public uint MinHeight; } }
24.1875
86
0.69509
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/D3D12_VIDEO_SIZE_RANGE.cs
389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Data; using BTCPayServer.Migrations; using Microsoft.EntityFrameworkCore; using NBitcoin; using NBitcoin.DataEncoders; namespace BTCPayServer.Services.Stores { public class StoreRepository { private readonly ApplicationDbContextFactory _ContextFactory; public ApplicationDbContext CreateDbContext() { return _ContextFactory.CreateContext(); } public StoreRepository(ApplicationDbContextFactory contextFactory) { _ContextFactory = contextFactory ?? throw new ArgumentNullException(nameof(contextFactory)); } public async Task<StoreData> FindStore(string storeId) { if (storeId == null) return null; using (var ctx = _ContextFactory.CreateContext()) { var result = await ctx.FindAsync<StoreData>(storeId).ConfigureAwait(false); return result; } } public async Task<StoreData> FindStore(string storeId, string userId) { if (userId == null) throw new ArgumentNullException(nameof(userId)); using (var ctx = _ContextFactory.CreateContext()) { return (await ctx .UserStore .Where(us => us.ApplicationUserId == userId && us.StoreDataId == storeId) .Select(us => new { Store = us.StoreData, Role = us.Role }).ToArrayAsync()) .Select(us => { us.Store.Role = us.Role; return us.Store; }).FirstOrDefault(); } } public class StoreUser { public string Id { get; set; } public string Email { get; set; } public string Role { get; set; } } public async Task<StoreUser[]> GetStoreUsers(string storeId) { if (storeId == null) throw new ArgumentNullException(nameof(storeId)); using (var ctx = _ContextFactory.CreateContext()) { return await ctx .UserStore .Where(u => u.StoreDataId == storeId) .Select(u => new StoreUser() { Id = u.ApplicationUserId, Email = u.ApplicationUser.Email, Role = u.Role }).ToArrayAsync(); } } public async Task<StoreData[]> GetStoresByUserId(string userId, IEnumerable<string> storeIds = null) { using (var ctx = _ContextFactory.CreateContext()) { return (await ctx.UserStore .Where(u => u.ApplicationUserId == userId && (storeIds == null || storeIds.Contains(u.StoreDataId))) .Select(u => new { u.StoreData, u.Role }) .ToArrayAsync()) .Select(u => { u.StoreData.Role = u.Role; return u.StoreData; }).ToArray(); } } public async Task<bool> AddStoreUser(string storeId, string userId, string role) { using (var ctx = _ContextFactory.CreateContext()) { var userStore = new UserStore() { StoreDataId = storeId, ApplicationUserId = userId, Role = role }; ctx.UserStore.Add(userStore); try { await ctx.SaveChangesAsync(); return true; } catch (Microsoft.EntityFrameworkCore.DbUpdateException) { return false; } } } public async Task CleanUnreachableStores() { using (var ctx = _ContextFactory.CreateContext()) { if (!ctx.Database.SupportDropForeignKey()) return; foreach (var store in await ctx.Stores.Where(s => !s.UserStores.Where(u => u.Role == StoreRoles.Owner).Any()).ToArrayAsync()) { ctx.Stores.Remove(store); } await ctx.SaveChangesAsync(); } } public async Task RemoveStoreUser(string storeId, string userId) { using (var ctx = _ContextFactory.CreateContext()) { var userStore = new UserStore() { StoreDataId = storeId, ApplicationUserId = userId }; ctx.UserStore.Add(userStore); ctx.Entry<UserStore>(userStore).State = Microsoft.EntityFrameworkCore.EntityState.Deleted; await ctx.SaveChangesAsync(); } await DeleteStoreIfOrphan(storeId); } private async Task DeleteStoreIfOrphan(string storeId) { using (var ctx = _ContextFactory.CreateContext()) { if (ctx.Database.SupportDropForeignKey()) { if (!await ctx.UserStore.Where(u => u.StoreDataId == storeId && u.Role == StoreRoles.Owner).AnyAsync()) { var store = await ctx.Stores.FindAsync(storeId); if (store != null) { ctx.Stores.Remove(store); await ctx.SaveChangesAsync(); } } } } } private void SetNewStoreHints(ref StoreData storeData) { var blob = storeData.GetStoreBlob(); blob.Hints = new Data.StoreBlob.StoreHints { Wallet = true, Lightning = true }; storeData.SetStoreBlob(blob); } public async Task CreateStore(string ownerId, StoreData storeData) { if (!string.IsNullOrEmpty(storeData.Id)) throw new ArgumentException("id should be empty", nameof(storeData.StoreName)); if (string.IsNullOrEmpty(storeData.StoreName)) throw new ArgumentException("name should not be empty", nameof(storeData.StoreName)); if (ownerId == null) throw new ArgumentNullException(nameof(ownerId)); using (var ctx = _ContextFactory.CreateContext()) { storeData.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32)); var userStore = new UserStore { StoreDataId = storeData.Id, ApplicationUserId = ownerId, Role = StoreRoles.Owner, }; SetNewStoreHints(ref storeData); ctx.Add(storeData); ctx.Add(userStore); await ctx.SaveChangesAsync(); } } public async Task<StoreData> CreateStore(string ownerId, string name) { var store = new StoreData() { StoreName = name }; SetNewStoreHints(ref store); await CreateStore(ownerId, store); return store; } public async Task<WebhookData[]> GetWebhooks(string storeId) { using var ctx = _ContextFactory.CreateContext(); return await ctx.StoreWebhooks .Where(s => s.StoreId == storeId) .Select(s => s.Webhook).ToArrayAsync(); } public async Task<WebhookDeliveryData> GetWebhookDelivery(string storeId, string webhookId, string deliveryId) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); if (storeId == null) throw new ArgumentNullException(nameof(storeId)); using var ctx = _ContextFactory.CreateContext(); return await ctx.StoreWebhooks .Where(d => d.StoreId == storeId && d.WebhookId == webhookId) .SelectMany(d => d.Webhook.Deliveries) .Where(d => d.Id == deliveryId) .FirstOrDefaultAsync(); } public async Task AddWebhookDelivery(WebhookDeliveryData delivery) { using var ctx = _ContextFactory.CreateContext(); ctx.WebhookDeliveries.Add(delivery); var invoiceWebhookDelivery = delivery.GetBlob().ReadRequestAs<InvoiceWebhookDeliveryData>(); if (invoiceWebhookDelivery.InvoiceId != null) { ctx.InvoiceWebhookDeliveries.Add(new InvoiceWebhookDeliveryData() { InvoiceId = invoiceWebhookDelivery.InvoiceId, DeliveryId = delivery.Id }); } await ctx.SaveChangesAsync(); } public async Task<WebhookDeliveryData[]> GetWebhookDeliveries(string storeId, string webhookId, int? count) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); if (storeId == null) throw new ArgumentNullException(nameof(storeId)); using var ctx = _ContextFactory.CreateContext(); IQueryable<WebhookDeliveryData> req = ctx.StoreWebhooks .Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .SelectMany(s => s.Webhook.Deliveries) .OrderByDescending(s => s.Timestamp); if (count is int c) req = req.Take(c); return await req .ToArrayAsync(); } public async Task<string> CreateWebhook(string storeId, WebhookBlob blob) { if (storeId == null) throw new ArgumentNullException(nameof(storeId)); if (blob == null) throw new ArgumentNullException(nameof(blob)); using var ctx = _ContextFactory.CreateContext(); WebhookData data = new WebhookData(); data.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); if (string.IsNullOrEmpty(blob.Secret)) blob.Secret = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); data.SetBlob(blob); StoreWebhookData storeWebhook = new StoreWebhookData(); storeWebhook.StoreId = storeId; storeWebhook.WebhookId = data.Id; ctx.StoreWebhooks.Add(storeWebhook); ctx.Webhooks.Add(data); await ctx.SaveChangesAsync(); return data.Id; } public async Task<WebhookData> GetWebhook(string storeId, string webhookId) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); if (storeId == null) throw new ArgumentNullException(nameof(storeId)); using var ctx = _ContextFactory.CreateContext(); return await ctx.StoreWebhooks .Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Select(s => s.Webhook) .FirstOrDefaultAsync(); } public async Task<WebhookData> GetWebhook(string webhookId) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); using var ctx = _ContextFactory.CreateContext(); return await ctx.StoreWebhooks .Where(s => s.WebhookId == webhookId) .Select(s => s.Webhook) .FirstOrDefaultAsync(); } public async Task DeleteWebhook(string storeId, string webhookId) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); if (storeId == null) throw new ArgumentNullException(nameof(storeId)); using var ctx = _ContextFactory.CreateContext(); var hook = await ctx.StoreWebhooks .Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Select(s => s.Webhook) .FirstOrDefaultAsync(); if (hook is null) return; ctx.Webhooks.Remove(hook); await ctx.SaveChangesAsync(); } public async Task UpdateWebhook(string storeId, string webhookId, WebhookBlob webhookBlob) { if (webhookId == null) throw new ArgumentNullException(nameof(webhookId)); if (storeId == null) throw new ArgumentNullException(nameof(storeId)); if (webhookBlob == null) throw new ArgumentNullException(nameof(webhookBlob)); using var ctx = _ContextFactory.CreateContext(); var hook = await ctx.StoreWebhooks .Where(s => s.StoreId == storeId && s.WebhookId == webhookId) .Select(s => s.Webhook) .FirstOrDefaultAsync(); if (hook is null) return; hook.SetBlob(webhookBlob); await ctx.SaveChangesAsync(); } public async Task RemoveStore(string storeId, string userId) { using (var ctx = _ContextFactory.CreateContext()) { var storeUser = await ctx.UserStore.AsQueryable().FirstOrDefaultAsync(o => o.StoreDataId == storeId && o.ApplicationUserId == userId); if (storeUser == null) return; ctx.UserStore.Remove(storeUser); await ctx.SaveChangesAsync(); } await DeleteStoreIfOrphan(storeId); } public async Task UpdateStore(StoreData store) { using (var ctx = _ContextFactory.CreateContext()) { var existing = await ctx.FindAsync<StoreData>(store.Id); ctx.Entry(existing).CurrentValues.SetValues(store); await ctx.SaveChangesAsync().ConfigureAwait(false); } } public async Task<bool> DeleteStore(string storeId) { using (var ctx = _ContextFactory.CreateContext()) { if (!ctx.Database.SupportDropForeignKey()) return false; var store = await ctx.Stores.FindAsync(storeId); if (store == null) return false; var webhooks = await ctx.StoreWebhooks .Select(o => o.Webhook) .ToArrayAsync(); foreach (var w in webhooks) ctx.Webhooks.Remove(w); ctx.Stores.Remove(store); await ctx.SaveChangesAsync(); return true; } } public bool CanDeleteStores() { using (var ctx = _ContextFactory.CreateContext()) { return ctx.Database.SupportDropForeignKey(); } } } }
38.959288
150
0.524133
[ "MIT" ]
esky33kubernetes/btcpayliquid
BTCPayServer/Services/Stores/StoreRepository.cs
15,311
C#
using System.Collections.Generic; namespace HotChocolate.Language { public sealed class ObjectTypeDefinitionNode : ObjectTypeDefinitionNodeBase , ITypeDefinitionNode { public ObjectTypeDefinitionNode( Location? location, NameNode name, StringValueNode? description, IReadOnlyList<DirectiveNode> directives, IReadOnlyList<NamedTypeNode> interfaces, IReadOnlyList<FieldDefinitionNode> fields) : base(location, name, directives, interfaces, fields) { Description = description; } public override NodeKind Kind { get; } = NodeKind.ObjectTypeDefinition; public StringValueNode? Description { get; } public override IEnumerable<ISyntaxNode> GetNodes() { if (Description is { }) { yield return Description; } yield return Name; foreach (NamedTypeNode interfaceName in Interfaces) { yield return interfaceName; } foreach (DirectiveNode directive in Directives) { yield return directive; } foreach (FieldDefinitionNode field in Fields) { yield return field; } } public ObjectTypeDefinitionNode WithLocation(Location? location) { return new ObjectTypeDefinitionNode( location, Name, Description, Directives, Interfaces, Fields); } public ObjectTypeDefinitionNode WithName(NameNode name) { return new ObjectTypeDefinitionNode( Location, name, Description, Directives, Interfaces, Fields); } public ObjectTypeDefinitionNode WithDescription( StringValueNode? description) { return new ObjectTypeDefinitionNode( Location, Name, description, Directives, Interfaces, Fields); } public ObjectTypeDefinitionNode WithDirectives( IReadOnlyList<DirectiveNode> directives) { return new ObjectTypeDefinitionNode( Location, Name, Description, directives, Interfaces, Fields); } public ObjectTypeDefinitionNode WithInterfaces( IReadOnlyList<NamedTypeNode> interfaces) { return new ObjectTypeDefinitionNode( Location, Name, Description, Directives, interfaces, Fields); } public ObjectTypeDefinitionNode WithFields( IReadOnlyList<FieldDefinitionNode> fields) { return new ObjectTypeDefinitionNode( Location, Name, Description, Directives, Interfaces, fields); } } }
30.092784
79
0.577595
[ "MIT" ]
barticus/hotchocolate
src/HotChocolate/Language/src/Language.SyntaxTree/ObjectTypeDefinitionNode.cs
2,921
C#
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX - License - Identifier: Apache - 2.0 // snippet-start:[dynamodb.dotnet35.LowLevelBatchWriteExample] using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; namespace LowLevelBatchWrite { public class LowLevelBatchWrite { private static string _table1Name = "Forum"; private static string _table2Name = "Thread"; public static void TestBatchWrite(AmazonDynamoDBClient client) { var request = new BatchWriteItemRequest { ReturnConsumedCapacity = "TOTAL", RequestItems = new Dictionary<string, List<WriteRequest>> { { _table1Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "S3 forum" } }, { "Threads", new AttributeValue { N = "0" }} } } } } }, { _table2Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string, AttributeValue> { { "ForumName", new AttributeValue { S = "S3 forum" } }, { "Subject", new AttributeValue { S = "My sample question" } }, { "Message", new AttributeValue { S = "Message Text." } }, { "KeywordTags", new AttributeValue { SS = new List<string> { "S3", "Bucket" } } } } } }, new WriteRequest { // For the operation to delete an item, if you provide a primary key value // that does not exist in the table, there is no error, it is just a no-op. DeleteRequest = new DeleteRequest { Key = new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Some partition key value" } }, { "Subject", new AttributeValue { S = "Some sort key value" } } } } } } } } }; CallBatchWriteTillCompletion(client, request); } private static async void CallBatchWriteTillCompletion(AmazonDynamoDBClient client, BatchWriteItemRequest request) { BatchWriteItemResponse response; int callCount = 0; do { Console.WriteLine("Making request"); response = await client.BatchWriteItemAsync(request); callCount++; // Check the response. var tableConsumedCapacities = response.ConsumedCapacity; var unprocessed = response.UnprocessedItems; Console.WriteLine("Per-table consumed capacity"); foreach (var tableConsumedCapacity in tableConsumedCapacities) { Console.WriteLine("{0} - {1}", tableConsumedCapacity.TableName, tableConsumedCapacity.CapacityUnits); } Console.WriteLine("Unprocessed"); foreach (var unp in unprocessed) { Console.WriteLine("{0} - {1}", unp.Key, unp.Value.Count); } Console.WriteLine(); // For the next iteration, the request will have unprocessed items. request.RequestItems = unprocessed; } while (response.UnprocessedItems.Count > 0); Console.WriteLine("Total # of batch write API calls made: {0}", callCount); } static void Main() { var client = new AmazonDynamoDBClient(); TestBatchWrite(client); } } } // snippet-end:[dynamodb.dotnet35.LowLevelBatchWriteExample]
39.773723
122
0.398238
[ "Apache-2.0" ]
awsa2ron/aws-doc-sdk-examples
dotnetv3/dynamodb/low-level-api/LowLevelBatchWrite/LowLevelBatchWrite.cs
5,451
C#
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using NClient.CodeGeneration.Abstractions; using NClient.CodeGeneration.Abstractions.Enums; using NJsonSchema.CodeGeneration.CSharp; using NSwag; using NSwag.CodeGeneration.OperationNameGenerators; namespace NClient.CodeGeneration.Facades.NSwag { public class NSwagFacadeGenerator : INClientFacadeGenerator { private readonly ILogger? _logger; public NSwagFacadeGenerator(ILogger? logger) { _logger = logger; } public async Task<string> GenerateAsync(string specification, FacadeGenerationSettings generationSettings, CancellationToken cancellationToken = default) { var openApiDocument = await OpenApiDocument.FromJsonAsync(specification, cancellationToken); var settings = new CSharpFacadeGeneratorSettings { GenerateClientInterfaces = true, GenerateResponseClasses = false, OperationNameGenerator = new MultipleClientsFromFirstTagAndOperationIdGenerator(), GenerateClients = generationSettings.GenerateClients, GenerateFacades = generationSettings.GenerateFacades, ClassName = generationSettings.Name .Replace("{facade}", "{controller}") .Replace("{client}", "{controller}"), GenerateModelValidationAttributes = generationSettings.UseModelValidationAttributes, GenerateDtoTypes = generationSettings.UseDtoTypes, UseCancellationToken = generationSettings.UseCancellationToken, CSharpGeneratorSettings = { Namespace = generationSettings.Namespace, GenerateNullableReferenceTypes = generationSettings.UseNullableReferenceTypes, JsonLibrary = generationSettings.SerializeType switch { SerializeType.SystemJsonText => CSharpJsonLibrary.SystemTextJson, SerializeType.NewtonsoftJson => CSharpJsonLibrary.NewtonsoftJson, { } => throw new NotSupportedException($"Serializer type '{generationSettings.SerializeType}' not supported.") } } }; settings.CSharpGeneratorSettings.TemplateFactory = new FacadeTemplateFactory(settings.CSharpGeneratorSettings, new[] { typeof(NSwagFacadeGenerator).GetTypeInfo().Assembly, typeof(CSharpGenerator).GetTypeInfo().Assembly }); var generator = new CSharpFacadeGenerator(openApiDocument, settings, _logger); return generator.GenerateFile(); } } }
44.753846
161
0.642489
[ "Apache-2.0" ]
nclient/NClient
src/NClient.CodeGeneration/NClient.CodeGeneration.Facades.NSwag/NSwagFacadeGenerator.cs
2,909
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DivClient.DivMath { [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="DivMath.IMyMath")] public interface IMyMath { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyMath/Div", ReplyAction="http://tempuri.org/IMyMath/DivResponse")] int Div(int a, int b); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IMyMath/Div", ReplyAction="http://tempuri.org/IMyMath/DivResponse")] System.Threading.Tasks.Task<int> DivAsync(int a, int b); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface IMyMathChannel : DivClient.DivMath.IMyMath, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class MyMathClient : System.ServiceModel.ClientBase<DivClient.DivMath.IMyMath>, DivClient.DivMath.IMyMath { public MyMathClient() { } public MyMathClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public MyMathClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public MyMathClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public MyMathClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public int Div(int a, int b) { return base.Channel.Div(a, b); } public System.Threading.Tasks.Task<int> DivAsync(int a, int b) { return base.Channel.DivAsync(a, b); } } }
41.672131
151
0.623131
[ "MIT" ]
vadimvoyevoda/WCF_Programming
WCF/IncludeExceptionDetailsInFaults/DivClient/Service References/DivMath/Reference.cs
2,544
C#
using Alex.ResourcePackLib.Json.Models.Entities; using Microsoft.Xna.Framework; namespace Alex.Entities.Models { public partial class PufferfishModel : EntityModel { public PufferfishModel() { Name = "definition.pufferfish"; VisibleBoundsWidth = 0; VisibleBoundsHeight = 0; VisibleBoundsOffset = new Vector3(0f, 0f, 0f); Texturewidth = 0; Textureheight = 0; Bones = new EntityModelBone[0]; } } }
18.28
52
0.676149
[ "MPL-2.0" ]
TheBlackPlague/Alex
src/Alex/Entities/Models/PufferfishModel.cs
457
C#
using GitVersion.BuildServers; using GitVersion.Cache; using Microsoft.Extensions.DependencyInjection; using GitVersion.Configuration; using GitVersion.Logging; using GitVersion.OutputVariables; using GitVersion.VersionCalculation; using GitVersion.VersionCalculation.BaseVersionCalculators; using GitVersion.Configuration.Init; using GitVersion.Extensions; namespace GitVersion { public class GitVersionCoreModule : IGitVersionModule { public void RegisterTypes(IServiceCollection services) { services.AddSingleton<IFileSystem, FileSystem>(); services.AddSingleton<IEnvironment, Environment>(); services.AddSingleton<ILog, Log>(); services.AddSingleton<IConsole, ConsoleAdapter>(); services.AddSingleton<IGitVersionCache, GitVersionCache>(); services.AddSingleton<IConfigProvider, ConfigProvider>(); services.AddSingleton<IVariableProvider, VariableProvider>(); services.AddSingleton<IGitVersionFinder, GitVersionFinder>(); services.AddSingleton<IMetaDataCalculator, MetaDataCalculator>(); services.AddSingleton<IBaseVersionCalculator, BaseVersionCalculator>(); services.AddSingleton<IMainlineVersionCalculator, MainlineVersionCalculator>(); services.AddSingleton<INextVersionCalculator, NextVersionCalculator>(); services.AddSingleton<IGitVersionCalculator, GitVersionCalculator>(); services.AddSingleton<IBuildServerResolver, BuildServerResolver>(); services.AddSingleton<IGitPreparer, GitPreparer>(); services.AddSingleton<IConfigFileLocatorFactory, ConfigFileLocatorFactory>(); services.AddSingleton(sp => sp.GetService<IConfigFileLocatorFactory>().Create()); RegisterBuildServers(services); RegisterVersionStrategies(services); services.AddModule(new GitVersionInitModule()); } private static void RegisterBuildServers(IServiceCollection services) { services.AddSingleton<IBuildServer, ContinuaCi>(); services.AddSingleton<IBuildServer, TeamCity>(); services.AddSingleton<IBuildServer, AppVeyor>(); services.AddSingleton<IBuildServer, MyGet>(); services.AddSingleton<IBuildServer, Jenkins>(); services.AddSingleton<IBuildServer, GitLabCi>(); services.AddSingleton<IBuildServer, AzurePipelines>(); services.AddSingleton<IBuildServer, TravisCi>(); services.AddSingleton<IBuildServer, EnvRun>(); services.AddSingleton<IBuildServer, Drone>(); services.AddSingleton<IBuildServer, CodeBuild>(); services.AddSingleton<IBuildServer, GitHubActions>(); } private static void RegisterVersionStrategies(IServiceCollection services) { services.AddSingleton<IVersionStrategy, FallbackVersionStrategy>(); services.AddSingleton<IVersionStrategy, ConfigNextVersionVersionStrategy>(); services.AddSingleton<IVersionStrategy, TaggedCommitVersionStrategy>(); services.AddSingleton<IVersionStrategy, MergeMessageVersionStrategy>(); services.AddSingleton<IVersionStrategy, VersionInBranchNameVersionStrategy>(); services.AddSingleton<IVersionStrategy, TrackReleaseBranchesVersionStrategy>(); } } }
47.364865
94
0.699572
[ "MIT" ]
BaY1251/GitVersion
src/GitVersionCore/GitVersionCoreModule.cs
3,432
C#
using System; namespace b { class Program { static void Main(string[] args) { Console.WriteLine("Q#53 (b)"); int x = 10 , y = 15; x= x++; y=++y; Console.WriteLine(x); Console.WriteLine(y); } } }
17.888889
43
0.385093
[ "Apache-2.0" ]
AbdulMueed209/Assingnment-4
Q#53 b.cs
324
C#
namespace TickTrader.FDK.Common { /// <summary> /// The enumeration describes possible time directions. /// </summary> public enum TimeDirection { /// <summary> /// From past to future. /// </summary> Forward = 1, /// <summary> /// From future to past. /// </summary> Backward = 2 } }
19.736842
59
0.498667
[ "MIT" ]
SoftFx/FDK2
Common/TimeDirection.cs
377
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.MachineLearningCompute.Outputs { [OutputType] public sealed class StorageAccountPropertiesResponse { /// <summary> /// ARM resource ID of the Azure Storage Account to store CLI specific files. If not provided one will be created. This cannot be changed once the cluster is created. /// </summary> public readonly string? ResourceId; [OutputConstructor] private StorageAccountPropertiesResponse(string? resourceId) { ResourceId = resourceId; } } }
31.035714
174
0.697353
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/MachineLearningCompute/Outputs/StorageAccountPropertiesResponse.cs
869
C#
using System; namespace WebApiExtensibilityDemo.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
25.27027
141
0.518717
[ "MIT" ]
CodeFuller/web-api-extensibility-demo
WebApiExtensibilityDemo/Areas/HelpPage/SampleGeneration/TextSample.cs
935
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Linq; using System.Collections.Generic; using System.Diagnostics; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Screens.Play { public class SongProgressGraph : SquareGraph { private IEnumerable<HitObject> objects; public IEnumerable<HitObject> Objects { set { objects = value; const int granularity = 200; Values = new int[granularity]; if (!objects.Any()) return; var firstHit = objects.First().StartTime; var lastHit = objects.Max(o => (o as IHasEndTime)?.EndTime ?? o.StartTime); if (lastHit == 0) lastHit = objects.Last().StartTime; var interval = (lastHit - firstHit + 1) / granularity; foreach (var h in objects) { var endTime = (h as IHasEndTime)?.EndTime ?? h.StartTime; Debug.Assert(endTime >= h.StartTime); int startRange = (int)((h.StartTime - firstHit) / interval); int endRange = (int)((endTime - firstHit) / interval); for (int i = startRange; i <= endRange; i++) Values[i]++; } } } } }
31.196078
93
0.508485
[ "MIT" ]
StefanYohansson/osu
osu.Game/Screens/Play/SongProgressGraph.cs
1,593
C#
public static class GlobalVariables { public static float speed = 2f; public static bool collisionTop = false; public static bool collisionBottom = false; public static bool newHighscore = false; }
26.875
47
0.734884
[ "BSD-2-Clause" ]
NotMyTschopp/Alpha-vTschopp
Assets/Scripts/GlobalVariables.cs
217
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("DiyLinq")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Princess Yachts International plc")] [assembly: AssemblyProduct("DiyLinq")] [assembly: AssemblyCopyright("Copyright © Princess Yachts International plc 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("370d11a7-9231-447e-9912-e6c420dee26e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.27027
84
0.75086
[ "Apache-2.0" ]
jonathanody/WhereMineLinq
DiyLinq/Properties/AssemblyInfo.cs
1,456
C#
#if UNITY_EDITOR using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; #endif namespace UniGLTF.ShaderPropExporter { public enum ShaderPropertyType { TexEnv, Color, Range, Float, Vector, } public struct ShaderProperty { public string Key; public ShaderPropertyType ShaderPropertyType; public ShaderProperty(string key, ShaderPropertyType propType) { Key = key; ShaderPropertyType = propType; } } public class ShaderProps { public ShaderProperty[] Properties; #if UNITY_EDITOR static ShaderPropertyType ConvType(ShaderUtil.ShaderPropertyType src) { switch (src) { case ShaderUtil.ShaderPropertyType.TexEnv: return ShaderPropertyType.TexEnv; case ShaderUtil.ShaderPropertyType.Color: return ShaderPropertyType.Color; case ShaderUtil.ShaderPropertyType.Float: return ShaderPropertyType.Float; case ShaderUtil.ShaderPropertyType.Range: return ShaderPropertyType.Range; case ShaderUtil.ShaderPropertyType.Vector: return ShaderPropertyType.Vector; default: throw new NotImplementedException(); } } public static ShaderProps FromShader(Shader shader) { var properties = new List<ShaderProperty>(); for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i) { var name = ShaderUtil.GetPropertyName(shader, i); var propType = ShaderUtil.GetPropertyType(shader, i); properties.Add(new ShaderProperty(name, ConvType(propType))); } return new ShaderProps { Properties = properties.ToArray(), }; } static string EscapeShaderName(string name) { return name.Replace("/", "_").Replace(" ", "_"); } public string ToString(string shaderName) { var list = new List<string>(); foreach (var prop in Properties) { list.Add(string.Format("new ShaderProperty(\"{0}\", ShaderPropertyType.{1})\r\n", prop.Key, prop.ShaderPropertyType)); } return string.Format(@"using System.Collections.Generic; namespace UniGLTF.ShaderPropExporter {{ public static partial class PreShaderPropExporter {{ [PreExportShader] static KeyValuePair<string, ShaderProps> {0} {{ get {{ return new KeyValuePair<string, ShaderProps>( ""{1}"", new ShaderProps {{ Properties = new ShaderProperty[]{{ {2} }} }} ); }} }} }} }} " , EscapeShaderName(shaderName) , shaderName , String.Join(",", list.ToArray())); } #endif } }
27.410714
134
0.558958
[ "MIT" ]
AkashiAkatsuki/VRMBase
Assets/VRM/UniGLTF/Scripts/IO/ShaderPropExporter/ShaderProps.cs
3,072
C#
using System.Collections.Generic; using SkiaSharp; using Svg.Model.Painting.ColorFilters; using Svg.Model.Painting.ImageFilters; using Svg.Model.Painting; using Svg.Model.Primitives.PathCommands; using Svg.Model.Painting.PathEffects; using Svg.Model.Primitives; using Svg.Model.Primitives.CanvasCommands; using Svg.Model.Painting.Shaders; namespace Svg.Skia { public static class SkiaModelExtensions { public static SKPoint ToSKPoint(this Point point) { return new SKPoint(point.X, point.Y); } public static SKPoint3 ToSKPoint3(this Point3 point3) { return new SKPoint3(point3.X, point3.Y, point3.Z); } public static SKPoint[] ToSKPoints(this IList<Point> points) { var skPoints = new SKPoint[points.Count]; for (int i = 0; i < points.Count; i++) { skPoints[i] = points[i].ToSKPoint(); } return skPoints; } public static SKPointI ToSKPointI(this PointI pointI) { return new SKPointI(pointI.X, pointI.Y); } public static SKSize ToSKSize(this Size size) { return new SKSize(size.Width, size.Height); } public static SKSizeI ToSKSizeI(this SizeI sizeI) { return new SKSizeI(sizeI.Width, sizeI.Height); } public static SKRect ToSKRect(this Rect rect) { return new SKRect(rect.Left, rect.Top, rect.Right, rect.Bottom); } public static SKMatrix ToSKMatrix(this Matrix matrix) { return new SKMatrix( matrix.ScaleX, matrix.SkewX, matrix.TransX, matrix.SkewY, matrix.ScaleY, matrix.TransY, matrix.Persp0, matrix.Persp1, matrix.Persp2); } public static SKImage ToSKImage(this Image image) { return SKImage.FromEncodedData(image.Data); } public static SKPaintStyle ToSKPaintStyle(this PaintStyle paintStyle) { return paintStyle switch { PaintStyle.Fill => SKPaintStyle.Fill, PaintStyle.Stroke => SKPaintStyle.Stroke, PaintStyle.StrokeAndFill => SKPaintStyle.StrokeAndFill, _ => SKPaintStyle.Fill }; } public static SKStrokeCap ToSKStrokeCap(this StrokeCap strokeCap) { return strokeCap switch { StrokeCap.Butt => SKStrokeCap.Butt, StrokeCap.Round => SKStrokeCap.Round, StrokeCap.Square => SKStrokeCap.Square, _ => SKStrokeCap.Butt }; } public static SKStrokeJoin ToSKStrokeJoin(this StrokeJoin strokeJoin) { return strokeJoin switch { StrokeJoin.Miter => SKStrokeJoin.Miter, StrokeJoin.Round => SKStrokeJoin.Round, StrokeJoin.Bevel => SKStrokeJoin.Bevel, _ => SKStrokeJoin.Miter }; } public static SKTextAlign ToSKTextAlign(this TextAlign textAlign) { return textAlign switch { TextAlign.Left => SKTextAlign.Left, TextAlign.Center => SKTextAlign.Center, TextAlign.Right => SKTextAlign.Right, _ => SKTextAlign.Left }; } public static SKTextEncoding ToSKTextEncoding(this TextEncoding textEncoding) { return textEncoding switch { TextEncoding.Utf8 => SKTextEncoding.Utf8, TextEncoding.Utf16 => SKTextEncoding.Utf16, TextEncoding.Utf32 => SKTextEncoding.Utf32, TextEncoding.GlyphId => SKTextEncoding.GlyphId, _ => SKTextEncoding.Utf8 }; } public static SKFontStyleWeight ToSKFontStyleWeight(this FontStyleWeight fontStyleWeight) { return fontStyleWeight switch { FontStyleWeight.Invisible => SKFontStyleWeight.Invisible, FontStyleWeight.Thin => SKFontStyleWeight.Thin, FontStyleWeight.ExtraLight => SKFontStyleWeight.ExtraLight, FontStyleWeight.Light => SKFontStyleWeight.Light, FontStyleWeight.Normal => SKFontStyleWeight.Normal, FontStyleWeight.Medium => SKFontStyleWeight.Medium, FontStyleWeight.SemiBold => SKFontStyleWeight.SemiBold, FontStyleWeight.Bold => SKFontStyleWeight.Bold, FontStyleWeight.ExtraBold => SKFontStyleWeight.ExtraBold, FontStyleWeight.Black => SKFontStyleWeight.Black, FontStyleWeight.ExtraBlack => SKFontStyleWeight.ExtraBlack, _ => SKFontStyleWeight.Invisible }; } public static SKFontStyleWidth ToSKFontStyleWidth(this FontStyleWidth fontStyleWidth) { return fontStyleWidth switch { FontStyleWidth.UltraCondensed => SKFontStyleWidth.UltraCondensed, FontStyleWidth.ExtraCondensed => SKFontStyleWidth.ExtraCondensed, FontStyleWidth.Condensed => SKFontStyleWidth.Condensed, FontStyleWidth.SemiCondensed => SKFontStyleWidth.SemiCondensed, FontStyleWidth.Normal => SKFontStyleWidth.Normal, FontStyleWidth.SemiExpanded => SKFontStyleWidth.SemiExpanded, FontStyleWidth.Expanded => SKFontStyleWidth.Expanded, FontStyleWidth.ExtraExpanded => SKFontStyleWidth.ExtraExpanded, FontStyleWidth.UltraExpanded => SKFontStyleWidth.UltraExpanded, _ => SKFontStyleWidth.UltraCondensed }; } public static SKFontStyleSlant ToSKFontStyleSlant(this FontStyleSlant fontStyleSlant) { return fontStyleSlant switch { FontStyleSlant.Upright => SKFontStyleSlant.Upright, FontStyleSlant.Italic => SKFontStyleSlant.Italic, FontStyleSlant.Oblique => SKFontStyleSlant.Oblique, _ => SKFontStyleSlant.Upright }; } public static SKTypeface? ToSKTypeface(this Typeface? typeface) { if (typeface is null || typeface.FamilyName is null) { return SKTypeface.Default; } var fontFamily = typeface.FamilyName; var fontWeight = typeface.Weight.ToSKFontStyleWeight(); var fontWidth = typeface.Width.ToSKFontStyleWidth(); var fontStyle = typeface.Style.ToSKFontStyleSlant(); if (SKSvgSettings.s_typefaceProviders is { } && SKSvgSettings.s_typefaceProviders.Count > 0) { foreach (var typefaceProviders in SKSvgSettings.s_typefaceProviders) { var skTypeface = typefaceProviders.FromFamilyName(fontFamily, fontWeight, fontWidth, fontStyle); if (skTypeface is { }) { return skTypeface; } } } return SKTypeface.FromFamilyName(fontFamily, fontWeight, fontWidth, fontStyle); } public static SKColor ToSKColor(this Color color) { return new SKColor(color.Red, color.Green, color.Blue, color.Alpha); } public static SKColor[] ToSKColors(this Color[] colors) { var skColors = new SKColor[colors.Length]; for (int i = 0; i < colors.Length; i++) { skColors[i] = colors[i].ToSKColor(); } return skColors; } public static SKColorF ToSKColor(this ColorF color) { return new SKColorF(color.Red, color.Green, color.Blue, color.Alpha); } public static SKColorF[] ToSKColors(this ColorF[] colors) { var skColors = new SKColorF[colors.Length]; for (int i = 0; i < colors.Length; i++) { skColors[i] = colors[i].ToSKColor(); } return skColors; } public static SKShaderTileMode ToSKShaderTileMode(this ShaderTileMode shaderTileMode) { return shaderTileMode switch { ShaderTileMode.Clamp => SKShaderTileMode.Clamp, ShaderTileMode.Repeat => SKShaderTileMode.Repeat, ShaderTileMode.Mirror => SKShaderTileMode.Mirror, ShaderTileMode.Decal => SKShaderTileMode.Decal, _ => SKShaderTileMode.Clamp }; } public static SKShader? ToSKShader(this Shader? shader) { switch (shader) { case ColorShader colorShader: { return SKShader.CreateColor( colorShader.Color.ToSKColor(), colorShader.ColorSpace == ColorSpace.Srgb ? SKSvgSettings.s_srgb : SKSvgSettings.s_srgbLinear); } case LinearGradientShader linearGradientShader: { if (linearGradientShader.Colors is null || linearGradientShader.ColorPos is null) { return null; } if (linearGradientShader.LocalMatrix is { }) { return SKShader.CreateLinearGradient( linearGradientShader.Start.ToSKPoint(), linearGradientShader.End.ToSKPoint(), linearGradientShader.Colors.ToSKColors(), linearGradientShader.ColorSpace == ColorSpace.Srgb ? SKSvgSettings.s_srgb : SKSvgSettings.s_srgbLinear, linearGradientShader.ColorPos, linearGradientShader.Mode.ToSKShaderTileMode(), linearGradientShader.LocalMatrix.Value.ToSKMatrix()); } return SKShader.CreateLinearGradient( linearGradientShader.Start.ToSKPoint(), linearGradientShader.End.ToSKPoint(), linearGradientShader.Colors.ToSKColors(), linearGradientShader.ColorSpace == ColorSpace.Srgb ? SKSvgSettings.s_srgb : SKSvgSettings.s_srgbLinear, linearGradientShader.ColorPos, linearGradientShader.Mode.ToSKShaderTileMode()); } case TwoPointConicalGradientShader twoPointConicalGradientShader: { if (twoPointConicalGradientShader.Colors is null || twoPointConicalGradientShader.ColorPos is null) { return null; } if (twoPointConicalGradientShader.LocalMatrix is { }) { return SKShader.CreateTwoPointConicalGradient( twoPointConicalGradientShader.Start.ToSKPoint(), twoPointConicalGradientShader.StartRadius, twoPointConicalGradientShader.End.ToSKPoint(), twoPointConicalGradientShader.EndRadius, twoPointConicalGradientShader.Colors.ToSKColors(), twoPointConicalGradientShader.ColorSpace == ColorSpace.Srgb ? SKSvgSettings.s_srgb : SKSvgSettings.s_srgbLinear, twoPointConicalGradientShader.ColorPos, twoPointConicalGradientShader.Mode.ToSKShaderTileMode(), twoPointConicalGradientShader.LocalMatrix.Value.ToSKMatrix()); } return SKShader.CreateTwoPointConicalGradient( twoPointConicalGradientShader.Start.ToSKPoint(), twoPointConicalGradientShader.StartRadius, twoPointConicalGradientShader.End.ToSKPoint(), twoPointConicalGradientShader.EndRadius, twoPointConicalGradientShader.Colors.ToSKColors(), twoPointConicalGradientShader.ColorSpace == ColorSpace.Srgb ? SKSvgSettings.s_srgb : SKSvgSettings.s_srgbLinear, twoPointConicalGradientShader.ColorPos, twoPointConicalGradientShader.Mode.ToSKShaderTileMode()); } case PictureShader pictureShader: { if (pictureShader.Src is null) { return null; } return SKShader.CreatePicture( pictureShader.Src.ToSKPicture(), SKShaderTileMode.Repeat, SKShaderTileMode.Repeat, pictureShader.LocalMatrix.ToSKMatrix(), pictureShader.Tile.ToSKRect()); } case PerlinNoiseFractalNoiseShader perlinNoiseFractalNoiseShader: { return SKShader.CreatePerlinNoiseFractalNoise( perlinNoiseFractalNoiseShader.BaseFrequencyX, perlinNoiseFractalNoiseShader.BaseFrequencyY, perlinNoiseFractalNoiseShader.NumOctaves, perlinNoiseFractalNoiseShader.Seed, perlinNoiseFractalNoiseShader.TileSize.ToSKPointI()); } case PerlinNoiseTurbulenceShader perlinNoiseTurbulenceShader: { return SKShader.CreatePerlinNoiseTurbulence( perlinNoiseTurbulenceShader.BaseFrequencyX, perlinNoiseTurbulenceShader.BaseFrequencyY, perlinNoiseTurbulenceShader.NumOctaves, perlinNoiseTurbulenceShader.Seed, perlinNoiseTurbulenceShader.TileSize.ToSKPointI()); } default: return null; } } public static SKColorFilter? ToSKColorFilter(this ColorFilter? colorFilter) { switch (colorFilter) { case BlendModeColorFilter blendModeColorFilter: { return SKColorFilter.CreateBlendMode( blendModeColorFilter.Color.ToSKColor(), blendModeColorFilter.Mode.ToSKBlendMode()); } case ColorMatrixColorFilter colorMatrixColorFilter: { if (colorMatrixColorFilter.Matrix is null) { return null; } return SKColorFilter.CreateColorMatrix(colorMatrixColorFilter.Matrix); } case LumaColorColorFilter _: { return SKColorFilter.CreateLumaColor(); } case TableColorFilter tableColorFilter: { if (tableColorFilter.TableA is null || tableColorFilter.TableR is null || tableColorFilter.TableG is null || tableColorFilter.TableB is null) { return null; } return SKColorFilter.CreateTable( tableColorFilter.TableA, tableColorFilter.TableR, tableColorFilter.TableG, tableColorFilter.TableB); } default: return null; } } public static SKImageFilter.CropRect ToCropRect(this CropRect cropRect) { return new SKImageFilter.CropRect(cropRect.Rect.ToSKRect()); } public static SKColorChannel ToSKColorChannel(this ColorChannel colorChannel) { return colorChannel switch { ColorChannel.R => SKColorChannel.R, ColorChannel.G => SKColorChannel.G, ColorChannel.B => SKColorChannel.B, ColorChannel.A => SKColorChannel.A, _ => SKColorChannel.R }; } public static SKImageFilter? ToSKImageFilter(this ImageFilter? imageFilter) { switch (imageFilter) { case ArithmeticImageFilter arithmeticImageFilter: { if (arithmeticImageFilter.Background is null) { return null; } return SKImageFilter.CreateArithmetic( arithmeticImageFilter.K1, arithmeticImageFilter.K2, arithmeticImageFilter.K3, arithmeticImageFilter.K4, arithmeticImageFilter.EforcePMColor, arithmeticImageFilter.Background?.ToSKImageFilter(), arithmeticImageFilter.Foreground?.ToSKImageFilter(), arithmeticImageFilter.CropRect?.ToCropRect()); } case BlendModeImageFilter blendModeImageFilter: { if (blendModeImageFilter.Background is null) { return null; } return SKImageFilter.CreateBlendMode( blendModeImageFilter.Mode.ToSKBlendMode(), blendModeImageFilter.Background?.ToSKImageFilter(), blendModeImageFilter.Foreground?.ToSKImageFilter(), blendModeImageFilter.CropRect?.ToCropRect()); } case BlurImageFilter blurImageFilter: { return SKImageFilter.CreateBlur( blurImageFilter.SigmaX, blurImageFilter.SigmaY, blurImageFilter.Input?.ToSKImageFilter(), blurImageFilter.CropRect?.ToCropRect()); } case ColorFilterImageFilter colorFilterImageFilter: { if (colorFilterImageFilter.ColorFilter is null) { return null; } return SKImageFilter.CreateColorFilter( colorFilterImageFilter.ColorFilter?.ToSKColorFilter(), colorFilterImageFilter.Input?.ToSKImageFilter(), colorFilterImageFilter.CropRect?.ToCropRect()); } case DilateImageFilter dilateImageFilter: { return SKImageFilter.CreateDilate( dilateImageFilter.RadiusX, dilateImageFilter.RadiusY, dilateImageFilter.Input?.ToSKImageFilter(), dilateImageFilter.CropRect?.ToCropRect()); } case DisplacementMapEffectImageFilter displacementMapEffectImageFilter: { if (displacementMapEffectImageFilter.Displacement is null) { return null; } return SKImageFilter.CreateDisplacementMapEffect( displacementMapEffectImageFilter.XChannelSelector.ToSKColorChannel(), displacementMapEffectImageFilter.YChannelSelector.ToSKColorChannel(), displacementMapEffectImageFilter.Scale, displacementMapEffectImageFilter.Displacement?.ToSKImageFilter(), displacementMapEffectImageFilter.Input?.ToSKImageFilter(), displacementMapEffectImageFilter.CropRect?.ToCropRect()); } case DistantLitDiffuseImageFilter distantLitDiffuseImageFilter: { return SKImageFilter.CreateDistantLitDiffuse( distantLitDiffuseImageFilter.Direction.ToSKPoint3(), distantLitDiffuseImageFilter.LightColor.ToSKColor(), distantLitDiffuseImageFilter.SurfaceScale, distantLitDiffuseImageFilter.Kd, distantLitDiffuseImageFilter.Input?.ToSKImageFilter(), distantLitDiffuseImageFilter.CropRect?.ToCropRect()); } case DistantLitSpecularImageFilter distantLitSpecularImageFilter: { return SKImageFilter.CreateDistantLitSpecular( distantLitSpecularImageFilter.Direction.ToSKPoint3(), distantLitSpecularImageFilter.LightColor.ToSKColor(), distantLitSpecularImageFilter.SurfaceScale, distantLitSpecularImageFilter.Ks, distantLitSpecularImageFilter.Shininess, distantLitSpecularImageFilter.Input?.ToSKImageFilter(), distantLitSpecularImageFilter.CropRect?.ToCropRect()); } case ErodeImageFilter erodeImageFilter: { return SKImageFilter.CreateErode( erodeImageFilter.RadiusX, erodeImageFilter.RadiusY, erodeImageFilter.Input?.ToSKImageFilter(), erodeImageFilter.CropRect?.ToCropRect()); } case ImageImageFilter imageImageFilter: { if (imageImageFilter.Image is null) { return null; } return SKImageFilter.CreateImage( imageImageFilter.Image.ToSKImage(), imageImageFilter.Src.ToSKRect(), imageImageFilter.Dst.ToSKRect(), SKFilterQuality.High); } case MatrixConvolutionImageFilter matrixConvolutionImageFilter: { if (matrixConvolutionImageFilter.Kernel is null) { return null; } return SKImageFilter.CreateMatrixConvolution( matrixConvolutionImageFilter.KernelSize.ToSKSizeI(), matrixConvolutionImageFilter.Kernel, matrixConvolutionImageFilter.Gain, matrixConvolutionImageFilter.Bias, matrixConvolutionImageFilter.KernelOffset.ToSKPointI(), matrixConvolutionImageFilter.TileMode.ToSKShaderTileMode(), matrixConvolutionImageFilter.ConvolveAlpha, matrixConvolutionImageFilter.Input?.ToSKImageFilter(), matrixConvolutionImageFilter.CropRect?.ToCropRect()); } case MergeImageFilter mergeImageFilter: { if (mergeImageFilter.Filters is null) { return null; } return SKImageFilter.CreateMerge( mergeImageFilter.Filters?.ToSKImageFilters(), mergeImageFilter.CropRect?.ToCropRect()); } case OffsetImageFilter offsetImageFilter: { return SKImageFilter.CreateOffset( offsetImageFilter.Dx, offsetImageFilter.Dy, offsetImageFilter.Input?.ToSKImageFilter(), offsetImageFilter.CropRect?.ToCropRect()); } case PaintImageFilter paintImageFilter: { if (paintImageFilter.Paint is null) { return null; } return SKImageFilter.CreatePaint( paintImageFilter.Paint.ToSKPaint(), paintImageFilter.CropRect?.ToCropRect()); } case PictureImageFilter pictureImageFilter: { if (pictureImageFilter.Picture is null) { return null; } return SKImageFilter.CreatePicture( pictureImageFilter.Picture.ToSKPicture(), pictureImageFilter.Picture.CullRect.ToSKRect()); } case PointLitDiffuseImageFilter pointLitDiffuseImageFilter: { return SKImageFilter.CreatePointLitDiffuse( pointLitDiffuseImageFilter.Location.ToSKPoint3(), pointLitDiffuseImageFilter.LightColor.ToSKColor(), pointLitDiffuseImageFilter.SurfaceScale, pointLitDiffuseImageFilter.Kd, pointLitDiffuseImageFilter.Input?.ToSKImageFilter(), pointLitDiffuseImageFilter.CropRect?.ToCropRect()); } case PointLitSpecularImageFilter pointLitSpecularImageFilter: { return SKImageFilter.CreatePointLitSpecular( pointLitSpecularImageFilter.Location.ToSKPoint3(), pointLitSpecularImageFilter.LightColor.ToSKColor(), pointLitSpecularImageFilter.SurfaceScale, pointLitSpecularImageFilter.Ks, pointLitSpecularImageFilter.Shininess, pointLitSpecularImageFilter.Input?.ToSKImageFilter(), pointLitSpecularImageFilter.CropRect?.ToCropRect()); } case SpotLitDiffuseImageFilter spotLitDiffuseImageFilter: { return SKImageFilter.CreateSpotLitDiffuse( spotLitDiffuseImageFilter.Location.ToSKPoint3(), spotLitDiffuseImageFilter.Target.ToSKPoint3(), spotLitDiffuseImageFilter.SpecularExponent, spotLitDiffuseImageFilter.CutoffAngle, spotLitDiffuseImageFilter.LightColor.ToSKColor(), spotLitDiffuseImageFilter.SurfaceScale, spotLitDiffuseImageFilter.Kd, spotLitDiffuseImageFilter.Input?.ToSKImageFilter(), spotLitDiffuseImageFilter.CropRect?.ToCropRect()); } case SpotLitSpecularImageFilter spotLitSpecularImageFilter: { return SKImageFilter.CreateSpotLitSpecular( spotLitSpecularImageFilter.Location.ToSKPoint3(), spotLitSpecularImageFilter.Target.ToSKPoint3(), spotLitSpecularImageFilter.SpecularExponent, spotLitSpecularImageFilter.CutoffAngle, spotLitSpecularImageFilter.LightColor.ToSKColor(), spotLitSpecularImageFilter.SurfaceScale, spotLitSpecularImageFilter.Ks, spotLitSpecularImageFilter.SpecularExponent, spotLitSpecularImageFilter.Input?.ToSKImageFilter(), spotLitSpecularImageFilter.CropRect?.ToCropRect()); } case TileImageFilter tileImageFilter: { return SKImageFilter.CreateTile( tileImageFilter.Src.ToSKRect(), tileImageFilter.Dst.ToSKRect(), tileImageFilter.Input?.ToSKImageFilter()); } default: return null; } } public static SKImageFilter[]? ToSKImageFilters(this ImageFilter[]? imageFilters) { if (imageFilters is null) { return null; } var skImageFilters = new SKImageFilter[imageFilters.Length]; for (int i = 0; i < imageFilters.Length; i++) { var imageFilter = imageFilters[i]; var skImageFilter = imageFilter.ToSKImageFilter(); if (skImageFilter is { }) { skImageFilters[i] = skImageFilter; } } return skImageFilters; } public static SKPathEffect? ToSKPathEffect(this PathEffect? pathEffect) { switch (pathEffect) { case DashPathEffect dashPathEffect: { return SKPathEffect.CreateDash( dashPathEffect.Intervals, dashPathEffect.Phase); } default: return null; } } public static SKBlendMode ToSKBlendMode(this BlendMode blendMode) { return blendMode switch { BlendMode.Clear => SKBlendMode.Clear, BlendMode.Src => SKBlendMode.Src, BlendMode.Dst => SKBlendMode.Dst, BlendMode.SrcOver => SKBlendMode.SrcOver, BlendMode.DstOver => SKBlendMode.DstOver, BlendMode.SrcIn => SKBlendMode.SrcIn, BlendMode.DstIn => SKBlendMode.DstIn, BlendMode.SrcOut => SKBlendMode.SrcOut, BlendMode.DstOut => SKBlendMode.DstOut, BlendMode.SrcATop => SKBlendMode.SrcATop, BlendMode.DstATop => SKBlendMode.DstATop, BlendMode.Xor => SKBlendMode.Xor, BlendMode.Plus => SKBlendMode.Plus, BlendMode.Modulate => SKBlendMode.Modulate, BlendMode.Screen => SKBlendMode.Screen, BlendMode.Overlay => SKBlendMode.Overlay, BlendMode.Darken => SKBlendMode.Darken, BlendMode.Lighten => SKBlendMode.Lighten, BlendMode.ColorDodge => SKBlendMode.ColorDodge, BlendMode.ColorBurn => SKBlendMode.ColorBurn, BlendMode.HardLight => SKBlendMode.HardLight, BlendMode.SoftLight => SKBlendMode.SoftLight, BlendMode.Difference => SKBlendMode.Difference, BlendMode.Exclusion => SKBlendMode.Exclusion, BlendMode.Multiply => SKBlendMode.Multiply, BlendMode.Hue => SKBlendMode.Hue, BlendMode.Saturation => SKBlendMode.Saturation, BlendMode.Color => SKBlendMode.Color, BlendMode.Luminosity => SKBlendMode.Luminosity, _ => SKBlendMode.Clear }; } public static SKFilterQuality ToSKFilterQuality(this FilterQuality filterQuality) { return filterQuality switch { FilterQuality.None => SKFilterQuality.None, FilterQuality.Low => SKFilterQuality.Low, FilterQuality.Medium => SKFilterQuality.Medium, FilterQuality.High => SKFilterQuality.High, _ => SKFilterQuality.None }; } public static SKPaint ToSKPaint(this Paint paint) { var style = paint.Style.ToSKPaintStyle(); var strokeCap = paint.StrokeCap.ToSKStrokeCap(); var strokeJoin = paint.StrokeJoin.ToSKStrokeJoin(); var textAlign = paint.TextAlign.ToSKTextAlign(); var typeface = paint.Typeface?.ToSKTypeface(); var textEncoding = paint.TextEncoding.ToSKTextEncoding(); var color = paint.Color is null ? SKColor.Empty : ToSKColor(paint.Color.Value); var shader = paint.Shader?.ToSKShader(); var colorFilter = paint.ColorFilter?.ToSKColorFilter(); var imageFilter = paint.ImageFilter?.ToSKImageFilter(); var pathEffect = paint.PathEffect?.ToSKPathEffect(); var blendMode = paint.BlendMode.ToSKBlendMode(); var filterQuality = paint.FilterQuality.ToSKFilterQuality(); return new SKPaint { Style = style, IsAntialias = paint.IsAntialias, StrokeWidth = paint.StrokeWidth, StrokeCap = strokeCap, StrokeJoin = strokeJoin, StrokeMiter = paint.StrokeMiter, TextSize = paint.TextSize, TextAlign = textAlign, Typeface = typeface, LcdRenderText = paint.LcdRenderText, SubpixelText = paint.SubpixelText, TextEncoding = textEncoding, Color = color, Shader = shader, ColorFilter = colorFilter, ImageFilter = imageFilter, PathEffect = pathEffect, BlendMode = blendMode, FilterQuality = filterQuality }; } public static SKClipOperation ToSKClipOperation(this ClipOperation clipOperation) { return clipOperation switch { ClipOperation.Difference => SKClipOperation.Difference, ClipOperation.Intersect => SKClipOperation.Intersect, _ => SKClipOperation.Difference }; } public static SKPathFillType ToSKPathFillType(this PathFillType pathFillType) { return pathFillType switch { PathFillType.Winding => SKPathFillType.Winding, PathFillType.EvenOdd => SKPathFillType.EvenOdd, _ => SKPathFillType.Winding }; } public static SKPathArcSize ToSKPathArcSize(this PathArcSize pathArcSize) { return pathArcSize switch { PathArcSize.Small => SKPathArcSize.Small, PathArcSize.Large => SKPathArcSize.Large, _ => SKPathArcSize.Small }; } public static SKPathDirection ToSKPathDirection(this PathDirection pathDirection) { return pathDirection switch { PathDirection.Clockwise => SKPathDirection.Clockwise, PathDirection.CounterClockwise => SKPathDirection.CounterClockwise, _ => SKPathDirection.Clockwise }; } public static void ToSKPath(this PathCommand pathCommand, SKPath skPath) { switch (pathCommand) { case MoveToPathCommand moveToPathCommand: { var x = moveToPathCommand.X; var y = moveToPathCommand.Y; skPath.MoveTo(x, y); } break; case LineToPathCommand lineToPathCommand: { var x = lineToPathCommand.X; var y = lineToPathCommand.Y; skPath.LineTo(x, y); } break; case ArcToPathCommand arcToPathCommand: { var rx = arcToPathCommand.Rx; var ry = arcToPathCommand.Ry; var xAxisRotate = arcToPathCommand.XAxisRotate; var largeArc = arcToPathCommand.LargeArc.ToSKPathArcSize(); var sweep = arcToPathCommand.Sweep.ToSKPathDirection(); var x = arcToPathCommand.X; var y = arcToPathCommand.Y; skPath.ArcTo(rx, ry, xAxisRotate, largeArc, sweep, x, y); } break; case QuadToPathCommand quadToPathCommand: { var x0 = quadToPathCommand.X0; var y0 = quadToPathCommand.Y0; var x1 = quadToPathCommand.X1; var y1 = quadToPathCommand.Y1; skPath.QuadTo(x0, y0, x1, y1); } break; case CubicToPathCommand cubicToPathCommand: { var x0 = cubicToPathCommand.X0; var y0 = cubicToPathCommand.Y0; var x1 = cubicToPathCommand.X1; var y1 = cubicToPathCommand.Y1; var x2 = cubicToPathCommand.X2; var y2 = cubicToPathCommand.Y2; skPath.CubicTo(x0, y0, x1, y1, x2, y2); } break; case ClosePathCommand _: { skPath.Close(); } break; case AddRectPathCommand addRectPathCommand: { var rect = addRectPathCommand.Rect.ToSKRect(); skPath.AddRect(rect); } break; case AddRoundRectPathCommand addRoundRectPathCommand: { var rect = addRoundRectPathCommand.Rect.ToSKRect(); var rx = addRoundRectPathCommand.Rx; var ry = addRoundRectPathCommand.Ry; skPath.AddRoundRect(rect, rx, ry); } break; case AddOvalPathCommand addOvalPathCommand: { var rect = addOvalPathCommand.Rect.ToSKRect(); skPath.AddOval(rect); } break; case AddCirclePathCommand addCirclePathCommand: { var x = addCirclePathCommand.X; var y = addCirclePathCommand.Y; var radius = addCirclePathCommand.Radius; skPath.AddCircle(x, y, radius); } break; case AddPolyPathCommand addPolyPathCommand: { if (addPolyPathCommand.Points is { }) { var points = addPolyPathCommand.Points.ToSKPoints(); var close = addPolyPathCommand.Close; skPath.AddPoly(points, close); } } break; } } public static SKPath ToSKPath(this Path path) { var skPath = new SKPath { FillType = path.FillType.ToSKPathFillType() }; if (path.Commands is null) { return skPath; } foreach (var pathCommand in path.Commands) { pathCommand.ToSKPath(skPath); } return skPath; } public static SKPath? ToSKPath(this ClipPath clipPath) { if (clipPath.Clips is null) { return null; } var skPathResult = default(SKPath); foreach (var clip in clipPath.Clips) { if (clip.Path is null) { return null; } var skPath = clip.Path.ToSKPath(); var skPathClip = clip.Clip?.ToSKPath(); if (skPathClip is { }) { skPath = skPath.Op(skPathClip, SKPathOp.Intersect); } if (clip.Transform is { }) { var skMatrix = clip.Transform.Value.ToSKMatrix(); skPath.Transform(skMatrix); } if (skPathResult is null) { skPathResult = skPath; } else { var result = skPathResult.Op(skPath, SKPathOp.Union); skPathResult = result; } } if (skPathResult is { }) { if (clipPath.Clip?.Clips is { }) { var skPathClip = clipPath.Clip.ToSKPath(); if (skPathClip is { }) { skPathResult = skPathResult.Op(skPathClip, SKPathOp.Intersect); } } if (clipPath.Transform is { }) { var skMatrix = clipPath.Transform.Value.ToSKMatrix(); skPathResult.Transform(skMatrix); } } return skPathResult; } public static SKPicture? ToSKPicture(this Picture? picture) { if (picture is null) { return null; } var skRect = picture.CullRect.ToSKRect(); using var skPictureRecorder = new SKPictureRecorder(); using var skCanvas = skPictureRecorder.BeginRecording(skRect); picture.Draw(skCanvas); return skPictureRecorder.EndRecording(); } public static void Draw(this CanvasCommand canvasCommand, SKCanvas skCanvas) { switch (canvasCommand) { case ClipPathCanvasCommand clipPathCanvasCommand: { var path = clipPathCanvasCommand.ClipPath.ToSKPath(); var operation = clipPathCanvasCommand.Operation.ToSKClipOperation(); var antialias = clipPathCanvasCommand.Antialias; skCanvas.ClipPath(path, operation, antialias); } break; case ClipRectCanvasCommand clipRectCanvasCommand: { var rect = clipRectCanvasCommand.Rect.ToSKRect(); var operation = clipRectCanvasCommand.Operation.ToSKClipOperation(); var antialias = clipRectCanvasCommand.Antialias; skCanvas.ClipRect(rect, operation, antialias); } break; case SaveCanvasCommand _: { skCanvas.Save(); } break; case RestoreCanvasCommand _: { skCanvas.Restore(); } break; case SetMatrixCanvasCommand setMatrixCanvasCommand: { var matrix = setMatrixCanvasCommand.Matrix.ToSKMatrix(); skCanvas.SetMatrix(matrix); } break; case SaveLayerCanvasCommand saveLayerCanvasCommand: { if (saveLayerCanvasCommand.Paint is { }) { var paint = saveLayerCanvasCommand.Paint.ToSKPaint(); skCanvas.SaveLayer(paint); } else { skCanvas.SaveLayer(); } } break; case DrawImageCanvasCommand drawImageCanvasCommand: { if (drawImageCanvasCommand.Image is { }) { var image = drawImageCanvasCommand.Image.ToSKImage(); var source = drawImageCanvasCommand.Source.ToSKRect(); var dest = drawImageCanvasCommand.Dest.ToSKRect(); var paint = drawImageCanvasCommand.Paint?.ToSKPaint(); skCanvas.DrawImage(image, source, dest, paint); } } break; case DrawPathCanvasCommand drawPathCanvasCommand: { if (drawPathCanvasCommand.Path is { } && drawPathCanvasCommand.Paint is { }) { var path = drawPathCanvasCommand.Path.ToSKPath(); var paint = drawPathCanvasCommand.Paint.ToSKPaint(); skCanvas.DrawPath(path, paint); } } break; case DrawTextBlobCanvasCommand drawPositionedTextCanvasCommand: { if (drawPositionedTextCanvasCommand.TextBlob?.Points is { } && drawPositionedTextCanvasCommand.Paint is { }) { var text = drawPositionedTextCanvasCommand.TextBlob.Text; var points = drawPositionedTextCanvasCommand.TextBlob.Points.ToSKPoints(); var paint = drawPositionedTextCanvasCommand.Paint.ToSKPaint(); var font = paint.ToFont(); var textBlob = SKTextBlob.CreatePositioned(text, font, points); skCanvas.DrawText(textBlob, 0, 0, paint); } } break; case DrawTextCanvasCommand drawTextCanvasCommand: { if (drawTextCanvasCommand.Paint is { }) { var text = drawTextCanvasCommand.Text; var x = drawTextCanvasCommand.X; var y = drawTextCanvasCommand.Y; var paint = drawTextCanvasCommand.Paint.ToSKPaint(); skCanvas.DrawText(text, x, y, paint); } } break; case DrawTextOnPathCanvasCommand drawTextOnPathCanvasCommand: { if (drawTextOnPathCanvasCommand.Path is { } && drawTextOnPathCanvasCommand.Paint is { }) { var text = drawTextOnPathCanvasCommand.Text; var path = drawTextOnPathCanvasCommand.Path.ToSKPath(); var hOffset = drawTextOnPathCanvasCommand.HOffset; var vOffset = drawTextOnPathCanvasCommand.VOffset; var paint = drawTextOnPathCanvasCommand.Paint.ToSKPaint(); skCanvas.DrawTextOnPath(text, path, hOffset, vOffset, paint); } } break; } } public static void Draw(this Picture picture, SKCanvas skCanvas) { if (picture.Commands is null) { return; } foreach (var canvasCommand in picture.Commands) { canvasCommand.Draw(skCanvas); } } } }
43.261633
144
0.496682
[ "MIT" ]
benjaminZale/Svg.Skia
src/Svg.Skia/SkiaModelExtensions.cs
49,277
C#
using UnityEngine; using System.Collections; public class CameraControlleur : MonoBehaviour { public GameObject player; private Vector3 offset; // Use this for initialization void Start () { offset = transform.position - player.transform.position; } // Update is called once per frame void LateUpdate () { transform.position = player.transform.position + offset; } }
21.578947
64
0.697561
[ "MIT" ]
Loupsito/Roll-ball-game
Assets/Scripts/CameraControlleur.cs
412
C#
using System; using System.Configuration; using log4net; namespace Blacker.MangaScraper.Library.Configuration { public class LibraryConfiguration : ConfigurationSection { private static readonly ILog _log = LogManager.GetLogger(typeof (LibraryConfiguration)); private static LibraryConfiguration _instance = null; private static readonly object _syncRoot = new object(); public static LibraryConfiguration Instance { get { lock (_syncRoot) { if (_instance == null) { LibraryConfiguration instance = null; try { instance = ConfigurationManager.GetSection("libraryConfiguration") as LibraryConfiguration; } catch (Exception ex) { _log.Warn("Unable to load configuration. Using default.", ex); } _instance = instance ?? new LibraryConfiguration(); } return _instance; } } } /// <summary> /// Storage location as can be found in the config file /// </summary> [ConfigurationProperty("storageLocation", IsRequired = false, DefaultValue = @"%APPDATA%\Blacker\MangaScraper\Data\library.sqlite")] public string StorageLocation { get { return (string) this["storageLocation"]; } } /// <summary> /// Storage location with expanded environmental variables /// </summary> public string StoragePath { get { return Environment.ExpandEnvironmentVariables(StorageLocation); } } } }
31.266667
140
0.525053
[ "BSD-2-Clause" ]
blacker-cz/MangaScraper
Blacker.MangaScraper.Library/Configuration/LibraryConfiguration.cs
1,878
C#
using System; using CMS.Ecommerce; namespace LearningKit.Models.Products { //DocSection:ProductListingModel public class ProductListItemViewModel { public readonly PriceDetailViewModel PriceModel; public string Name; public string ImagePath; public string PublicStatusName; public bool Available; public Guid ProductPageGuid; public string ProductPageAlias; /// <summary> /// Constructor for the ProductListItemViewModel class. /// </summary> /// <param name="productPage">Product's page.</param> /// <param name="priceDetail">Price of the product.</param> /// <param name="publicStatusName">Display name of the product's public status.</param> public ProductListItemViewModel(SKUTreeNode productPage, ProductCatalogPrices priceDetail, string publicStatusName) { // Sets the page information Name = productPage.DocumentName; ProductPageGuid = productPage.NodeGUID; ProductPageAlias = productPage.NodeAlias; // Sets the SKU information ImagePath = productPage.SKU.SKUImagePath; Available = !productPage.SKU.SKUSellOnlyAvailable || productPage.SKU.SKUAvailableItems > 0; PublicStatusName = publicStatusName; // Sets the price format information PriceModel = new PriceDetailViewModel { Price = priceDetail.Price, ListPrice = priceDetail.ListPrice, CurrencyFormatString = priceDetail.Currency.CurrencyFormatString }; } } //EndDocSection:ProductListingModel }
37.391304
123
0.640698
[ "MIT" ]
NattawatPin/LearningKit-Mvc
LearningKit/Models/Products/ProductListItemViewModel.cs
1,722
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Inicio()); } } }
23.636364
66
0.588462
[ "Apache-2.0" ]
darkangel100/jimenez
WindowsFormsApplication1/Program.cs
523
C#
using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; using UnityEngine.UIElements; public abstract class View<VM> : MonoBehaviour where VM:ViewModel<VM> { [SerializeField] protected UIDocument document; [SerializeField] private VM viewModel; CompositeDisposable disposable; protected VisualElement Root => document.rootVisualElement; private void OnEnable() { disposable = new CompositeDisposable(); viewModel.ObserveInit.Subscribe(x => { OnActivation(x, disposable); } ).AddTo(disposable); } public virtual void OnActivation(VM viewModel, CompositeDisposable disposable) { } private void OnDisable() { disposable.Dispose(); } }
19.463415
82
0.672932
[ "MIT" ]
crazyjackel/690-Project
Shared/Assets/Scripts/Functionality/View.cs
798
C#
using System; using System.Collections.Generic; using System.Net.Http.Headers; using KeyPayV2.Nz.Models.Common; using KeyPayV2.Nz.Enums; namespace KeyPayV2.Nz.Models.Business { public class BusinessAction { public DateTime Date { get; set; } public string Title { get; set; } public int Id { get; set; } public bool HighPriority { get; set; } } }
24
47
0.642157
[ "MIT" ]
KeyPay/keypay-dotnet-v2
src/keypay-dotnet/Nz/Models/Business/BusinessAction.cs
408
C#
using AdminWebsite.Helper; using System.Collections.Generic; using System.Security.Claims; using AdminWebsite.Models; namespace AdminWebsite.Security { public interface IUserIdentity { IEnumerable<string> GetGroupDisplayNames(); bool IsAdministratorRole(); string GetUserIdentityName(); bool IsVhOfficerAdministratorRole(); bool IsCaseAdministratorRole(); IEnumerable<string> GetAdministratorCaseTypes(); } public class UserIdentity : IUserIdentity { private readonly ClaimsPrincipal _currentUser; private readonly AdministratorRoleClaims _administratorRoleClaims; public UserIdentity(ClaimsPrincipal currentUser) { _currentUser = currentUser; _administratorRoleClaims = new AdministratorRoleClaims(_currentUser.Claims); } public IEnumerable<string> GetGroupDisplayNames() { return _administratorRoleClaims.UserCaseTypes; } /// <inheritdoc /> public IEnumerable<string> GetAdministratorCaseTypes() { return _administratorRoleClaims.UserCaseTypes; } public bool IsAdministratorRole() { return IsVhOfficerAdministratorRole() || IsCaseAdministratorRole(); } public bool IsVhOfficerAdministratorRole() { return _currentUser.IsInRole(AppRoles.VhOfficerRole); } public bool IsCaseAdministratorRole() { return _currentUser.IsInRole(AppRoles.CaseAdminRole); } public string GetUserIdentityName() { return _currentUser.Identity.Name; } } }
27.885246
88
0.656673
[ "MIT" ]
hmcts/vh-admin-web
AdminWebsite/AdminWebsite/Security/UserIdentity.cs
1,703
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/aspnet-contrib/AspNet.Security.OAuth.Providers * for more information concerning the license and the contributors participating to this project. */ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.OAuth; namespace AspNet.Security.OAuth.Lichess { /// <summary> /// Default values used by the Lichess authentication middleware. /// </summary> public static class LichessAuthenticationDefaults { /// <summary> /// Default value for <see cref="AuthenticationScheme.Name"/>. /// </summary> public const string AuthenticationScheme = "Lichess"; /// <summary> /// Default value for <see cref="AuthenticationScheme.DisplayName"/>. /// </summary> public const string DisplayName = "Lichess"; /// <summary> /// Default value for <see cref="AuthenticationSchemeOptions.ClaimsIssuer"/>. /// </summary> public const string Issuer = "Lichess"; /// <summary> /// Default value for <see cref="RemoteAuthenticationOptions.CallbackPath"/>. /// </summary> public const string CallbackPath = "/signin-lichess"; /// <summary> /// Default value for <see cref="OAuthOptions.AuthorizationEndpoint"/>. /// </summary> public const string AuthorizationEndpoint = "https://oauth.lichess.org/oauth/authorize"; /// <summary> /// Default value for <see cref="OAuthOptions.TokenEndpoint"/>. /// </summary> public const string TokenEndpoint = "https://oauth.lichess.org/oauth"; /// <summary> /// Default value for <see cref="OAuthOptions.UserInformationEndpoint"/>. /// </summary> public const string UserInformationEndpoint = "https://lichess.org/api/account"; /// <summary> /// Separate endpoint for retrieving email address /// </summary> public const string UserEmailsEndpoint = "https://lichess.org/api/account/email"; } }
37.017241
98
0.643223
[ "Apache-2.0" ]
Darkn1es/AspNet.Security.OAuth.Providers
src/AspNet.Security.OAuth.Lichess/LichessAuthenticationDefaults.cs
2,149
C#
#nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using VocaDb.Model.DataContracts.PVs; using VocaDb.Model.DataContracts.ReleaseEvents; using VocaDb.Model.DataContracts.Songs; using VocaDb.Model.Domain.Activityfeed; using VocaDb.Model.Domain.Albums; using VocaDb.Model.Domain.Artists; using VocaDb.Model.Domain.Comments; using VocaDb.Model.Domain.ExtLinks; using VocaDb.Model.Domain.Globalization; using VocaDb.Model.Domain.Images; using VocaDb.Model.Domain.PVs; using VocaDb.Model.Domain.Security; using VocaDb.Model.Domain.Songs; using VocaDb.Model.Domain.Tags; using VocaDb.Model.Domain.Users; using VocaDb.Model.Domain.Venues; using VocaDb.Model.Domain.Versioning; using VocaDb.Model.Helpers; namespace VocaDb.Model.Domain.ReleaseEvents { public class ReleaseEvent : IEntryWithNames<EventName>, IEntryWithVersions, IWebLinkFactory<ReleaseEventWebLink>, IReleaseEvent, IEntryImageInformation, IEntryWithComments<ReleaseEventComment>, IEntryWithStatus, INameFactory<EventName>, IEntryWithTags<EventTagUsage>, IEntryWithArtistLinks<ArtistForEvent> { IArchivedVersionsManager IEntryWithVersions.ArchivedVersionsManager => ArchivedVersionsManager; string IReleaseEvent.Name => DefaultName; INameManager IEntryWithNames.Names => Names; INameManager<EventName> IEntryWithNames<EventName>.Names => Names; string IEntryImageInformation.Mime => PictureMime; ImagePurpose IEntryImageInformation.Purpose => ImagePurpose.Main; private IList<Album> _albums = new List<Album>(); private ArchivedVersionManager<ArchivedReleaseEventVersion, ReleaseEventEditableFields> _archivedVersions = new(); private IList<ArtistForEvent> _artists = new List<ArtistForEvent>(); private IList<ReleaseEventComment> _comments = new List<ReleaseEventComment>(); private string _description; private NameManager<EventName> _names = new(); private PVManager<PVForEvent> _pvs = new(); private ReleaseEventSeries _series; private string _seriesSuffix; private IList<Song> _songs = new List<Song>(); private TagManager<EventTagUsage> _tags = new(); private IList<EventForUser> _users = new List<EventForUser>(); private IList<ReleaseEventWebLink> _webLinks = new List<ReleaseEventWebLink>(); public ReleaseEvent() { Category = EventCategory.Unspecified; CreateDate = DateTime.Now; Deleted = false; Description = SeriesSuffix = string.Empty; Status = EntryStatus.Draft; } public ReleaseEvent(string description, DateTime? date, ContentLanguageSelection defaultNameLanguage) : this() { ParamIs.NotNull(() => _names); Description = description; Date = date; TranslatedName.DefaultLanguage = defaultNameLanguage; TranslatedName.Clear(); } public ReleaseEvent(string description, DateTime? date, ReleaseEventSeries series, int seriesNumber, string seriesSuffix, ContentLanguageSelection defaultNameLanguage, bool customName) : this() { ParamIs.NotNull(() => series); Description = description; Date = date; Series = series; SeriesNumber = seriesNumber; SeriesSuffix = seriesSuffix; CustomName = customName; TranslatedName.Clear(); if (customName) { TranslatedName.DefaultLanguage = defaultNameLanguage; } else { TranslatedName.DefaultLanguage = Series.TranslatedName.DefaultLanguage; } } public virtual IEnumerable<Album> Albums => AllAlbums.Where(a => !a.Deleted); public virtual IList<Album> AllAlbums { get => _albums; set { ParamIs.NotNull(() => value); _albums = value; } } public virtual IList<ArtistForEvent> AllArtists { get => _artists; set { ParamIs.NotNull(() => value); _artists = value; } } public virtual IList<Song> AllSongs { get => _songs; set { ParamIs.NotNull(() => value); _songs = value; } } public virtual bool AllowNotifications => true; public virtual ArchivedVersionManager<ArchivedReleaseEventVersion, ReleaseEventEditableFields> ArchivedVersionsManager { get => _archivedVersions; set { ParamIs.NotNull(() => value); _archivedVersions = value; } } public virtual IEnumerable<ArtistForEvent> Artists => AllArtists.Where(a => a.Artist == null || !a.Artist.Deleted); public virtual EventCategory Category { get; set; } IEnumerable<Comment> IEntryWithComments.Comments => Comments; public virtual IList<ReleaseEventComment> AllComments { get => _comments; set { ParamIs.NotNull(() => value); _comments = value; } } public virtual IEnumerable<ReleaseEventComment> Comments => AllComments.Where(c => !c.Deleted); public virtual DateTime CreateDate { get; set; } public virtual bool CustomName { get; set; } public virtual Date Date { get; set; } public virtual string DefaultName => TranslatedName.Default; public virtual bool Deleted { get; set; } public virtual string Description { get => _description; set { ParamIs.NotNull(() => value); _description = value; } } public virtual Date EndDate { get; set; } public virtual EntryType EntryType => EntryType.ReleaseEvent; public virtual bool HasSeries => Series != null; public virtual int Id { get; set; } /// <summary> /// Event category inherited from series if there is one, otherwise event's own category. /// </summary> public virtual EventCategory InheritedCategory => HasSeries ? Series.Category : Category; public virtual NameManager<EventName> Names { get => _names; set { ParamIs.NotNull(() => value); _names = value; } } public virtual string PictureMime { get; set; } public virtual PVManager<PVForEvent> PVs { get => _pvs; set { ParamIs.NotNull(() => value); _pvs = value; } } public virtual ReleaseEventSeries Series { get => _series; set => _series = value; } public virtual int SeriesNumber { get; set; } public virtual string SeriesSuffix { get => _seriesSuffix; set { ParamIs.NotNull(() => value); _seriesSuffix = value; } } public virtual SongList SongList { get; set; } public virtual IEnumerable<Song> Songs => AllSongs.Where(a => !a.Deleted); public virtual EntryStatus Status { get; set; } public virtual TagManager<EventTagUsage> Tags { get => _tags; set { ParamIs.NotNull(() => value); _tags = value; } } ITagManager IEntryWithTags.Tags => Tags; public virtual TranslatedString TranslatedName => Names.SortNames; /// <summary> /// URL slug. Cannot be null. Can be empty. /// </summary> public virtual string UrlSlug => Utils.UrlFriendlyNameFactory.GetUrlFriendlyName(TranslatedName); public virtual IList<EventForUser> Users { get => _users; set { ParamIs.NotNull(() => value); _users = value; } } public virtual Venue Venue { get; set; } public virtual string VenueName { get; set; } public virtual int Version { get; set; } public virtual IList<ReleaseEventWebLink> WebLinks { get => _webLinks; set { ParamIs.NotNull(() => value); _webLinks = value; } } public virtual ArchivedReleaseEventVersion CreateArchivedVersion(XDocument data, ReleaseEventDiff diff, AgentLoginData author, EntryEditEvent reason, string notes) { var archived = new ArchivedReleaseEventVersion(this, data, diff, author, reason, notes); ArchivedVersionsManager.Add(archived); Version++; return archived; } #nullable enable public virtual Comment CreateComment(string message, AgentLoginData loginData) { ParamIs.NotNullOrEmpty(() => message); ParamIs.NotNull(() => loginData); var comment = new ReleaseEventComment(this, message, loginData); AllComments.Add(comment); return comment; } #nullable disable public virtual EventName CreateName(string val, ContentLanguageSelection language) { return CreateName(new LocalizedString(val, language)); } #nullable enable public virtual EventName CreateName(ILocalizedString localizedString) { ParamIs.NotNull(() => localizedString); var name = new EventName(this, localizedString); Names.Add(name); return name; } public virtual PVForEvent CreatePV(PVContract contract) { ParamIs.NotNull(() => contract); var pv = new PVForEvent(this, contract); PVs.Add(pv); return pv; } public virtual ReleaseEventWebLink CreateWebLink(string description, string url, WebLinkCategory category, bool disabled) { ParamIs.NotNull(() => description); ParamIs.NotNullOrEmpty(() => url); var link = new ReleaseEventWebLink(this, description, url, category, disabled); WebLinks.Add(link); return link; } public virtual bool Equals(ReleaseEvent? another) { if (another == null) return false; if (ReferenceEquals(this, another)) return true; if (Id == 0) return false; return Id == another.Id; } public override bool Equals(object? obj) { return Equals(obj as ReleaseEvent); } public override int GetHashCode() { return Id.GetHashCode(); } private async Task<ArtistForEvent> AddArtist(ArtistForEventContract contract, Func<int, Task<Artist>> artistGetter) { ArtistForEvent link; if (contract.Artist == null) { link = new ArtistForEvent(this, null) { Name = contract.Name, Roles = contract.Roles }; } else { var artist = await artistGetter(contract.Artist.Id); link = new ArtistForEvent(this, artist) { Roles = contract.Roles }; } AllArtists.Add(link); return link; } #nullable disable public virtual IEnumerable<LocalizedString> GetNamesFromSeries() { return Series.Names.Select(seriesName => new LocalizedString(Series.GetEventName(SeriesNumber, SeriesSuffix, seriesName.Value), seriesName.Language)); } public virtual void SetSeries(ReleaseEventSeries newSeries) { if (Equals(Series, newSeries)) return; Series?.AllEvents.Remove(this); newSeries?.AllEvents.Add(this); Series = newSeries; } public virtual void SetVenue(Venue newVenue) { if (Equals(Venue, newVenue)) return; Venue?.AllEvents.Remove(this); newVenue?.AllEvents.Add(this); Venue = newVenue; } #nullable enable public virtual async Task<CollectionDiffWithValue<ArtistForEvent, ArtistForEvent>> SyncArtists( IList<ArtistForEventContract> newArtists, Func<int, Task<Artist>> artistGetter) { ParamIs.NotNull(() => newArtists); Task<bool> Update(ArtistForEvent old, ArtistForEventContract newArtist) { if (old.Roles == newArtist.Roles) { return Task.FromResult(false); } old.Roles = newArtist.Roles; return Task.FromResult(true); } var diff = await CollectionHelper.SyncWithContentAsync(AllArtists, newArtists, (a1, a2) => a1.Id == a2.Id, async a => await AddArtist(a, artistGetter), Update, null); return diff; } public override string ToString() { return $"Release event '{DefaultName}' [{Id}]"; } #nullable disable } public interface IReleaseEvent : IEntryWithIntId { string Name { get; } } }
25.861915
179
0.683603
[ "MIT" ]
AgFlore/vocadb
VocaDbModel/Domain/ReleaseEvents/ReleaseEvent.cs
11,612
C#