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 file="ActorWithStashSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com> // Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using Akka.Actor; using Akka.Actor.Internal; using Akka.TestKit; using Akka.TestKit.TestActors; using Akka.Tests.TestUtils; using Xunit; namespace Akka.Tests.Actor.Stash { public class ActorWithStashSpec : AkkaSpec { private static StateObj _state; public ActorWithStashSpec() { _state = new StateObj(this); } [Fact] public void An_actor_with_unbounded_stash_must_have_a_stash_assigned_to_it() { var actor = ActorOfAsTestActorRef<UnboundedStashActor>(); Assert.NotNull(actor.UnderlyingActor.Stash); Assert.IsAssignableFrom<UnboundedStashImpl>(actor.UnderlyingActor.Stash); } [Fact] public void An_actor_with_bounded_stash_must_have_a_stash_assigned_to_it() { var actor = ActorOfAsTestActorRef<BoundedStashActor>(); Assert.NotNull(actor.UnderlyingActor.Stash); Assert.IsAssignableFrom<BoundedStashImpl>(actor.UnderlyingActor.Stash); } [Fact] public void An_actor_with_Stash_Must_stash_and_unstash_messages() { var stasher = ActorOf<StashingActor>("stashing-actor"); stasher.Tell("bye"); //will be stashed stasher.Tell("hello"); //forces UnstashAll _state.Finished.Await(); _state.S.ShouldBe("bye"); } [Fact] public void An_actor_Must_throw_an_exception_if_the_same_message_is_stashed_twice() { _state.ExpectedException = new TestLatch(); var stasher = ActorOf<StashingTwiceActor>("stashing-actor"); stasher.Tell("hello"); _state.ExpectedException.Ready(TimeSpan.FromSeconds(3)); } [Fact] public void An_actor_must_unstash_all_messages_on_PostStop() { var stasher = ActorOf<StashEverythingActor>("stasher"); Watch(stasher); //This message will be stashed by stasher stasher.Tell("message"); //When stasher is stopped it should unstash message during poststop to mailbox //the mailbox will be emptied and the messages will be sent to deadletters EventFilter.DeadLetter<string>(s=>s=="message", source: stasher.Path.ToString()).ExpectOne(() => { Sys.Stop(stasher); ExpectTerminated(stasher); }); } [Fact] public void An_actor_Must_process_stashed_messages_after_restart() { SupervisorStrategy strategy = new OneForOneStrategy(2, TimeSpan.FromSeconds(1), e => Directive.Restart); var boss = ActorOf(() => new Supervisor(strategy)); var restartLatch = CreateTestLatch(); var hasMsgLatch = CreateTestLatch(); var slaveProps = Props.Create(() => new SlaveActor(restartLatch, hasMsgLatch, "stashme")); //Send the props to supervisor, which will create an actor and return the ActorRef var slave = boss.AskAndWait<IActorRef>(slaveProps, TestKitSettings.DefaultTimeout); //send a message that will be stashed slave.Tell("stashme"); //this will crash the slave. slave.Tell("crash"); //During preRestart restartLatch is opened //After that the cell will unstash "stashme", it should be received by the slave and open hasMsgLatch restartLatch.Ready(TimeSpan.FromSeconds(10)); hasMsgLatch.Ready(TimeSpan.FromSeconds(10)); } [Fact] public void An_actor_that_clears_the_stash_on_preRestart_Must_not_receive_previously_stashed_messages() { SupervisorStrategy strategy = new OneForOneStrategy(2, TimeSpan.FromSeconds(1), e => Directive.Restart); var boss = ActorOf(() => new Supervisor(strategy)); var restartLatch = CreateTestLatch(); var slaveProps = Props.Create(() => new ActorsThatClearsStashOnPreRestart(restartLatch)); //Send the props to supervisor, which will create an actor and return the ActorRef var slave = boss.AskAndWait<IActorRef>(slaveProps, TestKitSettings.DefaultTimeout); //send messages that will be stashed slave.Tell("stashme 1"); slave.Tell("stashme 2"); slave.Tell("stashme 3"); //this will crash the slave. slave.Tell("crash"); //send a message that should not be stashed slave.Tell("this should bounce back"); //During preRestart restartLatch is opened //After that the cell will clear the stash //So when the cell tries to unstash, it will not unstash messages. If it would TestActor //would receive all stashme messages instead of "this should bounce back" restartLatch.Ready(TimeSpan.FromSeconds(1110)); ExpectMsg("this should bounce back"); } [Fact] public void An_actor_must_rereceive_unstashed_Terminated_messages() { ActorOf(Props.Create(() => new TerminatedMessageStashingActor(TestActor)), "terminated-message-stashing-actor"); ExpectMsg("terminated1"); ExpectMsg("terminated2"); } private class UnboundedStashActor : BlackHoleActor, IWithUnboundedStash { public IStash Stash { get; set; } } private class BoundedStashActor : BlackHoleActor, IWithBoundedStash { public IStash Stash { get; set; } } private class StashingActor : TestReceiveActor, IWithUnboundedStash { public StashingActor() { Receive("hello", m => { _state.S = "hello"; Stash.UnstashAll(); Become(Greeted); }); ReceiveAny(m => Stash.Stash()); } private void Greeted() { Receive("bye", _ => { _state.S = "bye"; _state.Finished.Await(); }); ReceiveAny(_ => { }); //Do nothing } public IStash Stash { get; set; } } private class StashEverythingActor : ReceiveActor, IWithUnboundedStash { public StashEverythingActor() { ReceiveAny(m=>Stash.Stash()); } public IStash Stash { get; set; } } private class StashingTwiceActor : TestReceiveActor, IWithUnboundedStash { public StashingTwiceActor() { Receive("hello", m => { Stash.Stash(); try { Stash.Stash(); } catch(IllegalActorStateException) { _state.ExpectedException.Open(); } }); ReceiveAny(m => { }); } private void Greeted() { Receive("bye", _ => { _state.S = "bye"; _state.Finished.Await(); }); ReceiveAny(_ => { }); //Do nothing } public IStash Stash { get; set; } } private class SlaveActor : TestReceiveActor, IWithUnboundedStash { private readonly TestLatch _restartLatch; public SlaveActor(TestLatch restartLatch, TestLatch hasMsgLatch, string expectedUnstashedMessage) { _restartLatch = restartLatch; Receive("crash", _ => { throw new Exception("Received \"crash\""); }); // when restartLatch is not yet open, stash all messages != "crash" Receive<object>(_ => !restartLatch.IsOpen, m => Stash.Stash()); // when restartLatch is open, must receive the unstashed message Receive(expectedUnstashedMessage, _ => hasMsgLatch.Open()); } protected override void PreRestart(Exception reason, object message) { if(!_restartLatch.IsOpen) _restartLatch.Open(); base.PreRestart(reason, message); } public IStash Stash { get; set; } } private class ActorsThatClearsStashOnPreRestart : TestReceiveActor, IWithUnboundedStash { private readonly TestLatch _restartLatch; public ActorsThatClearsStashOnPreRestart(TestLatch restartLatch) { _restartLatch = restartLatch; Receive("crash", _ => { throw new Exception("Received \"crash\""); }); // when restartLatch is not yet open, stash all messages != "crash" Receive<object>(_ => !restartLatch.IsOpen, m => Stash.Stash()); // when restartLatch is open we send all messages back ReceiveAny(m => Sender.Tell(m)); } protected override void PreRestart(Exception reason, object message) { if(!_restartLatch.IsOpen) _restartLatch.Open(); Stash.ClearStash(); base.PreRestart(reason, message); } public IStash Stash { get; set; } } private class TerminatedMessageStashingActor : TestReceiveActor, IWithUnboundedStash { public TerminatedMessageStashingActor(IActorRef probe) { var watchedActor=Context.Watch(Context.ActorOf<BlackHoleActor>("watched-actor")); var stashed = false; Context.Stop(watchedActor); Receive<Terminated>(w => w.ActorRef == watchedActor, w => { if(!stashed) { Stash.Stash(); //Stash the Terminated message stashed = true; Stash.UnstashAll(); //Unstash the Terminated message probe.Tell("terminated1"); } else { probe.Tell("terminated2"); } }); } public IStash Stash { get; set; } } private class StateObj { public StateObj(TestKitBase testKit) { S = ""; Finished = testKit.CreateTestBarrier(2); } public string S; public TestBarrier Finished; public TestLatch ExpectedException; } } }
36.351613
124
0.543704
[ "Apache-2.0" ]
WilliamBZA/akka.net
src/core/Akka.Tests/Actor/Stash/ActorWithStashSpec.cs
11,271
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.CostManagement.V20200601.Inputs { /// <summary> /// The order by expression to be used in the report. /// </summary> public sealed class ReportConfigSortingArgs : Pulumi.ResourceArgs { /// <summary> /// Direction of sort. /// </summary> [Input("direction")] public Input<string>? Direction { get; set; } /// <summary> /// The name of the column to sort. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; public ReportConfigSortingArgs() { } } }
27.171429
81
0.616193
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/CostManagement/V20200601/Inputs/ReportConfigSortingArgs.cs
951
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using Fossil.AbstractSyntaxTree; namespace Fossil { class NativeFunctionObject : ICallableObject { public NativeFunctionObject(string funcName, NativeFunction nativeFunction) { Contract.Requires<ArgumentNullException>(funcName != null); Contract.Requires<ArgumentNullException>(nativeFunction != null); this.funcName = funcName; this.nativeFunction = nativeFunction; } public Variant Call(Environment env, List<INode> parameters) { List<Variant> evaledParameters = parameters.Select(node => node.Eval(env)).ToList(); Variant result = nativeFunction.Invoke(evaledParameters); return result ?? new Variant(); } public string Name { get { return funcName; } } public delegate Variant NativeFunction(List<Variant> args); private readonly NativeFunction nativeFunction; private readonly string funcName; } }
32.25
96
0.666667
[ "MIT" ]
sakano/Fossil
Fossil/NativeFunctionObject.cs
1,163
C#
// DirectXSharp // // Copyright (C) 2021 Ronald van Manen <rvanmanen@gmail.com> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace DirectXSharp.Interop { /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9"]/*' /> public partial struct D3DVIEWPORT9 { /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.X"]/*' /> [NativeTypeName("DWORD")] public uint X; /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.Y"]/*' /> [NativeTypeName("DWORD")] public uint Y; /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.Width"]/*' /> [NativeTypeName("DWORD")] public uint Width; /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.Height"]/*' /> [NativeTypeName("DWORD")] public uint Height; /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.MinZ"]/*' /> public float MinZ; /// <include file='D3DVIEWPORT9.xml' path='doc/member[@name="D3DVIEWPORT9.MaxZ"]/*' /> public float MaxZ; } }
41.735849
96
0.685805
[ "MIT" ]
ronaldvanmanen/DirectXSharp
sources/DirectXSharp.Interop/d3d9/D3DVIEWPORT9.cs
2,212
C#
using UnityEngine; using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Threading; using WorldMapStrategyKit.ClipperLib; namespace WorldMapStrategyKit { public partial class WMSK_Editor : MonoBehaviour { /// <summary> /// Adjusts all countries frontiers to match the hexagonal grid /// </summary> public IEnumerator HexifyCountries (HexifyOpContext context) { Cell[] cells = _map.cells; if (cells == null) yield break; // Initialization cancelled = false; hexifyContext = context; if (procCells == null || procCells.Length < cells.Length) { procCells = new RegionCell[cells.Length]; } for (int k = 0; k < cells.Length; k++) { procCells [k].entityIndex = -1; } // Compute area of a single cell; for optimization purposes we'll ignore all regions whose surface is smaller than a 20% the size of a cell float minArea = 0; Region templateCellRegion = null; for (int k = 0; k < cells.Length; k++) { if (cells [k] != null) { templateCellRegion = new Region (null, 0); templateCellRegion.UpdatePointsAndRect (cells [k].points, true); minArea = templateCellRegion.rect2DArea * 0.2f; break; } } if (templateCellRegion == null) yield break; if (hexagonPoints == null || hexagonPoints.Length != 6) { hexagonPoints = new Vector2[6]; } for (int k = 0; k < 6; k++) { hexagonPoints [k] = templateCellRegion.points [k] - templateCellRegion.center; } // Pass 1: remove minor regions yield return RemoveSmallRegions (minArea, _map.countries); // Pass 2: assign all region centers to each country from biggest country to smallest country if (!cancelled) { yield return AssignRegionCenters (_map.countries); } // Pass 3: add cells to target countries if (!cancelled) { yield return AddHexagons (_map.countries); } // Pass 4: merge adjacent regions if (!cancelled) { yield return MergeAdjacentRegions (_map.countries); } // Pass 5: remove cells from other countries if (!cancelled) { yield return RemoveHexagons (_map.countries); } // Pass 6: update geometry of resulting countries if (!cancelled) { yield return UpdateCountries (); } if (!cancelled) { _map.OptimizeFrontiers (); _map.Redraw (true); } hexifyContext.progress (1f, hexifyContext.title, ""); // hide progress bar yield return null; if (hexifyContext.finish != null) { hexifyContext.finish (cancelled); } } IEnumerator UpdateCountries () { Country[] _countries = _map.countries; for (int k = 0; k < _countries.Length; k++) { if (k % 10 == 0) { if (hexifyContext.progress != null) { if (hexifyContext.progress ((float)k / _countries.Length, hexifyContext.title, "Pass 6/6: updating countries...")) { cancelled = true; hexifyContext.finish (true); yield break; } } yield return null; } Country country = _countries [k]; _map.CountrySanitize (k, 3, false); if (country.regions.Count == 0) { if (_map.CountryDelete (k, true, false)) { _countries = _map.countries; k--; } } else { _map.RefreshCountryGeometry (country); } } // Update cities and mount points City[] cities = _map.cities; int cityCount = cities.Length; for (int k = 0; k < cityCount; k++) { City city = cities [k]; int countryIndex = _map.GetCountryIndex (city.unity2DLocation); if (city.countryIndex != countryIndex) { city.countryIndex = countryIndex; city.province = ""; // clear province since it does not apply anymore } } int mountPointCount = _map.mountPoints.Count; for (int k = 0; k < mountPointCount; k++) { MountPoint mp = _map.mountPoints [k]; int countryIndex = _map.GetCountryIndex (mp.unity2DLocation); if (mp.countryIndex != countryIndex) { mp.countryIndex = countryIndex; mp.provinceIndex = -1; // same as cities - province cleared in case it's informed since it does not apply anymore } } } } }
26.435897
142
0.650097
[ "CC0-1.0" ]
lelehappy666/Refugees
Refugees/Assets/PlugInPackage/WorldMapStrategyKit/Scripts/MapEditor/Hexify/HexifyCountries.cs
4,124
C#
using System.Collections.ObjectModel; using Cirrious.MvvmCross.ViewModels; namespace StatusBar.Core { public class MessageViewModel : MvxViewModel { private readonly ObservableCollection<IMessageItem> _messages = new ObservableCollection<IMessageItem>(); public ObservableCollection<IMessageItem> Messages { get { return _messages; } } } }
24.9375
113
0.704261
[ "Apache-2.0" ]
lothrop/StatusBar.iOS
StatusBar.Core/MessageViewModel.cs
401
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace PdfImageExtractor { public partial class frmPromotion : PdfImageExtractor.CustomForm { public frmPromotion() { InitializeComponent(); } private void picPromotion_Click(object sender, EventArgs e) { VisitWebpage(); } private void VisitWebpage() { System.Diagnostics.Process.Start("https://onlinepdfapps.com"); } private void lnkPromotion_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { VisitWebpage(); } private void btnOK_Click(object sender, EventArgs e) { if (chkVisitWebpage.Checked) { VisitWebpage(); } Properties.Settings.Default.ShowPromotion = !chkDoNotShowAgain.Checked; Properties.Settings.Default.Save(); //this.DialogResult = DialogResult.OK; this.Close(); } } }
23.06
93
0.599306
[ "MIT" ]
fourDotsSoftware/FreePDFImageExtractor
PdfImageExtractor/frmPromotion.cs
1,155
C#
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Windows; namespace LeroyMerlinClient { [Serializable] public class Program { public string Продавец = ""; public List<Taga> listTables = new List<Taga>(); } public static class Win { // Массив открытых окон информации о клиентах public static List<InfoAboutClient> IAC = new List<InfoAboutClient>(); public static Program program = new Program(); public const string log = "apbx2@mail.ru", shablonsend = "Уважаемый клиент! Вашему заказу на товар ( <obj> ) присвоен №<num>. Как только товар поступит к нам в магазин, Вы получите оповещение в виде СМС или телефонного звонка нашего сотрудника. Удачных покупок в Leroy Merlin! :)", shablondata = "Здравствуйте <name>! К сожалению ваш заказ №<num> ( <obj> ) еще не поступил к нам в магазин. Предполагаемая дата поступления товара <dateE>", richObzvon2 = @"Позвоните клиенту по телефону указаному выше используя следующий скрипт диалога с клиентом: • Консультант: - 'Добрый день <name>, меня зовут (имя сотрудника ЛМ). Я звоню вам по поводу вашего заказа №<num> (<obj>). Хотел бы у вас поинтересоваться, заинтересованы ли вы еще в приобритении товара?' • КЛИЕНТА: 'ДА' • Консультант: - 'Отлично, тогда с радостью сообщаю вам о том, что ваш товар прибыл к нам в магазин и уже ждет вас. Товар будет закреплен за номером заказа в течении двух дней, по истечению двух дней товар снимается с резерва. Спасибо за ожидание товара, всего доброго!' • КЛИЕНТ: 'НЕТ' - 'Хорошо, могу ли я поинтересоваться? Вы приобрели аналог товара или же нашли данный товар в другом магазине? Спасибо! Тогда прошу прощение за беспокойство, всего доброго и хорошего дня!'"; public static string Shablon { get { return "Здравствуйте <name>! Ваш заказ №<num> ( <obj> ) прибыл в наш магазин! Товар будет ожидать Вас в течении 2-х суток. Большое спасибо за ожидание! :) Наш телефон: " + settings.TelephoneM; } } //Файл настроек public static SettingsProgram settings = new SettingsProgram(); // Основное окно public static MainWindow mainWindow; private static readonly BinaryFormatter formatter = new BinaryFormatter(); /// <summary> /// Сохраняет текущуюю базу /// </summary> public static void SaveThisBase() { if (settings.path != null && settings.path != "") try { using (FileStream fs = new FileStream(settings.path, FileMode.Create)) formatter.Serialize(fs, program); } catch { } else try { using (FileStream fs = new FileStream("Becap.lmb", FileMode.Create)) formatter.Serialize(fs, program); } catch { } } /// <summary> /// Открывает текущую базу /// </summary> public static void OpenThisBase() { if (settings.path != null) try { using (FileStream fs = new FileStream(settings.path, FileMode.OpenOrCreate)) program = (Program)formatter.Deserialize(fs); } catch { try { using (FileStream fs = new FileStream("Becap.lmb", FileMode.OpenOrCreate)) program = (Program)formatter.Deserialize(fs); } catch { program = new Program(); } } else try { if (File.Exists("Becap.lmb")) using (FileStream fs = new FileStream("Becap.lmb", FileMode.OpenOrCreate)) program = (Program)formatter.Deserialize(fs); else using (FileStream fs = new FileStream("Becap.lmb", FileMode.Create)) formatter.Serialize(fs, program); } catch { program = new Program(); } } /// <summary> /// Возращает только открытую базу /// </summary> /// <returns>class program</returns> public static Program GetOpenThisBase() { if (settings.path != null) try { using (FileStream fs = new FileStream(settings.path, FileMode.OpenOrCreate)) return (Program)formatter.Deserialize(fs); } catch { try { using (FileStream fs = new FileStream("Becap.lmb", FileMode.OpenOrCreate)) return (Program)formatter.Deserialize(fs); } catch { return null; } } else try { using (FileStream fs = new FileStream("Becap.lmb", FileMode.OpenOrCreate)) return (Program)formatter.Deserialize(fs); } catch { return null; } } /// <summary> /// Сохранение настроек /// </summary> public static void SaveSettings() { settings.state = mainWindow.WindowState; settings.posGrid[0] = mainWindow.Tablet.ColumnDefinitions[0].Width.Value; settings.posGrid[1] = mainWindow.Tablet.ColumnDefinitions[1].Width.Value; settings.posGrid[2] = mainWindow.Tablet.ColumnDefinitions[2].Width.Value; settings.posGrid[3] = mainWindow.Tablet.ColumnDefinitions[3].Width.Value; settings.posGrid[4] = mainWindow.Tablet.ColumnDefinitions[4].Width.Value; settings.posGrid[5] = mainWindow.Tablet.ColumnDefinitions[5].Width.Value; settings.position = new Point(mainWindow.Left, mainWindow.Top); settings.size = new Point(mainWindow.Width, mainWindow.Height); using (FileStream fs = new FileStream("S.settings", FileMode.Create)) formatter.Serialize(fs, settings); } public static void OpenSettings() { if (File.Exists("S.settings")) try { using (FileStream fs = new FileStream("S.settings", FileMode.OpenOrCreate)) settings = (SettingsProgram)formatter.Deserialize(fs); mainWindow.WindowState = settings.state; for (int i = 0; i < 6; i++) mainWindow.Tablet.ColumnDefinitions[i].Width = new GridLength(Win.settings.posGrid[i], GridUnitType.Star); mainWindow.Top = settings.position.Y; mainWindow.Left = settings.position.X; mainWindow.Width = settings.size.X; mainWindow.Height = settings.size.Y; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Непорядок"); } } /// <summary> /// Удаляет клиента из базы /// </summary> /// <param name="index">Номер клиента</param> public static void RemoveClient(int index) { OpenThisBase(); mainWindow.Components.Children.RemoveAt(index); program.listTables.RemoveAt(index); SaveThisBase(); } } }
32.141361
241
0.686431
[ "Apache-2.0" ]
danilinus/LMClient
LeroyMerlinClient/Program.cs
7,304
C#
using Entitas; using FineGameDesign.Utils; using System.Collections.Generic; namespace FineGameDesign.Entitas { public sealed class TriggerReactionSystem : ReactiveSystem<GameEntity> { private readonly GameContext m_Context; public TriggerReactionSystem(Contexts contexts) : base(contexts.game) { m_Context = contexts.game; } protected override ICollector<GameEntity> GetTrigger(IContext<GameEntity> context) { return context.CreateCollector( GameMatcher.TriggerEnter.Added() ); } protected override bool Filter(GameEntity entity) { var trigger = entity.triggerEnter; GameEntity other = m_Context.GetEntityWithId(trigger.otherId); if (other == null) return false; if (!entity.hasReceiver) return false; return ReceiverUtils.Filter(entity.receiver, other); } protected override void Execute(List<GameEntity> entities) { foreach (GameEntity triggerEntity in entities) { ReplaceReaction(triggerEntity, true); } } public static void ReplaceReaction(GameEntity entity, bool isReaction) { entity.isReaction = !isReaction; entity.isReaction = isReaction; } } }
27.882353
90
0.601266
[ "MIT" ]
ethankennerly/digestion-defense
DigestionDefense/Assets/Sources/Logic/Game/TriggerReactionSystem.cs
1,422
C#
// <copyright file="ClickAt.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Globalization; using System.Text; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; namespace Selenium.Internal.SeleniumEmulation { /// <summary> /// Defines the command for the click keyword. /// </summary> internal class ClickAt : SeleneseCommand { private ElementFinder finder; private AlertOverride alert; /// <summary> /// Initializes a new instance of the <see cref="ClickAt"/> class. /// </summary> /// <param name="alert">An <see cref="AlertOverride"/> object used to handle JavaScript alerts.</param> /// <param name="finder">An <see cref="ElementFinder"/> used to find the element on which to execute the command.</param> public ClickAt(AlertOverride alert, ElementFinder finder) { this.finder = finder; this.alert = alert; } /// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { this.alert.ReplaceAlertMethod(); IWebElement element = this.finder.FindElement(driver, locator); string[] parts = value.Split(new char[] { ',' }); int offsetX = int.Parse(parts[0], CultureInfo.InvariantCulture); int offsetY = int.Parse(parts[1], CultureInfo.InvariantCulture); new Actions(driver).MoveToElement(element, offsetX, offsetY).Click().Perform(); return null; } } }
41.984848
129
0.670516
[ "Apache-2.0" ]
BlackSmith/selenium
dotnet/src/webdriverbackedselenium/Internal/SeleniumEmulation/ClickAt.cs
2,771
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CustomProject.Common; namespace CustomProject.Entity { [Table(PrimaryColumn = "ShipperID", TableName = "Shippers",IdendityColumn = "ShipperID")] public class Shippers { public int ShipperID { get; set; } public string CompanyName { get; set; } public string Phone { get; set; } } }
23.526316
93
0.691275
[ "MIT" ]
baristutakli/NA-203-Notes
Ders22/CustomProject.Entity/Shippers.cs
449
C#
using System.Collections.Generic; using System.Text; using UnityEngine; using UnityEngine.UI; using VektorLibrary.Utility; namespace VoxelEngine.Utility { /// <summary> /// Utility class for drawing various debug readouts to the game screen. /// </summary> public class DevReadout : MonoBehaviour { // Singleton Instance & Accessor public static DevReadout Instance { get; private set; } // Unity Inspector [Header("Debug Readout Config")] [SerializeField] private KeyCode _toggleKey = KeyCode.F2; [SerializeField] private KeyCode _showTargetingKey = KeyCode.F3; [SerializeField] private Text _debugText; // Private: Debug Fields private readonly Dictionary<string, string> _debugFields = new Dictionary<string, string>(); // Private: FPS Counter private FpsCounter _fpsCounter; // Private: State private bool _enabled; // Property: State public static bool Enabled => Instance._enabled; [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] private static void Preload() { // Load the prefab from the common objects folder var prefab = Resources.Load<Canvas>("Common/DebugReadout"); // Destroy any existing instances if (Instance != null) Destroy(Instance.gameObject); // Instantiate and assign the instance var instance = Instantiate(prefab, Vector3.zero, Quaternion.identity); Instance = instance.GetComponentInChildren<DevReadout>(); // Ensure this singleton does not get destroyed on scene load DontDestroyOnLoad(Instance.transform.root); // Initialize the instance Instance.Initialize(); } // Initialization private void Initialize() { // Set up some default readouts var version = Debug.isDebugBuild ? "DEVELOPMENT" : "DEPLOY"; UpdateField("VektorKnight ", $"Voxel Engine [{version}]"); UpdateField("CPU", $"{SystemInfo.processorCount} x {SystemInfo.processorType}"); UpdateField("GPU", $"{SystemInfo.graphicsDeviceName} [{SystemInfo.graphicsDeviceType}]"); AddField("FPS"); _fpsCounter = new FpsCounter(); _enabled = true; } // Toggle display the of readout public static void ToggleReadout() { if (Instance._enabled) { Instance._debugText.enabled = false; Instance._enabled = false; } else { Instance._debugText.enabled = true; Instance._enabled = true; } } // Toggle the display of the readout based on a bool public static void ToggleReadout(bool state) { if (state) { Instance._debugText.enabled = true; Instance._enabled = true; } else { Instance._debugText.enabled = false; Instance._enabled = false; } } // Add a debug field to the readout public static void AddField(string key) { // Exit if the specified key already exists if (Instance._debugFields.ContainsKey(key)) return; // Add the key to the dictionary with the given value Instance._debugFields.Add(key, "null"); } // Remove a debug field from the readout public static void RemoveField(string key) { // Exit if the specified key does not exist if (!Instance._debugFields.ContainsKey(key)) return; // Remove the key from the dictionary Instance._debugFields.Remove(key); } // Update an existing debug field public static void UpdateField(string key, string value) { // Create a new field if the specified field doesn't exist if (!Instance._debugFields.ContainsKey(key)) Instance._debugFields.Add(key, value); // Update the specified field with the new value Instance._debugFields[key] = value; } // Unity Update private void Update() { // Check for key presses if (Input.GetKeyDown(Instance._toggleKey)) ToggleReadout(); // Exit if the readout is disabled if (!_enabled) return; // Update FPS Counter UpdateField("FPS", $"{Instance._fpsCounter.UpdateValues()} (Δ{Time.deltaTime * 1000f:n1}ms)"); // Iterate through the debug fields and add them to the readout var displayText = new StringBuilder(); foreach (var field in Instance._debugFields) { displayText.Append($"{field.Key}: {field.Value}\n"); } // Set the readout text Instance._debugText.text = displayText.ToString(); } } }
37.368794
106
0.565193
[ "MIT" ]
VektorKnight/VoxelEngine
Assets/VoxelEngine/Source/Utility/DevReadout.cs
5,272
C#
using System; using System.Linq; using System.Text; /// <summary> ///项目名称:Diana轻量级开发框架 ///版本:0.0.1版 ///开发团队成员:胡凯雨,张梦丽,艾美珍,易传佳,陈祚送,康文洋,张婷婷,王露,周庆,夏萍萍,陈兰兰 ///模块和代码页功能描述:角色资源关联实体类 ///最后修改时间:2018/1/26 /// </summary> namespace Diana.model { public class role_resource { /// <summary> /// Desc:- /// Default:- /// Nullable:False /// </summary> public int id { get; set; } /// <summary> /// Desc:- /// Default:- /// Nullable:False /// </summary> public int roleid { get; set; } /// <summary> /// Desc:- /// Default:- /// Nullable:False /// </summary> public int resoureceid { get; set; } } }
19.815789
51
0.487384
[ "MIT" ]
ecjtuseclab/Diana
code/Diana0.01/model/Model/role_resource.cs
937
C#
namespace AAC.ABPDemo.Configuration { public static class AppSettingNames { public const string UiTheme = "App.UiTheme"; } }
18.25
52
0.671233
[ "MIT" ]
Ramos66/ABPDemo
aspnet-core/src/AAC.ABPDemo.Core/Configuration/AppSettingNames.cs
148
C#
namespace ItemSystem.GUI.Interfaces { public interface IView { public void RaiseActivated(); } }
14.571429
36
0.745098
[ "MIT" ]
PerfectlyFineCode/itemsystem
src/ItemSystem/ItemSystem.GUI/Interfaces/IView.cs
104
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; namespace Suchmasy.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), Name = table.Column<string>(maxLength: 256, nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), UserName = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), Email = table.Column<string>(maxLength: 256, nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), PasswordHash = table.Column<string>(nullable: true), SecurityStamp = table.Column<string>(nullable: true), ConcurrencyStamp = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), TwoFactorEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), LockoutEnabled = table.Column<bool>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), RoleId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), UserId = table.Column<string>(nullable: false), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(maxLength: 128, nullable: false), ProviderKey = table.Column<string>(maxLength: 128, nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(maxLength: 128, nullable: false), Name = table.Column<string>(maxLength: 128, nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); table.ForeignKey( name: "FK_AspNetUserTokens_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName", unique: true, filter: "[NormalizedName] IS NOT NULL"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName", unique: true, filter: "[NormalizedUserName] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
43.072398
122
0.498372
[ "MIT" ]
draganov89/Suchmasy
Suchmasy/Suchmasy/Data/Migrations/00000000000000_CreateIdentitySchema.cs
9,521
C#
using System; namespace ZeldaOracle.Common.Geometry { /// <summary>A static class for advanced game-related mathematical functions and /// calculations.</summary> public static partial class GMath { //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- /// <summary>Represents the ratio of the circumference of a circle to its /// diameter, specified by the constant, pi.</summary> public const float Pi = 3.14159265358979323846f; /// <summary>Represents the natural logarithmic base, specified by the /// constant, e.</summary> public const float E = 2.71828182845904523536f; /// <summary>Returns twice the value of pi.</summary> public const float TwoPi = Pi * 2f; /// <summary>Returns half the value of pi.</summary> public const float HalfPi = Pi * 0.5f; /// <summary>Returns a quarter of the value of pi.</summary> public const float QuarterPi = Pi * 0.25f; /// <summary>A full angle in radians.</summary> public const float FullAngle = TwoPi; /// <summary>Three quarters of a full angle in radians.</summary> public const float ThreeFourthsAngle = Pi + HalfPi; /// <summary>Half of a full angle in radians.</summary> public const float HalfAngle = Pi; /// <summary>Quarter of a full angle in radians.</summary> public const float QuarterAngle = HalfPi; /// <summary>Eighth of a full angle in radians.</summary> public const float EighthAngle = QuarterPi; } }
39.769231
81
0.635719
[ "MIT" ]
trigger-death/ZeldaOracle
ZeldaOracle/GameCommon/Common/Geometry/GMath.Constants.cs
1,553
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 health-2016-08-04.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AWSHealth.Model { /// <summary> /// Container for the parameters to the DescribeAffectedEntitiesForOrganization operation. /// Returns a list of entities that have been affected by one or more events for one or /// more accounts in your organization in AWS Organizations, based on the filter criteria. /// Entities can refer to individual customer resources, groups of customer resources, /// or any other construct, depending on the AWS service. /// /// /// <para> /// At least one event ARN and account ID are required. Results are sorted by the <code>lastUpdatedTime</code> /// of the entity, starting with the most recent. /// </para> /// /// <para> /// Before you can call this operation, you must first enable AWS Health to work with /// AWS Organizations. To do this, call the <a>EnableHealthServiceAccessForOrganization</a> /// operation from your organization's master account. /// </para> /// </summary> public partial class DescribeAffectedEntitiesForOrganizationRequest : AmazonAWSHealthRequest { private string _locale; private int? _maxResults; private string _nextToken; private List<EventAccountFilter> _organizationEntityFilters = new List<EventAccountFilter>(); /// <summary> /// Gets and sets the property Locale. /// <para> /// The locale (language) to return information in. English (en) is the default and the /// only supported value at this time. /// </para> /// </summary> [AWSProperty(Min=2, Max=256)] public string Locale { get { return this._locale; } set { this._locale = value; } } // Check to see if Locale property is set internal bool IsSetLocale() { return this._locale != null; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of items to return in one batch, between 10 and 100, inclusive. /// </para> /// </summary> [AWSProperty(Min=10, Max=100)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// If the results of a search are large, only a portion of the results are returned, /// and a <code>nextToken</code> pagination token is returned in the response. To retrieve /// the next batch of results, reissue the search request and include the returned token. /// When all results have been returned, the response does not contain a pagination token /// value. /// </para> /// </summary> [AWSProperty(Min=4, Max=10000)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property OrganizationEntityFilters. /// <para> /// A JSON set of elements including the <code>awsAccountId</code> and the <code>eventArn</code>. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=10)] public List<EventAccountFilter> OrganizationEntityFilters { get { return this._organizationEntityFilters; } set { this._organizationEntityFilters = value; } } // Check to see if OrganizationEntityFilters property is set internal bool IsSetOrganizationEntityFilters() { return this._organizationEntityFilters != null && this._organizationEntityFilters.Count > 0; } } }
36.5
114
0.62696
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/AWSHealth/Generated/Model/DescribeAffectedEntitiesForOrganizationRequest.cs
5,037
C#
using jQueryApi; using jQueryApi.UI.Widgets; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Serenity { [Editor, DisplayName("Date/Time")] [Element("<input type=\"text\"/>")] public class DateTimeEditor : Widget<DateTimeEditorOptions>, IStringValue, IReadOnly { static DateTimeEditor() { Q.Prop(typeof(DateTimeEditor), "value"); Q.Prop(typeof(DateTimeEditor), "valueAsDate"); } private jQueryObject time; public DateTimeEditor(jQueryObject input, DateTimeEditorOptions opt) : base(input, opt) { input.AddClass("dateQ s-DateTimeEditor") .DatePicker(new DatePickerOptions { ShowOn = "button", BeforeShow = new Func<bool>(delegate { return !input.HasClass("readonly"); }) }); input.Bind("keyup." + this.uniqueName, e => { if (e.Which == 32 && !ReadOnly) this.ValueAsDate = JsDate.Now; else DateEditor.DateInputKeyup(e); }); input.Bind("change." + this.uniqueName, DateEditor.DateInputChange); time = J("<select/>").AddClass("editor s-DateTimeEditor time"); var after = input.Next(".ui-datepicker-trigger"); if (after.Length > 0) time.InsertAfter(after); else { after = input.Prev(".ui-datepicker-trigger"); if (after.Length > 0) time.InsertBefore(after); else time.InsertAfter(input); } foreach (var t in GetTimeOptions(fromHour: options.StartHour ?? 0, toHour: options.EndHour ?? 23, stepMins: options.IntervalMinutes ?? 5)) Q.AddOption(time, t, t); input.AddValidationRule(this.uniqueName, e => { var value = this.Value; if (string.IsNullOrEmpty(value)) return null; if (!string.IsNullOrEmpty(MinValue) && String.Compare(value, MinValue) < 0) return String.Format(Q.Text("Validation.MinDate"), Q.FormatDate(MinValue)); if (!string.IsNullOrEmpty(MaxValue) && String.Compare(value, MaxValue) >= 0) return String.Format(Q.Text("Validation.MaxDate"), Q.FormatDate(MaxValue)); return null; }); SqlMinMax = true; J("<div class='inplace-button inplace-now'><b></b></div>") .Attribute("title", "set to now") .InsertAfter(time) .Click(e => { if (this.Element.HasClass("readonly")) return; this.ValueAsDate = JsDate.Now; }); } private static List<string> GetTimeOptions(int fromHour = 0, int fromMin = 0, int toHour = 23, int toMin = 59, int stepMins = 30) { var list = new List<string>(); if (toHour >= 23) toHour = 23; if (toMin >= 60) toMin = 59; var hour = fromHour; var min = fromMin; while (true) { if (hour > toHour || (hour == toHour && min > toMin)) break; var t = (hour >= 10 ? "" : "0") + hour + ":" + (min >= 10 ? "" : "0") + min; list.Add(t); min += stepMins; if (min >= 60) { min -= 60; hour++; } } return list; } public string Value { get { string value = this.element.GetValue().Trim(); if (value != null && value.Length == 0) return null; var datePart = Q.FormatDate(value, "yyyy-MM-dd"); var timePart = this.time.GetValue(); return datePart + "T" + timePart + ":00.000"; } set { if (string.IsNullOrEmpty(value)) { this.element.Value(""); this.time.Value("00:00"); } else if (value.ToLower() == "today") { this.element.Value(Q.FormatDate(JsDate.Today)); this.time.Value("00:00"); } else { var val = value.ToLower() == "now" ? JsDate.Now : (Q.Externals.ParseISODateTime(value)); val = RoundToMinutes(val, options.IntervalMinutes ?? 5); this.element.Value(Q.FormatDate(val)); this.time.Value(Q.FormatDate(val, "HH:mm")); } } } public static JsDate RoundToMinutes(JsDate date, int minutesStep) { date = new JsDate(date.GetTime()); var m = (int)(Math.Round((double)date.GetMinutes() / minutesStep) * minutesStep); date.SetMinutes(m); date.SetSeconds(0); date.SetMilliseconds(0); return date; } public JsDate ValueAsDate { get { if (string.IsNullOrEmpty(Value)) return null; return Q.ParseISODateTime(this.Value); } set { if (value == null) this.Value = null; this.Value = Q.FormatDate(value, "yyyy-MM-ddTHH:mm"); } } [Option] public string MinValue { get; set; } [Option] public string MaxValue { get; set; } public JsDate MinDate { get { return Q.ParseISODateTime(MinValue); } set { MinValue = Q.FormatDate(value, "yyyy-MM-ddTHH:mm:ss"); } } public JsDate MaxDate { get { return Q.ParseISODateTime(MaxValue); } set { MaxValue = Q.FormatDate(value, "yyyy-MM-ddTHH:mm:ss"); } } [Option] public bool SqlMinMax { get { return MinValue == "1753-01-01" && MaxValue == "9999-12-31"; } set { if (value) { MinValue = "1753-01-01"; MaxValue = "9999-12-31"; } else { MinValue = null; MaxValue = null; } } } public bool ReadOnly { get { return this.element.HasClass("readonly"); } set { if (value != ReadOnly) { if (value) { this.element.AddClass("readonly").Attribute("readonly", "readonly"); this.element.NextAll(".ui-datepicker-trigger").CSS("opacity", "0.1"); } else { this.element.RemoveClass("readonly").RemoveAttr("readonly"); this.element.NextAll(".ui-datepicker-trigger").CSS("opacity", "1"); } EditorUtils.SetReadOnly(time, value); } } } } [Imported, Serializable] public class DateTimeEditorOptions { public int? StartHour { get; set; } public int? EndHour { get; set; } public int? IntervalMinutes { get; set; } } }
31.56391
109
0.418294
[ "MIT" ]
dfaruque/Serenity
Serenity.Script.UI/Editor/DateTimeEditor.cs
8,398
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using essentialMix.Extensions; using Other.Microsoft.MultiLanguage; using JetBrains.Annotations; namespace essentialMix.Helpers { public static class EncodingHelper { static EncodingHelper() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); EncodingInfo[] encodings = Encoding.GetEncodings(); SystemEncodingCount = encodings.Length; IList<EncodingInfo> streamEncodings = new List<EncodingInfo>(); IList<EncodingInfo> mimeEncodings = new List<EncodingInfo>(); IList<EncodingInfo> allEncodings = new List<EncodingInfo>(); // ASCII - most simple so put it in first place... EncodingInfo encodingInfo = Encoding.ASCII.EncodingInfo(); streamEncodings.Add(encodingInfo); mimeEncodings.Add(encodingInfo); allEncodings.Add(encodingInfo); // add default 2nd for all encodings encodingInfo = Default.EncodingInfo(); allEncodings.Add(encodingInfo); // default is single byte? if (Default.IsSingleByte) { // put it in second place streamEncodings.Add(encodingInfo); mimeEncodings.Add(encodingInfo); } // prefer JIS over JIS-SHIFT (JIS is detected better than JIS-SHIFT) // this one does include Cyrillic (strange but true) encodingInfo = Encoding.GetEncoding(50220).EncodingInfo(); allEncodings.Add(encodingInfo); mimeEncodings.Add(encodingInfo); // always allow Unicode flavors for streams (they all have a preamble) streamEncodings.Add(Encoding.Unicode.EncodingInfo()); foreach (EncodingInfo enc in encodings) { if (streamEncodings.Contains(enc)) continue; Encoding encoding = Encoding.GetEncoding(enc.CodePage); if (encoding.GetPreamble().Length == 0) continue; streamEncodings.Add(enc); } PreferredStreamEncodings = streamEncodings.ToArray(); PreferredStreamEncodingCodePages = streamEncodings.Select(e => e.CodePage).ToArray(); // all single byte encodings foreach (EncodingInfo enc in encodings) { if (!enc.GetEncoding().IsSingleByte || allEncodings.Contains(enc)) continue; allEncodings.Add(enc); // only add ISO and IBM encodings to mime encodings if (enc.CodePage > 1258) continue; mimeEncodings.Add(enc); } // add the rest (multi-byte) foreach (EncodingInfo enc in encodings) { if (enc.GetEncoding().IsSingleByte || allEncodings.Contains(enc)) continue; allEncodings.Add(enc); // only add ISO and IBM encodings to mime encodings if (enc.CodePage > 1258) continue; mimeEncodings.Add(enc); } // add Unicode mimeEncodings.Add(Encoding.Unicode.EncodingInfo()); // this contains all code pages, sorted by preference and byte usage PreferredMimeEncodings = mimeEncodings.ToArray(); PreferredMimeEncodingCodePages = mimeEncodings.Select(e => e.CodePage).ToArray(); // this contains all code pages, sorted by preference and byte usage Encodings = allEncodings.ToArray(); EncodingCodePages = allEncodings.Select(e => e.CodePage).ToArray(); } [NotNull] public static Encoding Default => Encoding.Default; public static EncodingInfo[] Encodings { get; } public static int[] EncodingCodePages { get; } public static EncodingInfo[] PreferredMimeEncodings { get; } public static int[] PreferredMimeEncodingCodePages { get; } public static EncodingInfo[] PreferredEncodings => PreferredMimeEncodings; public static int[] PreferredEncodingCodePages => PreferredMimeEncodingCodePages; public static EncodingInfo[] PreferredStreamEncodings { get; } public static int[] PreferredStreamEncodingCodePages { get; } public static int SystemEncodingCount { get; } [NotNull] public static Encoding GetEncoding(string input) { return FindEncoding(input, EncodingCodePages); } [NotNull] public static Encoding GetEncoding(string input, bool preserveOrder) { return FindEncoding(input, EncodingCodePages, preserveOrder); } [NotNull] public static Encoding GetEncoding(char[] input) { return input.IsNullOrEmpty() ? Default : FindEncoding(new string(input), EncodingCodePages); } public static Encoding GetEncoding(byte[] input) { try { Encoding[] detected = GetEncodings(input, 1); return detected.Length > 0 ? detected[0] : Default; } catch (COMException) { // return default code page on error return Default; } } [NotNull] public static Encoding[] GetEncodings(string input) { return FindEncodings(input, EncodingCodePages, true); } [NotNull] public static Encoding[] GetEncodings(string input, bool preserveOrder) { return FindEncodings(input, EncodingCodePages, preserveOrder); } [NotNull] public static Encoding[] GetEncodings(byte[] input, int maxEncodings) { if (input.IsNullOrEmpty()) { return new[] { Default }; } if (maxEncodings < 1) maxEncodings = 1; // expand the string to be at least 256 bytes if (input.Length < 256) { byte[] newInput = new byte[256]; int steps = 256 / input.Length; for (int i = 0; i < steps; i++) Buffer.BlockCopy(input, 0, newInput, input.Length * i, input.Length); int rest = 256 % input.Length; if (rest > 0) Buffer.BlockCopy(input, 0, newInput, steps * input.Length, rest); input = newInput; } List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage" interface IMultiLanguage2 multiLang2 = new CMultiLanguageClass(); if (multiLang2 == null) throw new COMException("Failed to get " + nameof(IMultiLanguage2)); try { DetectEncodingInfo[] detectedEncodings = new DetectEncodingInfo[maxEncodings]; int scores = detectedEncodings.Length; int srcLen = input.Length; // finally... call to DetectInputCodepage multiLang2.DetectInputCodepage(MLDETECTCP.MLDETECTCP_NONE, 0, ref input[0], ref srcLen, ref detectedEncodings[0], ref scores); // get result if (scores > 0) { for (int i = 0; i < scores; i++) result.Add(Encoding.GetEncoding((int)detectedEncodings[i].nCodePage)); } } finally { Marshal.FinalReleaseComObject(multiLang2); } return result.ToArray(); } [NotNull] public static Encoding GetPreferredEncoding(string input) { return FindEncoding(input, PreferredEncodingCodePages); } [NotNull] public static Encoding GetPreferredEncoding(string input, bool preserveOrder) { return FindEncoding(input, PreferredEncodingCodePages, preserveOrder); } [NotNull] public static Encoding[] GetPreferredEncodings(string input) { return FindEncodings(input, PreferredEncodingCodePages, true); } [NotNull] public static Encoding[] GetPreferredEncodings(string input, bool preserveOrder) { return FindEncodings(input, PreferredEncodingCodePages, preserveOrder); } [NotNull] public static Encoding GetPreferredStreamEncoding(string input) { return FindEncoding(input, PreferredStreamEncodingCodePages); } [NotNull] public static Encoding GetPreferredStreamEncoding(string input, bool preserveOrder) { return FindEncoding(input, PreferredStreamEncodingCodePages, preserveOrder); } [NotNull] public static Encoding[] GetPreferredStreamEncodings(string input) { return FindEncodings(input, PreferredStreamEncodingCodePages, true); } [NotNull] public static Encoding[] GetPreferredStreamEncodings(string input, bool preserveOrder) { return FindEncodings(input, PreferredStreamEncodingCodePages, preserveOrder); } [NotNull] private static Encoding FindEncoding(string input, int[] preferredEncodings) { Encoding enc = FindEncoding(input, preferredEncodings, true); if (enc.CodePage != Encoding.Unicode.CodePage) return enc; // Unicode.. hmmm... check for smallest encoding int byteCount = Encoding.UTF7.GetByteCount(input); int bestByteCount = byteCount; enc = Encoding.UTF7; // utf8 smaller? byteCount = Encoding.UTF8.GetByteCount(input); if (byteCount < bestByteCount) { enc = Encoding.UTF8; bestByteCount = byteCount; } // Unicode smaller? byteCount = Encoding.Unicode.GetByteCount(input); if (byteCount < bestByteCount) enc = Encoding.Unicode; return enc; } [NotNull] private static Encoding FindEncoding(string input, int[] preferredEncodings, bool preserveOrder) { // empty strings can always be encoded as ASCII if (string.IsNullOrEmpty(input)) return Default; bool bPrefEnc = !preferredEncodings.IsNullOrEmpty(); Encoding result = Default; // get the IMultiLanguage3 interface IMultiLanguage3 multiLang3 = new CMultiLanguageClass(); if (multiLang3 == null) throw new COMException("Failed to get " + nameof(IMultiLanguage3)); try { int count = bPrefEnc ? preferredEncodings.Length : SystemEncodingCount; int[] resultCodePages = new int[count]; uint detectedCodePages = (uint)resultCodePages.Length; ushort specialChar = '?'; // get unmanaged arrays IntPtr preferred = bPrefEnc ? Marshal.AllocCoTaskMem(sizeof(uint) * preferredEncodings.Length) : IntPtr.Zero; IntPtr detected = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (bPrefEnc) Marshal.Copy(preferredEncodings, 0, preferred, preferredEncodings.Length); Marshal.Copy(resultCodePages, 0, detected, resultCodePages.Length); MLCPF options = MLCPF.MLDETECTF_VALID_NLS; if (preserveOrder) options |= MLCPF.MLDETECTF_PRESERVE_ORDER; if (bPrefEnc) options |= MLCPF.MLDETECTF_PREFERRED_ONLY; multiLang3.DetectOutboundCodePage(options, input, (uint)input.Length, preferred, (uint)(bPrefEnc ? preferredEncodings.Length : 0), detected, ref detectedCodePages, ref specialChar); // get result if (detectedCodePages > 0) { int[] theResult = new int[detectedCodePages]; Marshal.Copy(detected, theResult, 0, theResult.Length); result = Encoding.GetEncoding(theResult[0]); } } finally { if (!preferred.IsZero()) Marshal.FreeCoTaskMem(preferred); Marshal.FreeCoTaskMem(detected); } } finally { Marshal.FinalReleaseComObject(multiLang3); } return result; } [NotNull] private static Encoding[] FindEncodings(string input, int[] preferredEncodings, bool preserveOrder) { // empty strings can always be encoded as ASCII if (string.IsNullOrEmpty(input)) { return new[] { Default }; } bool bPrefEnc = !preferredEncodings.IsNullOrEmpty(); List<Encoding> result = new List<Encoding>(); // get the IMultiLanguage3 interface IMultiLanguage3 multiLang3 = new CMultiLanguageClass(); if (multiLang3 == null) throw new COMException("Failed to get " + nameof(IMultiLanguage3)); try { int count = bPrefEnc ? preferredEncodings.Length : SystemEncodingCount; int[] resultCodePages = new int[count]; uint detectedCodePages = (uint)resultCodePages.Length; ushort specialChar = '?'; // get unmanaged arrays IntPtr preferred = bPrefEnc ? Marshal.AllocCoTaskMem(sizeof(uint) * preferredEncodings.Length) : IntPtr.Zero; IntPtr detected = Marshal.AllocCoTaskMem(sizeof(uint) * resultCodePages.Length); try { if (bPrefEnc) Marshal.Copy(preferredEncodings, 0, preferred, preferredEncodings.Length); Marshal.Copy(resultCodePages, 0, detected, resultCodePages.Length); MLCPF options = MLCPF.MLDETECTF_VALID_NLS; if (preserveOrder) options |= MLCPF.MLDETECTF_PRESERVE_ORDER; if (bPrefEnc) options |= MLCPF.MLDETECTF_PREFERRED_ONLY; // finally... call to DetectOutboundCodePage multiLang3.DetectOutboundCodePage(options, input, (uint)input.Length, preferred, (uint)(bPrefEnc ? preferredEncodings.Length : 0), detected, ref detectedCodePages, ref specialChar); // get result if (detectedCodePages > 0) { int[] theResult = new int[detectedCodePages]; Marshal.Copy(detected, theResult, 0, theResult.Length); // get the encodings for the code pages for (int i = 0; i < detectedCodePages; i++) result.Add(Encoding.GetEncoding(theResult[i])); } } finally { if (!preferred.IsZero()) Marshal.FreeCoTaskMem(preferred); Marshal.FreeCoTaskMem(detected); } } finally { Marshal.FinalReleaseComObject(multiLang3); } return result.ToArray(); } } }
31.562025
170
0.713564
[ "MIT" ]
asm2025/asm
Standard/essentialMix/Helpers/EncodingHelper.cs
12,469
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace EntityFramework.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Articles", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(type: "nvarchar(max)", nullable: true), Body = table.Column<string>(type: "nvarchar(max)", nullable: true), DateTime = table.Column<DateTime>(type: "datetime2", nullable: false), Link = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedDate = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedDate = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Articles", x => x.Id); }); migrationBuilder.CreateTable( name: "ParsersConfigs", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), SiteLink = table.Column<string>(type: "nvarchar(max)", nullable: true), XPathArticles = table.Column<string>(type: "nvarchar(max)", nullable: true), XPathLinkArticle = table.Column<string>(type: "nvarchar(max)", nullable: true), XPathTitle = table.Column<string>(type: "nvarchar(max)", nullable: true), XPathBody = table.Column<string>(type: "nvarchar(max)", nullable: true), XPathDateTime = table.Column<string>(type: "nvarchar(max)", nullable: true), DateTimeFormat = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedDate = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedDate = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_ParsersConfigs", x => x.Id); }); migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Login = table.Column<string>(type: "nvarchar(max)", nullable: true), FirstName = table.Column<string>(type: "nvarchar(max)", nullable: true), LastName = table.Column<string>(type: "nvarchar(max)", nullable: true), PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedDate = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedDate = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "Tokens", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), UserId = table.Column<int>(type: "int", nullable: false), RefreshToken = table.Column<string>(type: "nvarchar(max)", nullable: true), ExpiryDate = table.Column<DateTime>(type: "datetime2", nullable: false), RemoteIpAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), UserAgent = table.Column<string>(type: "nvarchar(max)", nullable: true), Used = table.Column<bool>(type: "bit", nullable: false), CreatedDate = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedDate = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Tokens", x => x.Id); table.ForeignKey( name: "FK_Tokens_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "ParsersConfigs", columns: new[] { "Id", "CreatedDate", "DateTimeFormat", "SiteLink", "UpdatedDate", "XPathArticles", "XPathBody", "XPathDateTime", "XPathLinkArticle", "XPathTitle" }, values: new object[] { 1, new DateTime(2021, 5, 17, 4, 55, 14, 776, DateTimeKind.Local).AddTicks(2904), "dd M yyyy, HH:mm", "https://tengrinews.kz", null, "//div[@class='tn-main-news-item']", "//div[@class='tn-news-content']", "//h1[@class='tn-content-title']//span[@class='tn-hidden']", "//a[@class='tn-link']", "//h1[@class='tn-content-title']" }); migrationBuilder.InsertData( table: "ParsersConfigs", columns: new[] { "Id", "CreatedDate", "DateTimeFormat", "SiteLink", "UpdatedDate", "XPathArticles", "XPathBody", "XPathDateTime", "XPathLinkArticle", "XPathTitle" }, values: new object[] { 2, new DateTime(2021, 5, 17, 4, 55, 14, 776, DateTimeKind.Local).AddTicks(3336), "HH:mm, dd.MM.yyyy", "https://24.kz/ru/", null, "//div[@class='nspArt']", "//div[@class='itemBody']", "//ul//li[@class='itemDate']//time", "//a[@class='nspImageWrapper tleft fnull']", "//article[@class='view-article itemView']//div[@class='itemheader']//header//h1" }); migrationBuilder.InsertData( table: "Users", columns: new[] { "Id", "CreatedDate", "FirstName", "LastName", "Login", "PasswordHash", "UpdatedDate" }, values: new object[] { 1, new DateTime(2021, 5, 17, 4, 55, 14, 774, DateTimeKind.Local).AddTicks(8344), "Jon", "Snow", "jon", "AQAAAAEAACcQAAAAEKOPbIyZyjFf6xY8FWjzMTOxW66msNg49k/41Z+z6TweZ6Ekl1Bn69HuEjKv1UWYgw==", null }); migrationBuilder.CreateIndex( name: "IX_Tokens_UserId", table: "Tokens", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Articles"); migrationBuilder.DropTable( name: "ParsersConfigs"); migrationBuilder.DropTable( name: "Tokens"); migrationBuilder.DropTable( name: "Users"); } } }
55.6
389
0.529884
[ "MIT" ]
temir-kussainov/ArticleParser
EntityFramework/Migrations/20210516225515_Initial.cs
7,230
C#
using System; using System.Linq; using NUnit.Framework; using EventStore.Core.Data; using EventStore.Projections.Core.Services.Management; using EventStore.Common.Options; using EventStore.Core.Bus; using EventStore.Core.Messages; using EventStore.Core.TransactionLog.LogRecords; using EventStore.Projections.Core.Messages; using EventStore.Core.Tests.Fakes; using EventStore.Core.Tests.Services.Replication; using System.Collections.Generic; namespace EventStore.Projections.Core.Tests.Services.core_coordinator { [TestFixture] public class when_stopping_with_projection_type_all { private FakePublisher[] queues; private FakePublisher publisher; private ProjectionCoreCoordinator _coordinator; private TimeoutScheduler[] timeoutScheduler = {}; private FakeEnvelope envelope = new FakeEnvelope(); [SetUp] public void Setup() { queues = new List<FakePublisher>(){new FakePublisher()}.ToArray(); publisher = new FakePublisher(); _coordinator = new ProjectionCoreCoordinator(ProjectionType.All,timeoutScheduler,queues,publisher,envelope); _coordinator.Handle(new SystemMessage.BecomeMaster(Guid.NewGuid())); _coordinator.Handle(new SystemMessage.SystemCoreReady()); _coordinator.Handle(new SystemMessage.EpochWritten(new EpochRecord(0,0,Guid.NewGuid(),0,DateTime.Now))); //force stop _coordinator.Handle(new SystemMessage.BecomeUnknown(Guid.NewGuid())); } [Test] public void should_publish_stop_reader_messages() { Assert.AreEqual(1,queues[0].Messages.FindAll(x => x is ReaderCoreServiceMessage.StopReader).Count); } [Test] public void should_publish_stop_core_messages() { Assert.AreEqual(1,queues[0].Messages.FindAll(x => x.GetType() == typeof(ProjectionCoreServiceMessage.StopCore)).Count); } } }
37.169811
128
0.708122
[ "Apache-2.0", "CC0-1.0" ]
cuteant/EventStore-DotNetty-Fork
src/EventStore.Projections.Core.Tests/Services/core_coordinator/when_stopping_with_projection_type_all.cs
1,972
C#
// Copyright 2019 Florian Gather <florian.gather@tngtech.com> // Copyright 2019 Paula Ruiz <paularuiz22@gmail.com> // Copyright 2019 Fritz Brandhuber <fritz.brandhuber@tngtech.com> // // SPDX-License-Identifier: Apache-2.0 using System; using System.Collections; using System.Collections.Generic; using ArchUnitNET.Domain; using ArchUnitNET.Domain.Extensions; using ArchUnitNETTests.Fluent.Extensions; namespace ArchUnitNETTests.Domain.Dependencies.Attributes { public static class AttributeTestsBuild { private static readonly Architecture Architecture = StaticTestArchitectures.AttributeDependencyTestArchitecture; private static object[] BuildTypeAttributeTestData(Type classType, Type attributeType) { var targetClass = Architecture.GetITypeOfType(classType); var attributeClass = Architecture.GetClassOfType(attributeType); var attribute = targetClass.GetAttributeOfType(attributeClass); return new object[] {targetClass, attributeClass, attribute}; } private static object[] BuildMemberAttributeTestData(Type classType, string memberName, Type attributeType) { if (classType == null) { throw new ArgumentNullException(nameof(classType)); } if (memberName == null) { throw new ArgumentNullException(nameof(memberName)); } if (attributeType == null) { throw new ArgumentNullException(nameof(attributeType)); } var targetClass = Architecture.GetClassOfType(classType); var targetMember = targetClass.Members[memberName]; targetMember.RequiredNotNull(); var attributeClass = Architecture.GetClassOfType(attributeType); var attribute = targetMember.GetAttributeFromMember(attributeClass); attribute.RequiredNotNull(); return new object[] {targetMember, attributeClass, attribute}; } public class TypeAttributesAreFoundData : IEnumerable<object[]> { private readonly List<object[]> _typeAttributeData = new List<object[]> { BuildTypeAttributeTestData(typeof(ClassWithExampleAttribute), typeof(ExampleClassAttribute)), BuildTypeAttributeTestData(typeof(DelegateWithAttribute), typeof(ExampleDelegateAttribute)), BuildTypeAttributeTestData(typeof(EnumWithAttribute), typeof(ExampleEnumAttribute)), BuildTypeAttributeTestData(typeof(IInterfaceWithExampleAttribute), typeof(ExampleInterfaceAttribute)), BuildTypeAttributeTestData(typeof(StructWithAttribute), typeof(ExampleStructAttribute)) }; public IEnumerator<object[]> GetEnumerator() { return _typeAttributeData.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class MemberAttributesAreFoundData : IEnumerable<object[]> { private readonly List<object[]> _memberAttributeData = new List<object[]> { BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.FieldA), typeof(ExampleFieldAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.MethodWithAttribute).BuildMethodMemberName(), typeof(ExampleMethodAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.MethodWithParameterAttribute) .BuildMethodMemberName(typeof(string)), typeof(ExampleParameterAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.PropertyA), typeof(ExamplePropertyAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.MethodWithReturnAttribute).BuildMethodMemberName(), typeof(ExampleReturnAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.set_ParameterProperty).BuildMethodMemberName(typeof(string)), typeof(ExampleParameterAttribute)), BuildMemberAttributeTestData(typeof(ClassWithExampleAttribute), nameof(ClassWithExampleAttribute.FieldWithAbstractAttributeImplemented), typeof(ChildOfAbstractAttribute)) }; public IEnumerator<object[]> GetEnumerator() { return _memberAttributeData.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
44.034188
120
0.654503
[ "Apache-2.0" ]
DialLuesebrink/ArchUnitNET
ArchUnitNETTests/Domain/Dependencies/Attributes/AttributeTestsBuild.cs
5,152
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Common { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; /*============================================================ ** ** Class: ReadOnlyDictionary<TKey, TValue> ** ** <OWNER>gpaperin</OWNER> ** ** Purpose: Read-only wrapper for another generic dictionary. ** ===========================================================*/ #if !WINDOWS_UWP [Serializable] #endif [DebuggerDisplay("Count = {Count}")] public sealed class ReadOnlyDictionary45<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary //, IReadOnlyDictionary<TKey, TValue> { readonly IDictionary<TKey, TValue> m_dictionary; #if !WINDOWS_UWP [NonSerialized] #endif Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif KeyCollection m_keys; #if !WINDOWS_UWP [NonSerialized] #endif ValueCollection m_values; #if !WINDOWS_UWP [NonSerialized] #endif IReadOnlyIndicator m_readOnlyIndicator; public ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary) : this(dictionary, new AlwaysReadOnlyIndicator()) { } internal ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary, IReadOnlyIndicator readOnlyIndicator) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } Contract.EndContractBlock(); m_dictionary = dictionary; m_readOnlyIndicator = readOnlyIndicator; } protected IDictionary<TKey, TValue> Dictionary { get { return m_dictionary; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys, this.m_readOnlyIndicator); } return m_keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values, this.m_readOnlyIndicator); } return m_values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return m_dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return m_dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return m_dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(key, value); } bool IDictionary<TKey, TValue>.Remove(TKey key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(key); } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return m_dictionary[key]; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[key] = value; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return m_dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return m_dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { m_dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(item); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(item); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } return key is TKey; } void IDictionary.Add(object key, object value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add((TKey)key, (TValue)value); } void IDictionary.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = m_dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(m_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Remove((TKey)key); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[(TKey)key] = (TValue)value; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { Fx.Exception.ArgumentNull("array"); } if (array.Rank != 1 || array.GetLowerBound(0) != 0) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } if (index < 0 || index > array.Length) { throw Fx.Exception.ArgumentOutOfRange("index", index, Resources.ValueMustBeNonNegative); } if (array.Length - index < Count) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { m_dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in m_dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } try { foreach (var item in m_dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_dictionary as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #if !WINDOWS_UWP [Serializable] #endif private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { m_dictionary = dictionary; m_enumerator = m_dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); } } public object Key { get { return m_enumerator.Current.Key; } } public object Value { get { return m_enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return m_enumerator.MoveNext(); } public void Reset() { m_enumerator.Reset(); } } #endregion [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP [Serializable] #endif public sealed class KeyCollection : ICollection<TKey>, ICollection { private readonly ICollection<TKey> m_collection; #if !WINDOWS_UWP [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal KeyCollection(ICollection<TKey> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TKey>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TKey>.Contains(TKey item) { return m_collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion } [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP [Serializable] #endif public sealed class ValueCollection : ICollection<TValue>, ICollection { private readonly ICollection<TValue> m_collection; #if !WINDOWS_UWP [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal ValueCollection(ICollection<TValue> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TValue>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TValue>.Contains(TValue item) { return m_collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion ICollection Members } class AlwaysReadOnlyIndicator : IReadOnlyIndicator { public bool IsReadOnly { get { return true; } } } } internal interface IReadOnlyIndicator { bool IsReadOnly { get; } } }
27.998674
137
0.489839
[ "MIT" ]
17zhangw/azure-iot-sdks
csharp/service/Microsoft.Azure.Devices/Common/ReadOnlyDictionary45.cs
21,111
C#
using System.Web.Mvc; namespace BrockAllen.MembershipReboot.Mvc.Areas.UserAccount { public class UserAccountAreaRegistration : AreaRegistration { public override string AreaName { get { return "UserAccount"; } } public override void RegisterArea(AreaRegistrationContext context) { //context.MapRoute("oauth2", // BrockAllen.OAuth2.OAuth2Client.OAuthCallbackUrl, // new { controller = "LinkedAccount", action = "OAuthCallback" }); context.MapRoute( "UserAccount_default", "UserAccount/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } } }
26.866667
82
0.548387
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AstrixAstrix/automatic-adventurePRo
ANDP.ProvisionCenter.Mvc/Areas/UserAccount/UserAccountAreaRegistration.cs
808
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("06.SortTextFile")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.SortTextFile")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("46c2e653-2772-4c82-afcc-090c91d73b75")] // 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")]
37.918919
84
0.744833
[ "MIT" ]
Steffkn/TelerikAcademy
Programming/02. CSharp Part 2/07.Text-Files/06.SortTextFile/Properties/AssemblyInfo.cs
1,406
C#
using System.Collections.Generic; namespace rbkApiModules.Diagnostics.Core { public class FilterOptionListData { public FilterOptionListData() { Versions = new List<string>(); Areas = new List<string>(); Layers = new List<string>(); Domains = new List<string>(); Users = new List<string>(); Browsers = new List<string>(); Agents = new List<string>(); Devices = new List<string>(); OperatinSystems = new List<string>(); Messages = new List<string>(); Sources = new List<string>(); } public List<string> Versions { get; set; } public List<string> Areas { get; set; } public List<string> Layers { get; set; } public List<string> Domains { get; set; } public List<string> Users { get; set; } public List<string> Browsers { get; set; } public List<string> Agents { get; set; } public List<string> Devices { get; set; } public List<string> OperatinSystems { get; set; } public List<string> Messages { get; set; } public List<string> Sources { get; set; } } }
35.647059
57
0.554455
[ "MIT" ]
rbasniak/rbk-api-modules
rbkApiModules.Diagnostics.Core/Models/FilterOptionListData.cs
1,214
C#
using System; namespace SuperheroesUniverse.Data.Repositories.Contracts { public interface IUnitOfWork : IDisposable { void Commit(); } }
16
57
0.69375
[ "MIT" ]
pavelhristov/CSharpDatabases
Exam-8Nov2016/01. Code-first/SuperheroesUniverse/SuperheroesUniverse.Data/Repositories/Contracts/IUnitOfWork.cs
162
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Xml.XPath; using System.Text.RegularExpressions; namespace DigitalPlatform.Marc { /// <summary> /// MARC 基本节点 /// </summary> public class MarcNode { /// <summary> /// 父节点 /// </summary> public MarcNode Parent = null; /// <summary> /// 节点类型 /// </summary> public NodeType NodeType = NodeType.None; /// <summary> /// 子节点集合 /// </summary> public ChildNodeList ChildNodes = new ChildNodeList(); #region 构造函数 /// <summary> /// 初始化一个 MarcNode 对象 /// </summary> public MarcNode() { this.Parent = null; this.ChildNodes.owner = this; } /// <summary> /// 初始化一个 MarcNode对象,并设置好其 Parent 成员 /// </summary> /// <param name="parent">上级 MarcNode 对象</param> public MarcNode(MarcNode parent) { this.Parent = parent; this.ChildNodes.owner = this; } #endregion // Name internal string m_strName = ""; /// <summary> /// 节点的名字 /// </summary> public virtual string Name { get { return this.m_strName; } set { this.m_strName = value; } } // Indicator internal string m_strIndicator = ""; /// <summary> /// 节点的指示符 /// </summary> public virtual string Indicator { get { return this.m_strIndicator; } set { this.m_strIndicator = value; } } /// <summary> /// 指示符的第一个字符 /// </summary> public virtual char Indicator1 { get { if (string.IsNullOrEmpty(m_strIndicator) == true) return (char)0; return this.m_strIndicator[0]; } set { // 没有动作。需要派生类实现 } } /// <summary> /// 指示符的第二个字符 /// </summary> public virtual char Indicator2 { get { if (string.IsNullOrEmpty(m_strIndicator) == true) return (char)0; if (m_strIndicator.Length < 2) return (char)0; return this.m_strIndicator[1]; } set { // 没有动作。需要派生类实现 } } // Content // 这个是缺省的实现方式,可以直接用于没有下级的纯内容节点 internal string m_strContent = ""; /// <summary> /// 节点的正文内容 /// </summary> public virtual string Content { get { return this.m_strContent; } set { this.m_strContent = value; } } // Text 用于构造MARC机内格式字符串的表示当前节点部分的字符串 // /// <summary> /// 节点的全部文字,MARC 机内格式表现形态 /// </summary> public virtual string Text { get { return this.Name + this.Indicator + this.Content; } set { this.Content = value; // 这是个草率的实现,需要具体节点重载本函数 } } /// <summary> /// 创建一个新的节点对象,从当前对象复制出全部内容 /// </summary> /// <returns>新的节点对象</returns> public virtual MarcNode clone() { throw new Exception("not implemented"); } // 看一个字段名是否是控制字段。所谓控制字段没有指示符概念 // parameters: // strFieldName 字段名 // return: // true 是控制字段 // false 不是控制字段 /// <summary> /// 检测一个字段名是否为控制字段(的字段名) /// </summary> /// <param name="strFieldName">要检测的字段名</param> /// <returns>true表示是控制字段,false表示不是控制字段</returns> public static bool isControlFieldName(string strFieldName) { if (String.Compare(strFieldName, "hdr", true) == 0) return true; if (String.Compare(strFieldName, "###", true) == 0) return true; if ( ( String.Compare(strFieldName, "001") >= 0 && String.Compare(strFieldName, "009") <= 0 ) || String.Compare(strFieldName, "-01") == 0 ) return true; return false; } /// <summary> /// 输出当前对象的全部子对象的调试用字符串 /// </summary> /// <returns>表示内容的字符串</returns> public virtual string dumpChildren() { StringBuilder strResult = new StringBuilder(4096); for (int i = 0; i < this.ChildNodes.count; i++) { MarcNode child = this.ChildNodes[i]; strResult.Append(child.dump()); } return strResult.ToString(); } /// <summary> /// 输出当前对象的调试用字符串 /// </summary> /// <returns>表示内容的字符串</returns> public virtual string dump() { // 一般实现 return this.Name + this.Indicator + dumpChildren(); } /// <summary> /// 获得根节点 /// </summary> /// <returns>根节点</returns> public MarcNode getRootNode() { MarcNode node = this; while (node.Parent != null) node = node.Parent; Debug.Assert(node.Parent == null, ""); return node; } // 根 /// <summary> /// 根节点 /// </summary> public MarcNode Root { get { MarcNode node = this; while (node.Parent != null) { node = node.Parent; } #if DEBUG if (node != this) { Debug.Assert(node.NodeType == Marc.NodeType.Record || node.NodeType == Marc.NodeType.None, ""); } #endif return node; } } // /// <summary> /// 获得表示当前对象的位置的路径。用于比较节点之间的位置关系 /// </summary> /// <returns>路径字符串</returns> public string getPath() { MarcNode parent = this.Parent; if (parent == null) return "0"; int index = parent.ChildNodes.indexOf(this); if (index == -1) throw new Exception("在父节点的 ChildNodes 中没有找到自己"); string strParentPath = this.Parent.getPath(); return strParentPath + "/" + index.ToString(); } // 内容是否为空? /// <summary> /// 检测节点内容是否为空 /// </summary> public bool isEmpty { get { if (string.IsNullOrEmpty(this.Content) == true) return true; return false; } } /// <summary> /// 将当前节点从父节点摘除。但依然保留对当前节点对下级的拥有关系 /// </summary> /// <returns>已经被摘除的当前节点</returns> public MarcNode detach() { MarcNode parent = this.Parent; if (parent == null) return this; // 自己是根节点,或者先前已经被摘除 int index = parent.ChildNodes.indexOf(this); if (index == -1) { throw new Exception("parent的ChildNodes中居然没有找到自己"); return this; } parent.ChildNodes.removeAt(index); this.Parent = null; return this; } /// <summary> /// 将指定节点插入到当前节点的前面兄弟位置 /// </summary> /// <param name="source">要插入的节点</param> /// <returns>当前节点</returns> public MarcNode before(MarcNode source) { MarcNode parent = this.Parent; // 自己是根节点,无法具有兄弟 if (parent == null) throw new Exception("无法在根节点同级插入新节点"); int index = parent.ChildNodes.indexOf(this); if (index == -1) { throw new Exception("parent的ChildNodes中居然没有找到自己"); } // 进行类型检查,同级只能插入相同类型的元素 if (this.NodeType != source.NodeType) throw new Exception("无法在节点同级插入不同类型的新节点。this.NodeTYpe=" + this.NodeType.ToString() + ", source.NodeType=" + source.NodeType.ToString()); source.detach(); parent.ChildNodes.insert(index, source); source.Parent = this.Parent; return this; } // 把source插入到this的后面。返回this /// <summary> /// 将指定节点插入到当前节点的后面兄弟位置 /// </summary> /// <param name="source">要插入的节点</param> /// <returns>当前节点</returns> public MarcNode after(MarcNode source) { MarcNode parent = this.Parent; // 自己是根节点,无法具有兄弟 if (parent == null) throw new Exception("无法在根节点同级插入新节点"); int index = parent.ChildNodes.indexOf(this); if (index == -1) { throw new Exception("parent的ChildNodes中居然没有找到自己"); } // 进行类型检查,同级只能插入相同类型的元素 if (this.NodeType != source.NodeType) throw new Exception("无法在节点同级插入不同类型的新节点。this.NodeTYpe=" + this.NodeType.ToString() + ", source.NodeType=" + source.NodeType.ToString()); source.detach(); parent.ChildNodes.insert(index + 1, source); source.Parent = this.Parent; return this; } // 把strText构造的新对象插入到this的后面。返回this /// <summary> /// 用指定的字符串构造出新的节点,插入到当前节点的后面兄弟位置 /// </summary> /// <param name="strText">用于构造新节点的字符串</param> /// <returns>当前节点</returns> public MarcNode after(string strText) { MarcNodeList targets = new MarcNodeList(this); targets.after(strText); return this; } // 把source插入到this的下级末尾位置。返回this /// <summary> /// 将指定节点追加到当前节点的子节点尾部 /// </summary> /// <param name="source">要追加的节点</param> /// <returns>当前节点</returns> public MarcNode append(MarcNode source) { source.detach(); this.ChildNodes.add(source); source.Parent = this; return this; } // 把strText构造的新对象插入到this的下级末尾位置。返回this /// <summary> /// 用指定的字符串构造出新的节点,追加到当前节点的子节点末尾 /// </summary> /// <param name="strText">用于构造新节点的字符串</param> /// <returns>当前节点</returns> public MarcNode append(string strText) { MarcNodeList targets = new MarcNodeList(this); targets.append(strText); return this; } // this 插入到 target 儿子的末尾 /// <summary> /// 将当前节点追加到指定(目标)节点的子节点末尾 /// </summary> /// <param name="target">目标节点</param> /// <returns>当前节点</returns> public MarcNode appendTo(MarcNode target) { this.detach(); target.ChildNodes.add(this); this.Parent = target; return this; } // 把source插入到this的下级开头位置。返回this /// <summary> /// 将指定的(源)节点插入到当前节点的子节点开头位置 /// </summary> /// <param name="source">源节点</param> /// <returns>当前节点</returns> public MarcNode prepend(MarcNode source) { source.detach(); this.ChildNodes.insert(0, source); source.Parent = this; return this; } // 把strText构造的新对象插入到this的下级开头位置。返回this /// <summary> /// 用指定的字符串构造出新节点,插入到当前节点的子节点开头 /// </summary> /// <param name="strText">用于构造新节点的字符串</param> /// <returns>当前节点</returns> public MarcNode prepend(string strText) { MarcNodeList targets = new MarcNodeList(this); targets.prepend(strText); return this; } // this 插入到 target 的儿子的第一个 /// <summary> /// 将当前节点插入到指定的(目标)节点的子节点的开头 /// </summary> /// <param name="target">目标节点</param> /// <returns>当前节点</returns> public MarcNode prependTo(MarcNode target) { this.detach(); target.ChildNodes.insert(0, this); this.Parent = target; return this; } #if NO public virtual MarcNavigator CreateNavigator() { return new MarcNavigator(this); } #endif /// <summary> /// 用 XPath 字符串选择节点 /// </summary> /// <param name="strXPath">XPath 字符串</param> /// <returns>被选中的节点集合</returns> public MarcNodeList select(string strXPath) { return select(strXPath, -1); } // 针对DOM树进行 XPath 筛选 // parameters: // nMaxCount 至多选择开头这么多个元素。-1表示不限制 /// <summary> /// 用 XPath 字符串选择节点 /// </summary> /// <param name="strXPath">XPath 字符串</param> /// <param name="nMaxCount">限制命中的最多节点数。-1表示不限制</param> /// <returns>被选中的节点集合</returns> public MarcNodeList select(string strXPath, int nMaxCount/* = -1*/) { MarcNodeList results = new MarcNodeList(); MarcNavigator nav = new MarcNavigator(this); // 出发点在当前对象 XPathNodeIterator ni = nav.Select(strXPath); while (ni.MoveNext() && (nMaxCount == -1 || results.count < nMaxCount)) { NaviItem item = ((MarcNavigator)ni.Current).Item; if (item.Type != NaviItemType.Element) { // if (bSkipNoneElement == false) throw new Exception("xpath '" + strXPath + "' 命中了非元素类型的节点,这是不允许的"); continue; } results.add(item.MarcNode); } return results; } /* public MarcNode SelectSingleNode(string strXpath) { MarcNavigator nav = new MarcNavigator(this); XPathNodeIterator ni = nav.Select(strXpath); ni.MoveNext(); return ((MarcNavigator)ni.Current).Item.MarcNode; } * */ #if NO public MarcNodeList SelectNodes(string strPath) { string strFirstPart = GetFirstPart(ref strPath); if (strFirstPart == "/") { /* if (this.Parent == null) return this.SelectNodes(strPath); * */ return GetRootNode().SelectNodes(strPath); } if (strFirstPart == "..") { return this.Parent.SelectNodes(strPath); } if (strFirstPart == ".") { return this.SelectNodes(strPath); } // tagname[@attrname=''] string strTagName = ""; string strCondition = ""; int nRet = strFirstPart.IndexOf("["); if (nRet == -1) strTagName = strFirstPart; else { strCondition = strFirstPart.Substring(nRet + 1); if (strCondition.Length > 0) { // 去掉末尾的']' if (strCondition[strCondition.Length - 1] == ']') strCondition.Substring(0, strCondition.Length - 1); } strTagName = strFirstPart.Substring(0, nRet); } MarcNodeList results = new MarcNodeList(null); for (int i = 0; i < this.ChildNodes.Count; i++) { MarcNode node = this.ChildNodes[i]; Debug.Assert(node.Parent != null, ""); if (strTagName == "*" || node.Name == strTagName) { if (results.Parent == null) results.Parent = node.Parent; results.Add(node); } } if (String.IsNullOrEmpty(strPath) == true) { // 到了path的末级。用strFirstPart筛选对象 return results; } return results.SelectNodes(strPath); } // 获得路径的第一部分 static string GetFirstPart(ref string strPath) { if (String.IsNullOrEmpty(strPath) == true) return ""; if (strPath[0] == '/') { strPath = strPath.Substring(1); return "/"; } string strResult = ""; int nRet = strPath.IndexOf("/"); if (nRet == -1) { strResult = strPath; strPath = ""; return strResult; } strResult = strPath.Substring(0, nRet); strPath = strPath.Substring(nRet + 1); return strResult; } #endif // 删除自己 // 但是this.Parent指针还是没有清除 /// <summary> /// 从父节点(的子节点集合中)将当前节点移走。注意,本操作并不修改当前节点的 Parent 成员,也就是说 Parent 成员依然指向父节点 /// </summary> /// <returns>当前节点</returns> public MarcNode remove() { if (this.Parent != null) { this.Parent.ChildNodes.remove(this); return this; } return null; // biaoshi zhaobudao , yejiu wucong shanchu } #region 访问各种位置 /// <summary> /// 当前节点的第一个子节点 /// </summary> public MarcNode FirstChild { get { if (this.ChildNodes.count == 0) return null; return this.ChildNodes[0]; } } /// <summary> /// 当前节点的最后一个子节点 /// </summary> public MarcNode LastChild { get { if (this.ChildNodes.count == 0) return null; return this.ChildNodes[this.ChildNodes.count - 1]; } } /// <summary> /// 当前节点的前一个兄弟节点 /// </summary> public MarcNode PrevSibling { get { MarcNode parent = this.Parent; // 自己是根节点,无法具有兄弟 if (parent == null) return null; int index = parent.ChildNodes.indexOf(this); if (index == -1) { throw new Exception("parent的ChildNodes中居然没有找到自己"); } if (index == 0) return null; return parent.ChildNodes[index - 1]; } } /// <summary> /// 当前节点的下一个兄弟节点 /// </summary> public MarcNode NextSibling { get { MarcNode parent = this.Parent; // 自己是根节点,无法具有兄弟 if (parent == null) return null; int index = parent.ChildNodes.indexOf(this); if (index == -1) { throw new Exception("parent的ChildNodes中居然没有找到自己"); } if (index >= parent.ChildNodes.count - 1) return null; return parent.ChildNodes[index + 1]; } } #endregion } /// <summary> /// 专用于存储下级节点的集合类 /// <para></para> /// </summary> /// <remarks> /// 继承 MarcNodeList 类而来,完善了 add() 方法,能自动把每个元素的 Parent 成员设置好 /// </remarks> public class ChildNodeList : MarcNodeList { internal MarcNode owner = null; // 追加 // 对node先要摘除 /// <summary> /// 在当前集合末尾追加一个节点元素 /// </summary> /// <param name="node">要追加的节点</param> public new void add(MarcNode node) { node.detach(); base.add(node); Debug.Assert(owner != null, ""); node.Parent = owner; } // 检查加入,不去摘除 node 原来的关系,也不自动修改 node.Parent internal void baseAdd(MarcNode node) { base.add(node); } // 追加 /// <summary> /// 在当前集合末尾追加若干节点元素 /// </summary> /// <param name="list">要追加的若干节点元素</param> public new void add(MarcNodeList list) { base.add(list); Debug.Assert(owner != null, ""); foreach (MarcNode node in list) { node.Parent = owner; } } /// <summary> /// 向当前集合中添加一个节点元素,按节点名字顺序决定加入的位置 /// </summary> /// <param name="node">要加入的节点</param> /// <param name="style">如何加入</param> /// <param name="comparer">用于比较大小的接口</param> public override void insertSequence(MarcNode node, InsertSequenceStyle style = InsertSequenceStyle.PreferHead, IComparer<MarcNode> comparer = null) { base.insertSequence(node, style, comparer); node.Parent = owner; } /// <summary> /// 清除当前集合,并把集合中的元素全部摘除 /// </summary> public new void clear() { clearAndDetach(); } // 清除集合,并把原先的每个元素的Parent清空。 // 主要用于ChildNodes摘除关系 internal void clearAndDetach() { foreach (MarcNode node in this) { node.Parent = null; } base.clear(); } } /// <summary> /// 节点类型 /// </summary> public enum NodeType { /// <summary> /// 尚未确定 /// </summary> None = 0, /// <summary> /// 记录 /// </summary> Record = 1, /// <summary> /// 字段 /// </summary> Field = 2, /// <summary> /// 子字段 /// </summary> Subfield = 3, } /// <summary> /// dump()方法的操作风格 /// </summary> [Flags] public enum DumpStyle { /// <summary> /// 无 /// </summary> None = 0, /// <summary> /// 包含行号 /// </summary> LineNumber = 0x01, } }
26.453475
151
0.454606
[ "Apache-2.0" ]
DigitalPlatform/dp2core
DigitalPlatform.MarcQuery/MarcNode.cs
25,639
C#
namespace BudgetToolsDAL.Models { public class Message { public int ErrorLevel { get; set; } public string MessageText { get; set; } } }
15.272727
47
0.60119
[ "MIT" ]
myokapis/BudgetTools
BudgetToolsDAL/Models/Message.cs
170
C#
using System; using System.Collections.Generic; using JetBrains.Annotations; using VkNet.Model.Attachments; using VkNet.Utils; namespace VkNet.Model.RequestParams { /// <summary> /// Параметры метода wall.addComment /// </summary> [Serializable] public class WallCreateCommentParams { /// <summary> /// Идентификатор пользователя или сообщества, на чьей стене находится запись, к /// которой необходимо добавить /// комментарий. Обратите внимание, идентификатор сообщества в параметре owner_id /// необходимо указывать со знаком "-" — /// например, owner_id=-1 соответствует идентификатору сообщества ВКонтакте API /// (club1) целое число, по умолчанию /// идентификатор текущего пользователя. /// </summary> public long? OwnerId { get; set; } /// <summary> /// Идентификатор записи на стене пользователя или сообщества. положительное число, /// обязательный параметр. /// </summary> public long PostId { get; set; } /// <summary> /// Идентификатор сообщества, от имени которого публикуется комментарий. По /// умолчанию: 0. /// </summary> public long FromGroup { get; set; } /// <summary> /// Текст комментария. Обязательный параметр, если не передан параметр attachments /// </summary> [CanBeNull] public string Message { get; set; } /// <summary> /// Идентификатор комментария, в ответ на который должен быть добавлен новый /// комментарий. целое число. /// </summary> public long? ReplyToComment { get; set; } /// <summary> /// Список объектов, приложенных к комментарию и разделённых символом ",". Поле /// attachments представляется в формате: /// &lt;type&gt;&lt;owner_id&gt;_&lt;media_id&gt;,&lt;type&gt;&lt;owner_id&gt;_&lt; /// media_id&gt; /// &lt;type&gt; — тип медиа-вложения: /// photo — фотография /// video — видеозапись /// audio — аудиозапись /// doc — документ /// &lt;owner_id&gt; — идентификатор владельца медиа-вложения /// &lt;media_id&gt; — идентификатор медиа-вложения. /// Например: /// photo100172_166443618,photo66748_265827614 /// Параметр является обязательным, если не задан параметр text. список строк, /// разделенных через запятую. /// </summary> [CanBeNull] public IEnumerable<MediaAttachment> Attachments { get; set; } /// <summary> /// Идентификатор стикера. положительное число. /// </summary> public long? StickerId { get; set; } /// <summary> /// Уникальный идентификатор, предназначенный для предотвращения повторной отправки /// одинакового комментария. . /// </summary> [CanBeNull] public string Guid { get; set; } /// <summary> /// Идентификатор капчи /// </summary> public long? CaptchaSid { get; set; } /// <summary> /// текст, который ввел пользователь /// </summary> [CanBeNull] public string CaptchaKey { get; set; } /// <summary> /// Привести к типу VkParameters. /// </summary> /// <param name="p"> Параметры. </param> /// <returns> </returns> [NotNull] public static VkParameters ToVkParameters([NotNull] WallCreateCommentParams p) { return new VkParameters { { "owner_id", p.OwnerId } , { "post_id", p.PostId } , { "from_group", p.FromGroup } , { "message", p.Message } , { "reply_to_comment", p.ReplyToComment } , { "attachments", p.Attachments } , { "sticker_id", p.StickerId } , { "guid", p.Guid } , { "captcha_sid", p.CaptchaSid } , { "captcha_key", p.CaptchaKey } }; } } }
29.700855
85
0.663309
[ "MIT" ]
Empty322/vk
VkNet/Model/RequestParams/Wall/WallCreateCommentParams.cs
4,582
C#
/** * The MIT License * Copyright (c) 2016 Population Register Centre (VRK) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using PTV.DataMapper.ConsoleApp.Models; using PTV.DataMapper.ConsoleApp.Services.Interfaces; using PTV.Domain.Model.Models.Interfaces; using PTV.Domain.Model.Models.Interfaces.OpenApi; using PTV.Domain.Model.Models.OpenApi; using PTV.Domain.Model.Models.OpenApi.V2; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using PTV.Domain.Model.Models.Interfaces.OpenApi.V2; namespace PTV.DataMapper.ConsoleApp.Services { public class DataMapper : IDataMapper { private IVmOpenApiOrganizationVersionBase organization; private IServiceProvider serviceProvider; private ILogger<DataMapper> logger; protected DataSource source; public DataMapper(IVmOpenApiOrganizationVersionBase organization, DataSource source, IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } this.organization = organization; this.source = source; this.serviceProvider = serviceProvider; this.logger = this.serviceProvider.GetService<ILoggerFactory>().CreateLogger<DataMapper>(); } public List<int> GetSourceServiceChannels() { var channels = new List<int>(); if (!string.IsNullOrEmpty(source.DebugChannels)) { return ConvertStringToIntegerList(source.DebugChannels); } else { GetSourceData<List<SourceListItem>>(source.ChannelListUrl).ForEach(c => channels.Add(c.id)); } return channels; } public List<int> GetSourceServiceChannels(int serviceId) { var channels = new List<int>(); GetSourceData<List<SourceListItem>>(string.Format("{0}&service={1}", source.ChannelListUrl, serviceId)).ForEach(c => channels.Add(c.id)); LogMsg($"Channel count: { channels.Count() }."); return channels; } public List<int> GetSourceServices() { if (!string.IsNullOrEmpty(source.DebugServices)) { return ConvertStringToIntegerList(source.DebugServices); } else { var services = new List<int>(); GetSourceData<List<SourceListItem>>(source.ServiceDetailUrl).ForEach(s => { if (s.main_description) services.Add(s.id); }); return services; } } public virtual IVmOpenApiServiceInVersionBase MapService(int id) { IVmOpenApiServiceInVersionBase vmService = new VmOpenApiServiceInVersionBase(); try { var serviceDescriptionUrl = source.ServiceUrl + id; LogMsg($"Service url: {serviceDescriptionUrl}", true); var serviceDescriptions = GetSourceData<List<SourceListItem>>(serviceDescriptionUrl); LogMsg($"Service description count: { serviceDescriptions.Count }."); // TODO - what do we do if there is several descriptions for a service! var serviceDetailUrl = source.ServiceDetailUrl + serviceDescriptions.FirstOrDefault().id; LogMsg($"Service detail url: { serviceDetailUrl }."); var serviceDetail = GetSourceData<SourceService>(serviceDetailUrl); vmService = serviceDetail.ConvertToVm(organization.Id.ToString(), organization.Oid, id); if (!string.IsNullOrEmpty(serviceDetail.ErrorMsg)) { LogMsg(serviceDetail.ErrorMsg); } } catch (Exception ex) { logger.LogError($"Error occured while mapping a service { id }. { ex.Message }."); throw; } return vmService; } public VmOpenApiServiceLocationChannelInVersionBase MapServiceChannel(int id) { var vmChannel = new VmOpenApiServiceLocationChannelInVersionBase(); try { var url = source.ChannelDetailUrl + id; LogMsg($"Channel url: {url}"); var channelDetails = GetSourceData<SourceChannel>(url); vmChannel = channelDetails.ConvertToVm(organization.Id.ToString(), organization.Oid); if (!string.IsNullOrEmpty(channelDetails.ErrorMsg)) { LogMsg(channelDetails.ErrorMsg); } ValidateObject(vmChannel); } catch (Exception ex) { logger.LogError($"Error occured while mapping a channel { id }. { ex.Message }."); throw; } return vmChannel; } public void ValidateObject(Object obj) { var valContext = new ValidationContext(obj); var valResults = new List<ValidationResult>(); bool isValid = Validator.TryValidateObject(obj, valContext, valResults, true); if (!isValid) { StringBuilder msg = new StringBuilder(); valResults.ForEach(v => msg.AppendLine(v.ToString())); throw new Exception($"Error validating model: { msg.ToString() } { JsonConvert.SerializeObject(obj) }"); } } protected T GetSourceData<T>(string url) { var reader = new DataReader(url); return reader.GetData<T>(); } private List<int> ConvertStringToIntegerList(string str) { var intList = new List<int>(); var list = str.Split(',').ToList(); list.ForEach(c => { int id = 0; int.TryParse(c, out id); if (id != 0) { intList.Add(id); } }); return intList; } private void LogMsg(string msg, bool newLine = false) { if (newLine) { Console.WriteLine(); logger.LogDebug(Environment.NewLine); } logger.LogDebug(msg); Console.WriteLine(msg); } } }
37.252427
149
0.598645
[ "MIT" ]
MikkoVirenius/ptv-1.7
src/PTV.DataMapper.ConsoleApp/Services/DataMapper.cs
7,676
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0xD93B3F5E)] public class STU_D93B3F5E : STU_9C74F0E2 { } }
21.888889
54
0.746193
[ "MIT" ]
Mike111177/OWLib
TankLib/STU/Types/STU_D93B3F5E.cs
197
C#
using System; using Microsoft.Xna.Framework; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; namespace Nano.Engine.Graphics.Tileset { public class RegularTileset : ITileset { #region member data readonly string m_Name; readonly List<Rectangle> m_Bounds; #endregion #region public properties public Point Offset { get; set; } public ITexture2D Texture { get; set; } /// <summary> /// Gets the size of the tileset ( i.e. number of tiles) /// </summary> public int Size { get { return m_Bounds.Count; } } /// <summary> /// Gets the name of the tileset /// </summary> public string Name { get { return m_Name; } } public IList<Rectangle> Bounds { get { return m_Bounds; } } #endregion public RegularTileset(string name, ITexture2D texture, int columnCount, int rowCount, int tileWidth, int tileHeight) { if (columnCount * tileWidth > texture.Width) throw new ArgumentException("tile set size exceeds texture size"); if (rowCount * tileHeight > texture.Height) throw new ArgumentException("tile set size exceeds texture size"); m_Name = name; Texture = texture; Offset = new Point(0,0); m_Bounds = new List<Rectangle>(); for(int y = 0; y < rowCount; y++) { for(int x = 0; x < columnCount; x++) { m_Bounds.Add(new Rectangle(x * tileWidth, y * tileHeight, tileWidth, tileHeight)); } } } } }
21.773333
118
0.587875
[ "MIT" ]
SirNanoCat/nano-tile-engine
Nano/Engine/Graphics/Tileset/RegularTileset.cs
1,633
C#
using addon365.Database.Entity.Inventory.Catalog; using addon365.Database.Service.Base; using addon365.IService.pos; using Threenine.Data; namespace addon365.Database.Service.pos { public class CatelogItemService : BaseService<CatalogItem>, ICatelogItemService { public CatelogItemService(IUnitOfWork unitOfWork) : base(unitOfWork) { } } }
24.125
76
0.727979
[ "Apache-2.0" ]
addon365/b1ke-sh0wr00m
src/DotNet/Should be removed/addon365.Database.Service/pos/CatelogItemService.cs
388
C#
using System; using System.IO; using System.Reflection; using System.Windows.Forms; using WriteDown.Themes; using WriteDown.Util; using Newtonsoft.Json; namespace WriteDown { static class Program { [STAThread] static void Main() { Config.loadConfig(); AppDomain.CurrentDomain.AssemblyResolve += resolver; var json = File.ReadAllText(Path.Combine(Globals.APP_PATH, "testtheme.json")); Globals.LEXER_THEME = JsonConvert.DeserializeObject<SyntaxTheme>(json); Globals.initCef(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } private static Assembly resolver(object sender, ResolveEventArgs args) { if (args.Name.StartsWith("CefSharp")) { var assemblyName = args.Name.Split(new[] {','}, 2)[0] + ".dll"; var archSpecificPath = Path.Combine(Globals.APP_PATH, Environment.Is64BitProcess ? "x64" : "x86", assemblyName); return File.Exists(archSpecificPath) ? Assembly.LoadFile(archSpecificPath) : null; } return null; } } }
36.558824
113
0.623492
[ "MIT" ]
Lomeli12/WriteDown
WriteDown/Program.cs
1,245
C#
using FRTools.Common; using FRTools.Web.Infrastructure; using FRTools.Web.Models; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading.Tasks; using System.Web.Mvc; namespace FRTools.Web.Controllers { [RoutePrefix("scryer")] public class ScryerController : BaseController { [Route("dress", Name = "ScryerDresser")] public ActionResult Dress() => View(); [Route("dress")] [HttpPost] public async Task<ActionResult> DressResult(DressModelViewModel model) { var scryerDragon = FRHelpers.ParseUrlForDragon(model.ScryerUrl); var dressingRoomDragon = FRHelpers.ParseUrlForDragon(model.DressingRoomUrl); if (scryerDragon.Age == Data.Age.Hatchling) { AddErrorNotification($"You can only dress an adult dragon!"); return RedirectToRoute("ScryerDresser"); } if (scryerDragon.DragonType != dressingRoomDragon.DragonType) { AddErrorNotification($"The breeds of the two images do not match. Scryer image is a <b>{scryerDragon.DragonType}</b> while the dressing room is a <b>{dressingRoomDragon.DragonType}</b>!"); return RedirectToRoute("ScryerDresser"); } if (scryerDragon.Gender != dressingRoomDragon.Gender) { AddErrorNotification($"The genders of the two images do not match. Scryer image is a <b>{scryerDragon.Gender}</b> while the dressing room is a <b>{dressingRoomDragon.Gender}</b>!"); return RedirectToRoute("ScryerDresser"); } var azureImageService = new AzureImageService(); var azureImagePreviewPath = $@"previews\dresser\{scryerDragon.ToString().Trim('_')}\{dressingRoomDragon.Apparel?.Replace(',', '-').ToString()}.png"; var previewUrl = await azureImageService.Exists(azureImagePreviewPath); if (previewUrl == null) { var invisibleDragon = await FRHelpers.GetInvisibleDressingRoomDragon(dressingRoomDragon); var baseDragon = await FRHelpers.GetDragonBaseImage(scryerDragon); using (var graphics = Graphics.FromImage(baseDragon)) { graphics.DrawImage(invisibleDragon, new Rectangle(0, 0, 350, 350)); } using (var memStream = new MemoryStream()) { baseDragon.Save(memStream, ImageFormat.Png); memStream.Position = 0; previewUrl = await azureImageService.WriteImage(azureImagePreviewPath, memStream); } } return View(new DressModelResultViewModel { PreviewUrl = previewUrl }); } } }
40.927536
204
0.617564
[ "MIT" ]
Nensec/FRTools
FRTools.Web/Controllers/ScryerController.cs
2,826
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 runtime.lex-2016-11-28.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.Lex { /// <summary> /// Configuration for accessing Amazon Lex service /// </summary> public partial class AmazonLexConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.3.0.0"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonLexConfig() { this.AuthenticationServiceName = "lex"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "runtime.lex"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2016-11-28"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
25.85
109
0.581721
[ "Apache-2.0" ]
miltador-forks/aws-sdk-net
sdk/src/Services/Lex/Generated/AmazonLexConfig.cs
2,068
C#
namespace WebApiDotNetCore20.Features.WithCache { using Cacheable; using MediatR; using Models; public class CommandHandler : IRequestHandler<Command, Result>, ICacheableRequestHandler { private readonly IResultBuilder resultBuilder; public CommandHandler(IResultBuilder resultBuilder) { this.resultBuilder = resultBuilder; } Result IRequestHandler<Command, Result>.Handle(Command message) { return resultBuilder.GetResult(message.Number); } } }
26.333333
92
0.672694
[ "MIT" ]
neekgreen/Cacheable
samples/MediatR/WebApiDotNetCore20/Features/WithCache/CommandHandler.cs
555
C#
using System; using System.Collections.Generic; namespace WebApplication.Models { public partial class ScheduleInstance { public long ScheduleInstanceId { get; set; } public long? ScheduleMasterId { get; set; } public DateTime? ScheduledDateUtc { get; set; } public DateTimeOffset? ScheduledDateTimeOffset { get; set; } public bool ActiveYn { get; set; } } }
27.533333
68
0.673123
[ "MIT" ]
hboiled/azure-data-services-go-fast-codebase
solution/WebApplication/WebApplication/Models/ScheduleInstance.cs
415
C#
using System; using DCL.Controllers; using DCL.Interface; using DCL.Models; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Profiling; namespace DCL { public sealed class SceneMetricsCounter : ISceneMetricsCounter { public static class LimitsConfig { // number of entities public const int entities = 200; // Number of faces (per parcel) public const int triangles = 10000; public const int bodies = 300; public const int textures = 10; public const int materials = 20; public const int meshes = 200; public const float height = 20; public const float visibleRadius = 10; } private static bool VERBOSE = false; private static Logger logger = new Logger("SceneMetricsCounter") { verboseEnabled = VERBOSE }; public event Action<ISceneMetricsCounter> OnMetricsUpdated; private SceneMetricsModel maxCountValue = new SceneMetricsModel(); private SceneMetricsModel currentCountValue = new SceneMetricsModel(); public SceneMetricsModel currentCount { get { UpdateMetrics(); return currentCountValue.Clone(); } } public SceneMetricsModel maxCount => maxCountValue.Clone(); public bool dirty { get; private set; } private string sceneId; private Vector2Int scenePosition; private int sceneParcelCount; private DataStore_WorldObjects data; private bool enabled = false; public SceneMetricsCounter(DataStore_WorldObjects dataStore, string sceneId, Vector2Int scenePosition, int sceneParcelCount) { this.data = dataStore; Configure(sceneId, scenePosition, sceneParcelCount); } public SceneMetricsCounter(DataStore_WorldObjects dataStore) { this.data = dataStore; } public void Configure(string sceneId, Vector2Int scenePosition, int sceneParcelCount) { this.sceneId = sceneId; this.scenePosition = scenePosition; this.sceneParcelCount = sceneParcelCount; Assert.IsTrue( !string.IsNullOrEmpty(sceneId), "Scene must have an ID!" ); maxCountValue = ComputeMaxCount(); } public void Dispose() { } public void Enable() { if ( enabled ) return; var sceneData = data.sceneData[sceneId]; sceneData.materials.OnAdded += OnDataChanged; sceneData.materials.OnRemoved += OnDataChanged; sceneData.textures.OnAdded += OnTextureAdded; sceneData.textures.OnRemoved += OnTextureRemoved; sceneData.meshes.OnAdded += OnDataChanged; sceneData.meshes.OnRemoved += OnDataChanged; sceneData.animationClipSize.OnChange += OnAnimationClipSizeChange; sceneData.meshDataSize.OnChange += OnMeshDataSizeChange; sceneData.audioClips.OnAdded += OnAudioClipAdded; sceneData.audioClips.OnRemoved += OnAudioClipRemoved; sceneData.renderers.OnAdded += OnDataChanged; sceneData.renderers.OnRemoved += OnDataChanged; sceneData.owners.OnAdded += OnDataChanged; sceneData.owners.OnRemoved += OnDataChanged; sceneData.triangles.OnChange += OnDataChanged; enabled = true; } public void Disable() { if ( !enabled ) return; var sceneData = data.sceneData[sceneId]; sceneData.materials.OnAdded -= OnDataChanged; sceneData.materials.OnRemoved -= OnDataChanged; sceneData.textures.OnAdded -= OnTextureAdded; sceneData.textures.OnRemoved -= OnTextureRemoved; sceneData.meshes.OnAdded -= OnDataChanged; sceneData.meshes.OnRemoved -= OnDataChanged; sceneData.animationClipSize.OnChange -= OnAnimationClipSizeChange; sceneData.meshDataSize.OnChange -= OnMeshDataSizeChange; sceneData.audioClips.OnAdded -= OnAudioClipAdded; sceneData.audioClips.OnRemoved -= OnAudioClipRemoved; sceneData.renderers.OnAdded -= OnDataChanged; sceneData.renderers.OnRemoved -= OnDataChanged; sceneData.owners.OnAdded -= OnDataChanged; sceneData.owners.OnRemoved -= OnDataChanged; sceneData.triangles.OnChange -= OnDataChanged; enabled = false; } private SceneMetricsModel ComputeMaxCount() { var result = new SceneMetricsModel(); float log = Mathf.Log(sceneParcelCount + 1, 2); float lineal = sceneParcelCount; result.triangles = (int) (lineal * LimitsConfig.triangles); result.bodies = (int) (lineal * LimitsConfig.bodies); result.entities = (int) (lineal * LimitsConfig.entities); result.materials = (int) (log * LimitsConfig.materials); result.textures = (int) (log * LimitsConfig.textures); result.meshes = (int) (log * LimitsConfig.meshes); result.sceneHeight = (int) (log * LimitsConfig.height); return result; } public bool IsInsideTheLimits() { UpdateMetrics(); SceneMetricsModel limits = ComputeMaxCount(); SceneMetricsModel usage = currentCountValue; if (usage.triangles > limits.triangles) return false; if (usage.bodies > limits.bodies) return false; if (usage.entities > limits.entities) return false; if (usage.materials > limits.materials) return false; if (usage.textures > limits.textures) return false; if (usage.meshes > limits.meshes) return false; return true; } private void MarkDirty() { dirty = true; } public void SendEvent() { if (!dirty) return; dirty = false; UpdateMetrics(); Interface.WebInterface.ReportOnMetricsUpdate(sceneId, currentCountValue.ToMetricsModel(), maxCount.ToMetricsModel()); } void OnAudioClipAdded(AudioClip audioClip) { MarkDirty(); currentCountValue.audioClipMemory += MetricsScoreUtils.ComputeAudioClipScore(audioClip); } void OnAudioClipRemoved(AudioClip audioClip) { MarkDirty(); currentCountValue.audioClipMemory -= MetricsScoreUtils.ComputeAudioClipScore(audioClip); } private void OnMeshDataSizeChange(long current, long previous) { MarkDirty(); currentCountValue.meshMemory = current; } void OnAnimationClipSizeChange(long animationClipSize, long previous) { MarkDirty(); currentCountValue.animationClipMemory = animationClipSize; } void OnTextureAdded(Texture texture) { MarkDirty(); if (texture is Texture2D tex2D) { currentCountValue.textureMemory += MetricsScoreUtils.ComputeTextureScore(tex2D); } } void OnTextureRemoved(Texture texture) { MarkDirty(); if (texture is Texture2D tex2D) { currentCountValue.textureMemory -= MetricsScoreUtils.ComputeTextureScore(tex2D); } } void OnDataChanged<T>(T obj) where T : class { MarkDirty(); } void OnDataChanged(int obj1, int obj2) { MarkDirty(); } private void UpdateMetrics() { if (string.IsNullOrEmpty(sceneId)) return; if (data != null && data.sceneData.ContainsKey(sceneId)) { var sceneData = data.sceneData[sceneId]; if (sceneData != null) { currentCountValue.materials = sceneData.materials.Count(); currentCountValue.textures = sceneData.textures.Count(); currentCountValue.meshes = sceneData.meshes.Count(); currentCountValue.entities = sceneData.owners.Count(); currentCountValue.bodies = sceneData.renderers.Count(); currentCountValue.triangles = sceneData.triangles.Get() / 3; } } logger.Verbose($"Current metrics: {currentCountValue}"); RaiseMetricsUpdate(); } private void UpdateWorstMetricsOffense() { DataStore_SceneMetrics metricsData = DataStore.i.Get<DataStore_SceneMetrics>(); if ( maxCountValue != null && metricsData.worstMetricOffenseComputeEnabled.Get() ) { bool isOffending = currentCountValue > maxCountValue; if ( !isOffending ) return; bool firstOffense = false; if (!metricsData.worstMetricOffenses.ContainsKey(sceneId)) { firstOffense = true; metricsData.worstMetricOffenses[sceneId] = currentCountValue.Clone(); } SceneMetricsModel worstOffense = metricsData.worstMetricOffenses[sceneId]; SceneMetricsModel currentOffense = maxCountValue - currentCountValue; if ( firstOffense ) logger.Verbose($"New offending scene {sceneId} ({scenePosition})!\n{currentCountValue}"); if ( currentOffense < worstOffense ) return; metricsData.worstMetricOffenses[sceneId] = currentOffense; logger.Verbose($"New offending scene {sceneId} {scenePosition}!\nmetrics: {currentCountValue}\nlimits: {maxCountValue}\ndelta:{currentOffense}"); } } private void RaiseMetricsUpdate() { UpdateWorstMetricsOffense(); OnMetricsUpdated?.Invoke(this); } } }
31.435435
161
0.584543
[ "Apache-2.0" ]
CarlosPolygonalMind/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/SceneMetricsCounter/SceneMetricsCounter.cs
10,468
C#
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- using System; using System.ServiceModel; namespace Microsoft.Samples.ReliableSession { // Define a service contract. [ServiceContract(Namespace="http://Microsoft.Samples.ReliableSession")] public interface ICalculator { [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); } // Service class which implements the service contract. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] public class CalculatorService : ICalculator { public double Add(double n1, double n2) { return n1 + n2; } public double Subtract(double n1, double n2) { return n1 - n2; } public double Multiply(double n1, double n2) { return n1 * n2; } public double Divide(double n1, double n2) { return n1 / n2; } } }
26.66
75
0.549887
[ "Apache-2.0" ]
jdm7dv/visual-studio
Samples/NET 4.6/WF_WCF_Samples/WCF/Basic/Binding/Custom/ReliableSession/CS/service/service.cs
1,335
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Stride.Core.Assets; using Stride.Core; using Stride.Graphics; namespace Stride.Assets { public static class GameSettingsAssetExtensions { /// <summary> /// Retrieves the <see cref="GameSettingsAsset"/> from the given <see cref="Package"/> if available, or null otherwise. /// </summary> /// <param name="package">The package from which to retrieve the game settings.</param> /// <returns>The <see cref="GameSettingsAsset"/> from the given <see cref="Package"/> if available. Null otherwise.</returns> public static GameSettingsAsset GetGameSettingsAsset(this Package package) { var gameSettingsAsset = package.FindAsset(GameSettingsAsset.GameSettingsLocation); if (gameSettingsAsset == null && package.TemporaryAssets.Count > 0) { gameSettingsAsset = package.TemporaryAssets.Find(x => x.Location == GameSettingsAsset.GameSettingsLocation); } return gameSettingsAsset?.Asset as GameSettingsAsset; } /// <summary> /// Retrieves the <see cref="GameSettingsAsset"/> from the given <see cref="Package"/> if available, /// or otherwise attempts to retrieve it from the from the <see cref="PackageSession.CurrentPackage"/> of the session. /// If none is available, this method returns a new default instance. /// </summary> /// <param name="package">The package from which to retrieve the game settings.</param> /// <returns>The <see cref="GameSettingsAsset"/> from either the given package or the session if available. A new default instance otherwise.</returns> public static GameSettingsAsset GetGameSettingsAssetOrDefault(this Package package) { var gameSettings = package.GetGameSettingsAsset(); if (gameSettings == null) { gameSettings = package.Session.CurrentProject?.Package.GetGameSettingsAsset(); } return gameSettings ?? GameSettingsFactory.Create(); } /// <summary> /// Retrieves the <see cref="GameSettingsAsset"/> from the <see cref="PackageSession.CurrentPackage"/> of the given session if available, /// or a new default instance otherwise. /// </summary> /// <param name="session">The package session from which to retrieve the game settings.</param> /// <returns>The <see cref="GameSettingsAsset"/> from the given session if available. A new default instance otherwise.</returns> private static GameSettingsAsset GetGameSettingsAssetOrDefault(this PackageSession session) { return session.CurrentProject?.Package.GetGameSettingsAsset() ?? GameSettingsFactory.Create(); } /// <summary> /// Retrieves the reference <see cref="ColorSpace"/> to use according to the <see cref="PackageSession.CurrentPackage"/> of the given package. /// If the current package is null, this method returns the value of <see cref="RenderingSettings.DefaultColorSpace"/>. /// </summary> /// <param name="session">The package session from which to retrieve the color space.</param> /// <param name="platform">The platform for which to return the color space.</param> /// <returns>The color space of the current package of the session, or <see cref="RenderingSettings.DefaultColorSpace"/>.</returns> public static ColorSpace GetReferenceColorSpace(this PackageSession session, PlatformType platform) { return GetGameSettingsAssetOrDefault(session).GetOrCreate<RenderingSettings>(platform).ColorSpace; } } }
57.514706
159
0.676809
[ "MIT" ]
Aggror/Stride
sources/engine/Stride.Assets/GameSettingsAssetExtensions.cs
3,911
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/Uxtheme.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="TA_TRANSFORM" /> struct.</summary> public static unsafe class TA_TRANSFORMTests { /// <summary>Validates that the <see cref="TA_TRANSFORM" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<TA_TRANSFORM>(), Is.EqualTo(sizeof(TA_TRANSFORM))); } /// <summary>Validates that the <see cref="TA_TRANSFORM" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(TA_TRANSFORM).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="TA_TRANSFORM" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(TA_TRANSFORM), Is.EqualTo(20)); } } }
37.333333
145
0.65997
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/Uxtheme/TA_TRANSFORMTests.cs
1,346
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Web.Models { public interface IDraftApprenticeshipViewModel { long ProviderId { get; } string CohortReference { get; } } }
20.571429
50
0.722222
[ "MIT" ]
SkillsFundingAgency/das-providercommitments
src/SFA.DAS.ProviderCommitments/SFA.DAS.ProviderCommitments.Web/Models/IDraftApprenticeshipViewModel.cs
290
C#
using System; using System.Collections.Generic; using System.Linq; namespace Unleashed { public class Serbian { public static void Main() { } } }
13.142857
33
0.603261
[ "MIT" ]
akaraatanasov/SoftUni
Technologies Fundamentals/Programming Fundamentals/Dictionaries and LINQ - Exercises/Unleashed/Serbian.cs
186
C#
using System; using DNTFrameworkCore.Common; using Microsoft.Extensions.Options; namespace DNTFrameworkCore.Tenancy.Options { /// <summary> /// Dictionary of tenant specific options caches /// </summary> /// <typeparam name="TOptions"></typeparam> internal sealed class TenantOptionsDictionary<TOptions> : LockingConcurrentDictionary<string, IOptionsMonitorCache<TOptions>> where TOptions : class { public TenantOptionsDictionary() : base(StringComparer.OrdinalIgnoreCase) { } /// <summary> /// Get options for specific tenant (create if not exists) /// </summary> /// <param name="tenantId"></param> /// <returns></returns> public IOptionsMonitorCache<TOptions> Get(string tenantId) { return GetOrAdd(tenantId, key => new OptionsCache<TOptions>()); } } }
31.068966
111
0.6404
[ "Apache-2.0" ]
rabbal/DNTFrameworkCore
src/DNTFrameworkCore/Tenancy/Options/TenantOptionsDictionary.cs
901
C#
using Application.Enums; using Infrastructure.AuditModels; using Infrastructure.Identity.Models; using WebUI.Abstractions; using Application.Features.Logs.Commands; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Threading.Tasks; using WebUI.Areas.Admin.Models; namespace WebUI.Areas.Admin { [Area("Admin")] [Authorize(Roles = "SuperAdmin")] public class RoleController : BaseController<RoleController> { #region Fields private readonly RoleManager<IdentityRole> _roleManager; private readonly UserManager<ApplicationUser> _userManager; #endregion public RoleController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { _userManager = userManager; _roleManager = roleManager; } #region Main Controller Methods public IActionResult Index() { return View(); } public async Task<IActionResult> LoadAll() { var roles = await _roleManager.Roles.ToListAsync(); return PartialView("_ViewAll", _mapper.Map<IEnumerable<RoleViewModel>>(roles)); } public async Task<IActionResult> OnGetCreateOrEdit(string id) { if (string.IsNullOrEmpty(id)) { return new JsonResult(new { isValid = true, html = await _viewRenderer.RenderViewToStringAsync("_Create", new RoleViewModel()) }); } else { var roleViewModel = _mapper.Map<RoleViewModel>(await _roleManager.FindByIdAsync(id)); return new JsonResult(new { isValid = true, html = await _viewRenderer.RenderViewToStringAsync("_Create", roleViewModel) }); } } [HttpPost] public async Task<IActionResult> OnPostCreateOrEdit(RoleViewModel role) { if (ModelState.IsValid) { if (await _roleManager.FindByNameAsync(role.Name) != null) { _notify.Information($"Роль {role.Name} вже існує"); return new JsonResult(new { isValid = true, html = await GetJSONRolesListAsync() }); } if (string.IsNullOrEmpty(role.Id)) { var result = await _roleManager.CreateAsync(new IdentityRole(role.Name)); if (result.Succeeded) { Log log = new Log() { UserId = _userService.UserId, Action = "Create", TableName = "Roles", NewValues = role }; await _mediator.Send(new AddLogCommand() { Log = log }); _notify.Success($"Роль {role.Name} створено"); } else _notify.Error($"Помилка при створені ролі {role.Name}"); } else { var existingRole = await _roleManager.FindByIdAsync(role.Id); Log log = new Log() { UserId = _userService.UserId, Action = "Update", TableName = "Roles", Key = existingRole.Id, OldValues = _mapper.Map<RoleViewModel>(existingRole), NewValues = role }; existingRole.Name = role.Name; existingRole.NormalizedName = role.Name.ToUpper(); var result = await _roleManager.UpdateAsync(existingRole); if (result.Succeeded) { _notify.Success($"Роль {role.Name} змінено"); await _mediator.Send(new AddLogCommand() { Log = log }); } else _notify.Error($"Помилка при збережені змін до {role.Name}"); } return new JsonResult(new { isValid = true, html = await GetJSONRolesListAsync() }); } else { var html = await _viewRenderer.RenderViewToStringAsync("_CreateOrEdit", role); return new JsonResult(new { isValid = false, html = html }); } } [HttpPost] public async Task<JsonResult> OnPostDelete(string id) { var existingRole = await _roleManager.FindByIdAsync(id); if (existingRole.Name != Roles.SuperAdmin.ToString() && existingRole.Name != Roles.Worker.ToString()) { var allUsers = await _userManager.Users.ToListAsync(); bool roleIsNotUsed = true; foreach (var user in allUsers) if (await _userManager.IsInRoleAsync(user, existingRole.Name)) { roleIsNotUsed = false; break; } if (roleIsNotUsed) { if ((await _roleManager.DeleteAsync(existingRole)).Succeeded) { Log log = new Log() { UserId = _userService.UserId, Key = existingRole.Id, Action = "Delete", TableName = "Roles", OldValues = _mapper.Map<RoleViewModel>(existingRole) }; await _mediator.Send(new AddLogCommand() { Log = log }); _notify.Success($"Роль {existingRole.Name} видалено"); } else _notify.Error($"Помилка при видалені ролі {existingRole.Name}"); } else _notify.Warning($"Роль {existingRole.Name} використовується"); } else _notify.Error($"Роль {existingRole.Name} не може бути видаленою"); return new JsonResult(new { isValid = true, html = await GetJSONRolesListAsync() }); } #endregion #region Other Methods private async Task<string> GetJSONRolesListAsync() { var roles = await _roleManager.Roles.ToListAsync(); var mappedRoles = _mapper.Map<IEnumerable<RoleViewModel>>(roles); return await _viewRenderer.RenderViewToStringAsync("_ViewAll", mappedRoles); } #endregion } }
26.823834
104
0.676647
[ "MIT" ]
DurkaTechnologies/AdminPanel
WebUI/Areas/Admin/Controllers/RoleController.cs
5,338
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Outputs.Machinelearning.V1 { [OutputType] public sealed class SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersStartupProbeHttpGetHttpHeaders { /// <summary> /// The header field name /// </summary> public readonly string Name; /// <summary> /// The header field value /// </summary> public readonly string Value; [OutputConstructor] private SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersStartupProbeHttpGetHttpHeaders( string name, string value) { Name = name; Value = value; } } }
27.888889
121
0.663347
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/seldon-operator/dotnet/Kubernetes/Crds/Operators/SeldonOperator/Machinelearning/V1/Outputs/SeldonDeploymentSpecPredictorsComponentSpecsSpecEphemeralContainersStartupProbeHttpGetHttpHeaders.cs
1,004
C#
using MvcContrib.FluentHtml.Elements; namespace MvcContrib.FluentHtml.Behaviors { public interface IMemberBehavior : IBehaviorMarker { void Execute(IMemberElement element); } }
18.3
51
0.808743
[ "Apache-2.0" ]
torkelo/MvcContrib
src/MvcContrib.FluentHtml/Behaviors/IMemberBehavior.cs
183
C#
//------------------------------------------------------------------------------ // Copyright (c) 2014-2016 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ using Robotlegs.Bender.Extensions.EnhancedLogging.Impl; using Robotlegs.Bender.Framework.API; namespace Robotlegs.Bender.Extensions.EnhancedLogging { public class ConsoleLoggingExtension : IExtension { public void Extend (IContext context) { context.AddLogTarget(new ConsoleLogTarget(context)); } } }
31.956522
82
0.57551
[ "MIT" ]
KieranBond/robotlegs-sharp-framework
src/Robotlegs/Bender/Extensions/EnhancedLogging/ConsoleLoggingExtension.cs
735
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdNet6.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; namespace IdNet6 { /// <summary> /// Model properties of an IdentityServer user /// </summary> internal class IdentityServerUser { /// <summary> /// Subject ID (mandatory) /// </summary> public string SubjectId { get; } /// <summary> /// Display name (optional) /// </summary> public string DisplayName { get; set; } /// <summary> /// Identity provider (optional) /// </summary> public string IdentityProvider { get; set; } /// <summary> /// Authentication methods /// </summary> public ICollection<string> AuthenticationMethods { get; set; } = new HashSet<string>(); /// <summary> /// Authentication time /// </summary> public DateTime? AuthenticationTime { get; set; } /// <summary> /// Additional claims /// </summary> public ICollection<Claim> AdditionalClaims { get; set; } = new HashSet<Claim>(new ClaimComparer()); /// <summary> /// Initializes a user identity /// </summary> /// <param name="subjectId">The subject ID</param> public IdentityServerUser(string subjectId) { if (subjectId.IsMissing()) throw new ArgumentException("SubjectId is mandatory", nameof(subjectId)); SubjectId = subjectId; } /// <summary> /// Creates an IdentityServer claims principal /// </summary> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public ClaimsPrincipal CreatePrincipal() { if (SubjectId.IsMissing()) throw new ArgumentException("SubjectId is mandatory", nameof(SubjectId)); var claims = new List<Claim> { new Claim(JwtClaimTypes.Subject, SubjectId) }; if (DisplayName.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.Name, DisplayName)); } if (IdentityProvider.IsPresent()) { claims.Add(new Claim(JwtClaimTypes.IdentityProvider, IdentityProvider)); } if (AuthenticationTime.HasValue) { claims.Add(new Claim(JwtClaimTypes.AuthenticationTime, new DateTimeOffset(AuthenticationTime.Value).ToUnixTimeSeconds().ToString())); } if (AuthenticationMethods.Any()) { foreach (var amr in AuthenticationMethods) { claims.Add(new Claim(JwtClaimTypes.AuthenticationMethod, amr)); } } claims.AddRange(AdditionalClaims); var id = new ClaimsIdentity(claims.Distinct(new ClaimComparer()), Constants.IdentityServerAuthenticationType, JwtClaimTypes.Name, JwtClaimTypes.Role); return new ClaimsPrincipal(id); } } }
32.757576
162
0.587419
[ "Apache-2.0" ]
simple0x47/IdNet6
src/Storage/src/IdentityServerUser.cs
3,243
C#
using FluentValidation; using System; using System.Collections.Generic; using System.Text; namespace Boxters.Application.Orders.Queries.GetOrders.GetOrderById { public class GetOrderQueryValidator : AbstractValidator<GetOrderQuery> { public GetOrderQueryValidator() { RuleFor(x => x.OrderId).NotNull(); } } }
22.4375
74
0.699164
[ "MIT" ]
AmazingSuka/two-bros
Two.Application/Orders/Queries/GetOrders/GetOrderById/GetOrderQueryValidator.cs
361
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ram-2018-01-04.normal.json service model. */ using System; using System.Collections.Generic; using System.Net; using Amazon.RAM.Model; using Amazon.RAM.Model.Internal.MarshallTransformations; using Amazon.RAM.Internal; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.RAM { /// <summary> /// Implementation for accessing RAM /// /// Use AWS Resource Access Manager to share AWS resources between AWS accounts. To share /// a resource, you create a resource share, associate the resource with the resource /// share, and specify the principals that can access the resources associated with the /// resource share. The following principals are supported: AWS accounts, organizational /// units (OU) from AWS Organizations, and organizations from AWS Organizations. /// /// /// <para> /// For more information, see the <a href="https://docs.aws.amazon.com/ram/latest/userguide/">AWS /// Resource Access Manager User Guide</a>. /// </para> /// </summary> public partial class AmazonRAMClient : AmazonServiceClient, IAmazonRAM { private static IServiceMetadata serviceMetadata = new AmazonRAMMetadata(); #region Constructors /// <summary> /// Constructs AmazonRAMClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> public AmazonRAMClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonRAMConfig()) { } /// <summary> /// Constructs AmazonRAMClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="region">The region to connect.</param> public AmazonRAMClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonRAMConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonRAMClient with the credentials loaded from the application's /// default configuration, and if unsuccessful from the Instance Profile service on an EC2 instance. /// /// Example App.config with credentials set. /// <code> /// &lt;?xml version="1.0" encoding="utf-8" ?&gt; /// &lt;configuration&gt; /// &lt;appSettings&gt; /// &lt;add key="AWSProfileName" value="AWS Default"/&gt; /// &lt;/appSettings&gt; /// &lt;/configuration&gt; /// </code> /// /// </summary> /// <param name="config">The AmazonRAMClient Configuration Object</param> public AmazonRAMClient(AmazonRAMConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonRAMClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonRAMClient(AWSCredentials credentials) : this(credentials, new AmazonRAMConfig()) { } /// <summary> /// Constructs AmazonRAMClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonRAMClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonRAMConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonRAMClient with AWS Credentials and an /// AmazonRAMClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonRAMClient Configuration Object</param> public AmazonRAMClient(AWSCredentials credentials, AmazonRAMConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonRAMConfig()) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonRAMConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID, AWS Secret Key and an /// AmazonRAMClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonRAMClient Configuration Object</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonRAMConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonRAMConfig()) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonRAMConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonRAMClient with AWS Access Key ID, AWS Secret Key and an /// AmazonRAMClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonRAMClient Configuration Object</param> public AmazonRAMClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonRAMConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } /// <summary> /// Capture metadata for the service. /// </summary> protected override IServiceMetadata ServiceMetadata { get { return serviceMetadata; } } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AcceptResourceShareInvitation /// <summary> /// Accepts an invitation to a resource share from another AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AcceptResourceShareInvitation service method.</param> /// /// <returns>The response from the AcceptResourceShareInvitation service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyAcceptedException"> /// The invitation was already accepted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException"> /// The invitation was already rejected. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException"> /// The Amazon Resource Name (ARN) for an invitation was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException"> /// The invitation is expired. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AcceptResourceShareInvitation">REST API Reference for AcceptResourceShareInvitation Operation</seealso> public virtual AcceptResourceShareInvitationResponse AcceptResourceShareInvitation(AcceptResourceShareInvitationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AcceptResourceShareInvitationRequestMarshaller.Instance; options.ResponseUnmarshaller = AcceptResourceShareInvitationResponseUnmarshaller.Instance; return Invoke<AcceptResourceShareInvitationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the AcceptResourceShareInvitation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AcceptResourceShareInvitation operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAcceptResourceShareInvitation /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AcceptResourceShareInvitation">REST API Reference for AcceptResourceShareInvitation Operation</seealso> public virtual IAsyncResult BeginAcceptResourceShareInvitation(AcceptResourceShareInvitationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = AcceptResourceShareInvitationRequestMarshaller.Instance; options.ResponseUnmarshaller = AcceptResourceShareInvitationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the AcceptResourceShareInvitation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginAcceptResourceShareInvitation.</param> /// /// <returns>Returns a AcceptResourceShareInvitationResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AcceptResourceShareInvitation">REST API Reference for AcceptResourceShareInvitation Operation</seealso> public virtual AcceptResourceShareInvitationResponse EndAcceptResourceShareInvitation(IAsyncResult asyncResult) { return EndInvoke<AcceptResourceShareInvitationResponse>(asyncResult); } #endregion #region AssociateResourceShare /// <summary> /// Associates the specified resource share with the specified principals and resources. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateResourceShare service method.</param> /// /// <returns>The response from the AssociateResourceShare service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException"> /// The requested state transition is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException"> /// The requested resource share exceeds the limit for your account. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceShare">REST API Reference for AssociateResourceShare Operation</seealso> public virtual AssociateResourceShareResponse AssociateResourceShare(AssociateResourceShareRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateResourceShareResponseUnmarshaller.Instance; return Invoke<AssociateResourceShareResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the AssociateResourceShare operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssociateResourceShare operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAssociateResourceShare /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceShare">REST API Reference for AssociateResourceShare Operation</seealso> public virtual IAsyncResult BeginAssociateResourceShare(AssociateResourceShareRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateResourceShareResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the AssociateResourceShare operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginAssociateResourceShare.</param> /// /// <returns>Returns a AssociateResourceShareResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceShare">REST API Reference for AssociateResourceShare Operation</seealso> public virtual AssociateResourceShareResponse EndAssociateResourceShare(IAsyncResult asyncResult) { return EndInvoke<AssociateResourceShareResponse>(asyncResult); } #endregion #region AssociateResourceSharePermission /// <summary> /// Associates a permission with a resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AssociateResourceSharePermission service method.</param> /// /// <returns>The response from the AssociateResourceSharePermission service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceSharePermission">REST API Reference for AssociateResourceSharePermission Operation</seealso> public virtual AssociateResourceSharePermissionResponse AssociateResourceSharePermission(AssociateResourceSharePermissionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateResourceSharePermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateResourceSharePermissionResponseUnmarshaller.Instance; return Invoke<AssociateResourceSharePermissionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the AssociateResourceSharePermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AssociateResourceSharePermission operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndAssociateResourceSharePermission /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceSharePermission">REST API Reference for AssociateResourceSharePermission Operation</seealso> public virtual IAsyncResult BeginAssociateResourceSharePermission(AssociateResourceSharePermissionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = AssociateResourceSharePermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = AssociateResourceSharePermissionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the AssociateResourceSharePermission operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginAssociateResourceSharePermission.</param> /// /// <returns>Returns a AssociateResourceSharePermissionResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/AssociateResourceSharePermission">REST API Reference for AssociateResourceSharePermission Operation</seealso> public virtual AssociateResourceSharePermissionResponse EndAssociateResourceSharePermission(IAsyncResult asyncResult) { return EndInvoke<AssociateResourceSharePermissionResponse>(asyncResult); } #endregion #region CreateResourceShare /// <summary> /// Creates a resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateResourceShare service method.</param> /// /// <returns>The response from the CreateResourceShare service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException"> /// The requested state transition is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException"> /// The requested resource share exceeds the limit for your account. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.TagPolicyViolationException"> /// The specified tag is a reserved word and cannot be used. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/CreateResourceShare">REST API Reference for CreateResourceShare Operation</seealso> public virtual CreateResourceShareResponse CreateResourceShare(CreateResourceShareRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateResourceShareResponseUnmarshaller.Instance; return Invoke<CreateResourceShareResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the CreateResourceShare operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateResourceShare operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateResourceShare /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/CreateResourceShare">REST API Reference for CreateResourceShare Operation</seealso> public virtual IAsyncResult BeginCreateResourceShare(CreateResourceShareRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = CreateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateResourceShareResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the CreateResourceShare operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateResourceShare.</param> /// /// <returns>Returns a CreateResourceShareResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/CreateResourceShare">REST API Reference for CreateResourceShare Operation</seealso> public virtual CreateResourceShareResponse EndCreateResourceShare(IAsyncResult asyncResult) { return EndInvoke<CreateResourceShareResponse>(asyncResult); } #endregion #region DeleteResourceShare /// <summary> /// Deletes the specified resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteResourceShare service method.</param> /// /// <returns>The response from the DeleteResourceShare service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException"> /// The requested state transition is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DeleteResourceShare">REST API Reference for DeleteResourceShare Operation</seealso> public virtual DeleteResourceShareResponse DeleteResourceShare(DeleteResourceShareRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteResourceShareResponseUnmarshaller.Instance; return Invoke<DeleteResourceShareResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DeleteResourceShare operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteResourceShare operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteResourceShare /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DeleteResourceShare">REST API Reference for DeleteResourceShare Operation</seealso> public virtual IAsyncResult BeginDeleteResourceShare(DeleteResourceShareRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DeleteResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = DeleteResourceShareResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DeleteResourceShare operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteResourceShare.</param> /// /// <returns>Returns a DeleteResourceShareResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DeleteResourceShare">REST API Reference for DeleteResourceShare Operation</seealso> public virtual DeleteResourceShareResponse EndDeleteResourceShare(IAsyncResult asyncResult) { return EndInvoke<DeleteResourceShareResponse>(asyncResult); } #endregion #region DisassociateResourceShare /// <summary> /// Disassociates the specified principals or resources from the specified resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateResourceShare service method.</param> /// /// <returns>The response from the DisassociateResourceShare service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidStateTransitionException"> /// The requested state transition is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareLimitExceededException"> /// The requested resource share exceeds the limit for your account. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceShare">REST API Reference for DisassociateResourceShare Operation</seealso> public virtual DisassociateResourceShareResponse DisassociateResourceShare(DisassociateResourceShareRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateResourceShareResponseUnmarshaller.Instance; return Invoke<DisassociateResourceShareResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DisassociateResourceShare operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisassociateResourceShare operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisassociateResourceShare /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceShare">REST API Reference for DisassociateResourceShare Operation</seealso> public virtual IAsyncResult BeginDisassociateResourceShare(DisassociateResourceShareRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateResourceShareResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DisassociateResourceShare operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisassociateResourceShare.</param> /// /// <returns>Returns a DisassociateResourceShareResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceShare">REST API Reference for DisassociateResourceShare Operation</seealso> public virtual DisassociateResourceShareResponse EndDisassociateResourceShare(IAsyncResult asyncResult) { return EndInvoke<DisassociateResourceShareResponse>(asyncResult); } #endregion #region DisassociateResourceSharePermission /// <summary> /// Disassociates an AWS RAM permission from a resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisassociateResourceSharePermission service method.</param> /// /// <returns>The response from the DisassociateResourceSharePermission service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceSharePermission">REST API Reference for DisassociateResourceSharePermission Operation</seealso> public virtual DisassociateResourceSharePermissionResponse DisassociateResourceSharePermission(DisassociateResourceSharePermissionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateResourceSharePermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateResourceSharePermissionResponseUnmarshaller.Instance; return Invoke<DisassociateResourceSharePermissionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the DisassociateResourceSharePermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisassociateResourceSharePermission operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDisassociateResourceSharePermission /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceSharePermission">REST API Reference for DisassociateResourceSharePermission Operation</seealso> public virtual IAsyncResult BeginDisassociateResourceSharePermission(DisassociateResourceSharePermissionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = DisassociateResourceSharePermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = DisassociateResourceSharePermissionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the DisassociateResourceSharePermission operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDisassociateResourceSharePermission.</param> /// /// <returns>Returns a DisassociateResourceSharePermissionResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/DisassociateResourceSharePermission">REST API Reference for DisassociateResourceSharePermission Operation</seealso> public virtual DisassociateResourceSharePermissionResponse EndDisassociateResourceSharePermission(IAsyncResult asyncResult) { return EndInvoke<DisassociateResourceSharePermissionResponse>(asyncResult); } #endregion #region EnableSharingWithAwsOrganization /// <summary> /// Enables resource sharing within your AWS Organization. /// /// /// <para> /// The caller must be the master account for the AWS Organization. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the EnableSharingWithAwsOrganization service method.</param> /// /// <returns>The response from the EnableSharingWithAwsOrganization service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/EnableSharingWithAwsOrganization">REST API Reference for EnableSharingWithAwsOrganization Operation</seealso> public virtual EnableSharingWithAwsOrganizationResponse EnableSharingWithAwsOrganization(EnableSharingWithAwsOrganizationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = EnableSharingWithAwsOrganizationRequestMarshaller.Instance; options.ResponseUnmarshaller = EnableSharingWithAwsOrganizationResponseUnmarshaller.Instance; return Invoke<EnableSharingWithAwsOrganizationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the EnableSharingWithAwsOrganization operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EnableSharingWithAwsOrganization operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndEnableSharingWithAwsOrganization /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/EnableSharingWithAwsOrganization">REST API Reference for EnableSharingWithAwsOrganization Operation</seealso> public virtual IAsyncResult BeginEnableSharingWithAwsOrganization(EnableSharingWithAwsOrganizationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = EnableSharingWithAwsOrganizationRequestMarshaller.Instance; options.ResponseUnmarshaller = EnableSharingWithAwsOrganizationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the EnableSharingWithAwsOrganization operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginEnableSharingWithAwsOrganization.</param> /// /// <returns>Returns a EnableSharingWithAwsOrganizationResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/EnableSharingWithAwsOrganization">REST API Reference for EnableSharingWithAwsOrganization Operation</seealso> public virtual EnableSharingWithAwsOrganizationResponse EndEnableSharingWithAwsOrganization(IAsyncResult asyncResult) { return EndInvoke<EnableSharingWithAwsOrganizationResponse>(asyncResult); } #endregion #region GetPermission /// <summary> /// Gets the contents of an AWS RAM permission in JSON format. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetPermission service method.</param> /// /// <returns>The response from the GetPermission service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetPermission">REST API Reference for GetPermission Operation</seealso> public virtual GetPermissionResponse GetPermission(GetPermissionRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetPermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = GetPermissionResponseUnmarshaller.Instance; return Invoke<GetPermissionResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetPermission operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetPermission operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetPermission /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetPermission">REST API Reference for GetPermission Operation</seealso> public virtual IAsyncResult BeginGetPermission(GetPermissionRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetPermissionRequestMarshaller.Instance; options.ResponseUnmarshaller = GetPermissionResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetPermission operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetPermission.</param> /// /// <returns>Returns a GetPermissionResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetPermission">REST API Reference for GetPermission Operation</seealso> public virtual GetPermissionResponse EndGetPermission(IAsyncResult asyncResult) { return EndInvoke<GetPermissionResponse>(asyncResult); } #endregion #region GetResourcePolicies /// <summary> /// Gets the policies for the specified resources that you own and have shared. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetResourcePolicies service method.</param> /// /// <returns>The response from the GetResourcePolicies service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceArnNotFoundException"> /// An Amazon Resource Name (ARN) was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourcePolicies">REST API Reference for GetResourcePolicies Operation</seealso> public virtual GetResourcePoliciesResponse GetResourcePolicies(GetResourcePoliciesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourcePoliciesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourcePoliciesResponseUnmarshaller.Instance; return Invoke<GetResourcePoliciesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetResourcePolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourcePolicies operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourcePolicies /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourcePolicies">REST API Reference for GetResourcePolicies Operation</seealso> public virtual IAsyncResult BeginGetResourcePolicies(GetResourcePoliciesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourcePoliciesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourcePoliciesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetResourcePolicies operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResourcePolicies.</param> /// /// <returns>Returns a GetResourcePoliciesResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourcePolicies">REST API Reference for GetResourcePolicies Operation</seealso> public virtual GetResourcePoliciesResponse EndGetResourcePolicies(IAsyncResult asyncResult) { return EndInvoke<GetResourcePoliciesResponse>(asyncResult); } #endregion #region GetResourceShareAssociations /// <summary> /// Gets the resources or principals for the resource shares that you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetResourceShareAssociations service method.</param> /// /// <returns>The response from the GetResourceShareAssociations service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareAssociations">REST API Reference for GetResourceShareAssociations Operation</seealso> public virtual GetResourceShareAssociationsResponse GetResourceShareAssociations(GetResourceShareAssociationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceShareAssociationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceShareAssociationsResponseUnmarshaller.Instance; return Invoke<GetResourceShareAssociationsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetResourceShareAssociations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceShareAssociations operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourceShareAssociations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareAssociations">REST API Reference for GetResourceShareAssociations Operation</seealso> public virtual IAsyncResult BeginGetResourceShareAssociations(GetResourceShareAssociationsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceShareAssociationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceShareAssociationsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetResourceShareAssociations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResourceShareAssociations.</param> /// /// <returns>Returns a GetResourceShareAssociationsResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareAssociations">REST API Reference for GetResourceShareAssociations Operation</seealso> public virtual GetResourceShareAssociationsResponse EndGetResourceShareAssociations(IAsyncResult asyncResult) { return EndInvoke<GetResourceShareAssociationsResponse>(asyncResult); } #endregion #region GetResourceShareInvitations /// <summary> /// Gets the invitations for resource sharing that you've received. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetResourceShareInvitations service method.</param> /// /// <returns>The response from the GetResourceShareInvitations service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidMaxResultsException"> /// The specified value for MaxResults is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException"> /// The Amazon Resource Name (ARN) for an invitation was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareInvitations">REST API Reference for GetResourceShareInvitations Operation</seealso> public virtual GetResourceShareInvitationsResponse GetResourceShareInvitations(GetResourceShareInvitationsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceShareInvitationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceShareInvitationsResponseUnmarshaller.Instance; return Invoke<GetResourceShareInvitationsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetResourceShareInvitations operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceShareInvitations operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourceShareInvitations /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareInvitations">REST API Reference for GetResourceShareInvitations Operation</seealso> public virtual IAsyncResult BeginGetResourceShareInvitations(GetResourceShareInvitationsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceShareInvitationsRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceShareInvitationsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetResourceShareInvitations operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResourceShareInvitations.</param> /// /// <returns>Returns a GetResourceShareInvitationsResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShareInvitations">REST API Reference for GetResourceShareInvitations Operation</seealso> public virtual GetResourceShareInvitationsResponse EndGetResourceShareInvitations(IAsyncResult asyncResult) { return EndInvoke<GetResourceShareInvitationsResponse>(asyncResult); } #endregion #region GetResourceShares /// <summary> /// Gets the resource shares that you own or the resource shares that are shared with /// you. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetResourceShares service method.</param> /// /// <returns>The response from the GetResourceShares service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShares">REST API Reference for GetResourceShares Operation</seealso> public virtual GetResourceSharesResponse GetResourceShares(GetResourceSharesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceSharesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceSharesResponseUnmarshaller.Instance; return Invoke<GetResourceSharesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the GetResourceShares operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceShares operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetResourceShares /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShares">REST API Reference for GetResourceShares Operation</seealso> public virtual IAsyncResult BeginGetResourceShares(GetResourceSharesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = GetResourceSharesRequestMarshaller.Instance; options.ResponseUnmarshaller = GetResourceSharesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the GetResourceShares operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetResourceShares.</param> /// /// <returns>Returns a GetResourceSharesResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/GetResourceShares">REST API Reference for GetResourceShares Operation</seealso> public virtual GetResourceSharesResponse EndGetResourceShares(IAsyncResult asyncResult) { return EndInvoke<GetResourceSharesResponse>(asyncResult); } #endregion #region ListPendingInvitationResources /// <summary> /// Lists the resources in a resource share that is shared with you but that the invitation /// is still pending for. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPendingInvitationResources service method.</param> /// /// <returns>The response from the ListPendingInvitationResources service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException"> /// A required input parameter is missing. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException"> /// The invitation was already rejected. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException"> /// The Amazon Resource Name (ARN) for an invitation was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException"> /// The invitation is expired. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPendingInvitationResources">REST API Reference for ListPendingInvitationResources Operation</seealso> public virtual ListPendingInvitationResourcesResponse ListPendingInvitationResources(ListPendingInvitationResourcesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListPendingInvitationResourcesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPendingInvitationResourcesResponseUnmarshaller.Instance; return Invoke<ListPendingInvitationResourcesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListPendingInvitationResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPendingInvitationResources operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPendingInvitationResources /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPendingInvitationResources">REST API Reference for ListPendingInvitationResources Operation</seealso> public virtual IAsyncResult BeginListPendingInvitationResources(ListPendingInvitationResourcesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListPendingInvitationResourcesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPendingInvitationResourcesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListPendingInvitationResources operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPendingInvitationResources.</param> /// /// <returns>Returns a ListPendingInvitationResourcesResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPendingInvitationResources">REST API Reference for ListPendingInvitationResources Operation</seealso> public virtual ListPendingInvitationResourcesResponse EndListPendingInvitationResources(IAsyncResult asyncResult) { return EndInvoke<ListPendingInvitationResourcesResponse>(asyncResult); } #endregion #region ListPermissions /// <summary> /// Lists the AWS RAM permissions. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPermissions service method.</param> /// /// <returns>The response from the ListPermissions service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPermissions">REST API Reference for ListPermissions Operation</seealso> public virtual ListPermissionsResponse ListPermissions(ListPermissionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListPermissionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPermissionsResponseUnmarshaller.Instance; return Invoke<ListPermissionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListPermissions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPermissions operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPermissions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPermissions">REST API Reference for ListPermissions Operation</seealso> public virtual IAsyncResult BeginListPermissions(ListPermissionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListPermissionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPermissionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListPermissions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPermissions.</param> /// /// <returns>Returns a ListPermissionsResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPermissions">REST API Reference for ListPermissions Operation</seealso> public virtual ListPermissionsResponse EndListPermissions(IAsyncResult asyncResult) { return EndInvoke<ListPermissionsResponse>(asyncResult); } #endregion #region ListPrincipals /// <summary> /// Lists the principals that you have shared resources with or that have shared resources /// with you. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListPrincipals service method.</param> /// /// <returns>The response from the ListPrincipals service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPrincipals">REST API Reference for ListPrincipals Operation</seealso> public virtual ListPrincipalsResponse ListPrincipals(ListPrincipalsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListPrincipalsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPrincipalsResponseUnmarshaller.Instance; return Invoke<ListPrincipalsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListPrincipals operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPrincipals operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListPrincipals /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPrincipals">REST API Reference for ListPrincipals Operation</seealso> public virtual IAsyncResult BeginListPrincipals(ListPrincipalsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListPrincipalsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListPrincipalsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListPrincipals operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListPrincipals.</param> /// /// <returns>Returns a ListPrincipalsResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListPrincipals">REST API Reference for ListPrincipals Operation</seealso> public virtual ListPrincipalsResponse EndListPrincipals(IAsyncResult asyncResult) { return EndInvoke<ListPrincipalsResponse>(asyncResult); } #endregion #region ListResources /// <summary> /// Lists the resources that you added to a resource shares or the resources that are /// shared with you. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListResources service method.</param> /// /// <returns>The response from the ListResources service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidResourceTypeException"> /// The specified resource type is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResources">REST API Reference for ListResources Operation</seealso> public virtual ListResourcesResponse ListResources(ListResourcesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourcesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourcesResponseUnmarshaller.Instance; return Invoke<ListResourcesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListResources operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListResources /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResources">REST API Reference for ListResources Operation</seealso> public virtual IAsyncResult BeginListResources(ListResourcesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourcesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourcesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListResources operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListResources.</param> /// /// <returns>Returns a ListResourcesResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResources">REST API Reference for ListResources Operation</seealso> public virtual ListResourcesResponse EndListResources(IAsyncResult asyncResult) { return EndInvoke<ListResourcesResponse>(asyncResult); } #endregion #region ListResourceSharePermissions /// <summary> /// Lists the AWS RAM permissions that are associated with a resource share. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListResourceSharePermissions service method.</param> /// /// <returns>The response from the ListResourceSharePermissions service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceSharePermissions">REST API Reference for ListResourceSharePermissions Operation</seealso> public virtual ListResourceSharePermissionsResponse ListResourceSharePermissions(ListResourceSharePermissionsRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourceSharePermissionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourceSharePermissionsResponseUnmarshaller.Instance; return Invoke<ListResourceSharePermissionsResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListResourceSharePermissions operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListResourceSharePermissions operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListResourceSharePermissions /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceSharePermissions">REST API Reference for ListResourceSharePermissions Operation</seealso> public virtual IAsyncResult BeginListResourceSharePermissions(ListResourceSharePermissionsRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourceSharePermissionsRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourceSharePermissionsResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListResourceSharePermissions operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListResourceSharePermissions.</param> /// /// <returns>Returns a ListResourceSharePermissionsResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceSharePermissions">REST API Reference for ListResourceSharePermissions Operation</seealso> public virtual ListResourceSharePermissionsResponse EndListResourceSharePermissions(IAsyncResult asyncResult) { return EndInvoke<ListResourceSharePermissionsResponse>(asyncResult); } #endregion #region ListResourceTypes /// <summary> /// Lists the shareable resource types supported by AWS RAM. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListResourceTypes service method.</param> /// /// <returns>The response from the ListResourceTypes service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidNextTokenException"> /// The specified value for NextToken is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceTypes">REST API Reference for ListResourceTypes Operation</seealso> public virtual ListResourceTypesResponse ListResourceTypes(ListResourceTypesRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourceTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourceTypesResponseUnmarshaller.Instance; return Invoke<ListResourceTypesResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the ListResourceTypes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListResourceTypes operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListResourceTypes /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceTypes">REST API Reference for ListResourceTypes Operation</seealso> public virtual IAsyncResult BeginListResourceTypes(ListResourceTypesRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = ListResourceTypesRequestMarshaller.Instance; options.ResponseUnmarshaller = ListResourceTypesResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the ListResourceTypes operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListResourceTypes.</param> /// /// <returns>Returns a ListResourceTypesResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/ListResourceTypes">REST API Reference for ListResourceTypes Operation</seealso> public virtual ListResourceTypesResponse EndListResourceTypes(IAsyncResult asyncResult) { return EndInvoke<ListResourceTypesResponse>(asyncResult); } #endregion #region PromoteResourceShareCreatedFromPolicy /// <summary> /// Resource shares that were created by attaching a policy to a resource are visible /// only to the resource share owner, and the resource share cannot be modified in AWS /// RAM. /// /// /// <para> /// Use this API action to promote the resource share. When you promote the resource share, /// it becomes: /// </para> /// <ul> <li> /// <para> /// Visible to all principals that it is shared with. /// </para> /// </li> <li> /// <para> /// Modifiable in AWS RAM. /// </para> /// </li> </ul> /// </summary> /// <param name="request">Container for the necessary parameters to execute the PromoteResourceShareCreatedFromPolicy service method.</param> /// /// <returns>The response from the PromoteResourceShareCreatedFromPolicy service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException"> /// A required input parameter is missing. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/PromoteResourceShareCreatedFromPolicy">REST API Reference for PromoteResourceShareCreatedFromPolicy Operation</seealso> public virtual PromoteResourceShareCreatedFromPolicyResponse PromoteResourceShareCreatedFromPolicy(PromoteResourceShareCreatedFromPolicyRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = PromoteResourceShareCreatedFromPolicyRequestMarshaller.Instance; options.ResponseUnmarshaller = PromoteResourceShareCreatedFromPolicyResponseUnmarshaller.Instance; return Invoke<PromoteResourceShareCreatedFromPolicyResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the PromoteResourceShareCreatedFromPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PromoteResourceShareCreatedFromPolicy operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndPromoteResourceShareCreatedFromPolicy /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/PromoteResourceShareCreatedFromPolicy">REST API Reference for PromoteResourceShareCreatedFromPolicy Operation</seealso> public virtual IAsyncResult BeginPromoteResourceShareCreatedFromPolicy(PromoteResourceShareCreatedFromPolicyRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = PromoteResourceShareCreatedFromPolicyRequestMarshaller.Instance; options.ResponseUnmarshaller = PromoteResourceShareCreatedFromPolicyResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the PromoteResourceShareCreatedFromPolicy operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginPromoteResourceShareCreatedFromPolicy.</param> /// /// <returns>Returns a PromoteResourceShareCreatedFromPolicyResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/PromoteResourceShareCreatedFromPolicy">REST API Reference for PromoteResourceShareCreatedFromPolicy Operation</seealso> public virtual PromoteResourceShareCreatedFromPolicyResponse EndPromoteResourceShareCreatedFromPolicy(IAsyncResult asyncResult) { return EndInvoke<PromoteResourceShareCreatedFromPolicyResponse>(asyncResult); } #endregion #region RejectResourceShareInvitation /// <summary> /// Rejects an invitation to a resource share from another AWS account. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RejectResourceShareInvitation service method.</param> /// /// <returns>The response from the RejectResourceShareInvitation service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyAcceptedException"> /// The invitation was already accepted. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationAlreadyRejectedException"> /// The invitation was already rejected. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationArnNotFoundException"> /// The Amazon Resource Name (ARN) for an invitation was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceShareInvitationExpiredException"> /// The invitation is expired. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/RejectResourceShareInvitation">REST API Reference for RejectResourceShareInvitation Operation</seealso> public virtual RejectResourceShareInvitationResponse RejectResourceShareInvitation(RejectResourceShareInvitationRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = RejectResourceShareInvitationRequestMarshaller.Instance; options.ResponseUnmarshaller = RejectResourceShareInvitationResponseUnmarshaller.Instance; return Invoke<RejectResourceShareInvitationResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the RejectResourceShareInvitation operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RejectResourceShareInvitation operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndRejectResourceShareInvitation /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/RejectResourceShareInvitation">REST API Reference for RejectResourceShareInvitation Operation</seealso> public virtual IAsyncResult BeginRejectResourceShareInvitation(RejectResourceShareInvitationRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = RejectResourceShareInvitationRequestMarshaller.Instance; options.ResponseUnmarshaller = RejectResourceShareInvitationResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the RejectResourceShareInvitation operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginRejectResourceShareInvitation.</param> /// /// <returns>Returns a RejectResourceShareInvitationResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/RejectResourceShareInvitation">REST API Reference for RejectResourceShareInvitation Operation</seealso> public virtual RejectResourceShareInvitationResponse EndRejectResourceShareInvitation(IAsyncResult asyncResult) { return EndInvoke<RejectResourceShareInvitationResponse>(asyncResult); } #endregion #region TagResource /// <summary> /// Adds the specified tags to the specified resource share that you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the TagResource service method.</param> /// /// <returns>The response from the TagResource service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ResourceArnNotFoundException"> /// An Amazon Resource Name (ARN) was not found. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.TagLimitExceededException"> /// The requested tags exceed the limit for your account. /// </exception> /// <exception cref="Amazon.RAM.Model.TagPolicyViolationException"> /// The specified tag is a reserved word and cannot be used. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse TagResource(TagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return Invoke<TagResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TagResource operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndTagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/TagResource">REST API Reference for TagResource Operation</seealso> public virtual IAsyncResult BeginTagResource(TagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = TagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = TagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the TagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginTagResource.</param> /// /// <returns>Returns a TagResourceResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/TagResource">REST API Reference for TagResource Operation</seealso> public virtual TagResourceResponse EndTagResource(IAsyncResult asyncResult) { return EndInvoke<TagResourceResponse>(asyncResult); } #endregion #region UntagResource /// <summary> /// Removes the specified tags from the specified resource share that you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UntagResource service method.</param> /// /// <returns>The response from the UntagResource service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse UntagResource(UntagResourceRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return Invoke<UntagResourceResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UntagResource operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUntagResource /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual IAsyncResult BeginUntagResource(UntagResourceRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = UntagResourceRequestMarshaller.Instance; options.ResponseUnmarshaller = UntagResourceResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the UntagResource operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUntagResource.</param> /// /// <returns>Returns a UntagResourceResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UntagResource">REST API Reference for UntagResource Operation</seealso> public virtual UntagResourceResponse EndUntagResource(IAsyncResult asyncResult) { return EndInvoke<UntagResourceResponse>(asyncResult); } #endregion #region UpdateResourceShare /// <summary> /// Updates the specified resource share that you own. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateResourceShare service method.</param> /// /// <returns>The response from the UpdateResourceShare service method, as returned by RAM.</returns> /// <exception cref="Amazon.RAM.Model.IdempotentParameterMismatchException"> /// A client token input parameter was reused with an operation, but at least one of the /// other input parameters is different from the previous call to the operation. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidClientTokenException"> /// A client token is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.InvalidParameterException"> /// A parameter is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MalformedArnException"> /// The format of an Amazon Resource Name (ARN) is not valid. /// </exception> /// <exception cref="Amazon.RAM.Model.MissingRequiredParameterException"> /// A required input parameter is missing. /// </exception> /// <exception cref="Amazon.RAM.Model.OperationNotPermittedException"> /// The requested operation is not permitted. /// </exception> /// <exception cref="Amazon.RAM.Model.ServerInternalException"> /// The service could not respond to the request due to an internal problem. /// </exception> /// <exception cref="Amazon.RAM.Model.ServiceUnavailableException"> /// The service is not available. /// </exception> /// <exception cref="Amazon.RAM.Model.UnknownResourceException"> /// A specified resource was not found. /// </exception> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UpdateResourceShare">REST API Reference for UpdateResourceShare Operation</seealso> public virtual UpdateResourceShareResponse UpdateResourceShare(UpdateResourceShareRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateResourceShareResponseUnmarshaller.Instance; return Invoke<UpdateResourceShareResponse>(request, options); } /// <summary> /// Initiates the asynchronous execution of the UpdateResourceShare operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateResourceShare operation on AmazonRAMClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateResourceShare /// operation.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UpdateResourceShare">REST API Reference for UpdateResourceShare Operation</seealso> public virtual IAsyncResult BeginUpdateResourceShare(UpdateResourceShareRequest request, AsyncCallback callback, object state) { var options = new InvokeOptions(); options.RequestMarshaller = UpdateResourceShareRequestMarshaller.Instance; options.ResponseUnmarshaller = UpdateResourceShareResponseUnmarshaller.Instance; return BeginInvoke(request, options, callback, state); } /// <summary> /// Finishes the asynchronous execution of the UpdateResourceShare operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateResourceShare.</param> /// /// <returns>Returns a UpdateResourceShareResult from RAM.</returns> /// <seealso href="http://docs.aws.amazon.com/goto/WebAPI/ram-2018-01-04/UpdateResourceShare">REST API Reference for UpdateResourceShare Operation</seealso> public virtual UpdateResourceShareResponse EndUpdateResourceShare(IAsyncResult asyncResult) { return EndInvoke<UpdateResourceShareResponse>(asyncResult); } #endregion } }
57.248335
201
0.663609
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/RAM/Generated/_bcl35/AmazonRAMClient.cs
120,336
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Elevator : MonoBehaviour { [SerializeField] Transform depositLocation; [SerializeField] Deposit elevatorDeposit; [SerializeField] ElevatorMiner elevatorMiner; public Transform DepositLocation => depositLocation; public Deposit ElevatorDeposit => elevatorDeposit; public ElevatorMiner ElevatorMiner => elevatorMiner; }
29.133333
56
0.791762
[ "MIT" ]
IHunelI/-Prototype-IdleMinerTycoon
IdleClicker/Assets/Scripts/Elevator/Elevator.cs
439
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class EndButton : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { GameObject player = GameObject.Find("Player"); Vector3 playFloor = player.transform.position + Vector3.down; if (playFloor == transform.position){ //End Game SceneManager.LoadScene("StartScreen"); } } }
21.961538
69
0.642732
[ "MIT" ]
sagar5534/Ilsa-Journey
Ilsa's Journey/Assets/Scripts/EndButton.cs
573
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.ApplicationInsights.Extensibility; namespace CacheMeIfYouCan.Redis { public sealed class DistributedCacheApplicationInsightsWrapper<TKey, TValue> : DistributedCacheEventsWrapperBase<TKey, TValue> { private readonly TelemetryProcessor _telemetryProcessor; public DistributedCacheApplicationInsightsWrapper(IDistributedCache<TKey, TValue> innerCache, IDistributedCacheConfig cacheConfig, ITelemetryProcessor telemetryProcessor, ITelemetryConfig telemetryConfig) : base(innerCache) { _telemetryProcessor = new TelemetryProcessor(cacheConfig, telemetryProcessor, telemetryConfig); } protected override void OnTryGetCompletedSuccessfully(TKey key, bool resultSuccess, ValueAndTimeToLive<TValue> resultValue, TimeSpan duration) { _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", $"Key '{key}'", true); base.OnTryGetCompletedSuccessfully(key, resultSuccess, resultValue, duration); } protected override void OnSetManyCompletedSuccessfully(ReadOnlySpan<KeyValuePair<TKey, TValue>> values, TimeSpan timeToLive, TimeSpan duration) { var keys = $"Keys '{string.Join(",", values.ToArray().Select(d => d.Key))}'"; _telemetryProcessor.Add(duration, "StringSetAsync", keys, true); base.OnSetManyCompletedSuccessfully(values, timeToLive, duration); } protected override void OnGetManyCompletedSuccessfully(ReadOnlySpan<TKey> keys, ReadOnlySpan<KeyValuePair<TKey, ValueAndTimeToLive<TValue>>> values, TimeSpan duration) { var keysText = $"Keys '{string.Join(",", keys.ToArray())}'"; _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", keysText, true); base.OnGetManyCompletedSuccessfully(keys, values, duration); } protected override void OnGetManyException(ReadOnlySpan<TKey> keys, TimeSpan duration, Exception exception, out bool exceptionHandled) { var keysText = $"Keys '{string.Join(",", keys.ToArray())}'"; _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", keysText, false); base.OnGetManyException(keys, duration, exception, out exceptionHandled); } protected override void OnSetCompletedSuccessfully(TKey key, TValue value, TimeSpan timeToLive, TimeSpan duration) { _telemetryProcessor.Add(duration, "StringSetAsync", $"Key '{key}'", true); base.OnSetCompletedSuccessfully(key, value, timeToLive, duration); } protected override void OnSetException(TKey key, TValue value, TimeSpan timeToLive, TimeSpan duration, Exception exception, out bool exceptionHandled) { _telemetryProcessor.Add(duration, "StringSetAsync", $"Key '{key}'", false); base.OnSetException(key, value, timeToLive, duration, exception, out exceptionHandled); } protected override void OnSetManyException(ReadOnlySpan<KeyValuePair<TKey, TValue>> values, TimeSpan timeToLive, TimeSpan duration, Exception exception, out bool exceptionHandled) { var keys = $"Keys '{string.Join(",", values.ToArray().Select(d => d.Key))}'"; _telemetryProcessor.Add(duration, "StringSetAsync", keys, false); base.OnSetManyException(values, timeToLive, duration, exception, out exceptionHandled); } protected override void OnTryGetException(TKey key, TimeSpan duration, Exception exception, out bool exceptionHandled) { _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", $"Key '{key}'", false); base.OnTryGetException(key, duration, exception, out exceptionHandled); } protected override void OnTryRemoveCompletedSuccessfully(TKey key, bool wasRemoved, TimeSpan duration) { _telemetryProcessor.Add(duration, "KeyDeleteAsync", $"Key '{key}'", true); base.OnTryRemoveCompletedSuccessfully(key, wasRemoved, duration); } protected override void OnTryRemoveException(TKey key, TimeSpan duration, Exception exception, out bool exceptionHandled) { _telemetryProcessor.Add(duration, "KeyDeleteAsync", $"Key '{key}'", false); base.OnTryRemoveException(key, duration, exception, out exceptionHandled); } } public sealed class DistributedCacheApplicationInsightsWrapper<TOuterKey, TInnerKey, TValue> : DistributedCacheEventsWrapperBase<TOuterKey, TInnerKey, TValue> { private readonly TelemetryProcessor _telemetryProcessor; public DistributedCacheApplicationInsightsWrapper(IDistributedCache<TOuterKey, TInnerKey, TValue> innerCache, IDistributedCacheConfig cacheConfig, ITelemetryProcessor telemetryProcessor, ITelemetryConfig telemetryConfig) : base(innerCache) { _telemetryProcessor = new TelemetryProcessor(cacheConfig, telemetryProcessor, telemetryConfig); } protected override void OnSetManyException(TOuterKey outerKey, ReadOnlySpan<KeyValuePair<TInnerKey, TValue>> values, TimeSpan timeToLive, TimeSpan duration, Exception exception, out bool exceptionHandled) { var keys = $"Keys {string.Join(",", values.ToArray().Select(innerKeyValue => $"'{outerKey}.{innerKeyValue.Key}'"))}"; _telemetryProcessor.Add(duration, "StringSetAsync", keys, false); base.OnSetManyException(outerKey, values, timeToLive, duration, exception, out exceptionHandled); } protected override void OnTryRemoveCompletedSuccessfully(TOuterKey outerKey, TInnerKey innerKey, bool wasRemoved, TimeSpan duration) { _telemetryProcessor.Add(duration, "KeyDeleteAsync", $"Key '{outerKey}.{innerKey}'", true); base.OnTryRemoveCompletedSuccessfully(outerKey, innerKey, wasRemoved, duration); } protected override void OnTryRemoveException(TOuterKey outerKey, TInnerKey innerKey, TimeSpan duration, Exception exception, out bool exceptionHandled) { _telemetryProcessor.Add(duration, "KeyDeleteAsync", $"Key '{outerKey}.{innerKey}'", false); base.OnTryRemoveException(outerKey, innerKey, duration, exception, out exceptionHandled); } protected override void OnGetManyException(TOuterKey outerKey, ReadOnlySpan<TInnerKey> innerKeys, TimeSpan duration, Exception exception, out bool exceptionHandled) { var keys = $"Keys {string.Join(",", innerKeys.ToArray().Select(innerKey => $"'{outerKey}.{innerKey}'"))}"; _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", keys, false); base.OnGetManyException(outerKey, innerKeys, duration, exception, out exceptionHandled); } protected override void OnSetManyCompletedSuccessfully(TOuterKey outerKey, ReadOnlySpan<KeyValuePair<TInnerKey, TValue>> values, TimeSpan timeToLive, TimeSpan duration) { var keys = $"Keys {string.Join(",", values.ToArray().Select(innerKeyValue => $"'{outerKey}.{innerKeyValue.Key}'"))}"; _telemetryProcessor.Add(duration, "StringSetAsync", keys, true); base.OnSetManyCompletedSuccessfully(outerKey, values, timeToLive, duration); } protected override void OnGetManyCompletedSuccessfully(TOuterKey outerKey, ReadOnlySpan<TInnerKey> innerKeys, ReadOnlySpan<KeyValuePair<TInnerKey, ValueAndTimeToLive<TValue>>> values, TimeSpan duration) { var keys = $"Keys {string.Join(",", innerKeys.ToArray().Select(innerKey => $"'{outerKey}.{innerKey}'"))}"; _telemetryProcessor.Add(duration, "StringGetWithExpiryAsync", keys, true); base.OnGetManyCompletedSuccessfully(outerKey, innerKeys, values, duration); } } }
44.385027
122
0.675542
[ "MIT" ]
ncomben/CacheMeIfYouCan
src/CacheMeIfYouCan.Redis/DistributedCacheApplicationInsightsWrapper.cs
8,302
C#
// SPDX-License-Identifier: MIT // The content of this file has been developed in the context of the MOSIM research project. // Original author(s): Felix Gaisbauer using MMIStandard; using System; using System.Collections.Generic; namespace MMICoSimulation { /// <summary> /// A container class representing an individual frame of the co-simulation /// </summary> [Serializable] public class CoSimulationFrame { /// <summary> /// The initial posture /// </summary> public MAvatarPostureValues Initial; /// <summary> /// The absolute simulation time /// </summary> public TimeSpan Time; /// <summary> /// The frame number /// </summary> public int FrameNumber; /// <summary> /// All individual results /// </summary> public List<MSimulationResult> Results; /// <summary> /// The merged result /// </summary> public MSimulationResult MergedResult; /// <summary> /// The results gathered form the cosimulation solvers /// </summary> public List<MSimulationResult> CoSimulationSolverResults; /// <summary> /// The ids of the corresponding instructions /// </summary> public List<string> Instructions; /// <summary> /// Basic constructor /// </summary> /// <param name="frameNumber"></param> /// <param name="time"></param> public CoSimulationFrame(int frameNumber, TimeSpan time) { this.FrameNumber = frameNumber; this.Time = time; this.Results = new List<MSimulationResult>(); this.Instructions = new List<string>(); this.CoSimulationSolverResults = new List<MSimulationResult>(); } } }
26.394366
92
0.580043
[ "MIT" ]
Daimler/MOSIM_Core
CoSimulation/MMICoSimulation/CoSimulationFrame.cs
1,876
C#
using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace MahApps.Metro.Controls { /// <summary> /// Defines a helper class for selected items binding on collections with multiselector elements /// </summary> public static class MultiSelectorHelper { public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached( "SelectedItems", typeof(IList), typeof(MultiSelectorHelper), new FrameworkPropertyMetadata(null, OnSelectedItemsChanged)); /// <summary> /// Handles disposal and creation of old and new bindings /// </summary> private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(d is ListBox || d is MultiSelector)) throw new ArgumentException("The property 'SelectedItems' may only be set on ListBox or MultiSelector elements."); if (e.OldValue != e.NewValue) { var oldBinding = GetSelectedItemBinding(d); oldBinding?.UnBind(); var multiSelectorBinding = new MultiSelectorBinding((Selector)d, (IList)e.NewValue); SetSelectedItemBinding(d, multiSelectorBinding); multiSelectorBinding.Bind(); } } /// <summary> /// Gets the selected items property binding /// </summary> [Category(AppName.MahApps)] [AttachedPropertyBrowsableForType(typeof(ListBox))] [AttachedPropertyBrowsableForType(typeof(MultiSelector))] public static IList GetSelectedItems(DependencyObject element) { return (IList)element.GetValue(SelectedItemsProperty); } /// <summary> /// Sets the selected items property binding /// </summary> [Category(AppName.MahApps)] [AttachedPropertyBrowsableForType(typeof(ListBox))] [AttachedPropertyBrowsableForType(typeof(MultiSelector))] public static void SetSelectedItems(DependencyObject element, IList value) { element.SetValue(SelectedItemsProperty, value); } private static readonly DependencyProperty SelectedItemBindingProperty = DependencyProperty.RegisterAttached( "SelectedItemBinding", typeof(MultiSelectorBinding), typeof(MultiSelectorHelper)); /// <summary> /// Gets the <see cref="MultiSelectorBinding"/> for a binding /// </summary> [AttachedPropertyBrowsableForType(typeof(ListBox))] [AttachedPropertyBrowsableForType(typeof(MultiSelector))] private static MultiSelectorBinding GetSelectedItemBinding(DependencyObject element) { return (MultiSelectorBinding)element.GetValue(SelectedItemBindingProperty); } /// <summary> /// Sets the <see cref="MultiSelectorBinding"/> for a bining /// </summary> [AttachedPropertyBrowsableForType(typeof(ListBox))] [AttachedPropertyBrowsableForType(typeof(MultiSelector))] private static void SetSelectedItemBinding(DependencyObject element, MultiSelectorBinding value) { element.SetValue(SelectedItemBindingProperty, value); } /// <summary> /// Defines a binding between multi selector and property /// </summary> private class MultiSelectorBinding { private readonly Selector _selector; private readonly IList _collection; /// <summary> /// Creates an instance of <see cref="MultiSelectorBinding"/> /// </summary> /// <param name="selector">The selector of this binding</param> /// <param name="collection">The bound collection</param> public MultiSelectorBinding(Selector selector, IList collection) { _selector = selector; _collection = collection; if (selector is ListBox listbox) { listbox.SelectedItems.Clear(); foreach (var newItem in collection) { listbox.SelectedItems.Add(newItem); } } else if (_selector is MultiSelector multiSelector) { multiSelector.SelectedItems.Clear(); foreach (var newItem in collection) { multiSelector.SelectedItems.Add(newItem); } } } /// <summary> /// Registers the event handlers for selector and collection changes /// </summary> public void Bind() { // prevent multiple event registration UnBind(); _selector.SelectionChanged += OnSelectionChanged; if (_collection is INotifyCollectionChanged notifyCollection) { notifyCollection.CollectionChanged += this.OnCollectionChanged; } } /// <summary> /// Unregisters the event handlers for selector and collection changes /// </summary> public void UnBind() { _selector.SelectionChanged -= OnSelectionChanged; if (_collection is INotifyCollectionChanged notifyCollection) { notifyCollection.CollectionChanged -= this.OnCollectionChanged; } } /// <summary> /// Updates the collection with changes made in the selector /// </summary> private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var notifyCollection = _collection as INotifyCollectionChanged; if (notifyCollection != null) { notifyCollection.CollectionChanged -= this.OnCollectionChanged; } try { foreach (var oldItem in e.RemovedItems) { _collection.Remove(oldItem); } foreach (var newItem in e.AddedItems) { _collection.Add(newItem); } } finally { if (notifyCollection != null) { notifyCollection.CollectionChanged += this.OnCollectionChanged; } } } /// <summary> /// Updates the selector with changes made in the collection /// </summary> private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { _selector.SelectionChanged -= OnSelectionChanged; try { if (_selector is ListBox listBox) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var newItem in e.NewItems) { listBox.SelectedItems.Add(newItem); } break; case NotifyCollectionChangedAction.Remove: foreach (var oldItem in e.OldItems) { listBox.SelectedItems.Remove(oldItem); } break; case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: RemoveItems(listBox.SelectedItems, e); AddItems(listBox.SelectedItems, e); break; case NotifyCollectionChangedAction.Reset: listBox.SelectedItems.Clear(); break; } } else if (_selector is MultiSelector multiSelector) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var newItem in e.NewItems) { multiSelector.SelectedItems.Add(newItem); } break; case NotifyCollectionChangedAction.Remove: foreach (var oldItem in e.OldItems) { multiSelector.SelectedItems.Remove(oldItem); } break; case NotifyCollectionChangedAction.Move: case NotifyCollectionChangedAction.Replace: RemoveItems(multiSelector.SelectedItems, e); AddItems(multiSelector.SelectedItems, e); break; case NotifyCollectionChangedAction.Reset: multiSelector.SelectedItems.Clear(); break; } } } finally { _selector.SelectionChanged += OnSelectionChanged; } } private static void RemoveItems(IList list, NotifyCollectionChangedEventArgs e) { var itemCount = e.OldItems.Count; // For the number of items being removed, remove the item from the old starting index // (this will cause following items to be shifted down to fill the hole). for (var i = 0; i < itemCount; i++) { list.RemoveAt(e.OldStartingIndex); } } private static void AddItems(IList list, NotifyCollectionChangedEventArgs e) { var itemCount = e.NewItems.Count; for (var i = 0; i < itemCount; i++) { var insertionPoint = e.NewStartingIndex + i; if (insertionPoint > list.Count) { list.Add(e.NewItems[i]); } else { list.Insert(insertionPoint, e.NewItems[i]); } } } } } }
38.889655
169
0.497606
[ "MIT" ]
Fleetingold/MahApps.Metro
src/MahApps.Metro/Controls/Helper/MultiSelectorHelper.cs
11,280
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("WnMAiModule")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WnMAiModule")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("53e05140-aa25-490c-9ff5-f9d21291b224")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.486486
56
0.71474
[ "MIT" ]
michaelgx2/wnmai
WnMAiModule/Properties/AssemblyInfo.cs
1,284
C#
// *********************************************************************** // Assembly : Noob.Core // Author : Administrator // Created : 2020-04-19 // // Last Modified By : Administrator // Last Modified On : 2020-04-19 // *********************************************************************** // <copyright file="IDatabaseApiContainer.cs" company="Noob.Core"> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** using System; using JetBrains.Annotations; using Noob.DependencyInjection; namespace Noob.Uow { /// <summary> /// Interface IDatabaseApiContainer /// Implements the <see cref="Noob.DependencyInjection.IServiceProviderAccessor" /> /// </summary> /// <seealso cref="Noob.DependencyInjection.IServiceProviderAccessor" /> public interface IDatabaseApiContainer : IServiceProviderAccessor { /// <summary> /// Finds the database API. /// </summary> /// <param name="key">The key.</param> /// <returns>IDatabaseApi.</returns> [CanBeNull] IDatabaseApi FindDatabaseApi([NotNull] string key); /// <summary> /// Adds the database API. /// </summary> /// <param name="key">The key.</param> /// <param name="api">The API.</param> void AddDatabaseApi([NotNull] string key, [NotNull] IDatabaseApi api); /// <summary> /// Gets the or add database API. /// </summary> /// <param name="key">The key.</param> /// <param name="factory">The factory.</param> /// <returns>IDatabaseApi.</returns> [NotNull] IDatabaseApi GetOrAddDatabaseApi([NotNull] string key, [NotNull] Func<IDatabaseApi> factory); } }
35.941176
101
0.533552
[ "MIT" ]
noobwu/DncZeus
Noob.Core/Uow/IDatabaseApiContainer.cs
1,835
C#
using UnityEngine; using UnityEditor; using System.Collections.Generic; /* * Unity extension to set a custom font. * Set by using the information of fnt file bmfont outputs. * * Install: * Copy to Assets\Editor\ , this script. * * Use: * Custom -> Custom Font Setting -> Chr Rect Set. * * D&D, "Custom Font", "font texture" and "fnt file(.txt)" * Push "Set" button. * * or split. * D&D, "Custom Font" and "font texture". * input, Use Texture Area, Count X, Count Y and Char Length. * Push "Set" button. * * License: * Public Domain. */ public class ChrRectSet : EditorWindow { public Font customFontObj; public TextAsset fontPosTbl; public Texture fontTexture; public bool xoffsetEnable = true; public Vector2 scrollPos; public Rect useTexRect = new Rect(0, 0, 256, 256); public int fontCountX = 8; public int fontCountY = 8; public int fontLength = 64; struct ChrRect { public int id; public int x; public int y; public int w; public int h; public int xofs; public int yofs; public int index; public float uvX; public float uvY; public float uvW; public float uvH; public float vertX; public float vertY; public float vertW; public float vertH; public float width; } // add menu [MenuItem("Custom/Custom Font Setting/Chr Rect Set")] static void Init() { EditorWindow.GetWindow(typeof(ChrRectSet)); } // layout window void OnGUI() { EditorGUILayout.BeginScrollView(scrollPos); // use .fnt(.txt) customFontObj = (Font)EditorGUILayout.ObjectField("Custom Font", customFontObj, typeof(Font), false); fontTexture = (Texture)EditorGUILayout.ObjectField("Font Texture", fontTexture, typeof(Texture), false); EditorGUILayout.Space(); EditorGUILayout.LabelField("Use BMFont fnt File", EditorStyles.boldLabel); fontPosTbl = (TextAsset)EditorGUILayout.ObjectField("BMFont fnt (.txt)", fontPosTbl, typeof(TextAsset), false); xoffsetEnable = EditorGUILayout.Toggle("xoffset Enable", xoffsetEnable); if (GUILayout.Button("Set Character Rects")) { if (customFontObj == null) this.ShowNotification(new GUIContent("No Custom Font selected")); else if (fontTexture == null) this.ShowNotification(new GUIContent("No Font Texture selected")); else if (fontPosTbl == null) this.ShowNotification(new GUIContent("No Font Position Table file selected")); else { CalcChrRect(customFontObj, fontPosTbl, fontTexture); } } // split EditorGUILayout.Space(); EditorGUILayout.LabelField("Grid Layout", EditorStyles.boldLabel); useTexRect = EditorGUILayout.RectField("Use Texture Area", useTexRect); fontCountX = EditorGUILayout.IntField("Font Count X", fontCountX); fontCountY = EditorGUILayout.IntField("Font Count Y", fontCountY); fontLength = EditorGUILayout.IntField("Character Length", fontLength); if (GUILayout.Button("Set Character Rects")) { if (customFontObj == null) this.ShowNotification(new GUIContent("No Custom Font selected")); else if (fontTexture == null) this.ShowNotification(new GUIContent("No Font Texture selected")); else CalcChrRectGrid(customFontObj, fontTexture, useTexRect, fontCountX, fontCountY, fontLength); } EditorGUILayout.EndScrollView(); } void OnInspectorUpdate() { this.Repaint(); } // set by .fnt(.txt) void CalcChrRect(Font fontObj, TextAsset posTbl, Texture tex) { float imgw = (float)tex.width; float imgh = (float)tex.height; string txt = posTbl.text; List<ChrRect> tblList = new List<ChrRect>(); int asciiStartOffset = int.MaxValue; int maxH = 0; foreach (string line in txt.Split('\n')) { if (line.IndexOf("char id=") == 0) { ChrRect d = GetChrRect(line, imgw, imgh); if (asciiStartOffset > d.id) asciiStartOffset = d.id; if (maxH < d.h) maxH = d.h; tblList.Add(d); } } ChrRect[] tbls = tblList.ToArray(); // index value for (int i = 0; i < tbls.Length; i++) { tbls[i].index = tbls[i].id - asciiStartOffset; } // make new CharacterInfo SetCharacterInfo(tbls, fontObj); // fontObj.asciiStartOffset = asciiStartOffset; this.ShowNotification(new GUIContent("Complete")); } // set by split void CalcChrRectGrid(Font fontObj, Texture tex, Rect area, int xc, int yc, int num) { float imgw = (float)tex.width; float imgh = (float)tex.height; int fw = (int)(area.width - area.x) / xc; int fh = (int)(area.height - area.y) / yc; List<ChrRect> tblList = new List<ChrRect>(); for (int i = 0; i < num; i++) { int xi = i % xc; int yi = i / xc; ChrRect d = new ChrRect(); d.index = i; d.uvX = (float)(area.x + (fw * xi)) / imgw; d.uvY = (float)(imgh - (area.y + (fh * yi) + fh)) / imgh; d.uvW = (float)fw / imgw; d.uvH = (float)fh / imgh; d.vertX = 0; d.vertY = 0; d.vertW = fw; d.vertH = -fh; d.width = fw; tblList.Add(d); } ChrRect[] tbls = tblList.ToArray(); SetCharacterInfo(tbls, fontObj); this.ShowNotification(new GUIContent("Complete")); } // over write custom font by new CharacterInfo void SetCharacterInfo(ChrRect[] tbls, Font fontObj) { CharacterInfo[] nci = new CharacterInfo[tbls.Length]; for (int i = 0; i < tbls.Length; i++) { nci[i].index = tbls[i].index; nci[i].width = tbls[i].width; nci[i].uv.x = tbls[i].uvX; nci[i].uv.y = tbls[i].uvY; nci[i].uv.width = tbls[i].uvW; nci[i].uv.height = tbls[i].uvH; nci[i].vert.x = tbls[i].vertX; nci[i].vert.y = tbls[i].vertY; nci[i].vert.width = tbls[i].vertW; nci[i].vert.height = tbls[i].vertH; } fontObj.characterInfo = nci; } // get font table one line. ChrRect GetChrRect(string line, float imgw, float imgh) { ChrRect d = new ChrRect(); foreach (string s in line.Split(' ')) { if (s.IndexOf("id=") >= 0) d.id = GetParamInt(s, "id="); else if (s.IndexOf("x=") >= 0) d.x = GetParamInt(s, "x="); else if (s.IndexOf("y=") >= 0) d.y = GetParamInt(s, "y="); else if (s.IndexOf("width=") >= 0) d.w = GetParamInt(s, "width="); else if (s.IndexOf("height=") >= 0) d.h = GetParamInt(s, "height="); else if (s.IndexOf("xoffset=") >= 0) d.xofs = GetParamInt(s, "xoffset="); else if (s.IndexOf("yoffset=") >= 0) d.yofs = GetParamInt(s, "yoffset="); else if (s.IndexOf("xadvance=") >= 0) d.width = GetParamInt(s, "xadvance="); } d.uvX = (float)d.x / imgw; d.uvY = (float)(imgh - d.y - d.h) / imgh; d.uvW = (float)d.w / imgw; d.uvH = (float)d.h / imgh; d.vertX = (xoffsetEnable) ? (float)d.xofs : 0.0f; d.vertY = -(float)d.yofs; d.vertW = d.w; d.vertH = -d.h; return d; } // "wd=int" to int int GetParamInt(string s, string wd) { if (s.IndexOf(wd) >= 0) { int v; if (int.TryParse(s.Substring(wd.Length), out v)) return v; } return int.MaxValue; } }
35.678899
119
0.567884
[ "MIT" ]
buzzler/titan
Assets/Editor/ChrRectSet.cs
7,780
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("02.ReverseNumbersWithStack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02.ReverseNumbersWithStack")] [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("d664740f-ec0e-437c-be94-f0753233c4e1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.513514
84
0.748772
[ "MIT" ]
EmilMitev/Telerik-Academy
DSA/Homeworks/02. Linear-Data-Structures/LinearDataStructures/02.ReverseNumbersWithStack/Properties/AssemblyInfo.cs
1,428
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZY.Framework.Data.ICommon { /// <summary> /// 数据上下文工厂接口 /// </summary> /// <typeparam name="TContext"></typeparam> public interface IDbContextFactory<TContext> where TContext : new() { TContext GetDbContext(); } }
21
71
0.674603
[ "MIT" ]
lovepoco/ZYFW
Code/ZY.Framework.Data.ICommon/IDbContextFactory.cs
398
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v8.6.4 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder.Embedded; namespace Umbraco.Web.PublishedModels { /// <summary>Person</summary> [PublishedModel("person")] public partial class Person : PublishedContentModel, INavigationBase { // helpers #pragma warning disable 0109 // new is redundant [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] public new const string ModelTypeAlias = "person"; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] public new const PublishedItemType ModelItemType = PublishedItemType.Content; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] public new static IPublishedContentType GetModelContentType() => PublishedModelUtility.GetModelContentType(ModelItemType, ModelTypeAlias); [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] public static IPublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Person, TValue>> selector) => PublishedModelUtility.GetModelPropertyType(GetModelContentType(), selector); #pragma warning restore 0109 // ctor public Person(IPublishedContent content) : base(content) { } // properties ///<summary> /// Department ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("department")] public global::System.Collections.Generic.IEnumerable<string> Department => this.Value<global::System.Collections.Generic.IEnumerable<string>>("department"); ///<summary> /// Email ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("email")] public string Email => this.Value<string>("email"); ///<summary> /// Facebook username ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("facebookUsername")] public string FacebookUsername => this.Value<string>("facebookUsername"); ///<summary> /// Instagram Username ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("instagramUsername")] public string InstagramUsername => this.Value<string>("instagramUsername"); ///<summary> /// LinkedIn username ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("linkedInUsername")] public string LinkedInUsername => this.Value<string>("linkedInUsername"); ///<summary> /// Photo ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("photo")] public global::Umbraco.Core.Models.PublishedContent.IPublishedContent Photo => this.Value<global::Umbraco.Core.Models.PublishedContent.IPublishedContent>("photo"); ///<summary> /// Twitter username ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("twitterUsername")] public string TwitterUsername => this.Value<string>("twitterUsername"); ///<summary> /// Keywords: Keywords that describe the content of the page. This is considered optional since most modern search engines don't use this anymore ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("keywords")] public global::System.Collections.Generic.IEnumerable<string> Keywords => global::Umbraco.Web.PublishedModels.NavigationBase.GetKeywords(this); ///<summary> /// Description: A brief description of the content on your page. This text is shown below the title in a google search result and also used for Social Sharing Cards. The ideal length is between 130 and 155 characters ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("seoMetaDescription")] public string SeoMetaDescription => global::Umbraco.Web.PublishedModels.NavigationBase.GetSeoMetaDescription(this); ///<summary> /// Hide in Navigation: If you don't want this page to appear in the navigation, check this box ///</summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Umbraco.ModelsBuilder", "8.6.4")] [ImplementPropertyType("umbracoNavihide")] public bool UmbracoNavihide => global::Umbraco.Web.PublishedModels.NavigationBase.GetUmbracoNavihide(this); } }
43.398305
219
0.732474
[ "MIT" ]
OwainWilliams/multipleDatePicker
multipleDatePicker.Web/App_Data/Models/Person.generated.cs
5,121
C#
namespace JewelleryShop.Web.ViewModels.Products { using Common.Mapping; using Microsoft.AspNetCore.Http; using Services.Products.Models; using System.ComponentModel.DataAnnotations; using static WebConstants; public class ProductFormViewModel : IMapFrom<ProductDetailsServiceModel> { [Required(ErrorMessage = TitleError)] public string Title { get; set; } [Required(ErrorMessage = DescriptionError)] public string Description { get; set; } [Required(ErrorMessage = PurchaseNumberError)] public string PurchaseNumber { get; set; } [Required(ErrorMessage = PriceError)] [Range(0, double.MaxValue)] public decimal Price { get; set; } public IFormFile Image { get; set; } public bool IsEditModel { get; set; } public string ImagePath { get; set; } } }
27.65625
76
0.663277
[ "MIT" ]
stefanMinch3v/MiniWebShops
src/JewelleryShop/Web/JewelleryShop.Web/ViewModels/Products/ProductFormViewModel.cs
887
C#
using System; using System.Collections.Generic; using System.Text; using System.Web; namespace Cumulocity.SDK.Client { public class TemplateUrlParser { public static string encode(string value) { try { return HttpUtility.UrlEncode(value, Encoding.UTF8); } catch (Exception e) { throw new Exception("UTF-8 is not supported!?", e); } } public virtual string replacePlaceholdersWithParams(string template, IDictionary<string, string> @params) { foreach (var entry in @params) { template = replaceAll(template, asPattern(entry.Key), encode(entry.Value)); } return template; } private string replaceAll(string template, string key, string value) { string[] tokens = template.Split("\\?", true); bool hasQuery = tokens.Length > 1; return replaceAllInPath(tokens[0], key, value) + (hasQuery ? replaceAllInQuery(tokens[1], key, value) : ""); } private string replaceAllInPath(string template, string key, string value) { return template.Replace(key, value.Replace("+", "%20")); } private string replaceAllInQuery(string template, string key, string value) { return "?" + template.Replace(key, value); } private string asPattern(string key) { return "{" + key + "}"; } } }
23.109091
111
0.681353
[ "MIT" ]
SoftwareAG/cumulocity-sdk-cs
REST-SDK/src/Cumulocity.SDK.Client/TemplateUrlParser.cs
1,273
C#
namespace Machete.Cursors { using System; using Contexts; using Contexts.Collections; public struct EmptyCursor<TInput> : Cursor<TInput> { public bool HasCurrent => false; public TInput Current => throw new InvalidOperationException("The cursor is empty, Current is not valid."); public bool HasNext => false; public Cursor<TInput> Next() { throw new InvalidOperationException("The cursor is empty, Next is not a valid operation."); } public bool HasContext(Type contextType) { return false; } public bool TryGetContext<T>(out T context) where T : class { context = default; return false; } public T GetOrAddContext<T>(ContextFactory<T> contextFactory) where T : class { throw new ContextNotFoundException(); } public T AddOrUpdateContext<T>(ContextFactory<T> addFactory, UpdateContextFactory<T> updateFactory) where T : class { throw new ContextNotFoundException(); } public IReadOnlyContextCollection CurrentContext => EmptyContextCollection.Shared.Empty; } }
27.434783
115
0.600634
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete/Cursors/EmptyCursor.cs
1,264
C#
namespace OpenShiftForVisualStudio.Vsix.Views { using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; /// <summary> /// Interaction logic for OpenShiftProjectWindowControl. /// </summary> public partial class OpenShiftProjectWindowControl : UserControl { /// <summary> /// Initializes a new instance of the <see cref="OpenShiftProjectWindowControl"/> class. /// </summary> public OpenShiftProjectWindowControl() { this.InitializeComponent(); } /// <summary> /// Handles click on the button by displaying a message box. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")] [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")] private void button1_Click(object sender, RoutedEventArgs e) { MessageBox.Show( string.Format(System.Globalization.CultureInfo.CurrentUICulture, "Invoked '{0}'", this.ToString()), "OpenShiftProjectWindow"); } } }
40.117647
158
0.648094
[ "MIT" ]
gbraad/OpenShift.Vsix
OpenShiftForVisualStudio.Vsix/Views/OpenShiftProjectWindowControl.xaml.cs
1,366
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="DEVICE_DATA_SET_SCRUB_EX_OUTPUT" /> struct.</summary> public static unsafe class DEVICE_DATA_SET_SCRUB_EX_OUTPUTTests { /// <summary>Validates that the <see cref="DEVICE_DATA_SET_SCRUB_EX_OUTPUT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DEVICE_DATA_SET_SCRUB_EX_OUTPUT>(), Is.EqualTo(sizeof(DEVICE_DATA_SET_SCRUB_EX_OUTPUT))); } /// <summary>Validates that the <see cref="DEVICE_DATA_SET_SCRUB_EX_OUTPUT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DEVICE_DATA_SET_SCRUB_EX_OUTPUT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DEVICE_DATA_SET_SCRUB_EX_OUTPUT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(DEVICE_DATA_SET_SCRUB_EX_OUTPUT), Is.EqualTo(48)); } } }
42.111111
145
0.698549
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/winioctl/DEVICE_DATA_SET_SCRUB_EX_OUTPUTTests.cs
1,518
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.Core; using Azure.ResourceManager.Models; namespace Azure.ResourceManager.CosmosDB.Models { /// <summary> Parameters to create and update Cosmos DB Table. </summary> public partial class TableCreateUpdateOptions : TrackedResource { /// <summary> Initializes a new instance of TableCreateUpdateOptions. </summary> /// <param name="location"> The location. </param> /// <param name="resource"> The standard JSON format of a Table. </param> /// <exception cref="ArgumentNullException"> <paramref name="resource"/> is null. </exception> public TableCreateUpdateOptions(AzureLocation location, TableResource resource) : base(location) { if (resource == null) { throw new ArgumentNullException(nameof(resource)); } Resource = resource; } /// <summary> Initializes a new instance of TableCreateUpdateOptions. </summary> /// <param name="id"> The id. </param> /// <param name="name"> The name. </param> /// <param name="type"> The type. </param> /// <param name="tags"> The tags. </param> /// <param name="location"> The location. </param> /// <param name="resource"> The standard JSON format of a Table. </param> /// <param name="options"> A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. </param> internal TableCreateUpdateOptions(ResourceIdentifier id, string name, ResourceType type, IDictionary<string, string> tags, AzureLocation location, TableResource resource, CreateUpdateOptions options) : base(id, name, type, tags, location) { Resource = resource; Options = options; } /// <summary> The standard JSON format of a Table. </summary> public TableResource Resource { get; set; } /// <summary> A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. </summary> public CreateUpdateOptions Options { get; set; } } }
44.596154
246
0.65373
[ "MIT" ]
AhmedLeithy/azure-sdk-for-net
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/Models/TableCreateUpdateOptions.cs
2,319
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace DirectoryHash.Tests { internal static class TestUtilities { public static void Run(this TemporaryDirectory directory, params string[] args) { Assert.Equal(0, Program.MainCore(directory.Directory, args)); } } }
22.166667
87
0.699248
[ "MIT" ]
jasonmalinowski/directoryhash
DirectoryHashTests/TestUtilities.cs
401
C#
// // (C) Copyright 2003-2019 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows.Forms; using System.Text; using System.Linq; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.UI.Selection; using Revit.SDK.Samples.NewRoof.RoofForms.CS; namespace Revit.SDK.Samples.NewRoof.RoofsManager.CS { /// <summary> /// The kinds of roof than can be created. /// </summary> public enum CreateRoofKind { FootPrintRoof, ExtrusionRoof }; /// <summary> /// The RoofsManager is used to manage the operations between Revit and UI. /// </summary> public class RoofsManager { // To store a reference to the commandData. ExternalCommandData m_commandData; // To store the levels info in the Revit. List<Level> m_levels; // To store the roof types info in the Revit. List<RoofType> m_roofTypes; // To store a reference to the FootPrintRoofManager to create footprint roof. FootPrintRoofManager m_footPrintRoofManager; // To store a reference to the ExtrusionRoofManager to create extrusion roof. ExtrusionRoofManager m_extrusionRoofManager; // To store the selected elements in the Revit Selection m_selection; // roofs list ElementSet m_footPrintRoofs; ElementSet m_extrusionRoofs; // To store the footprint roof lines. Autodesk.Revit.DB.CurveArray m_footPrint; // To store the profile lines. Autodesk.Revit.DB.CurveArray m_profile; // Reference Plane for creating extrusion roof List<ReferencePlane> m_referencePlanes; // Transaction for manual mode Transaction m_transaction; // Current creating roof kind. public CreateRoofKind RoofKind; /// <summary> /// The constructor of RoofsManager class. /// </summary> /// <param name="commandData">The ExternalCommandData</param> public RoofsManager(ExternalCommandData commandData) { m_commandData = commandData; m_levels = new List<Level>(); m_roofTypes = new List<RoofType>(); m_referencePlanes = new List<ReferencePlane>(); m_footPrint = new CurveArray(); m_profile = new CurveArray(); m_footPrintRoofManager = new FootPrintRoofManager(commandData); m_extrusionRoofManager = new ExtrusionRoofManager(commandData); m_selection = commandData.Application.ActiveUIDocument.Selection; m_transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document"); RoofKind = CreateRoofKind.FootPrintRoof; Initialize(); } /// <summary> /// Initialize the data member /// </summary> private void Initialize() { Document doc = m_commandData.Application.ActiveUIDocument.Document; FilteredElementIterator iter = (new FilteredElementCollector(doc)).OfClass(typeof(Level)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_levels.Add(iter.Current as Level); } FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc); filteredElementCollector.OfClass(typeof(RoofType)); m_roofTypes = filteredElementCollector.Cast<RoofType>().ToList<RoofType>(); // FootPrint Roofs m_footPrintRoofs = new ElementSet(); iter = (new FilteredElementCollector(doc)).OfClass(typeof(FootPrintRoof)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_footPrintRoofs.Insert(iter.Current as FootPrintRoof); } // Extrusion Roofs m_extrusionRoofs = new ElementSet(); iter = (new FilteredElementCollector(doc)).OfClass(typeof(ExtrusionRoof)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { m_extrusionRoofs.Insert(iter.Current as ExtrusionRoof); } // Reference Planes iter = (new FilteredElementCollector(doc)).OfClass(typeof(ReferencePlane)).GetElementIterator(); iter.Reset(); while (iter.MoveNext()) { ReferencePlane plane = iter.Current as ReferencePlane; // just use the vertical plane if (Math.Abs(plane.Normal.DotProduct(Autodesk.Revit.DB.XYZ.BasisZ)) < 1.0e-09) { if (plane.Name == "Reference Plane") { plane.Name = "Reference Plane" + "(" + plane.Id.IntegerValue.ToString() + ")"; } m_referencePlanes.Add(plane); } } } /// <summary> /// Get the Level elements. /// </summary> public ReadOnlyCollection<Level> Levels { get { return new ReadOnlyCollection<Level>(m_levels); } } /// <summary> /// Get the RoofTypes. /// </summary> public ReadOnlyCollection<RoofType> RoofTypes { get { return new ReadOnlyCollection<RoofType>(m_roofTypes); } } /// <summary> /// Get the RoofTypes. /// </summary> public ReadOnlyCollection<ReferencePlane> ReferencePlanes { get { return new ReadOnlyCollection<ReferencePlane>(m_referencePlanes); } } /// <summary> /// Get all the footprint roofs in Revit. /// </summary> public ElementSet FootPrintRoofs { get { return m_footPrintRoofs; } } /// <summary> /// Get all the extrusion roofs in Revit. /// </summary> public ElementSet ExtrusionRoofs { get { return m_extrusionRoofs; } } /// <summary> /// Get the footprint roof lines. /// </summary> public CurveArray FootPrint { get { return m_footPrint; } } /// <summary> /// Get the extrusion profile lines. /// </summary> public CurveArray Profile { get { return m_profile; } } /// <summary> /// Select elements in Revit to obtain the footprint roof lines or extrusion profile lines. /// </summary> /// <returns>A curve array to hold the footprint roof lines or extrusion profile lines.</returns> public CurveArray WindowSelect() { if (RoofKind == CreateRoofKind.FootPrintRoof) { return SelectFootPrint(); } else { return SelectProfile(); } } /// <summary> /// Select elements in Revit to obtain the footprint roof lines. /// </summary> /// <returns>A curve array to hold the footprint roof lines.</returns> public CurveArray SelectFootPrint() { m_footPrint.Clear(); while (true) { ElementSet es = new ElementSet(); foreach (ElementId elementId in m_selection.GetElementIds()) { es.Insert(m_commandData.Application.ActiveUIDocument.Document.GetElement(elementId)); } es.Clear(); IList<Element> selectResult; try { selectResult = m_selection.PickElementsByRectangle(); } catch (Exception ex) { Console.WriteLine(ex.Message); break; } if (selectResult.Count != 0) { foreach (Autodesk.Revit.DB.Element element in selectResult) { Wall wall = element as Wall; if (wall != null) { LocationCurve wallCurve = wall.Location as LocationCurve; m_footPrint.Append(wallCurve.Curve); continue; } ModelCurve modelCurve = element as ModelCurve; if (modelCurve != null) { m_footPrint.Append(modelCurve.GeometryCurve); } } break; } else { TaskDialogResult result = TaskDialog.Show("Warning", "You should select a curve loop, or a wall loop, or loops combination \r\nof walls and curves to create a footprint roof.", TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel); if (result == TaskDialogResult.Cancel) { break; } } } return m_footPrint; } /// <summary> /// Create a footprint roof. /// </summary> /// <param name="level">The base level of the roof to be created.</param> /// <param name="roofType">The type of the newly created roof.</param> /// <returns>Return a new created footprint roof.</returns> public FootPrintRoof CreateFootPrintRoof(Level level, RoofType roofType) { FootPrintRoof roof = null; roof = m_footPrintRoofManager.CreateFootPrintRoof(m_footPrint, level, roofType); if (roof != null) { this.m_footPrintRoofs.Insert(roof); } return roof; } /// <summary> /// Select elements in Revit to obtain the extrusion profile lines. /// </summary> /// <returns>A curve array to hold the extrusion profile lines.</returns> public CurveArray SelectProfile() { m_profile.Clear(); while (true) { m_selection.GetElementIds().Clear(); IList<Element> selectResult; try { selectResult = m_selection.PickElementsByRectangle(); } catch (Exception ex) { Console.WriteLine(ex.Message); break; } if (selectResult.Count != 0) { foreach (Autodesk.Revit.DB.Element element in selectResult) { ModelCurve modelCurve = element as ModelCurve; if (modelCurve != null) { m_profile.Append(modelCurve.GeometryCurve); continue; } } break; } else { TaskDialogResult result = TaskDialog.Show("Warning", "You should select a connected lines or arcs, \r\nnot closed in a loop to create extrusion roof.", TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel); if (result == TaskDialogResult.Cancel) { break; } } } return m_profile; } /// <summary> /// Create a extrusion roof. /// </summary> /// <param name="refPlane">The reference plane for the extrusion roof.</param> /// <param name="level">The reference level of the roof to be created.</param> /// <param name="roofType">The type of the newly created roof.</param> /// <param name="extrusionStart">The extrusion start point.</param> /// <param name="extrusionEnd">The extrusion end point.</param> /// <returns>Return a new created extrusion roof.</returns> public ExtrusionRoof CreateExtrusionRoof(ReferencePlane refPlane, Level level, RoofType roofType, double extrusionStart, double extrusionEnd) { ExtrusionRoof roof = null; roof = m_extrusionRoofManager.CreateExtrusionRoof(m_profile, refPlane, level, roofType, extrusionStart, extrusionEnd); if (roof != null) { m_extrusionRoofs.Insert(roof); } return roof; } /// <summary> /// Begin a transaction. /// </summary> /// <returns></returns> public TransactionStatus BeginTransaction() { if (m_transaction.GetStatus() == TransactionStatus.Started) { TaskDialog.Show("Revit", "Transaction started already"); } return m_transaction.Start(); } /// <summary> /// Finish a transaction. /// </summary> /// <returns></returns> public TransactionStatus EndTransaction() { return m_transaction.Commit(); } /// <summary> /// Abort a transaction. /// </summary> public TransactionStatus AbortTransaction() { return m_transaction.RollBack(); } } }
35.148492
259
0.522345
[ "MIT" ]
xin1627/RevitSdkSamples
SDK/Samples/NewRoof/CS/RoofsManager/RoofsManager.cs
15,149
C#
using System; namespace Test.Core { public interface IService { } public class Service1 : IService { } public class Service2 : IService { } public class Service3 : IService { } }
13.466667
40
0.653465
[ "MIT" ]
loresoft/KickStart
test/Test.Core/IService.cs
204
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.Logic.V20190501.Outputs { /// <summary> /// The integration service environment properties. /// </summary> [OutputType] public sealed class IntegrationServiceEnvironmentPropertiesResponse { /// <summary> /// The encryption configuration. /// </summary> public readonly Outputs.IntegrationServiceEnvironmenEncryptionConfigurationResponse? EncryptionConfiguration; /// <summary> /// The endpoints configuration. /// </summary> public readonly Outputs.FlowEndpointsConfigurationResponse? EndpointsConfiguration; /// <summary> /// Gets the tracking id. /// </summary> public readonly string? IntegrationServiceEnvironmentId; /// <summary> /// The network configuration. /// </summary> public readonly Outputs.NetworkConfigurationResponse? NetworkConfiguration; /// <summary> /// The provisioning state. /// </summary> public readonly string? ProvisioningState; /// <summary> /// The integration service environment state. /// </summary> public readonly string? State; [OutputConstructor] private IntegrationServiceEnvironmentPropertiesResponse( Outputs.IntegrationServiceEnvironmenEncryptionConfigurationResponse? encryptionConfiguration, Outputs.FlowEndpointsConfigurationResponse? endpointsConfiguration, string? integrationServiceEnvironmentId, Outputs.NetworkConfigurationResponse? networkConfiguration, string? provisioningState, string? state) { EncryptionConfiguration = encryptionConfiguration; EndpointsConfiguration = endpointsConfiguration; IntegrationServiceEnvironmentId = integrationServiceEnvironmentId; NetworkConfiguration = networkConfiguration; ProvisioningState = provisioningState; State = state; } } }
35.089552
117
0.67248
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Logic/V20190501/Outputs/IntegrationServiceEnvironmentPropertiesResponse.cs
2,351
C#
using RepoDb.Contexts.Execution; using RepoDb.Exceptions; using RepoDb.Extensions; using RepoDb.Interfaces; using RepoDb.Requests; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace RepoDb { /// <summary> /// Contains the extension methods for <see cref="IDbConnection"/> object. /// </summary> public static partial class DbConnectionExtension { #region Merge<TEntity> /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge<TEntity>(this IDbConnection connection, TEntity entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return Merge<TEntity>(connection: connection, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifier">The qualifer field to be used during merge operation.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge<TEntity>(this IDbConnection connection, TEntity entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return Merge<TEntity>(connection: connection, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge<TEntity>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeInternal<TEntity, object>(connection: connection, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TEntity, TResult>(this IDbConnection connection, TEntity entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return Merge<TEntity, TResult>(connection: connection, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifier">The qualifer field to be used during merge operation.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TEntity, TResult>(this IDbConnection connection, TEntity entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return Merge<TEntity, TResult>(connection: connection, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TEntity, TResult>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeInternal<TEntity, TResult>(connection: connection, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static TResult MergeInternal<TEntity, TResult>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { // Check the qualifiers if (qualifiers?.Any() != true) { var primary = GetAndGuardPrimaryKey<TEntity>(connection, transaction); qualifiers = primary.AsField().AsEnumerable(); } // Variables needed var setting = connection.GetDbSetting(); // Return the result if (setting.IsUseUpsert == false) { return MergeInternalBase<TEntity, TResult>(connection: connection, tableName: ClassMappedNameCache.Get<TEntity>(), entity: entity, fields: entity.AsFields(), qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder, skipIdentityCheck: false); } else { return UpsertInternalBase<TEntity, TResult>(connection: connection, tableName: ClassMappedNameCache.Get<TEntity>(), entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } } #endregion #region MergeAsync<TEntity> /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync<TEntity>(this IDbConnection connection, TEntity entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsync<TEntity>(connection: connection, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifier">The field to be used during merge operation.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync<TEntity>(this IDbConnection connection, TEntity entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsync<TEntity, object>(connection: connection, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync<TEntity>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsyncInternal<TEntity, object>(connection: connection, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TEntity, TResult>(this IDbConnection connection, TEntity entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsync<TEntity, TResult>(connection: connection, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifier">The field to be used during merge operation.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TEntity, TResult>(this IDbConnection connection, TEntity entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsync<TEntity, TResult>(connection: connection, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TEntity, TResult>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { return MergeAsyncInternal<TEntity, TResult>(connection: connection, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a data entity object into an existing data in the database in an asychronous way. /// </summary> /// <typeparam name="TEntity">The type of the data entity object.</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="entity">The object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static Task<TResult> MergeAsyncInternal<TEntity, TResult>(this IDbConnection connection, TEntity entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { // Check the qualifiers if (qualifiers?.Any() != true) { var primary = GetAndGuardPrimaryKey<TEntity>(connection, transaction); qualifiers = primary.AsField().AsEnumerable(); } // Variables needed var setting = connection.GetDbSetting(); // Return the result if (setting.IsUseUpsert == false) { return MergeAsyncInternalBase<TEntity, TResult>(connection: connection, tableName: ClassMappedNameCache.Get<TEntity>(), entity: entity, fields: entity.AsFields(), qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder, skipIdentityCheck: false); } else { return UpsertAsyncInternalBase<TEntity, TResult>(connection: connection, tableName: ClassMappedNameCache.Get<TEntity>(), entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } } #endregion #region Merge(TableName) /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge(this IDbConnection connection, string tableName, object entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return Merge(connection: connection, tableName: tableName, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifier">The qualifier field to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge(this IDbConnection connection, string tableName, object entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return Merge(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static object Merge(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeInternal<object>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TResult>(this IDbConnection connection, string tableName, object entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return Merge<TResult>(connection: connection, tableName: tableName, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifier">The qualifier field to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TResult>(this IDbConnection connection, string tableName, object entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return Merge<TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static TResult Merge<TResult>(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeInternal<TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static TResult MergeInternal<TResult>(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { // Variables needed var setting = connection.GetDbSetting(); // Return the result if (setting.IsUseUpsert == false) { return MergeInternalBase<object, TResult>(connection: connection, tableName: tableName, entity: entity, fields: entity.AsFields(), qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder, skipIdentityCheck: true); } else { return UpsertInternalBase<object, TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } } #endregion #region MergeAsync(TableName) /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync(this IDbConnection connection, string tableName, object entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsync(connection: connection, tableName: tableName, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifier">The qualifier field to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync(this IDbConnection connection, string tableName, object entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsync(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<object> MergeAsync(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsyncInternal<object>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TResult>(this IDbConnection connection, string tableName, object entity, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsync<TResult>(connection: connection, tableName: tableName, entity: entity, qualifier: null, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifier">The qualifier field to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TResult>(this IDbConnection connection, string tableName, object entity, Field qualifier, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsync<TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifier?.AsEnumerable(), hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> public static Task<TResult> MergeAsync<TResult>(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { return MergeAsyncInternal<TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } /// <summary> /// Merges a dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The dynamic object to be merged.</param> /// <param name="qualifiers">The qualifier <see cref="Field"/> objects to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static async Task<TResult> MergeAsyncInternal<TResult>(this IDbConnection connection, string tableName, object entity, IEnumerable<Field> qualifiers, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) { // Variables needed var setting = connection.GetDbSetting(); // Return the result if (setting.IsUseUpsert == false) { return await MergeAsyncInternalBase<object, TResult>(connection: connection, tableName: tableName, entity: entity, fields: entity.AsFields(), qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder, skipIdentityCheck: true); } else { return await UpsertAsyncInternalBase<object, TResult>(connection: connection, tableName: tableName, entity: entity, qualifiers: qualifiers, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } } #endregion #region MergeInternalBase<TEntity> /// <summary> /// Merges a data entity or dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The data entity or dynamic object to be merged.</param> /// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <param name="skipIdentityCheck">True to skip the identity check.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static TResult MergeInternalBase<TEntity, TResult>(this IDbConnection connection, string tableName, TEntity entity, IEnumerable<Field> fields = null, IEnumerable<Field> qualifiers = null, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null, bool skipIdentityCheck = false) where TEntity : class { // Get the database fields var dbFields = DbFieldCache.Get(connection, tableName, transaction); // Check the qualifiers if (qualifiers?.Any() != true) { // Get the DB primary var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary); // Throw if there is no primary if (primary == null) { throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'."); } // Set the primary as the qualifier qualifiers = primary.AsField().AsEnumerable(); } // Get the function var callback = new Func<MergeExecutionContext<TEntity>>(() => { // Variables needed var identity = (Field)null; var inputFields = new List<DbField>(); var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity); var dbSetting = connection.GetDbSetting(); // Set the identity field if (skipIdentityCheck == false) { identity = IdentityCache.Get<TEntity>()?.AsField(); if (identity == null && identityDbField != null) { identity = FieldCache.Get<TEntity>().FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)); } } // Filter the actual properties for input fields inputFields = dbFields? .Where(dbField => fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null) .AsList(); // Variables for the entity action var identityPropertySetter = (Action<TEntity, object>)null; // Get the identity setter if (skipIdentityCheck == false && identity != null) { identityPropertySetter = FunctionCache.GetDataEntityPropertyValueSetterFunction<TEntity>(identity); } // Identify the requests var mergeRequest = (MergeRequest)null; // Create a different kind of requests if (typeof(TEntity) == typeof(object)) { mergeRequest = new MergeRequest(tableName, connection, transaction, fields, qualifiers, hints, statementBuilder); } else { mergeRequest = new MergeRequest(typeof(TEntity), connection, transaction, fields, qualifiers, hints, statementBuilder); } // Return the value return new MergeExecutionContext<TEntity> { CommandText = CommandTextCache.GetMergeText(mergeRequest), InputFields = inputFields, ParametersSetterFunc = FunctionCache.GetDataEntityDbCommandParameterSetterFunction<TEntity>( string.Concat(typeof(TEntity).FullName, ".", tableName, ".Merge"), inputFields?.AsList(), null, dbSetting), IdentityPropertySetterFunc = identityPropertySetter }; }); // Get the context var context = MergeExecutionContextCache<TEntity>.Get(tableName, qualifiers, fields, callback); // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog(context.CommandText, entity, null); trace.BeforeMerge(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException(context.CommandText); } return default(TResult); } context.CommandText = (cancellableTraceLog.Statement ?? context.CommandText); entity = (TEntity)(cancellableTraceLog.Parameter ?? entity); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Execution variables var result = default(TResult); // Create the command using (var command = (DbCommand)connection.EnsureOpen().CreateCommand(context.CommandText, CommandType.Text, commandTimeout, transaction)) { // Set the values context.ParametersSetterFunc(command, entity); // Actual Execution result = ObjectConverter.ToType<TResult>(command.ExecuteScalar()); // Set the return value if (Equals(result, default(TResult)) == false) { context.IdentityPropertySetterFunc?.Invoke(entity, result); } } // After Execution if (trace != null) { trace.AfterMerge(new TraceLog(context.CommandText, entity, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Return the result return result; } #endregion #region UpsertInternalBase<TEntity> /// <summary> /// Upserts a data entity or dynamic object into an existing data in the database. /// </summary> /// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The data entity or dynamic object to be merged.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static TResult UpsertInternalBase<TEntity, TResult>(this IDbConnection connection, string tableName, TEntity entity, IEnumerable<Field> qualifiers = null, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { // Variables needed var type = entity?.GetType() ?? typeof(TEntity); var isObjectType = typeof(TEntity) == typeof(object); var dbFields = DbFieldCache.Get(connection, tableName, transaction); var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary); var properties = (IEnumerable<ClassProperty>)null; var primaryKey = (ClassProperty)null; // Get the properties if (type.GetTypeInfo().IsGenericType == true) { properties = type.GetClassProperties(); } else { properties = PropertyCache.Get(type); } // Check the qualifiers if (qualifiers?.Any() != true) { // Throw if there is no primary if (primary == null) { throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'."); } // Set the primary as the qualifier qualifiers = primary.AsField().AsEnumerable(); } // Set the primary key primaryKey = properties?.FirstOrDefault(p => string.Equals(primary?.Name, p.GetMappedName(), StringComparison.OrdinalIgnoreCase)); // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog("Upsert.Before", entity, null); trace.BeforeMerge(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException("Upsert.Cancelled"); } return default(TResult); } entity = (TEntity)(cancellableTraceLog.Parameter ?? entity); } // Expression var where = CreateQueryGroupForUpsert(entity, properties, qualifiers); // Validate if (where == null) { throw new Exceptions.InvalidExpressionException("The generated expression from the given qualifiers is not valid."); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Execution variables var result = default(TResult); var exists = false; if (isObjectType == true) { exists = connection.Exists(tableName, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { exists = connection.Exists<TEntity>(where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Check the existence if (exists == true) { // Call the update operation var updateResult = default(int); if (isObjectType == true) { updateResult = connection.Update(tableName, entity, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { updateResult = connection.Update<TEntity>(entity, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Check if there is result if (updateResult > 0) { if (primaryKey != null) { // Set the result result = ObjectConverter.ToType<TResult>(primaryKey.PropertyInfo.GetValue(entity)); } } } else { // Call the insert operation var insertResult = (object)null; if (isObjectType == true) { insertResult = connection.Insert(tableName, entity, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { insertResult = connection.Insert<TEntity>(entity, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Set the result result = ObjectConverter.ToType<TResult>(insertResult); } // After Execution if (trace != null) { trace.AfterMerge(new TraceLog("Upsert.After", entity, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Return the result return result; } #endregion #region MergeAsyncInternalBase<TEntity> /// <summary> /// Merges a data entity or dynamic object into an existing data in the database in an asynchronous way. /// </summary> /// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The data entity or dynamic object to be merged.</param> /// <param name="fields">The mapping list of <see cref="Field"/> objects to be used.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <param name="skipIdentityCheck">True to skip the identity check.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static async Task<TResult> MergeAsyncInternalBase<TEntity, TResult>(this IDbConnection connection, string tableName, TEntity entity, IEnumerable<Field> fields = null, IEnumerable<Field> qualifiers = null, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null, bool skipIdentityCheck = false) where TEntity : class { // Get the database fields var dbFields = await DbFieldCache.GetAsync(connection, tableName, transaction); // Get the function var callback = new Func<MergeExecutionContext<TEntity>>(() => { // Variables needed var identity = (Field)null; var inputFields = new List<DbField>(); var identityDbField = dbFields?.FirstOrDefault(f => f.IsIdentity); var dbSetting = connection.GetDbSetting(); // Set the identity field if (skipIdentityCheck == false) { identity = IdentityCache.Get<TEntity>()?.AsField(); if (identity == null && identityDbField != null) { identity = FieldCache.Get<TEntity>().FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), identityDbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)); } } // Filter the actual properties for input fields inputFields = dbFields? .Where(dbField => fields.FirstOrDefault(field => string.Equals(field.Name.AsUnquoted(true, dbSetting), dbField.Name.AsUnquoted(true, dbSetting), StringComparison.OrdinalIgnoreCase)) != null) .AsList(); // Variables for the entity action var identityPropertySetter = (Action<TEntity, object>)null; // Get the identity setter if (skipIdentityCheck == false && identity != null) { identityPropertySetter = FunctionCache.GetDataEntityPropertyValueSetterFunction<TEntity>(identity); } // Identify the requests var mergeRequest = (MergeRequest)null; // Create a different kind of requests if (typeof(TEntity) == typeof(object)) { mergeRequest = new MergeRequest(tableName, connection, transaction, fields, qualifiers, hints, statementBuilder); } else { mergeRequest = new MergeRequest(typeof(TEntity), connection, transaction, fields, qualifiers, hints, statementBuilder); } // Return the value return new MergeExecutionContext<TEntity> { CommandText = CommandTextCache.GetMergeText(mergeRequest), InputFields = inputFields, ParametersSetterFunc = FunctionCache.GetDataEntityDbCommandParameterSetterFunction<TEntity>( string.Concat(typeof(TEntity).FullName, ".", tableName, ".Merge"), inputFields?.AsList(), null, dbSetting), IdentityPropertySetterFunc = identityPropertySetter }; }); // Get the context var context = MergeExecutionContextCache<TEntity>.Get(tableName, qualifiers, fields, callback); // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog(context.CommandText, entity, null); trace.BeforeMerge(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException(context.CommandText); } return default(TResult); } context.CommandText = (cancellableTraceLog.Statement ?? context.CommandText); entity = (TEntity)(cancellableTraceLog.Parameter ?? entity); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Execution variables var result = default(TResult); // Create the command using (var command = (DbCommand)(await connection.EnsureOpenAsync()).CreateCommand(context.CommandText, CommandType.Text, commandTimeout, transaction)) { // Set the values context.ParametersSetterFunc(command, entity); // Actual Execution result = ObjectConverter.ToType<TResult>(await command.ExecuteScalarAsync()); // Set the return value if (Equals(result, default(TResult)) == false) { context.IdentityPropertySetterFunc?.Invoke(entity, result); } } // After Execution if (trace != null) { trace.AfterMerge(new TraceLog(context.CommandText, entity, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Return the result return result; } #endregion #region UpsertAsyncInternalBase<TEntity> /// <summary> /// Upserts a data entity or dynamic object into an existing data in the database in an . /// </summary> /// <typeparam name="TEntity">The type of the object (whether a data entity or a dynamic).</typeparam> /// <typeparam name="TResult">The target type of the result.</typeparam> /// <param name="connection">The connection object to be used.</param> /// <param name="tableName">The name of the target table to be used.</param> /// <param name="entity">The data entity or dynamic object to be merged.</param> /// <param name="qualifiers">The list of qualifer fields to be used.</param> /// <param name="hints">The table hints to be used. See <see cref="SqlServerTableHints"/> class.</param> /// <param name="commandTimeout">The command timeout in seconds to be used.</param> /// <param name="transaction">The transaction to be used.</param> /// <param name="trace">The trace object to be used.</param> /// <param name="statementBuilder">The statement builder object to be used.</param> /// <returns>The value of the identity field if present, otherwise, the value of primary field.</returns> internal static async Task<TResult> UpsertAsyncInternalBase<TEntity, TResult>(this IDbConnection connection, string tableName, TEntity entity, IEnumerable<Field> qualifiers = null, string hints = null, int? commandTimeout = null, IDbTransaction transaction = null, ITrace trace = null, IStatementBuilder statementBuilder = null) where TEntity : class { // Variables needed var type = entity?.GetType() ?? typeof(TEntity); var isObjectType = typeof(TEntity) == typeof(object); var dbFields = await DbFieldCache.GetAsync(connection, tableName, transaction); var primary = dbFields?.FirstOrDefault(dbField => dbField.IsPrimary); var properties = (IEnumerable<ClassProperty>)null; var primaryKey = (ClassProperty)null; // Get the properties if (type.GetTypeInfo().IsGenericType == true) { properties = type.GetClassProperties(); } else { properties = PropertyCache.Get(type); } // Check the qualifiers if (qualifiers?.Any() != true) { // Throw if there is no primary if (primary == null) { throw new PrimaryFieldNotFoundException($"There is no primary found for '{tableName}'."); } // Set the primary as the qualifier qualifiers = primary.AsField().AsEnumerable(); } // Set the primary key primaryKey = properties?.FirstOrDefault(p => string.Equals(primary?.Name, p.GetMappedName(), StringComparison.OrdinalIgnoreCase)); // Before Execution if (trace != null) { var cancellableTraceLog = new CancellableTraceLog("Upsert.Before", entity, null); trace.BeforeMerge(cancellableTraceLog); if (cancellableTraceLog.IsCancelled) { if (cancellableTraceLog.IsThrowException) { throw new CancelledExecutionException("Upsert.Cancelled"); } return default(TResult); } entity = (TEntity)(cancellableTraceLog.Parameter ?? entity); } // Expression var where = CreateQueryGroupForUpsert(entity, properties, qualifiers); // Validate if (where == null) { throw new Exceptions.InvalidExpressionException("The generated expression from the given qualifiers is not valid."); } // Before Execution Time var beforeExecutionTime = DateTime.UtcNow; // Execution variables var result = default(TResult); var exists = false; if (isObjectType == true) { exists = await connection.ExistsAsync(tableName, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { exists = await connection.ExistsAsync<TEntity>(where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Check the existence if (exists == true) { // Call the update operation var updateResult = default(int); if (isObjectType == true) { updateResult = await connection.UpdateAsync(tableName, entity, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { updateResult = await connection.UpdateAsync<TEntity>(entity, where, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Check if there is result if (updateResult > 0) { if (primaryKey != null) { // Set the result result = ObjectConverter.ToType<TResult>(primaryKey.PropertyInfo.GetValue(entity)); } } } else { // Call the insert operation var insertResult = (object)null; if (isObjectType == true) { insertResult = await connection.InsertAsync(tableName, entity, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } else { insertResult = await connection.InsertAsync<TEntity>(entity, hints: hints, commandTimeout: commandTimeout, transaction: transaction, trace: trace, statementBuilder: statementBuilder); } // Set the result result = ObjectConverter.ToType<TResult>(insertResult); } // After Execution if (trace != null) { trace.AfterMerge(new TraceLog("Upsert.After", entity, result, DateTime.UtcNow.Subtract(beforeExecutionTime))); } // Return the result return result; } #endregion } }
47.305617
196
0.564634
[ "Apache-2.0" ]
yeojdj/RepoDb
RepoDb.Core/RepoDb/Operations/DbConnection/Merge.cs
85,909
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics.ContractsLight; using System.IO; using BuildXL.Native.IO; using BuildXL.Storage.ChangeJournalService; using BuildXL.Storage.ChangeJournalService.Protocol; using BuildXL.Utilities; using static BuildXL.Utilities.FormattableStringEx; namespace BuildXL.Storage { /// <summary> /// Getter for <see cref="IChangeJournalAccessor" />. /// </summary> public static class JournalAccessorGetter { /// <summary> /// Tries to get <see cref="IChangeJournalAccessor"/>. /// </summary> public static Possible<IChangeJournalAccessor> TryGetJournalAccessor(VolumeMap volumeMap, string path) { Contract.Requires(volumeMap != null); Contract.Requires(!string.IsNullOrWhiteSpace(path)); var inprocAccessor = new InProcChangeJournalAccessor(); try { // When the current process runs with elevation, the process can access the journal directly. However, even with such a capability, // the process may fail in opening the volume handle. Thus, we need to verify that the process is able to open the volume handle. // If the operating system is Win10-RedStone2, it can directly access the journal as well. using (var file = FileUtilities.CreateFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) { var volume = volumeMap.TryGetVolumePathForHandle(file.SafeFileHandle); if (volume.IsValid) { // Journal accessor needs to know whether the OS allows unprivileged journal operations // because some operation names (e.g., reading journal, getting volume handle) are different. inprocAccessor.IsJournalUnprivileged = !CurrentProcess.IsElevated; // Attempt to access journal. Any error means that the journal operations are not unprivileged yet in the host computer. var result = inprocAccessor.QueryJournal(new QueryJournalRequest(volume)); if (!result.IsError) { if (result.Response.Succeeded) { return inprocAccessor; } else { return new Failure<string>(I($"Querying journal results in {result.Response.Status.ToString()}")); } } else { return new Failure<string>(result.Error.Message); } } else { return new Failure<string>(I($"Failed to get volume path for '{path}'")); } } } catch (BuildXLException ex) { return new Failure<string>(ex.Message); } } } }
45.373333
148
0.538055
[ "MIT" ]
breidikl/BuildXL
Public/Src/Utilities/Storage/JournalAccessorGetter.cs
3,403
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; namespace XamFormsEfficientNetworking.WinPhone { public partial class MainPage : global::Xamarin.Forms.Platform.WinPhone.FormsApplicationPage { public MainPage() { InitializeComponent(); SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape; global::Xamarin.Forms.Forms.Init(); LoadApplication(new XamFormsEfficientNetworking.App()); } } }
26.96
96
0.724036
[ "MIT" ]
PacktPublishing/Xamarin-Cross-Platform-Mobile-Application-Development
Module 2/Chapter 5/Windows/s04/xamformsefficientnetworking/xamformsefficientnetworking/XamFormsEfficientNetworking.WinPhone/MainPage.xaml.cs
676
C#
using System.Collections.Generic; using ESRI.ArcLogistics.Data; namespace ESRI.ArcLogistics.App.Import { /// <summary> /// Provides access to a collection of data objects with ability to track elements additions. /// </summary> /// <typeparam name="T">The type of data objects in the collection.</typeparam> interface IDataObjectContainer<T> : ICollection<T> where T : DataObject { /// <summary> /// Checks if the data object with the specified name exists in the collection. /// </summary> /// <param name="objectName">The name of the object to check existence for.</param> /// <returns>True if and only if the object with the specified name exists in /// the collection.</returns> bool Contains(string objectName); /// <summary> /// Gets data object with the specified name. /// </summary> /// <param name="objectName">The name of the data object to be retrieved.</param> /// <param name="value">Contains reference to the data object with the specified /// name or null if no such object was found.</param> /// <returns>True if and only if the object with the specified name exists in /// the collection.</returns> bool TryGetValue(string objectName, out T value); /// <summary> /// Gets reference to the collection of added data objects. /// </summary> /// <returns>A reference to the collection of added data objects.</returns> IEnumerable<T> GetAddedObjects(); } }
41.526316
97
0.637516
[ "Apache-2.0" ]
Esri/route-planner-csharp
RoutePlanner_DeveloperTools/Source/ArcLogisticsApp/Import/IDataObjectContainer.cs
1,580
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d2d1.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="ID2D1BitmapRenderTarget" /> struct.</summary> public static unsafe class ID2D1BitmapRenderTargetTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ID2D1BitmapRenderTarget" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ID2D1BitmapRenderTarget).GUID, Is.EqualTo(IID_ID2D1BitmapRenderTarget)); } /// <summary>Validates that the <see cref="ID2D1BitmapRenderTarget" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ID2D1BitmapRenderTarget>(), Is.EqualTo(sizeof(ID2D1BitmapRenderTarget))); } /// <summary>Validates that the <see cref="ID2D1BitmapRenderTarget" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ID2D1BitmapRenderTarget).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ID2D1BitmapRenderTarget" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ID2D1BitmapRenderTarget), Is.EqualTo(8)); } else { Assert.That(sizeof(ID2D1BitmapRenderTarget), Is.EqualTo(4)); } } } }
38.538462
145
0.651198
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/d2d1/ID2D1BitmapRenderTargetTests.cs
2,006
C#
//------------------------------------------------------------------------------ // <otomatik üretildi> // Bu kod bir araç tarafından oluşturuldu. // // Bu dosyada yapılacak değişiklikler yanlış davranışa neden olabilir ve // kod tekrar üretildi. // </otomatik üretildi> //------------------------------------------------------------------------------ namespace YemektTariflerim { public partial class KategoriDetayAdmin { /// <summary> /// TextBox1 denetimi. /// </summary> /// <remarks> /// Otomatik üretilmiş alan. /// Değiştirmek için, alan bildirimini tasarımcı dosyasından arka plan kod dosyasına taşıyın. /// </remarks> protected global::System.Web.UI.WebControls.TextBox TextBox1; /// <summary> /// TextBox2 denetimi. /// </summary> /// <remarks> /// Otomatik üretilmiş alan. /// Değiştirmek için, alan bildirimini tasarımcı dosyasından arka plan kod dosyasına taşıyın. /// </remarks> protected global::System.Web.UI.WebControls.TextBox TextBox2; /// <summary> /// FileUpload1 denetimi. /// </summary> /// <remarks> /// Otomatik üretilmiş alan. /// Değiştirmek için, alan bildirimini tasarımcı dosyasından arka plan kod dosyasına taşıyın. /// </remarks> protected global::System.Web.UI.WebControls.FileUpload FileUpload1; /// <summary> /// btnkategoriguncelle denetimi. /// </summary> /// <remarks> /// Otomatik üretilmiş alan. /// Değiştirmek için, alan bildirimini tasarımcı dosyasından arka plan kod dosyasına taşıyın. /// </remarks> protected global::System.Web.UI.WebControls.Button btnkategoriguncelle; } }
33.518519
101
0.558011
[ "MIT" ]
ebruaktas99/aspnetileyemektarifsitesi
YemekTarifSitesi/YemektTariflerim/YemektTariflerim/KategoriDuzenle.aspx.designer.cs
1,873
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Analytics.Admin.V1Alpha.Snippets { // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLinkProposal_async_flattened_resourceNames] using Google.Analytics.Admin.V1Alpha; using System.Threading.Tasks; public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets { /// <summary>Snippet for DeleteDisplayVideo360AdvertiserLinkProposalAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task DeleteDisplayVideo360AdvertiserLinkProposalResourceNamesAsync() { // Create client AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync(); // Initialize request argument(s) DisplayVideo360AdvertiserLinkProposalName name = DisplayVideo360AdvertiserLinkProposalName.FromPropertyDisplayVideo360AdvertiserLinkProposal("[PROPERTY]", "[DISPLAY_VIDEO_360_ADVERTISER_LINK_PROPOSAL]"); // Make the request await analyticsAdminServiceClient.DeleteDisplayVideo360AdvertiserLinkProposalAsync(name); } } // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteDisplayVideo360AdvertiserLinkProposal_async_flattened_resourceNames] }
49.5
215
0.76431
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Analytics.Admin.V1Alpha/Google.Analytics.Admin.V1Alpha.GeneratedSnippets/AnalyticsAdminServiceClient.DeleteDisplayVideo360AdvertiserLinkProposalResourceNamesAsyncSnippet.g.cs
2,079
C#
using System.Collections.Generic; using System.Linq; using QuestStoreNAT.web.Models; using QuestStoreNAT.web.DatabaseLayer; using QuestStoreNAT.web.DatabaseLayer.ConcreteDAO; using QuestStoreNAT.web.ViewModels; namespace QuestStoreNAT.web.Services { public class QuestManagement { private OwnedQuestStudentDAO _ownedStudentDAO { get; set; } private OwnedQuestGroupDAO _ownedGroupDAO { get; set; } private QuestDAO _questDAO { get; set; } public QuestManagement() { _ownedStudentDAO = new OwnedQuestStudentDAO(); _questDAO = new QuestDAO(); _ownedGroupDAO = new OwnedQuestGroupDAO(); } private List<OwnedQuestIdWithQuest> ReturnAllIndividualQuest(int studentId) { var ownedQuestIdWithQuestList = new List<OwnedQuestIdWithQuest>(); var allOwnedQuestByStudent = _ownedStudentDAO.FetchAllRecords(studentId); foreach(var ownedQuestByStudent in allOwnedQuestByStudent) { var ownedQuestIdWithQuest = new OwnedQuestIdWithQuest {OwnedId = ownedQuestByStudent.Id}; var model = _questDAO.FindOneRecordBy(ownedQuestByStudent.QuestId); model.QuestStatus = ownedQuestByStudent.CompletionStatus; ownedQuestIdWithQuest.OwnedQuest = model; ownedQuestIdWithQuestList.Add(ownedQuestIdWithQuest); } return ownedQuestIdWithQuestList; } private List<OwnedQuestIdWithQuest> ReturnAllGroupQuest(int groupId) { var ownedQuestIdWithQuestList = new List<OwnedQuestIdWithQuest>(); var allOwnedQuestByGroup = _ownedGroupDAO.FetchAllRecords(groupId); foreach (var ownedQuestByGroup in allOwnedQuestByGroup) { var ownedQuestIdWithQuest = new OwnedQuestIdWithQuest {OwnedId = ownedQuestByGroup.Id}; var model = _questDAO.FindOneRecordBy(ownedQuestByGroup.QuestId); model.QuestStatus = ownedQuestByGroup.CompletionStatus; ownedQuestIdWithQuest.OwnedQuest = model; ownedQuestIdWithQuestList.Add(ownedQuestIdWithQuest); } return ownedQuestIdWithQuestList; } public List<OwnedQuestIdWithQuest> ReturnListOfAllQuest(int studentId, int groupId) { var listIndividualQuest = ReturnAllIndividualQuest(studentId); var listGroupQuest = ReturnAllGroupQuest(groupId); return listIndividualQuest.Concat(listGroupQuest).ToList(); } public void ClaimIndividualQuest(OwnedQuestStudent claimedOwnedQuest) { _ownedStudentDAO.AddRecord(claimedOwnedQuest); } public void ClaimGroupQuest(OwnedQuestGroup claimedOwnedQuest) { _ownedGroupDAO.AddRecord(claimedOwnedQuest); } public void DeclaimIndividualQuest(int id) { _ownedStudentDAO.DeleteRecord(id); } public void DeclaimGroupQuest(int id) { _ownedGroupDAO.DeleteRecord(id); } } }
35
105
0.664762
[ "MIT" ]
chashafe/QuestStore
QuestStoreNAT/QuestStoreNAT.web/Services/QuestManagement.cs
3,152
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3dumddi.h(3439,5) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct _D3DDDICB_ALLOCATE__union_0 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public byte[] __bits; public IntPtr pAllocationInfo { get => InteropRuntime.Get<IntPtr>(__bits, 0, IntPtr.Size); set => InteropRuntime.Set<IntPtr>(value, __bits, 0, IntPtr.Size); } public IntPtr pAllocationInfo2 { get => InteropRuntime.Get<IntPtr>(__bits, 0, IntPtr.Size); set => InteropRuntime.Set<IntPtr>(value, __bits, 0, IntPtr.Size); } } }
46.705882
167
0.724181
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/_D3DDDICB_ALLOCATE__union_0.cs
796
C#
// <auto-generated /> using System; using CarDealer.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CarDealer.Migrations { [DbContext(typeof(CarDealerContext))] [Migration("20211028090310_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("CarDealer.Models.Car", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Make") .HasColumnType("nvarchar(max)"); b.Property<string>("Model") .HasColumnType("nvarchar(max)"); b.Property<long>("TravelledDistance") .HasColumnType("bigint"); b.HasKey("Id"); b.ToTable("Cars"); }); modelBuilder.Entity("CarDealer.Models.Customer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("BirthDate") .HasColumnType("datetime2"); b.Property<bool>("IsYoungDriver") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Customers"); }); modelBuilder.Entity("CarDealer.Models.Part", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<decimal>("Price") .HasColumnType("decimal(18,2)"); b.Property<int>("Quantity") .HasColumnType("int"); b.Property<int>("SupplierId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("SupplierId"); b.ToTable("Parts"); }); modelBuilder.Entity("CarDealer.Models.PartCar", b => { b.Property<int>("CarId") .HasColumnType("int"); b.Property<int>("PartId") .HasColumnType("int"); b.HasKey("CarId", "PartId"); b.HasIndex("PartId"); b.ToTable("PartCars"); }); modelBuilder.Entity("CarDealer.Models.Sale", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("CarId") .HasColumnType("int"); b.Property<int>("CustomerId") .HasColumnType("int"); b.Property<decimal>("Discount") .HasColumnType("decimal(18,2)"); b.HasKey("Id"); b.HasIndex("CarId"); b.HasIndex("CustomerId"); b.ToTable("Sales"); }); modelBuilder.Entity("CarDealer.Models.Supplier", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<bool>("IsImporter") .HasColumnType("bit"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Suppliers"); }); modelBuilder.Entity("CarDealer.Models.Part", b => { b.HasOne("CarDealer.Models.Supplier", "Supplier") .WithMany("Parts") .HasForeignKey("SupplierId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("CarDealer.Models.PartCar", b => { b.HasOne("CarDealer.Models.Car", "Car") .WithMany("PartCars") .HasForeignKey("CarId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CarDealer.Models.Part", "Part") .WithMany("PartCars") .HasForeignKey("PartId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("CarDealer.Models.Sale", b => { b.HasOne("CarDealer.Models.Car", "Car") .WithMany("Sales") .HasForeignKey("CarId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CarDealer.Models.Customer", "Customer") .WithMany("Sales") .HasForeignKey("CustomerId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.4375
125
0.464433
[ "MIT" ]
pirocorp/Databases-Advanced---Entity-Framework
Exercises/06. Extensible Markup Language - XML/CarDealer/Migrations/20211028090310_Initial.Designer.cs
6,806
C#
// =========== // DO NOT EDIT - this file is automatically regenerated. // =========== using System.Collections.Generic; using System; using Improbable.Gdk.Core; using Improbable.Worker.CInterop; namespace Improbable.Restricted { public partial class PlayerClient { public class DiffComponentStorage : IDiffUpdateStorage<Update>, IDiffComponentAddedStorage<Update>, IDiffAuthorityStorage { private readonly HashSet<EntityId> entitiesUpdated = new HashSet<EntityId>(); private List<EntityId> componentsAdded = new List<EntityId>(); private List<EntityId> componentsRemoved = new List<EntityId>(); private readonly AuthorityComparer authorityComparer = new AuthorityComparer(); private readonly UpdateComparer<Update> updateComparer = new UpdateComparer<Update>(); // Used to represent a state machine of authority changes. Valid state changes are: // authority lost -> authority lost temporarily // authority lost temporarily -> authority lost // authority gained -> authority gained // Creating the authority lost temporarily set is the aim as it signifies authority epoch changes private readonly HashSet<EntityId> authorityLost = new HashSet<EntityId>(); private readonly HashSet<EntityId> authorityGained = new HashSet<EntityId>(); private readonly HashSet<EntityId> authorityLostTemporary = new HashSet<EntityId>(); private MessageList<ComponentUpdateReceived<Update>> updateStorage = new MessageList<ComponentUpdateReceived<Update>>(); private MessageList<AuthorityChangeReceived> authorityChanges = new MessageList<AuthorityChangeReceived>(); public Type[] GetEventTypes() { return new Type[] { }; } public Type GetUpdateType() { return typeof(Update); } public uint GetComponentId() { return ComponentId; } public void Clear() { entitiesUpdated.Clear(); updateStorage.Clear(); authorityChanges.Clear(); componentsAdded.Clear(); componentsRemoved.Clear(); } public void RemoveEntityComponent(long entityId) { var id = new EntityId(entityId); // Adding a component always updates it, so this will catch the case where the component was just added if (entitiesUpdated.Remove(id)) { updateStorage.RemoveAll(update => update.EntityId.Id == entityId); authorityChanges.RemoveAll(change => change.EntityId.Id == entityId); } if (!componentsAdded.Remove(id)) { componentsRemoved.Add(id); } } public void AddEntityComponent(long entityId, Update component) { var id = new EntityId(entityId); if (!componentsRemoved.Remove(id)) { componentsAdded.Add(id); } AddUpdate(new ComponentUpdateReceived<Update>(component, id, 0)); } public void AddUpdate(ComponentUpdateReceived<Update> update) { entitiesUpdated.Add(update.EntityId); updateStorage.InsertSorted(update, updateComparer); } public void AddAuthorityChange(AuthorityChangeReceived authorityChange) { if (authorityChange.Authority == Authority.NotAuthoritative) { if (authorityLostTemporary.Remove(authorityChange.EntityId) || !authorityGained.Contains(authorityChange.EntityId)) { authorityLost.Add(authorityChange.EntityId); } } else if (authorityChange.Authority == Authority.Authoritative) { if (authorityLost.Remove(authorityChange.EntityId)) { authorityLostTemporary.Add(authorityChange.EntityId); } else { authorityGained.Add(authorityChange.EntityId); } } authorityChanges.InsertSorted(authorityChange, authorityComparer); } public List<EntityId> GetComponentsAdded() { return componentsAdded; } public List<EntityId> GetComponentsRemoved() { return componentsRemoved; } public ReceivedMessagesSpan<ComponentUpdateReceived<Update>> GetUpdates() { return new ReceivedMessagesSpan<ComponentUpdateReceived<Update>>(updateStorage); } public ReceivedMessagesSpan<ComponentUpdateReceived<Update>> GetUpdates(EntityId entityId) { var range = updateStorage.GetEntityRange(entityId); return new ReceivedMessagesSpan<ComponentUpdateReceived<Update>>(updateStorage, range.FirstIndex, range.Count); } public ReceivedMessagesSpan<AuthorityChangeReceived> GetAuthorityChanges() { return new ReceivedMessagesSpan<AuthorityChangeReceived>(authorityChanges); } public ReceivedMessagesSpan<AuthorityChangeReceived> GetAuthorityChanges(EntityId entityId) { var range = authorityChanges.GetEntityRange(entityId); return new ReceivedMessagesSpan<AuthorityChangeReceived>(authorityChanges, range.FirstIndex, range.Count); } } } }
37.968553
135
0.572304
[ "MIT" ]
footman136/dino-park
workers/unity/Assets/Generated/Source/improbable/restricted/PlayerClientComponentDiffStorage.cs
6,037
C#
using System; using Ceen.Mvc; namespace Ceen.PaaS.AdminHandlers { /// <summary> /// Marker interface for choosing the queue v1 /// </summary> [Name("admin")] public interface IAdminAPIv1 : API.IAPIv1 { } }
15.733333
50
0.622881
[ "MIT" ]
Peckmore/ceenhttpd
Ceen.PaaS/AdminHandlers/Interface.cs
236
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using MQTTnet.Implementations; using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace MQTTnet.Tests { [TestClass] public class MqttTcpChannel_Tests { [TestMethod] public async Task Dispose_Channel_While_Used() { var ct = new CancellationTokenSource(); var serverSocket = new CrossPlatformSocket(AddressFamily.InterNetwork); try { serverSocket.Bind(new IPEndPoint(IPAddress.Any, 50001)); serverSocket.Listen(0); #pragma warning disable 4014 Task.Run(async () => #pragma warning restore 4014 { while (!ct.IsCancellationRequested) { var client = await serverSocket.AcceptAsync(); var data = new byte[] { 128 }; await client.SendAsync(new ArraySegment<byte>(data), SocketFlags.None); } }, ct.Token); var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork); await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None); var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null); await Task.Delay(100, ct.Token); var buffer = new byte[1]; await tcpChannel.ReadAsync(buffer, 0, 1, ct.Token); Assert.AreEqual(128, buffer[0]); // This block should fail after dispose. #pragma warning disable 4014 Task.Run(() => #pragma warning restore 4014 { Task.Delay(200, ct.Token); tcpChannel.Dispose(); }, ct.Token); try { await tcpChannel.ReadAsync(buffer, 0, 1, CancellationToken.None); } catch (Exception exception) { Assert.IsInstanceOfType(exception, typeof(SocketException)); Assert.AreEqual(SocketError.OperationAborted, ((SocketException)exception).SocketErrorCode); } } finally { ct.Cancel(false); serverSocket.Dispose(); } } } }
32.328947
112
0.534799
[ "MIT" ]
765643729/MQTTnet
Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs
2,459
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/WebServices.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="WS_XML_INT32_TEXT" /> struct.</summary> public static unsafe partial class WS_XML_INT32_TEXTTests { /// <summary>Validates that the <see cref="WS_XML_INT32_TEXT" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<WS_XML_INT32_TEXT>(), Is.EqualTo(sizeof(WS_XML_INT32_TEXT))); } /// <summary>Validates that the <see cref="WS_XML_INT32_TEXT" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(WS_XML_INT32_TEXT).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="WS_XML_INT32_TEXT" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(WS_XML_INT32_TEXT), Is.EqualTo(8)); } }
37.657143
145
0.72003
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/Windows/um/WebServices/WS_XML_INT32_TEXTTests.cs
1,320
C#
using System.Collections.Generic; namespace TestingRestApiDemo { public class DataRepository { public static ResponseModel GetExpectedResponse(string currency, string date) { return currency switch { "GBP" => new ResponseModel { Table = "A", Currency = "funt szterling", Code = currency, Rates = new List<Rate> { new Rate() { No = "225/A/NBP/2019", EffectiveDate = date, Mid = 5.0144 } } }, "USD" => new ResponseModel { Table = "A", Currency = "dolar amerykański", Code = currency, Rates = new List<Rate> { new Rate() { No = "069/A/NBP/2019", EffectiveDate = date, Mid = 3.8188 } } }, _ => null, }; } } }
29.880952
85
0.330677
[ "MIT" ]
qa-services/testing-rest-api-demo
TestingRestApiDemo/DataRepository.cs
1,258
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.Data.SqlClient; namespace EmpresaX { public partial class Lista_de_Autores : Form { public string conString = "Data Source=GOICOECHEA;Initial Catalog=Biblioteca;Integrated Security=True"; public SqlConnection mycon = new SqlConnection(@"Data Source=GOICOECHEA;Initial Catalog=Biblioteca;Integrated Security=True"); public Lista_de_Autores() { InitializeComponent(); using (SqlConnection sqlCon = new SqlConnection(conString)) { sqlCon.Open(); SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Autor_Mstr", sqlCon); DataTable dtbl = new DataTable(); sqlDa.Fill(dtbl); dgv2.AutoGenerateColumns = false; dgv2.DataSource = dtbl; } } private void Button1_Click(object sender, EventArgs e) { Main objMain = new Main(); this.Hide(); objMain.Show(); } private void TxtFiltrarAutor_Click(object sender, EventArgs e) { txtFiltrarAutor.Clear(); } private void Button2_Click(object sender, EventArgs e) { using (SqlConnection sqlCon = new SqlConnection(conString)) { sqlCon.Open(); SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Autor_Mstr", sqlCon); DataTable dtbl = new DataTable(); sqlDa.Fill(dtbl); dgv2.AutoGenerateColumns = false; dgv2.DataSource = dtbl; } } private void BtnBuscarAutor_Click(object sender, EventArgs e) { if (txtFiltrarAutor.Text == "") { MessageBox.Show("Por favor llenar todos los campos."); } else { using (SqlConnection sqlCon = new SqlConnection(conString)) { sqlCon.Open(); SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Autor_Mstr WHERE Autor_Nombre = '" + txtFiltrarAutor.Text.ToString() + "' ", sqlCon); DataTable dtbl = new DataTable(); sqlDa.Fill(dtbl); dgv2.AutoGenerateColumns = false; dgv2.DataSource = dtbl; } } } private void Lista_de_Autores_Click(object sender, EventArgs e) { Application.Exit(); } private void Lista_de_Autores_Load(object sender, EventArgs e) { } private void Lista_de_Autores_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void Label1_Click(object sender, EventArgs e) { } private void TxtFiltrarAutor_MaskInputRejected(object sender, MaskInputRejectedEventArgs e) { } private void TxtFiltrarAutor_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (txtFiltrarAutor.Text == "") { MessageBox.Show("Por favor llenar todos los campos."); } else { using (SqlConnection sqlCon = new SqlConnection(conString)) { sqlCon.Open(); SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Autor_Mstr WHERE Autor_Nombre = '" + txtFiltrarAutor.Text.ToString() + "' ", sqlCon); DataTable dtbl = new DataTable(); sqlDa.Fill(dtbl); dgv2.AutoGenerateColumns = false; dgv2.DataSource = dtbl; } } } } } }
32.787879
167
0.50878
[ "MIT" ]
pellerano/EmpresaX
Proyecto/EmpresaX/Lista de Autores.cs
4,330
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using MSAst = System.Linq.Expressions; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; public class AssignmentStatement : Statement { // _left.Length is 1 for simple assignments like "x = 1" // _left.Length will be 3 for "x = y = z = 1" private readonly Expression[] _left; public AssignmentStatement(Expression[] left, Expression right) { _left = left; Right = right; } public IList<Expression> Left => _left; public Expression Right { get; } public override MSAst.Expression Reduce() { if (_left.Length == 1) { // Do not need temps for simple assignment return AssignOne(); } else { return AssignComplex(Right); } } private MSAst.Expression AssignComplex(MSAst.Expression right) { // Python assignment semantics: // - only evaluate RHS once. // - evaluates assignment from left to right // - does not evaluate getters. // // So // a=b[c]=d=f() // should be: // $temp = f() // a = $temp // b[c] = $temp // d = $temp List<MSAst.Expression> statements = new List<MSAst.Expression>(); // 1. Create temp variable for the right value MSAst.ParameterExpression right_temp = Expression.Variable(typeof(object), "assignment"); // 2. right_temp = right statements.Add(MakeAssignment(right_temp, right)); // Do left to right assignment foreach (Expression e in _left) { if (e == null) { continue; } // 3. e = right_temp MSAst.Expression transformed = e.TransformSet(Span, right_temp, PythonOperationKind.None); statements.Add(transformed); } // 4. Create and return the resulting suite statements.Add(AstUtils.Empty()); return GlobalParent.AddDebugInfoAndVoid( Ast.Block(new[] { right_temp }, statements.ToArray()), Span ); } private MSAst.Expression AssignOne() { Debug.Assert(_left.Length == 1); SequenceExpression seLeft = _left[0] as SequenceExpression; SequenceExpression seRight = Right as SequenceExpression; bool isStarred = seLeft != null && seLeft.Items.OfType<StarredExpression>().Any(); if (!isStarred && seLeft != null && seRight != null && seLeft.Items.Count == seRight.Items.Count) { int cnt = seLeft.Items.Count; // a, b = 1, 2, or [a,b] = 1,2 - not something like a, b = range(2) // we can do a fast parallel assignment MSAst.ParameterExpression[] tmps = new MSAst.ParameterExpression[cnt]; MSAst.Expression[] body = new MSAst.Expression[cnt * 2 + 1]; // generate the body, the 1st n are the temporary assigns, the // last n are the assignments to the left hand side // 0: tmp0 = right[0] // ... // n-1: tmpn-1 = right[n-1] // n: right[0] = tmp0 // ... // n+n-1: right[n-1] = tmpn-1 // allocate the temps first before transforming so we don't pick up a bad temp... for (int i = 0; i < cnt; i++) { MSAst.Expression tmpVal = seRight.Items[i]; tmps[i] = Ast.Variable(tmpVal.Type, "parallelAssign"); body[i] = Ast.Assign(tmps[i], tmpVal); } // then transform which can allocate more temps for (int i = 0; i < cnt; i++) { body[i + cnt] = seLeft.Items[i].TransformSet(SourceSpan.None, tmps[i], PythonOperationKind.None); } // 4. Create and return the resulting suite body[cnt * 2] = AstUtils.Empty(); return GlobalParent.AddDebugInfoAndVoid(Ast.Block(tmps, body), Span); } return _left[0].TransformSet(Span, Right, PythonOperationKind.None); } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { foreach (Expression e in _left) { e.Walk(walker); } Right.Walk(walker); } walker.PostWalk(this); } } }
35.737931
117
0.535508
[ "Apache-2.0" ]
AnandEmbold/ironpython3
Src/IronPython/Compiler/Ast/AssignmentStatement.cs
5,182
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x19_c40b-7b40bb33")] public void Method_0019_c40b() { ii(0x19_c40b, 4); enter(0x16, 0); /* enter 0x16, 0x0 */ ii(0x19_c40f, 1); push(di); /* push di */ ii(0x19_c410, 1); push(si); /* push si */ ii(0x19_c411, 1); push(ds); /* push ds */ ii(0x19_c412, 3); mov(ax, 0xa8); /* mov ax, 0xa8 */ ii(0x19_c415, 2); mov(ds, ax); /* mov ds, ax */ ii(0x19_c417, 3); les(bx, memw[ss, bp + 6]); /* les bx, [bp+0x6] */ ii(0x19_c41a, 4); les(si, memw[es, bx + 28]); /* les si, [es:bx+0x1c] */ ii(0x19_c41e, 3); mov(es, memw[ss, bp + 8]); /* mov es, [bp+0x8] */ ii(0x19_c421, 4); mov(ax, memw[es, bx + 84]); /* mov ax, [es:bx+0x54] */ ii(0x19_c425, 4); mov(dx, memw[es, bx + 86]); /* mov dx, [es:bx+0x56] */ ii(0x19_c429, 3); mov(memw[ss, bp - 4], ax); /* mov [bp-0x4], ax */ ii(0x19_c42c, 4); mov(cx, memw[es, bx + 80]); /* mov cx, [es:bx+0x50] */ ii(0x19_c430, 4); mov(si, memw[es, bx + 82]); /* mov si, [es:bx+0x52] */ ii(0x19_c434, 2); mov(di, cx); /* mov di, cx */ ii(0x19_c436, 2); mov(bx, cx); /* mov bx, cx */ ii(0x19_c438, 3); shl(di, 2); /* shl di, 0x2 */ ii(0x19_c43b, 2); mov(es, dx); /* mov es, dx */ ii(0x19_c43d, 3); mov(memw[ss, bp - 22], bx); /* mov [bp-0x16], bx */ ii(0x19_c440, 2); mov(bx, ax); /* mov bx, ax */ ii(0x19_c442, 4); mov(ax, memw[es, bx + di - 4]); /* mov ax, [es:bx+di-0x4] */ ii(0x19_c446, 4); mov(dx, memw[es, bx + di - 2]); /* mov dx, [es:bx+di-0x2] */ ii(0x19_c44a, 3); mov(di, memw[ss, bp - 22]); /* mov di, [bp-0x16] */ ii(0x19_c44d, 3); shl(di, 3); /* shl di, 0x3 */ ii(0x19_c450, 4); mov(memw[es, bx + di - 4], ax); /* mov [es:bx+di-0x4], ax */ ii(0x19_c454, 4); mov(memw[es, bx + di - 2], dx); /* mov [es:bx+di-0x2], dx */ ii(0x19_c458, 3); sub(cx, 1); /* sub cx, 0x1 */ ii(0x19_c45b, 3); sbb(si, 0); /* sbb si, 0x0 */ ii(0x19_c45e, 3); mov(memw[ss, bp - 16], cx); /* mov [bp-0x10], cx */ ii(0x19_c461, 3); mov(memw[ss, bp - 14], si); /* mov [bp-0xe], si */ ii(0x19_c464, 2); jmp(0x19_c46e, 8); goto l_0x19_c46e; /* jmp 0xc46e */ l_0x19_c466: ii(0x19_c466, 4); sub(memw[ss, bp - 16], 1); /* sub word [bp-0x10], 0x1 */ ii(0x19_c46a, 4); sbb(memw[ss, bp - 14], 0); /* sbb word [bp-0xe], 0x0 */ l_0x19_c46e: ii(0x19_c46e, 4); cmp(memw[ss, bp - 14], 0); /* cmp word [bp-0xe], 0x0 */ ii(0x19_c472, 2); if(jnz(0x19_c47a, 6)) goto l_0x19_c47a; /* jnz 0xc47a */ ii(0x19_c474, 4); cmp(memw[ss, bp - 16], 0); /* cmp word [bp-0x10], 0x0 */ ii(0x19_c478, 2); if(jz(0x19_c4a6, 0x2c)) goto l_0x19_c4a6;/* jz 0xc4a6 */ l_0x19_c47a: ii(0x19_c47a, 3); mov(bx, memw[ss, bp - 16]); /* mov bx, [bp-0x10] */ ii(0x19_c47d, 2); mov(ax, bx); /* mov ax, bx */ ii(0x19_c47f, 3); shl(bx, 2); /* shl bx, 0x2 */ ii(0x19_c482, 3); mov(si, memw[ss, bp - 4]); /* mov si, [bp-0x4] */ ii(0x19_c485, 3); mov(cx, memw[es, bx + si]); /* mov cx, [es:bx+si] */ ii(0x19_c488, 4); mov(dx, memw[es, bx + si + 2]); /* mov dx, [es:bx+si+0x2] */ ii(0x19_c48c, 2); mov(di, ax); /* mov di, ax */ ii(0x19_c48e, 3); shl(di, 3); /* shl di, 0x3 */ ii(0x19_c491, 2); add(di, si); /* add di, si */ ii(0x19_c493, 4); mov(memw[es, di - 4], cx); /* mov [es:di-0x4], cx */ ii(0x19_c497, 4); mov(memw[es, di - 2], dx); /* mov [es:di-0x2], dx */ ii(0x19_c49b, 2); mov(ax, cx); /* mov ax, cx */ ii(0x19_c49d, 3); mov(memw[es, di], ax); /* mov [es:di], ax */ ii(0x19_c4a0, 4); mov(memw[es, di + 2], dx); /* mov [es:di+0x2], dx */ ii(0x19_c4a4, 2); jmp(0x19_c466, -0x40); goto l_0x19_c466;/* jmp 0xc466 */ l_0x19_c4a6: ii(0x19_c4a6, 2); sub(ax, ax); /* sub ax, ax */ ii(0x19_c4a8, 1); pop(ds); /* pop ds */ ii(0x19_c4a9, 1); pop(si); /* pop si */ ii(0x19_c4aa, 1); pop(di); /* pop di */ ii(0x19_c4ab, 1); leave(); /* leave */ ii(0x19_c4ac, 1); retf(); /* retf */ } } }
75.763158
101
0.377214
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-0019-c40b.cs
5,758
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.PowerShell.EditorServices.Services.PowerShell.Execution { public enum ExecutionPriority { Normal, Next, } // Some of the fields of this class are not orthogonal, // so it's possible to construct self-contradictory execution options. // We should see if it's possible to rework this class to make the options less misconfigurable. // Generally the executor will do the right thing though; some options just priority over others. public record ExecutionOptions { public static ExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, }; public ExecutionPriority Priority { get; init; } public bool MustRunInForeground { get; init; } public bool InterruptCurrentForeground { get; init; } } public record PowerShellExecutionOptions : ExecutionOptions { public static new PowerShellExecutionOptions Default = new() { Priority = ExecutionPriority.Normal, MustRunInForeground = false, InterruptCurrentForeground = false, WriteOutputToHost = false, WriteInputToHost = false, ThrowOnError = true, AddToHistory = false, }; public bool WriteOutputToHost { get; init; } public bool WriteInputToHost { get; init; } public bool ThrowOnError { get; init; } public bool AddToHistory { get; init; } } }
30.814815
101
0.646635
[ "MIT" ]
CALISOULB/PowerShellEditorServices
src/PowerShellEditorServices/Services/PowerShell/Execution/ExecutionOptions.cs
1,666
C#
using System; using System.Collections.Generic; using b2xtranslator.CommonTranslatorLib; using System.Xml; using b2xtranslator.DocFileFormat; using b2xtranslator.OpenXmlLib; namespace b2xtranslator.WordprocessingMLMapping { public class CharacterPropertiesMapping : PropertiesMapping, IMapping<CharacterPropertyExceptions> { private WordDocument _doc; private XmlElement _rPr; private ushort _currentIstd; private RevisionData _revisionData; private bool _styleChpx; private ParagraphPropertyExceptions _currentPapx; List<CharacterPropertyExceptions> _hierarchy; private enum SuperscriptIndex { baseline, superscript, subscript } public CharacterPropertiesMapping(XmlWriter writer, WordDocument doc, RevisionData rev, ParagraphPropertyExceptions currentPapx, bool styleChpx) : base(writer) { this._doc = doc; this._rPr = this._nodeFactory.CreateElement("w", "rPr", OpenXmlNamespaces.WordprocessingML); this._revisionData = rev; this._currentPapx = currentPapx; this._styleChpx = styleChpx; this._currentIstd = UInt16.MaxValue; } public CharacterPropertiesMapping(XmlElement rPr, WordDocument doc, RevisionData rev, ParagraphPropertyExceptions currentPapx, bool styleChpx) : base(null) { this._doc = doc; this._nodeFactory = rPr.OwnerDocument; this._rPr = rPr; this._revisionData = rev; this._currentPapx = currentPapx; this._styleChpx = styleChpx; this._currentIstd = UInt16.MaxValue; } public void Apply(CharacterPropertyExceptions chpx) { //convert the normal SPRMS convertSprms(chpx.grpprl, this._rPr); //apend revision changes if (this._revisionData.Type == RevisionData.RevisionType.Changed) { var rPrChange = this._nodeFactory.CreateElement("w", "rPrChange", OpenXmlNamespaces.WordprocessingML); //date this._revisionData.Dttm.Convert(new DateMapping(rPrChange)); //author var author = this._nodeFactory.CreateAttribute("w", "author", OpenXmlNamespaces.WordprocessingML); author.Value = this._doc.RevisionAuthorTable.Strings[this._revisionData.Isbt]; rPrChange.Attributes.Append(author); //convert revision stack convertSprms(this._revisionData.Changes, rPrChange); this._rPr.AppendChild(rPrChange); } //write properties if (this._writer !=null && (this._rPr.ChildNodes.Count > 0 || this._rPr.Attributes.Count > 0)) { this._rPr.WriteTo(this._writer); } } private void convertSprms(List<SinglePropertyModifier> sprms, XmlElement parent) { var shd = this._nodeFactory.CreateElement("w", "shd", OpenXmlNamespaces.WordprocessingML); var rFonts = this._nodeFactory.CreateElement("w", "rFonts", OpenXmlNamespaces.WordprocessingML); var color = this._nodeFactory.CreateElement("w", "color", OpenXmlNamespaces.WordprocessingML); var colorVal = this._nodeFactory.CreateAttribute("w", "val", OpenXmlNamespaces.WordprocessingML); var lang = this._nodeFactory.CreateElement("w", "lang", OpenXmlNamespaces.WordprocessingML); foreach (var sprm in sprms) { switch ((int)sprm.OpCode) { //style id case 0x4A30: this._currentIstd = System.BitConverter.ToUInt16(sprm.Arguments, 0); appendValueElement(parent, "rStyle", StyleSheetMapping.MakeStyleId(this._doc.Styles.Styles[this._currentIstd]), true); break; //Element flags case 0x085A: appendFlagElement(parent, sprm, "rtl", true); break; case 0x0835: appendFlagElement(parent, sprm, "b", true); break; case 0x085C: appendFlagElement(parent, sprm, "bCs", true); break; case 0x083B: appendFlagElement(parent, sprm, "caps", true); ; break; case 0x0882: appendFlagElement(parent, sprm, "cs", true); break; case 0x2A53: appendFlagElement(parent, sprm, "dstrike", true); break; case 0x0858: appendFlagElement(parent, sprm, "emboss", true); break; case 0x0854: appendFlagElement(parent, sprm, "imprint", true); break; case 0x0836: appendFlagElement(parent, sprm, "i", true); break; case 0x085D: appendFlagElement(parent, sprm, "iCs", true); break; case 0x0875: appendFlagElement(parent, sprm, "noProof", true); break; case 0x0838: appendFlagElement(parent, sprm, "outline", true); break; case 0x0839: appendFlagElement(parent, sprm, "shadow", true); break; case 0x083A: appendFlagElement(parent, sprm, "smallCaps", true); break; case 0x0818: appendFlagElement(parent, sprm, "specVanish", true); break; case 0x0837: appendFlagElement(parent, sprm, "strike", true); break; case 0x083C: appendFlagElement(parent, sprm, "vanish", true); break; case 0x0811: appendFlagElement(parent, sprm, "webHidden", true); break; case 0x2A48: var iss = (SuperscriptIndex)sprm.Arguments[0]; appendValueElement(parent, "vertAlign", iss.ToString(), true); break; //language case 0x486D: case 0x4873: //latin var langid = new LanguageId(System.BitConverter.ToInt16(sprm.Arguments, 0)); langid.Convert(new LanguageIdMapping(lang, LanguageIdMapping.LanguageType.Default)); break; case 0x486E: case 0x4874: //east asia langid = new LanguageId(System.BitConverter.ToInt16(sprm.Arguments, 0)); langid.Convert(new LanguageIdMapping(lang, LanguageIdMapping.LanguageType.EastAsian)); break; case 0x485F: //bidi langid = new LanguageId(System.BitConverter.ToInt16(sprm.Arguments, 0)); langid.Convert(new LanguageIdMapping(lang, LanguageIdMapping.LanguageType.Complex)); break; //borders case 0x6865: case 0xCA72: XmlNode bdr = this._nodeFactory.CreateElement("w", "bdr", OpenXmlNamespaces.WordprocessingML); appendBorderAttributes(new BorderCode(sprm.Arguments), bdr); parent.AppendChild(bdr); break; //shading case 0x4866: case 0xCA71: var desc = new ShadingDescriptor(sprm.Arguments); appendShading(parent, desc); break; //color case 0x2A42: case 0x4A60: colorVal.Value = ((Global.ColorIdentifier)(sprm.Arguments[0])).ToString(); break; case 0x6870: //R colorVal.Value = string.Format("{0:x2}", sprm.Arguments[0]); //G colorVal.Value += string.Format("{0:x2}", sprm.Arguments[1]); //B colorVal.Value += string.Format("{0:x2}", sprm.Arguments[2]); break; //highlightning case 0x2A0C: appendValueElement(parent, "highlight", ((Global.ColorIdentifier)sprm.Arguments[0]).ToString(), true); break; //spacing case 0x8840: appendValueElement(parent, "spacing", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString(), true); break; //font size case 0x4A43: appendValueElement(parent, "sz", sprm.Arguments[0].ToString(), true); break; case 0x484B: appendValueElement(parent, "kern", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString(), true); break; case 0x4A61: appendValueElement(parent, "szCs", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString(), true); break; //font family case 0x4A4F: var ascii = this._nodeFactory.CreateAttribute("w", "ascii", OpenXmlNamespaces.WordprocessingML); var ffn = (FontFamilyName)this._doc.FontTable.Data[System.BitConverter.ToUInt16(sprm.Arguments, 0)]; ascii.Value = ffn.xszFtn; rFonts.Attributes.Append(ascii); break; case 0x4A50: var eastAsia = this._nodeFactory.CreateAttribute("w", "eastAsia", OpenXmlNamespaces.WordprocessingML); var ffnAsia = (FontFamilyName)this._doc.FontTable.Data[System.BitConverter.ToUInt16(sprm.Arguments, 0)]; eastAsia.Value = ffnAsia.xszFtn; rFonts.Attributes.Append(eastAsia); break; case 0x4A51: var ansi = this._nodeFactory.CreateAttribute("w", "hAnsi", OpenXmlNamespaces.WordprocessingML); var ffnAnsi = (FontFamilyName)this._doc.FontTable.Data[System.BitConverter.ToUInt16(sprm.Arguments, 0)]; ansi.Value = ffnAnsi.xszFtn; rFonts.Attributes.Append(ansi); break; case (int)SinglePropertyModifier.OperationCode.sprmCIdctHint: // it's complex script var hint = this._nodeFactory.CreateAttribute("w", "hint", OpenXmlNamespaces.WordprocessingML); hint.Value = "cs"; rFonts.Attributes.Append(hint); break; case (int)SinglePropertyModifier.OperationCode.sprmCFtcBi: // complex script font var cs = this._nodeFactory.CreateAttribute("w", "cs", OpenXmlNamespaces.WordprocessingML); var ffnCs = (FontFamilyName)this._doc.FontTable.Data[System.BitConverter.ToUInt16(sprm.Arguments, 0)]; cs.Value = ffnCs.xszFtn; rFonts.Attributes.Append(cs); break; //Underlining case 0x2A3E: appendValueElement(parent, "u", lowerFirstChar(((Global.UnderlineCode)sprm.Arguments[0]).ToString()), true); break; //char width case 0x4852: appendValueElement(parent, "w", System.BitConverter.ToInt16(sprm.Arguments, 0).ToString(), true); break; //animation case 0x2859: appendValueElement(parent, "effect", ((Global.TextAnimation)sprm.Arguments[0]).ToString(), true); break; default: break; } } //apend lang if (lang.Attributes.Count > 0) { parent.AppendChild(lang); } //append fonts if (rFonts.Attributes.Count > 0) { parent.AppendChild(rFonts); } //append color if (colorVal.Value != "") { color.Attributes.Append(colorVal); parent.AppendChild(color); } } /// <summary> /// CHPX flags are special flags because the can be 0,1,128 and 129, /// so this method overrides the appendFlagElement method. /// </summary> protected override void appendFlagElement(XmlElement node, SinglePropertyModifier sprm, string elementName, bool unique) { byte flag = sprm.Arguments[0]; if(flag != 128) { var ele = this._nodeFactory.CreateElement("w", elementName, OpenXmlNamespaces.WordprocessingML); var val = this._nodeFactory.CreateAttribute("w", "val", OpenXmlNamespaces.WordprocessingML); if (unique) { foreach (XmlElement exEle in node.ChildNodes) { if (exEle.Name == ele.Name) { node.RemoveChild(exEle); break; } } } if (flag == 0) { val.Value = "false"; ele.Attributes.Append(val); node.AppendChild(ele); } else if (flag == 1) { //dont append attribute val //no attribute means true node.AppendChild(ele); } else if(flag == 129) { //Invert the value of the style //determine the style id of the current style ushort styleId = 0; if (this._currentIstd != UInt16.MaxValue) { styleId = this._currentIstd; } else if(this._currentPapx != null) { styleId = this._currentPapx.istd; } //this chpx is the chpx of a style, //don't use the id of the chpx or the papx, use the baseOn style if (this._styleChpx) { var thisStyle = this._doc.Styles.Styles[styleId]; styleId = (ushort)thisStyle.istdBase; } //build the style hierarchy if (this._hierarchy == null) { this._hierarchy = buildHierarchy(this._doc.Styles, styleId); } //apply the toggle values to get the real value of the style bool stylesVal = applyToggleHierachy(sprm); //invert it if (stylesVal) { val.Value = "0"; ele.Attributes.Append(val); } node.AppendChild(ele); } } } private List<CharacterPropertyExceptions> buildHierarchy(StyleSheet styleSheet, ushort istdStart) { var hierarchy = new List<CharacterPropertyExceptions>(); int istd = (int)istdStart; bool goOn = true; while (goOn) { try { var baseChpx = styleSheet.Styles[istd].chpx; if (baseChpx != null) { hierarchy.Add(baseChpx); istd = (int)styleSheet.Styles[istd].istdBase; } else { goOn = false; } } catch (Exception) { goOn = false; } } return hierarchy; } private bool applyToggleHierachy(SinglePropertyModifier sprm) { bool ret = false; foreach (var ancientChpx in this._hierarchy) { foreach (var ancientSprm in ancientChpx.grpprl) { if (ancientSprm.OpCode == sprm.OpCode) { byte ancient = ancientSprm.Arguments[0]; ret = toogleValue(ret, ancient); break; } } } return ret; } private bool toogleValue(bool currentValue, byte toggle) { if (toggle == 1) return true; else if (toggle == 129) //invert the current value if (currentValue) return false; else return true; else if (toggle == 128) //use the current value return currentValue; else return false; } private string lowerFirstChar(string s) { return s.Substring(0, 1).ToLower() + s.Substring(1, s.Length - 1); } } }
41.07489
152
0.469648
[ "BSD-3-Clause" ]
EvolutionJobs/b2xtranslator
Doc/WordprocessingMLMapping/CharacterPropertiesMapping.cs
18,648
C#
using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Navigation; using TRGE.View.Utils; namespace TRGE.View.Windows { /// <summary> /// Interaction logic for AboutWindow.xaml /// </summary> public partial class AboutWindow : Window { #region Dependency Properties public static readonly DependencyProperty AppTitleProperty = DependencyProperty.Register ( "AppTitle", typeof(string), typeof(AboutWindow) ); public static readonly DependencyProperty VersionProperty = DependencyProperty.Register ( "Version", typeof(string), typeof(AboutWindow) ); public static readonly DependencyProperty CopyrightProperty = DependencyProperty.Register ( "Copyright", typeof(string), typeof(AboutWindow) ); public string AppTitle { get => (string)GetValue(AppTitleProperty); private set => SetValue(AppTitleProperty, value); } public string Version { get => (string)GetValue(VersionProperty); private set => SetValue(VersionProperty, value); } public string Copyright { get => (string)GetValue(CopyrightProperty); private set => SetValue(CopyrightProperty, value); } #endregion public AboutWindow() { InitializeComponent(); Owner = WindowUtils.GetActiveWindow(this); DataContext = this; Assembly assembly = Assembly.GetExecutingAssembly(); object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AppTitle = ((AssemblyTitleAttribute)attributes[0]).Title; } else { AppTitle = Path.GetFileNameWithoutExtension(assembly.CodeBase); } Version = ((App)Application.Current).TaggedVersion; attributes = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length > 0) { Copyright = ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } private void Window_Loaded(object sender, RoutedEventArgs e) { WindowUtils.TidyMenu(this); } private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { Process.Start(e.Uri.AbsoluteUri); e.Handled = true; } } }
30.375
102
0.600823
[ "MIT" ]
lahm86/TRGameflowEditor
TRGE.View/Windows/AboutWindow.xaml.cs
2,675
C#
namespace BookstoreApp.Migrations { using BookstoreApp.Data; using BookstoreApp.Models; using BookstoreApp.Models.Accounts; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.IO; using System.Linq; using System.Net.Http; internal sealed class Configuration : DbMigrationsConfiguration<BookstoreContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(BookstoreContext context) { try { this.SeedUsers(context); this.SeedBookCategories(context); this.SeedBooks(context); this.SeedOrders(context); this.SeedShoppingCarts(context); } catch (Exception ex) { throw ex; } } private void SeedBookCategories(BookstoreContext context) { foreach (var item in BookCategories) { var category = new Category() { CategoryName = item }; context.Categories.AddOrUpdate(c => c.CategoryName, category); } context.SaveChanges(); } private void SeedBooks(BookstoreContext context) { using (StreamReader reader = new StreamReader(@"D:\Coding\Telerik Academy Alpha\Module III\Databases\Teamwork Assignment\BookstoreApp\bookstore.csv")) { var client = new HttpClient(); var Random = new Random(); while (!reader.EndOfStream) { try { var line = reader.ReadLine().Split(',').ToArray(); string author = line[3].Trim(); string category = line[4].Trim(); string isbn = line[0]; string bookName = line[2]; string url = line[1]; decimal price = Random.Next(10,20); var image = client.GetByteArrayAsync(url).GetAwaiter().GetResult(); var bookImageToAdd = new BookImage() { Image = image }; var authorToAdd = new Author() { AuthorName = author }; var categoryToAdd = context.Categories .Where(c => c.CategoryName.Equals(category)) .First(); var bookToAdd = new Book() { Title = bookName, Isbn = isbn, Author = authorToAdd, Category = categoryToAdd, BookImage = bookImageToAdd, Price = price }; context.Books.AddOrUpdate(b => b.Isbn, bookToAdd); } catch (Exception ex) { throw ex; } } } context.SaveChanges(); } private void SeedUsers(BookstoreContext context) { var userStore = new UserStore<BookstoreUser, BookstoreRole, int, BookstoreUserLogin, BookstoreUserRole, BookstoreUserClaim>(context); var userManager = new UserManager<BookstoreUser, int>(userStore); #region Users var userSofi = new BookstoreUser() { FirstName = "Sofia", LastName = "Kiryakova", Email = "sf@kiryakova.me", PhoneNumber = "123456", PasswordHash = new PasswordHasher().HashPassword("admin"), UserAddress = "asd", UserName = "sofilofi" }; var userMe = new BookstoreUser() { FirstName = "admin", LastName = "admin", Email = "admin@admin.co", PhoneNumber = "123456", PasswordHash = new PasswordHasher().HashPassword("admin"), UserAddress = "asd", UserName = "vanchopancho" }; var userNick = new BookstoreUser() { FirstName = "Nikolay", LastName = "Nikolov", Email = "you@you", PhoneNumber = "123456", PasswordHash = new PasswordHasher().HashPassword("admin"), UserAddress = "asd", UserName = "nickpick" }; #endregion userManager.Create(userSofi); userManager.Create(userNick); userManager.Create(userMe); context.SaveChanges(); } private void SeedOrders(BookstoreContext context) { var statusInProgress = new OrderStatus() { OrderStatusDescription = "InProgress" }; var rand = new Random(); var entries = context.ChangeTracker.Entries<BookstoreUser>(); foreach (var entry in entries) { var books = context.Books .OrderBy(b => b.Id) .Skip(rand.Next(1, 100)) .Take(3) .ToList(); var order = new Order() { Books = books, OrderCompletedTime = DateTime.Now, ReceivedOrderTime = DateTime.Now, DeliveryAddress = "some address", PhoneNumber = "1234567", User = entry.Entity, OrderStatus = statusInProgress }; context.Orders.Add(order); } context.SaveChanges(); } private void SeedShoppingCarts(BookstoreContext context) { var shoppingCartStatus = new ShoppingCartStatus() { ShoppingCartStatusDescription = "Created" }; var rand = new Random(); var books = context.Books .OrderBy(b => b.Id) .Skip(rand.Next(1, 100)) .Take(5) .ToList(); var user = context.Users.FirstOrDefault(); var shoppingCart = new ShoppingCart() { Books = books, ShoppingCartStatus = shoppingCartStatus, User = user }; context.ShoppingCarts.Add(shoppingCart); context.SaveChanges(); } public static List<string> BookCategories = new List<string>() { "Arts & Photography", "Biographies & Memoirs", "Business & Money", "Calendars", "Children's Books", "Christian Books & Bibles", "Travel", "Test Preparation", "Teen & Young Adult", "Sports & Outdoors", "Self-Help", "Science Fiction & Fantasy", "Science & Math", "Romance", "Religion & Spirituality", "Reference", "Politics & Social Sciences", "Parenting & Relationships", "Mystery & Thriller & Suspense", "Medical Books", "Literature & Fiction", "Law", "Humor & Entertainment", "History", "Health & Fitness & Dieting", "Engineering & Transportation", "Crafts & Hobbies & Home", "Cookbooks & Food & Wine", "Computers & Technology", "Comics & Graphic Novels", }; } }
31.953488
162
0.459486
[ "MIT" ]
The-Lethal-Meerkats/BookstoreApp
BookstoreApp.Data/Migrations/Configuration.cs
8,244
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type WorkbookFunctionsTypeRequest. /// </summary> public partial class WorkbookFunctionsTypeRequest : BaseRequest, IWorkbookFunctionsTypeRequest { /// <summary> /// Constructs a new WorkbookFunctionsTypeRequest. /// </summary> public WorkbookFunctionsTypeRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { this.Method = "POST"; this.ContentType = "application/json"; this.RequestBody = new WorkbookFunctionsTypeRequestBody(); } /// <summary> /// Gets the request body. /// </summary> public WorkbookFunctionsTypeRequestBody RequestBody { get; private set; } /// <summary> /// Issues the POST request. /// </summary> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync() { return this.PostAsync(CancellationToken.None); } /// <summary> /// Issues the POST request. /// </summary> /// <param name=""cancellationToken"">The <see cref=""CancellationToken""/> for the request.</param> /// <returns>The task to await for async call.</returns> public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync( CancellationToken cancellationToken) { return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken); } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsTypeRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookFunctionsTypeRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } } }
35.987805
153
0.57472
[ "MIT" ]
MIchaelMainer/GraphAPI
src/Microsoft.Graph/Requests/Generated/WorkbookFunctionsTypeRequest.cs
2,951
C#
using ObjetoTransferencia2; using System; using System.Linq; using System.Reflection; using System.Windows.Forms; using AcessoBancoDados; using Negocios; namespace Loja_de_calcados.Forms { public partial class pesqItem : Form { public Item itemSelecionado { get; set; } public pesqItem() { InitializeComponent(); dgPesqItem.AutoGenerateColumns = false; } private void btPesqItem_Click(object sender, EventArgs e) { ItemNegocios itemNegocios = new ItemNegocios(); ItemColecao itemColecao = new ItemColecao(); int cod; if (int.TryParse(txPesqItem.Text, out cod) == true) itemColecao = itemNegocios.Consultar(cod, null); else itemColecao = itemNegocios.Consultar(null, txPesqItem.Text); dgPesqItem.DataSource = null; dgPesqItem.DataSource = itemColecao; dgPesqItem.Update(); dgPesqItem.Refresh(); } private object carregarPropriedade(object propriedade, string nomePropriedade) { try { object retorno = ""; if (nomePropriedade.Contains(".")) { PropertyInfo[] propertyInfoArray; string propriedadeAntesDoPonto; propriedadeAntesDoPonto = nomePropriedade.Substring(0, nomePropriedade.IndexOf(".")); if (propriedade != null) { propertyInfoArray = propriedade.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfoArray) { if (propertyInfo.Name == propriedadeAntesDoPonto) { retorno = carregarPropriedade(propertyInfo.GetValue(propriedade, null), nomePropriedade.Substring(nomePropriedade.IndexOf(".") + 1)); } } } } else { Type typePropertyInfo; PropertyInfo propertyInfo; if (propriedade != null) { typePropertyInfo = propriedade.GetType(); propertyInfo = typePropertyInfo.GetProperty(nomePropriedade); retorno = propertyInfo.GetValue(propriedade, null); } } return retorno; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } private void dgPesqItem_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { try { if ((dgPesqItem.Rows[e.RowIndex].DataBoundItem != null) && (dgPesqItem.Columns[e.ColumnIndex].DataPropertyName.Contains("."))) { e.Value = carregarPropriedade(dgPesqItem.Rows[e.RowIndex].DataBoundItem, dgPesqItem.Columns[e.ColumnIndex].DataPropertyName); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btSelecionar_Click(object sender, EventArgs e) { if (dgPesqItem.Rows.Count < 0) { MessageBox.Show("Nenhum registro selecionado."); return; } itemSelecionado = dgPesqItem.SelectedRows[0].DataBoundItem as Item; DialogResult = DialogResult.OK; } private void btCadastrar_Click(object sender, EventArgs e) { cadItens outroForm = new cadItens(); DialogResult dialogResult = outroForm.ShowDialog(); if (dialogResult == DialogResult.Yes) { MessageBox.Show("Item inserido com sucesso!"); } } } }
33.706349
146
0.496586
[ "MIT" ]
bbeltrame01/Calcados
Loja_de_calcados/Forms/pesqItem.cs
4,249
C#
using Akka.Util.Internal; using Krona.Network.P2P; using Krona.Network.P2P.Payloads; using Krona.Persistence; using Krona.Plugins; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; namespace Krona.Ledger { public class MemoryPool : IReadOnlyCollection<Transaction> { // Allow a reverified transaction to be rebroadcasted if it has been this many block times since last broadcast. private const int BlocksTillRebroadcastLowPriorityPoolTx = 30; private const int BlocksTillRebroadcastHighPriorityPoolTx = 10; private int RebroadcastMultiplierThreshold => Capacity / 10; private static readonly double MaxSecondsToReverifyHighPrioTx = (double)Blockchain.SecondsPerBlock / 3; private static readonly double MaxSecondsToReverifyLowPrioTx = (double)Blockchain.SecondsPerBlock / 5; // These two are not expected to be hit, they are just safegaurds. private static readonly double MaxSecondsToReverifyHighPrioTxPerIdle = (double)Blockchain.SecondsPerBlock / 15; private static readonly double MaxSecondsToReverifyLowPrioTxPerIdle = (double)Blockchain.SecondsPerBlock / 30; private readonly KronaSystem _system; // /// <summary> /// Guarantees consistency of the pool data structures. /// /// Note: The data structures are only modified from the `Blockchain` actor; so operations guaranteed to be /// performed by the blockchain actor do not need to acquire the read lock; they only need the write /// lock for write operations. /// </summary> private readonly ReaderWriterLockSlim _txRwLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); /// <summary> /// Store all verified unsorted transactions currently in the pool. /// </summary> private readonly Dictionary<UInt256, PoolItem> _unsortedTransactions = new Dictionary<UInt256, PoolItem>(); /// <summary> /// Stores the verified high priority sorted transactins currently in the pool. /// </summary> private readonly SortedSet<PoolItem> _sortedHighPrioTransactions = new SortedSet<PoolItem>(); /// <summary> /// Stores the verified low priority sorted transactions currently in the pool. /// </summary> private readonly SortedSet<PoolItem> _sortedLowPrioTransactions = new SortedSet<PoolItem>(); /// <summary> /// Store the unverified transactions currently in the pool. /// /// Transactions in this data structure were valid in some prior block, but may no longer be valid. /// The top ones that could make it into the next block get verified and moved into the verified data structures /// (_unsortedTransactions, _sortedLowPrioTransactions, and _sortedHighPrioTransactions) after each block. /// </summary> private readonly Dictionary<UInt256, PoolItem> _unverifiedTransactions = new Dictionary<UInt256, PoolItem>(); private readonly SortedSet<PoolItem> _unverifiedSortedHighPriorityTransactions = new SortedSet<PoolItem>(); private readonly SortedSet<PoolItem> _unverifiedSortedLowPriorityTransactions = new SortedSet<PoolItem>(); // Internal methods to aid in unit testing internal int SortedHighPrioTxCount => _sortedHighPrioTransactions.Count; internal int SortedLowPrioTxCount => _sortedLowPrioTransactions.Count; internal int UnverifiedSortedHighPrioTxCount => _unverifiedSortedHighPriorityTransactions.Count; internal int UnverifiedSortedLowPrioTxCount => _unverifiedSortedLowPriorityTransactions.Count; private int _maxTxPerBlock; private int _maxLowPriorityTxPerBlock; /// <summary> /// Total maximum capacity of transactions the pool can hold. /// </summary> public int Capacity { get; } /// <summary> /// Total count of transactions in the pool. /// </summary> public int Count { get { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Count + _unverifiedTransactions.Count; } finally { _txRwLock.ExitReadLock(); } } } /// <summary> /// Total count of verified transactions in the pool. /// </summary> public int VerifiedCount => _unsortedTransactions.Count; // read of 32 bit type is atomic (no lock) public int UnVerifiedCount => _unverifiedTransactions.Count; public MemoryPool(KronaSystem system, int capacity) { _system = system; Capacity = capacity; LoadMaxTxLimitsFromPolicyPlugins(); } public void LoadMaxTxLimitsFromPolicyPlugins() { _maxTxPerBlock = int.MaxValue; _maxLowPriorityTxPerBlock = int.MaxValue; foreach (IPolicyPlugin plugin in Plugin.Policies) { _maxTxPerBlock = Math.Min(_maxTxPerBlock, plugin.MaxTxPerBlock); _maxLowPriorityTxPerBlock = Math.Min(_maxLowPriorityTxPerBlock, plugin.MaxLowPriorityTxPerBlock); } } /// <summary> /// Determine whether the pool is holding this transaction and has at some point verified it. /// Note: The pool may not have verified it since the last block was persisted. To get only the /// transactions that have been verified during this block use GetVerifiedTransactions() /// </summary> /// <param name="hash">the transaction hash</param> /// <returns>true if the MemoryPool contain the transaction</returns> public bool ContainsKey(UInt256 hash) { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.ContainsKey(hash) || _unverifiedTransactions.ContainsKey(hash); } finally { _txRwLock.ExitReadLock(); } } public bool TryGetValue(UInt256 hash, out Transaction tx) { _txRwLock.EnterReadLock(); try { bool ret = _unsortedTransactions.TryGetValue(hash, out PoolItem item) || _unverifiedTransactions.TryGetValue(hash, out item); tx = ret ? item.Tx : null; return ret; } finally { _txRwLock.ExitReadLock(); } } // Note: This isn't used in Fill during consensus, fill uses GetSortedVerifiedTransactions() public IEnumerator<Transaction> GetEnumerator() { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Select(p => p.Value.Tx) .Concat(_unverifiedTransactions.Select(p => p.Value.Tx)) .ToList() .GetEnumerator(); } finally { _txRwLock.ExitReadLock(); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerable<Transaction> GetVerifiedTransactions() { _txRwLock.EnterReadLock(); try { return _unsortedTransactions.Select(p => p.Value.Tx).ToArray(); } finally { _txRwLock.ExitReadLock(); } } public void GetVerifiedAndUnverifiedTransactions(out IEnumerable<Transaction> verifiedTransactions, out IEnumerable<Transaction> unverifiedTransactions) { _txRwLock.EnterReadLock(); try { verifiedTransactions = _sortedHighPrioTransactions.Reverse().Select(p => p.Tx) .Concat(_sortedLowPrioTransactions.Reverse().Select(p => p.Tx)).ToArray(); unverifiedTransactions = _unverifiedSortedHighPriorityTransactions.Reverse().Select(p => p.Tx) .Concat(_unverifiedSortedLowPriorityTransactions.Reverse().Select(p => p.Tx)).ToArray(); } finally { _txRwLock.ExitReadLock(); } } public IEnumerable<Transaction> GetSortedVerifiedTransactions() { _txRwLock.EnterReadLock(); try { return _sortedHighPrioTransactions.Reverse().Select(p => p.Tx) .Concat(_sortedLowPrioTransactions.Reverse().Select(p => p.Tx)) .ToArray(); } finally { _txRwLock.ExitReadLock(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private PoolItem GetLowestFeeTransaction(SortedSet<PoolItem> verifiedTxSorted, SortedSet<PoolItem> unverifiedTxSorted, out SortedSet<PoolItem> sortedPool) { PoolItem minItem = unverifiedTxSorted.Min; sortedPool = minItem != null ? unverifiedTxSorted : null; PoolItem verifiedMin = verifiedTxSorted.Min; if (verifiedMin == null) return minItem; if (minItem != null && verifiedMin.CompareTo(minItem) >= 0) return minItem; sortedPool = verifiedTxSorted; minItem = verifiedMin; return minItem; } private PoolItem GetLowestFeeTransaction(out Dictionary<UInt256, PoolItem> unsortedTxPool, out SortedSet<PoolItem> sortedPool) { var minItem = GetLowestFeeTransaction(_sortedLowPrioTransactions, _unverifiedSortedLowPriorityTransactions, out sortedPool); if (minItem != null) { unsortedTxPool = Object.ReferenceEquals(sortedPool, _unverifiedSortedLowPriorityTransactions) ? _unverifiedTransactions : _unsortedTransactions; return minItem; } try { return GetLowestFeeTransaction(_sortedHighPrioTransactions, _unverifiedSortedHighPriorityTransactions, out sortedPool); } finally { unsortedTxPool = Object.ReferenceEquals(sortedPool, _unverifiedSortedHighPriorityTransactions) ? _unverifiedTransactions : _unsortedTransactions; } } // Note: this must only be called from a single thread (the Blockchain actor) internal bool CanTransactionFitInPool(Transaction tx) { if (Count < Capacity) return true; return GetLowestFeeTransaction(out _, out _).CompareTo(tx) <= 0; } /// <summary> /// Adds an already verified transaction to the memory pool. /// /// Note: This must only be called from a single thread (the Blockchain actor). To add a transaction to the pool /// tell the Blockchain actor about the transaction. /// </summary> /// <param name="hash"></param> /// <param name="tx"></param> /// <returns></returns> internal bool TryAdd(UInt256 hash, Transaction tx) { var poolItem = new PoolItem(tx); if (_unsortedTransactions.ContainsKey(hash)) return false; List<Transaction> removedTransactions = null; _txRwLock.EnterWriteLock(); try { _unsortedTransactions.Add(hash, poolItem); SortedSet<PoolItem> pool = tx.IsLowPriority ? _sortedLowPrioTransactions : _sortedHighPrioTransactions; pool.Add(poolItem); if (Count > Capacity) removedTransactions = RemoveOverCapacity(); } finally { _txRwLock.ExitWriteLock(); } foreach (IMemoryPoolTxObserverPlugin plugin in Plugin.TxObserverPlugins) { plugin.TransactionAdded(poolItem.Tx); if (removedTransactions != null) plugin.TransactionsRemoved(MemoryPoolTxRemovalReason.CapacityExceeded, removedTransactions); } return _unsortedTransactions.ContainsKey(hash); } private List<Transaction> RemoveOverCapacity() { List<Transaction> removedTransactions = new List<Transaction>(); do { PoolItem minItem = GetLowestFeeTransaction(out var unsortedPool, out var sortedPool); unsortedPool.Remove(minItem.Tx.Hash); sortedPool.Remove(minItem); removedTransactions.Add(minItem.Tx); } while (Count > Capacity); return removedTransactions; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryRemoveVerified(UInt256 hash, out PoolItem item) { if (!_unsortedTransactions.TryGetValue(hash, out item)) return false; _unsortedTransactions.Remove(hash); SortedSet<PoolItem> pool = item.Tx.IsLowPriority ? _sortedLowPrioTransactions : _sortedHighPrioTransactions; pool.Remove(item); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryRemoveUnVerified(UInt256 hash, out PoolItem item) { if (!_unverifiedTransactions.TryGetValue(hash, out item)) return false; _unverifiedTransactions.Remove(hash); SortedSet<PoolItem> pool = item.Tx.IsLowPriority ? _unverifiedSortedLowPriorityTransactions : _unverifiedSortedHighPriorityTransactions; pool.Remove(item); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void InvalidateVerifiedTransactions() { foreach (PoolItem item in _sortedHighPrioTransactions) { if (_unverifiedTransactions.TryAdd(item.Tx.Hash, item)) _unverifiedSortedHighPriorityTransactions.Add(item); } foreach (PoolItem item in _sortedLowPrioTransactions) { if (_unverifiedTransactions.TryAdd(item.Tx.Hash, item)) _unverifiedSortedLowPriorityTransactions.Add(item); } // Clear the verified transactions now, since they all must be reverified. _unsortedTransactions.Clear(); _sortedHighPrioTransactions.Clear(); _sortedLowPrioTransactions.Clear(); } // Note: this must only be called from a single thread (the Blockchain actor) internal void UpdatePoolForBlockPersisted(Block block, Snapshot snapshot) { _txRwLock.EnterWriteLock(); try { // First remove the transactions verified in the block. foreach (Transaction tx in block.Transactions) { if (TryRemoveVerified(tx.Hash, out _)) continue; TryRemoveUnVerified(tx.Hash, out _); } // Add all the previously verified transactions back to the unverified transactions InvalidateVerifiedTransactions(); } finally { _txRwLock.ExitWriteLock(); } // If we know about headers of future blocks, no point in verifying transactions from the unverified tx pool // until we get caught up. if (block.Index > 0 && block.Index < Blockchain.Singleton.HeaderHeight) return; if (Plugin.Policies.Count == 0) return; LoadMaxTxLimitsFromPolicyPlugins(); ReverifyTransactions(_sortedHighPrioTransactions, _unverifiedSortedHighPriorityTransactions, _maxTxPerBlock, MaxSecondsToReverifyHighPrioTx, snapshot); ReverifyTransactions(_sortedLowPrioTransactions, _unverifiedSortedLowPriorityTransactions, _maxLowPriorityTxPerBlock, MaxSecondsToReverifyLowPrioTx, snapshot); } internal void InvalidateAllTransactions() { _txRwLock.EnterWriteLock(); try { InvalidateVerifiedTransactions(); } finally { _txRwLock.ExitWriteLock(); } } private int ReverifyTransactions(SortedSet<PoolItem> verifiedSortedTxPool, SortedSet<PoolItem> unverifiedSortedTxPool, int count, double secondsTimeout, Snapshot snapshot) { DateTime reverifyCutOffTimeStamp = DateTime.UtcNow.AddSeconds(secondsTimeout); List<PoolItem> reverifiedItems = new List<PoolItem>(count); List<PoolItem> invalidItems = new List<PoolItem>(); // Since unverifiedSortedTxPool is ordered in an ascending manner, we take from the end. foreach (PoolItem item in unverifiedSortedTxPool.Reverse().Take(count)) { if (item.Tx.Verify(snapshot, _unsortedTransactions.Select(p => p.Value.Tx))) reverifiedItems.Add(item); else // Transaction no longer valid -- it will be removed from unverifiedTxPool. invalidItems.Add(item); if (DateTime.UtcNow > reverifyCutOffTimeStamp) break; } _txRwLock.EnterWriteLock(); try { int blocksTillRebroadcast = Object.ReferenceEquals(unverifiedSortedTxPool, _sortedHighPrioTransactions) ? BlocksTillRebroadcastHighPriorityPoolTx : BlocksTillRebroadcastLowPriorityPoolTx; if (Count > RebroadcastMultiplierThreshold) blocksTillRebroadcast = blocksTillRebroadcast * Count / RebroadcastMultiplierThreshold; var rebroadcastCutOffTime = DateTime.UtcNow.AddSeconds( -Blockchain.SecondsPerBlock * blocksTillRebroadcast); foreach (PoolItem item in reverifiedItems) { if (_unsortedTransactions.TryAdd(item.Tx.Hash, item)) { verifiedSortedTxPool.Add(item); if (item.LastBroadcastTimestamp < rebroadcastCutOffTime) { _system.LocalNode.Tell(new LocalNode.RelayDirectly { Inventory = item.Tx }, _system.Blockchain); item.LastBroadcastTimestamp = DateTime.UtcNow; } } _unverifiedTransactions.Remove(item.Tx.Hash); unverifiedSortedTxPool.Remove(item); } foreach (PoolItem item in invalidItems) { _unverifiedTransactions.Remove(item.Tx.Hash); unverifiedSortedTxPool.Remove(item); } } finally { _txRwLock.ExitWriteLock(); } var invalidTransactions = invalidItems.Select(p => p.Tx).ToArray(); foreach (IMemoryPoolTxObserverPlugin plugin in Plugin.TxObserverPlugins) plugin.TransactionsRemoved(MemoryPoolTxRemovalReason.NoLongerValid, invalidTransactions); return reverifiedItems.Count; } /// <summary> /// Reverify up to a given maximum count of transactions. Verifies less at a time once the max that can be /// persisted per block has been reached. /// /// Note: this must only be called from a single thread (the Blockchain actor) /// </summary> /// <param name="maxToVerify">Max transactions to reverify, the value passed should be >=2. If 1 is passed it /// will still potentially use 2.</param> /// <param name="snapshot">The snapshot to use for verifying.</param> /// <returns>true if more unsorted messages exist, otherwise false</returns> internal bool ReVerifyTopUnverifiedTransactionsIfNeeded(int maxToVerify, Snapshot snapshot) { if (Blockchain.Singleton.Height < Blockchain.Singleton.HeaderHeight) return false; if (_unverifiedSortedHighPriorityTransactions.Count > 0) { // Always leave at least 1 tx for low priority tx int verifyCount = _sortedHighPrioTransactions.Count > _maxTxPerBlock || maxToVerify == 1 ? 1 : maxToVerify - 1; maxToVerify -= ReverifyTransactions(_sortedHighPrioTransactions, _unverifiedSortedHighPriorityTransactions, verifyCount, MaxSecondsToReverifyHighPrioTxPerIdle, snapshot); if (maxToVerify == 0) maxToVerify++; } if (_unverifiedSortedLowPriorityTransactions.Count > 0) { int verifyCount = _sortedLowPrioTransactions.Count > _maxLowPriorityTxPerBlock ? 1 : maxToVerify; ReverifyTransactions(_sortedLowPrioTransactions, _unverifiedSortedLowPriorityTransactions, verifyCount, MaxSecondsToReverifyLowPrioTxPerIdle, snapshot); } return _unverifiedTransactions.Count > 0; } } }
41.083019
134
0.602554
[ "MIT" ]
krona-project/krona
krona-core/Ledger/MemoryPool.cs
21,776
C#