content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Seurat { [ExecuteInEditMode] public class SeuratAutomator : MonoBehaviour { // Capture Settings [SerializeField, Tooltip("Folders for each headbox will be created in this folder")] public string output_folder_; [SerializeField, Tooltip("If true, all child capture headboxes will have their parameters overriden by the Override settings below")] private bool override_all_ = true; [Header("Override Settings")] [SerializeField, Tooltip("The number of samples per face of the headbox.")] private PositionSampleCount samples_per_face_ = PositionSampleCount.k32; [SerializeField, Tooltip("The resolution of the center image, taken at the camera position at the center of the headbox. This should be 4x higher than the resolution of the remaining samples, for antialiasing.")] private CubeFaceResolution center_resolution_ = CubeFaceResolution.k4096; [SerializeField, Tooltip("The resolution of all samples other than the center.")] private CubeFaceResolution resolution_ = CubeFaceResolution.k1024; [SerializeField, Tooltip("Capture in standard (SDR) or high dynamic range (HDR). HDR requires floating-point render targets, the Camera Component have allow HDR enabled, and enables EXR output.")] private CaptureDynamicRange dynamic_range_ = CaptureDynamicRange.kSDR; // Pipeline Settings [SerializeField, Tooltip("Path to the executable that runs the seurat pipeline")] public string seurat_executable_path_; [Tooltip("If true, cache output geometry in cache folders. Cache speeds up repeated iterations, useful if iterating on textures. Unique folder will be created for each capture.")] public bool use_cache_; [Tooltip("Seurat Commandline Params")] public SeuratParams options = new SeuratParams { //Initialize with default values - note that premultiply_alphas is by default true, but Unity expects false premultiply_alphas = false, gamma = 1.0f, triangle_count = 72000, skybox_radius = 200.0f, fast_preview = false }; // Import Settings [Tooltip("Folder to import meshes & textures to")] public string asset_path_; [Tooltip("List of all seurat meshes imported")] public GameObject[] cur_meshes_; [Tooltip("List of all seurat textures imported")] public Texture2D[] cur_tex_; // Scene Builder Settings [Tooltip("Prefab to be resized for the headbox")] public GameObject headbox_prefab_; [Tooltip("Shader to use for each seurat material")] public Shader seurat_shader_; [Tooltip("Relative path to place each seurat mesh in, relative to the headbox prefab. Leave blank to spawn at root")] public string prefab_path_; [Tooltip("Target render queue position to set material to. Default is 1999, should be around there in order to interact with other objects in the scene.")] public int render_queue_ = 1999; [Tooltip("Select to save a material, instead of creating a local, scene relative material. Recommended")] public bool use_mat_ = true; [Tooltip("Path to place material in. Must be inside Asset folder.")] public string material_path_; [Tooltip("List of all materials built. If use_mat_ is false, this will not be used")] public Material[] cur_mats_; public void OverrideHeadbox(CaptureHeadbox head) { if (override_all_) { head.samples_per_face_ = samples_per_face_; head.center_resolution_ = center_resolution_; head.resolution_ = resolution_; head.dynamic_range_ = dynamic_range_; } } public void OverrideParams(CaptureHeadbox head) { head.options = options; } public void OverrideSceneBuilder(CaptureHeadbox head) { head.prefab_path_ = prefab_path_; head.headbox_prefab_ = headbox_prefab_; head.seurat_shader_ = seurat_shader_; head.render_queue_ = render_queue_; if (use_mat_) { head.material_path_ = material_path_; head.use_mat_ = use_mat_; } } public void BuildScene() { GameObject scene = Instantiate(this.gameObject); CaptureHeadbox[] headboxes = scene.GetComponentsInChildren<CaptureHeadbox>(); foreach (CaptureHeadbox box in headboxes) { box.BuildCapture(true, false); } SeuratAutomator auto = scene.GetComponent<SeuratAutomator>(); DestroyImmediate(auto); } } }
45.805556
220
0.65757
[ "MIT" ]
unoctium1/seurat-unity-plugin
SeuratCapture/Scripts/SeuratAutomator.cs
4,949
C#
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: DocClassEditDyna // ObjectType: DocClassEditDyna // CSLAType: DynamicEditableRoot using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using Csla.Rules; using Csla.Rules.CommonRules; using CslaGenFork.Rules.CollectionRules; using CslaGenFork.Rules.TransformationRules; using DocStore.Business.Security; using System.ComponentModel.DataAnnotations; using UsingLibrary; namespace DocStore.Business { /// <summary> /// Classes of document (dynamic root object).<br/> /// This is a generated <see cref="DocClassEditDyna"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="DocClassEditDynaColl"/> collection. /// </remarks> [Serializable] public partial class DocClassEditDyna : MyBusinessBase<DocClassEditDyna>, IHaveInterface, IHaveGenericInterface<DocClassEditDyna> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="DocClassID"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> DocClassIDProperty = RegisterProperty<int>(p => p.DocClassID, "Doc Class ID"); /// <summary> /// use ID = -1 with empty Name for accepting optional specification /// </summary> /// <value>The Doc Class ID.</value> public int DocClassID { get { return GetProperty(DocClassIDProperty); } } /// <summary> /// Maintains metadata about <see cref="DocClassName"/> property. /// </summary> public static readonly PropertyInfo<string> DocClassNameProperty = RegisterProperty<string>(p => p.DocClassName, "Doc Class Name"); /// <summary> /// Gets or sets the Doc Class Name. /// </summary> /// <value>The Doc Class Name.</value> [Required(AllowEmptyStrings = false, ErrorMessage = "Must fill.")] public string DocClassName { get { return GetProperty(DocClassNameProperty); } set { SetProperty(DocClassNameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date"); /// <summary> /// Date of creation /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUserID"/> property. /// </summary> public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID"); /// <summary> /// ID of the creating user /// </summary> /// <value>The Create User ID.</value> public int CreateUserID { get { return GetProperty(CreateUserIDProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Date of last change /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUserID"/> property. /// </summary> public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID"); /// <summary> /// ID of the last changing user /// </summary> /// <value>The Change User ID.</value> public int ChangeUserID { get { return GetProperty(ChangeUserIDProperty); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Row version counter for concurrency control /// </summary> /// <value>The Row Version.</value> internal byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Gets the Create User Name. /// </summary> /// <value>The Create User Name.</value> public string CreateUserName { get { var result = string.Empty; if (Admin.UserAllNVL.GetUserAllNVL().ContainsKey(CreateUserID)) result = Admin.UserAllNVL.GetUserAllNVL().GetItemByKey(CreateUserID).Value; return result; } } /// <summary> /// Gets the Change User Name. /// </summary> /// <value>The Change User Name.</value> public string ChangeUserName { get { var result = string.Empty; if (Admin.UserAllNVL.GetUserAllNVL().ContainsKey(ChangeUserID)) result = Admin.UserAllNVL.GetUserAllNVL().GetItemByKey(ChangeUserID).Value; return result; } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="DocClassEditDyna"/> object. /// </summary> /// <returns>A reference to the created <see cref="DocClassEditDyna"/> object.</returns> internal static DocClassEditDyna NewDocClassEditDyna() { return DataPortal.Create<DocClassEditDyna>(); } /// <summary> /// Factory method. Loads a <see cref="DocClassEditDyna"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="DocClassEditDyna"/> object.</returns> internal static DocClassEditDyna GetDocClassEditDyna(SafeDataReader dr) { DocClassEditDyna obj = new DocClassEditDyna(); obj.Fetch(dr); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } /// <summary> /// Factory method. Deletes a <see cref="DocClassEditDyna"/> object, based on given parameters. /// </summary> /// <param name="docClassID">The DocClassID of the DocClassEditDyna to delete.</param> internal static void DeleteDocClassEditDyna(int docClassID) { DataPortal.Delete<DocClassEditDyna>(docClassID); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="DocClassEditDyna"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> internal static void NewDocClassEditDyna(EventHandler<DataPortalResult<DocClassEditDyna>> callback) { DataPortal.BeginCreate<DocClassEditDyna>(callback); } /// <summary> /// Factory method. Asynchronously deletes a <see cref="DocClassEditDyna"/> object, based on given parameters. /// </summary> /// <param name="docClassID">The DocClassID of the DocClassEditDyna to delete.</param> /// <param name="callback">The completion callback method.</param> internal static void DeleteDocClassEditDyna(int docClassID, EventHandler<DataPortalResult<DocClassEditDyna>> callback) { DataPortal.BeginDelete<DocClassEditDyna>(docClassID, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DocClassEditDyna"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocClassEditDyna() { // Use factory methods and do not use direct creation. Saved += OnDocClassEditDynaSaved; } #endregion #region Cache Invalidation private void OnDocClassEditDynaSaved(object sender, Csla.Core.SavedEventArgs e) { // this runs on the client DocClassList.InvalidateCache(); DocClassNVL.InvalidateCache(); } /// <summary> /// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e) { if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server && e.Operation == DataPortalOperations.Update) { // this runs on the server DocClassList.InvalidateCache(); DocClassNVL.InvalidateCache(); } } #endregion #region Object Authorization /// <summary> /// Adds the object authorization rules. /// </summary> protected static void AddObjectAuthorizationRules() { BusinessRules.AddRule(typeof (DocClassEditDyna), new IsInRole(AuthorizationActions.CreateObject, "Admin")); BusinessRules.AddRule(typeof (DocClassEditDyna), new IsInRole(AuthorizationActions.GetObject, "User")); BusinessRules.AddRule(typeof (DocClassEditDyna), new IsInRole(AuthorizationActions.EditObject, "Admin")); BusinessRules.AddRule(typeof (DocClassEditDyna), new IsInRole(AuthorizationActions.DeleteObject, "Admin")); AddObjectAuthorizationRulesExtend(); } /// <summary> /// Allows the set up of custom object authorization rules. /// </summary> static partial void AddObjectAuthorizationRulesExtend(); /// <summary> /// Checks if the current user can create a new DocClassEditDyna object. /// </summary> /// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns> public static bool CanAddObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocClassEditDyna)); } /// <summary> /// Checks if the current user can retrieve DocClassEditDyna's properties. /// </summary> /// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns> public static bool CanGetObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocClassEditDyna)); } /// <summary> /// Checks if the current user can change DocClassEditDyna's properties. /// </summary> /// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns> public static bool CanEditObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocClassEditDyna)); } /// <summary> /// Checks if the current user can delete a DocClassEditDyna object. /// </summary> /// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns> public static bool CanDeleteObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocClassEditDyna)); } #endregion #region Business Rules and Property Authorization /// <summary> /// Override this method in your business class to be notified when you need to set up shared business rules. /// </summary> /// <remarks> /// This method is automatically called by CSLA.NET when your object should associate /// per-type validation rules with its properties. /// </remarks> protected override void AddBusinessRules() { base.AddBusinessRules(); // Property Business Rules // DocClassName BusinessRules.AddRule(new CollapseWhiteSpace(DocClassNameProperty) { Priority = -1 }); BusinessRules.AddRule(new NoDuplicates(DocClassNameProperty) { MessageText = "There shall be only one!" }); AddBusinessRulesExtend(); } /// <summary> /// Allows the set up of custom shared business rules. /// </summary> partial void AddBusinessRulesExtend(); #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="DocClassEditDyna"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(DocClassIDProperty, System.Threading.Interlocked.Decrement(ref _lastId)); LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now)); LoadProperty(CreateUserIDProperty, UserInformation.UserId); LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty)); LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty)); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="DocClassEditDyna"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(DocClassIDProperty, dr.GetInt32("DocClassID")); LoadProperty(DocClassNameProperty, dr.GetString("DocClassName")); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="DocClassEditDyna"/> object in the database. /// </summary> protected override void DataPortal_Insert() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("AddDocClassEditDyna", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@DocClassName", ReadProperty(DocClassNameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(DocClassIDProperty, (int) cmd.Parameters["@DocClassID"].Value); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } ctx.Commit(); } } /// <summary> /// Updates in the database all changes made to the <see cref="DocClassEditDyna"/> object. /// </summary> protected override void DataPortal_Update() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("UpdateDocClassEditDyna", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocClassID", ReadProperty(DocClassIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@DocClassName", ReadProperty(DocClassNameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } ctx.Commit(); } } private void SimpleAuditTrail() { LoadProperty(ChangeDateProperty, DateTime.Now); LoadProperty(ChangeUserIDProperty, UserInformation.UserId); OnPropertyChanged("ChangeUserName"); if (IsNew) { LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty)); LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty)); OnPropertyChanged("CreateUserName"); } } /// <summary> /// Self deletes the <see cref="DocClassEditDyna"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(DocClassID); } /// <summary> /// Deletes the <see cref="DocClassEditDyna"/> object from database. /// </summary> /// <param name="docClassID">The delete criteria.</param> protected void DataPortal_Delete(int docClassID) { // audit the object, just in case soft delete is used on this object SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("DeleteDocClassEditDyna", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocClassID", docClassID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, docClassID); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } ctx.Commit(); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
42.243194
140
0.594948
[ "MIT" ]
CslaGenFork/CslaGenFork
trunk/CoverageTest/Inherits/Inherits-WIN-CS/DocStore.Business/DocClassEditDyna.Designer.cs
23,276
C#
namespace Merchello.Core.Services { /// <summary> /// Defines the ServiceContext, which provides access to the following services: /// <see cref="ICustomerService"/> /// </summary> public interface IServiceContext { /// <summary> /// Gets the <see cref="ICustomerService"/> /// </summary> ICustomerService CustomerService { get; } /// <summary> /// Gets the <see cref="IGatewayProviderService"/> /// </summary> IGatewayProviderService GatewayProviderService { get; } /// <summary> /// Gets the <see cref="IInvoiceService"/> /// </summary> IInvoiceService InvoiceService { get; } /// <summary> /// Gets the <see cref="ItemCacheService"/> /// </summary> IItemCacheService ItemCacheService { get; } /// <summary> /// Gets the <see cref="IOrderService"/> /// </summary> IOrderService OrderService { get; } /// <summary> /// Gets the <see cref="IPaymentService"/> /// </summary> IPaymentService PaymentService { get; } /// <summary> /// Gets the <see cref="IProductService"/> /// </summary> IProductService ProductService { get; } /// <summary> /// Gets the <see cref="IProductVariantService"/> /// </summary> IProductVariantService ProductVariantService { get; } ///// <summary> ///// Gets the <see cref="IShipCountryService"/> ///// </summary> //IShipCountryService ShipCountryService { get; } /// <summary> /// Gets the <see cref="IStoreSettingService"/> /// </summary> IStoreSettingService StoreSettingService { get; } /// <summary> /// Gets the <see cref="IShipmentService"/> /// </summary> IShipmentService ShipmentService { get; } /// <summary> /// Gets the <see cref="IWarehouseService"/> /// </summary> IWarehouseService WarehouseService { get; } } }
29.464789
84
0.547323
[ "MIT" ]
bowserm/Merchello
src/Merchello.Core/Services/Interfaces/IServiceContext.cs
2,094
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Microsoft.ML; [assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.TestFramework" + PublicKey.Value)] [assembly: InternalsVisibleTo(assemblyName: "Microsoft.ML.Core.Tests" + PublicKey.TestValue)] [assembly: WantsToBeBestFriends]
44.090909
93
0.795876
[ "MIT" ]
GitHubPang/machinelearning
src/Microsoft.ML.Parquet/Properties/AssemblyInfo.cs
487
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; namespace FASTER.core { /// <summary> /// Scan buffering mode /// </summary> public enum ScanBufferingMode { /// <summary> /// Buffer only current page being scanned /// </summary> SinglePageBuffering, /// <summary> /// Buffer current and next page in scan sequence /// </summary> DoublePageBuffering } /// <summary> /// Scan iterator interface for FASTER log /// </summary> /// <typeparam name="Key"></typeparam> /// <typeparam name="Value"></typeparam> public interface IFasterScanIterator<Key, Value> : IDisposable { /// <summary> /// Get next record /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns>True if record found, false if end of scan</returns> bool GetNext(out Key key, out Value value); } }
25.95
73
0.571291
[ "MIT" ]
MasterMann/FASTER
cs/src/core/Allocator/IFasterScanIterator.cs
1,040
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NMatcher.Matching.Expanders { public interface IDoubleExpander { bool Matches(double value); } }
17.5
37
0.738776
[ "MIT" ]
defrag/NMatcher
src/NMatcher/Matching/Expanders/IDoubleExpander.cs
247
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace edu.cwru.weatherhead.WebConfigEncrypt.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
40.444444
151
0.588828
[ "MIT" ]
wsomweb/WebConfigEncrypt
WebConfigEncrypt/Properties/Settings.Designer.cs
1,094
C#
using Microsoft.Extensions.DependencyInjection; using Telegram.Bot.Advanced.Core.Holder; namespace Telegram.Bot.Advanced.Extensions { public static class ServiceCollectionExtensions { public static IServiceCollection AddTelegramHolder(this IServiceCollection services, params ITelegramBotData[] bots) { services.AddSingleton<ITelegramHolder, TelegramHolder>( holder => new TelegramHolder(bots) ); // Register controllers to DI foreach (var bot in bots) { bot.Dispatcher.RegisterController(services); } return services; } /* public static IServiceCollection AddTelegramPolling<TContext, TController>(this IServiceCollection services, params ITelegramBotData[] bots) where TContext : TelegramContext, new() where TController : class, ITelegramController<TContext>, new() { services.TryAddSingleton<ITelegramHolder>(); services.AddScoped<TController>(); return services; } */ } }
35.78125
149
0.627074
[ "MIT" ]
fuji97/Telegram.Bot.Advanced
Telegram.Bot.Advanced/Extensions/ServiceCollectionExtensions.cs
1,147
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; // <summary> // DirectOutput.Cab.Out is the namespace for all output controller related classes like different output controller classes (all implementing IOutputController). // </summary> namespace DirectOutput.Cab.Out { }
23.428571
162
0.753049
[ "MIT" ]
Ashram56/DirectOutput
DirectOutput/Cab/Out/Out.cs
330
C#
using Jobs; using Pandaros.API; using Pandaros.API.Items; using Pandaros.API.Models; using Pandaros.Civ.Jobs; using Pandaros.Civ.TimePeriods.PreHistory.Items; using Pandaros.Civ.TimePeriods.StoneAge.Items; using Recipes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pandaros.Civ.TimePeriods.PreHistory.Jobs { [ModLoader.ModManager] public static class PrimitiveBerryForagerModEntries { [ModLoader.ModCallback(ModLoader.EModCallbackType.AfterItemTypesDefined, GameSetup.NAMESPACE + ".TimePeriods.PreHistory.Jobs.PrimitiveBerryForagerModEntry")] [ModLoader.ModCallbackProvidesFor("create_savemanager")] public static void AfterDefiningNPCTypes() { ServerManager.BlockEntityCallbacks.RegisterEntityManager( new BlockJobManager<PandaGoalJob>( new PrimitiveBerryForager(), (setting, pos, type, bytedata) => new PandaGoalJob(setting, pos, type, bytedata), (setting, pos, type, colony) => new PandaGoalJob(setting, pos, type, colony) ) ); } } public class PrimitiveBerryForagerSettings : INPCTypeStandardSettings { public string keyName { get; set; } = PrimitiveBerryForager.Name; public string printName { get; set; } = "Primitive Berry Forager"; public float inventoryCapacity { get; set; } = 150f; public float movementSpeed { get; set; } = 2f; public UnityEngine.Color32 maskColor1 { get; set; } = new UnityEngine.Color32(161, 58, 47, 255); public UnityEngine.Color32 maskColor0 { get; set; } } public class PrimitiveBerryForager : ForagingJobSettings { public static string Name = GameSetup.GetNamespace("TimePeriods.PreHistory.Jobs", nameof(PrimitiveBerryForager)); public static LootTable SharedLootTable { get; set; } = new LootTable() { name = Name, LootPoolList = new List<LootPoolEntry>() { new LootPoolEntry(ColonyBuiltIn.ItemTypes.BERRY, 4, 8), new LootPoolEntry(ColonyBuiltIn.ItemTypes.BERRY, 2, 5, 0.4f), new LootPoolEntry(ColonyBuiltIn.ItemTypes.BERRY, 2, 4, 0.4f), new LootPoolEntry(ColonyBuiltIn.ItemTypes.BERRY, 2, 3, 0.1f) } }; public PrimitiveBerryForager() : base(Name, Name, SharedLootTable, 30, 40, 0) { } } public class PrimitiveBerryForagerJobType : CSGenerateType { public override string typeName => PrimitiveBerryForager.Name; public override string generateType => "jobOutline"; public override string outlineColor => "#a13a2f"; } }
38.260274
165
0.663086
[ "MIT" ]
JBurlison/Pandaros.Civ
Pandaros.Civ/TimePeriods/PreHistory/Jobs/PrimitiveBerryForager.cs
2,795
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. namespace Microsoft.Azure.Devices.Edge.Azure.Monitor { using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; public interface IMetricsPublisher { /// <summary> /// Publishes metrics to a source. /// </summary> /// <param name="metrics">Metrics to publish.</param> /// <param name="cancellationToken">Cancels task.</param> /// <returns>True if successful, false if unsuccessful and should be retried.</returns> Task<bool> PublishAsync(IEnumerable<Metric> metrics, CancellationToken cancellationToken); } }
33.142857
98
0.676724
[ "MIT" ]
Ellerbach/AzureMonitor
src/Microsoft.Azure.Devices.Edge.Azure.Monitor/IMetricsPublisher.cs
696
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { /// <summary> /// The status of categorization for the job. /// </summary> [StringEnum] public enum ModelCategorizationStatus { /// <summary> /// Categorization is performing acceptably well (or not being used at all). /// </summary> [EnumMember(Value = "ok")] OK, /// <summary> /// Categorization is detecting a distribution of categories that suggests the input data is inappropriate for categorization. /// Problems could be that there is only one category, more than 90% of categories are rare, the number of categories is greater /// than 50% of the number of categorized documents, there are no frequently matched categories, or more than 50% of categories /// are dead. /// </summary> [EnumMember(Value = "warn")] Warn } }
32.78125
130
0.723546
[ "Apache-2.0" ]
Atharvpatel21/elasticsearch-net
src/Nest/Cat/CatJobs/ModelCategorizationStatus.cs
1,049
C#
using System; using System.Collections.Generic; using System.Text; namespace Blog.Core.Model.ViewModels { /// <summary> /// 调度任务触发器信息实体 /// </summary> public class TaskInfoDto { /// <summary> /// 任务ID /// </summary> public string jobId { get; set; } /// <summary> /// 任务名称 /// </summary> public string jobName { get; set; } /// <summary> /// 任务分组 /// </summary> public string jobGroup { get; set; } /// <summary> /// 触发器ID /// </summary> public string triggerId { get; set; } /// <summary> /// 触发器名称 /// </summary> public string triggerName { get; set; } /// <summary> /// 触发器分组 /// </summary> public string triggerGroup { get; set; } /// <summary> /// 触发器状态 /// </summary> public string triggerStatus { get; set; } } }
23.095238
49
0.469072
[ "MIT" ]
861191244/Blog.Core
Blog.Core.Model/ViewModels/TaskInfoDto.cs
1,050
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class player_asteroids : MonoBehaviour { public int player_num; public float angularSpeed; private float horizontal; private Vector2 bulletPosition; public float offsetBullet; public GameObject bulletPrefab; public GameObject explosion; private int health = 2; public static bool playerIsAlive = true; public static string winMultiplayer; public static bool shooting; public float timeRemaining = 2.0f; // Start is called before the first frame update void Start() { playerIsAlive = true; } // Update is called once per frame void Update() { //horizontal = InputManager.Horizontal; // player_asteroids.shooting = InputManager.Fire; //Rotate(); if(timeRemaining>0){ timeRemaining -= Time.deltaTime; }else{ timeRemaining = 2.0f; if(player_asteroids.shooting == true){ Shoot(); } } // if (transform.rotation.x != 0|| transform.rotation.y != 0){ // print("Corrected!"); // transform.rotation = Quaternion.Euler(0,0,transform.rotation.z); // } } public void Rotate() { transform.Rotate(0, 0, -angularSpeed * horizontal * Time.deltaTime); } private void Shoot() { if(player_asteroids.shooting){ var pos = transform.up * offsetBullet + transform.position; var bullet = Instantiate( bulletPrefab, pos, transform.rotation ); Destroy(bullet, 5); player_asteroids.shooting = false; } } private void OnTriggerEnter2D(Collider2D other) { string msg; if (other.CompareTag("enemy")){ health--; if (health == 0) { Kill(); //Destroy Ship } else{ msg = "Force Field Damaged!"; print(msg); // Destroy(forceField.gameObject); Destroy(other.gameObject); } } } public void Kill(){ if(gameController.multiplayerLvl == true) { /* staticPorts.scorePlyr1 = staticPorts.scorePlyr1+1; staticPorts.scorePlyr2 = staticPorts.scorePlyr2+1; */ Destroy(gameObject); Instantiate(explosion, transform.position, transform.rotation); Destroy(explosion, 5); UpdateScore(player_num); // You pass the loser as an argument to update the score winMultiplayer = string.Format("Player {0} Lose!", player_num); print("You are dead!"); playerIsAlive = false; } else{ Destroy(gameObject); Instantiate(explosion, transform.position, transform.rotation); Destroy(explosion, 5); print("You are dead!"); playerIsAlive = false; } } void UpdateScore(int playerNumber){ if(playerNumber==2){ staticPorts.scorePlyr1 = staticPorts.scorePlyr1 + 1; }else if(playerNumber==1){ staticPorts.scorePlyr2 = staticPorts.scorePlyr2 + 1; } } }
27.507937
97
0.538084
[ "MIT" ]
BrunoBustos96/bci_jam_ssvep_unity
Assets/_manuel/MyScripts/player_asteroids.cs
3,466
C#
/* The MIT License (MIT) Copyright (c) 2016 Roaring Fangs Entertainment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; namespace RoaringFangs.Utility { [System.Serializable] public class KVPWrap<T, U> { public T Key; public U Value; public KeyValuePair<T, U> Self { get { return new KeyValuePair<T, U>(Key, Value); } set { Key = value.Key; Value = value.Value; } } public KVPWrap() { } public KVPWrap(KeyValuePair<T, U> self) { Key = self.Key; Value = self.Value; } } }
29.965517
77
0.663406
[ "MIT" ]
Tarocco/roaring-fangs-unity
Source/RoaringFangs/Utility/KVPWrap.cs
1,740
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1.Medium { public static class Class99 { } }
15
33
0.74359
[ "MIT" ]
mydim/CodingAlgorithm
ConsoleApp1/1Medium/Other/Class99.cs
197
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineCaptureDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMName = new RuntimeDefinedParameter(); pVMName.Name = "VMName"; pVMName.ParameterType = typeof(string); pVMName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMName", pVMName); var pVhdPrefix = new RuntimeDefinedParameter(); pVhdPrefix.Name = "VhdPrefix"; pVhdPrefix.ParameterType = typeof(string); pVhdPrefix.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pVhdPrefix.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VhdPrefix", pVhdPrefix); var pOverwriteVhd = new RuntimeDefinedParameter(); pOverwriteVhd.Name = "OverwriteVhd"; pOverwriteVhd.ParameterType = typeof(bool); pOverwriteVhd.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = false }); pOverwriteVhd.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("OverwriteVhd", pOverwriteVhd); var pDestinationContainerName = new RuntimeDefinedParameter(); pDestinationContainerName.Name = "DestinationContainerName"; pDestinationContainerName.ParameterType = typeof(string); pDestinationContainerName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 5, Mandatory = false }); pDestinationContainerName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("DestinationContainerName", pDestinationContainerName); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 6, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineCaptureMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmName = (string)ParseParameter(invokeMethodInputParameters[1]); var parameters = new VirtualMachineCaptureParameters(); var pVhdPrefix = (string) ParseParameter(invokeMethodInputParameters[2]); parameters.VhdPrefix = pVhdPrefix; var pOverwriteVhds = (bool) ParseParameter(invokeMethodInputParameters[3]); parameters.OverwriteVhds = pOverwriteVhds; var pDestinationContainerName = (string) ParseParameter(invokeMethodInputParameters[4]); parameters.DestinationContainerName = pDestinationContainerName; var result = VirtualMachinesClient.Capture(resourceGroupName, vmName, parameters); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineCaptureParameters() { string resourceGroupName = string.Empty; string vmName = string.Empty; VirtualMachineCaptureParameters parameters = new VirtualMachineCaptureParameters(); return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMName", "Parameters" }, new object[] { resourceGroupName, vmName, parameters }); } } }
43.888889
101
0.64193
[ "MIT" ]
FonsecaSergio/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Generated/VirtualMachine/VirtualMachineCaptureMethod.cs
6,177
C#
using System; using System.Collections.Generic; namespace SKIT.FlurlHttpClient.Wechat.Api.Events { /// <summary> /// <para>表示 EVENT.transport_add_order 事件的数据。</para> /// <para>REF: https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/immediate-delivery/by-provider/immediateDelivery.onOrderAdd.html </para> /// </summary> public class TransportAddOrderEvent : TransportPreCreateOrderEvent, WechatApiEvent.Serialization.IJsonSerializable { /// <summary> /// 获取或设置微信订单 Token。 /// </summary> [Newtonsoft.Json.JsonProperty("wx_token")] [System.Text.Json.Serialization.JsonPropertyName("wx_token")] public string Token { get; set; } = default!; } }
36.95
161
0.690122
[ "MIT" ]
arden27336/DotNetCore.SKIT.FlurlHttpClient.Wechat
src/SKIT.FlurlHttpClient.Wechat.Api/Events/WxaImmediateDelivery/TransportAddOrderEvent.cs
777
C#
using System; using System.IO; using System.Web; namespace Serenity.Web { public static class CssFileWatcher { public static void WatchForChanges(string path = "~/Content") { var sw = new FileSystemWatcher(HttpContext.Current.Server.MapPath(path)); sw.IncludeSubdirectories = true; sw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite; sw.Changed += (s, e) => Changed(e.Name); sw.Created += (s, e) => Changed(e.Name); sw.Deleted += (s, e) => Changed(e.Name); sw.Renamed += (s, e) => Changed(e.OldName); sw.EnableRaisingEvents = true; } private static void Changed(string name) { var extension = Path.GetExtension(name); if (extension == null || string.Compare(extension, ".css", StringComparison.OrdinalIgnoreCase) != 0) return; ContentHashCache.ScriptsChanged(); ScriptBundleManager.ScriptsChanged(); } } }
33.709677
112
0.583732
[ "MIT" ]
kingajay007/SeeSharper-Master
Serenity.Web/Common/CssFileWatcher.cs
1,047
C#
using System; using System.Diagnostics; using i64 = System.Int64; using u8 = System.Byte; using u32 = System.UInt32; using u64 = System.UInt64; namespace Community.CsharpSqlite { public partial class Globals { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code to implement a pseudo-random number ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* All threads share a single random number generator. ** This structure is the current state of the generator. */ public class sqlite3PrngType { public bool isInit; /* True if initialized */ public int i; public int j; /* State variables */ public u8[] s = new u8[256]; /* State variables */ public sqlite3PrngType Copy() { sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone(); cp.s = new u8[s.Length]; Array.Copy( s, cp.s, s.Length ); return cp; } } public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType(); /* ** Get a single 8-bit random value from the RC4 PRNG. The Mutex ** must be held while executing this routine. ** ** Why not just use a library random generator like lrand48() for this? ** Because the OP_NewRowid opcode in the VDBE depends on having a very ** good source of random numbers. The lrand48() library function may ** well be good enough. But maybe not. Or maybe lrand48() has some ** subtle problems on some systems that could cause problems. It is hard ** to know. To minimize the risk of problems due to bad lrand48() ** implementations, SQLite uses this random number generator based ** on RC4, which we know works very well. ** ** (Later): Actually, OP_NewRowid does not depend on a good source of ** randomness any more. But we will leave this code in all the same. */ static u8 randomu8() { u8 t; /* The "wsdPrng" macro will resolve to the pseudo-random number generator ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdPrng can refer directly ** to the "sqlite3Prng" state vector declared above. */ #if SQLITE_OMIT_WSD struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng); //# define wsdPrng p[0] #else //# define wsdPrng sqlite3Prng sqlite3PrngType wsdPrng = sqlite3Prng; #endif /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ if ( !wsdPrng.isInit ) { int i; u8[] k = new u8[256]; wsdPrng.j = 0; wsdPrng.i = 0; sqlite3OsRandomness( sqlite3_vfs_find( "" ), 256, k ); for ( i = 0; i < 255; i++ ) { wsdPrng.s[i] = (u8)i; } for ( i = 0; i < 255; i++ ) { wsdPrng.j = (u8)( wsdPrng.j + wsdPrng.s[i] + k[i] ); t = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = wsdPrng.s[i]; wsdPrng.s[i] = t; } wsdPrng.isInit = true; } /* Generate and return single random u8 */ wsdPrng.i++; t = wsdPrng.s[(u8)wsdPrng.i]; wsdPrng.j = (u8)( wsdPrng.j + t ); wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j]; wsdPrng.s[wsdPrng.j] = t; t += wsdPrng.s[(u8)wsdPrng.i]; return wsdPrng.s[t]; } /* ** Return N random u8s. */ static void sqlite3_randomness( int N, ref i64 pBuf ) { //u8[] zBuf = new u8[N]; pBuf = 0; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_PRNG ); #endif sqlite3_mutex_enter( mutex ); while ( N-- > 0 ) { pBuf = (u32)( ( pBuf << 8 ) + randomu8() );// zBuf[N] = randomu8(); } sqlite3_mutex_leave( mutex ); } static void sqlite3_randomness( byte[] pBuf, int Offset, int N ) { i64 iBuf = System.DateTime.Now.Ticks; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG); #endif sqlite3_mutex_enter( mutex ); while ( N-- > 0 ) { iBuf = (u32)( ( iBuf << 8 ) + randomu8() );// zBuf[N] = randomu8(); pBuf[Offset++] = (byte)iBuf; } sqlite3_mutex_leave( mutex ); } #if !SQLITE_OMIT_BUILTIN_TEST /* ** For testing purposes, we sometimes want to preserve the state of ** PRNG and restore the PRNG to its saved state at a later time, or ** to reset the PRNG to its initial state. These routines accomplish ** those tasks. ** ** The sqlite3_test_control() interface calls these routines to ** control the PRNG. */ static sqlite3PrngType sqlite3SavedPrng = null; static void sqlite3PrngSaveState() { sqlite3SavedPrng = sqlite3Prng.Copy(); // memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // sizeof(sqlite3Prng) //); } static void sqlite3PrngRestoreState() { sqlite3Prng = sqlite3SavedPrng.Copy(); //memcpy( // &GLOBAL(struct sqlite3PrngType, sqlite3Prng), // &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng), // sizeof(sqlite3Prng) //); } static void sqlite3PrngResetState() { sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } }
34.5
93
0.587525
[ "MIT" ]
ArsenShnurkov/csharp-sqlite
Community.CsharpSqlite/src/engine_basis/encryption/random_c.cs
7,038
C#
using Prism.Mvvm; using Prism.Navigation; namespace Prism.DI.Forms.Tests.Mocks.ViewModels { public class XamlViewMockAViewModel : BindableBase, INavigationAware { private string _fizz; private string _test = "Initial Value"; public string Fizz { get => _fizz; set => SetProperty(ref _fizz, value); } public string Test { get => _test; set => SetProperty(ref _test, value); } public void OnNavigatedFrom(INavigationParameters parameters) { } public void OnNavigatedTo(INavigationParameters parameters) { parameters.TryGetValue(nameof(Fizz), out _fizz); RaisePropertyChanged(nameof(Fizz)); } public void OnNavigatingTo(INavigationParameters parameters) { } } }
23.289474
72
0.587571
[ "MIT" ]
HenJigg/Prism
tests/Forms/Prism.DI.Forms.Tests/Mocks/ViewModels/XamlViewMockAViewModel.cs
885
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NationalInstruments.DataTypes; using NationalInstruments.Design; using NationalInstruments.SourceModel; using NationalInstruments.SourceModel.Envoys; namespace Rebar.SourceModel.TypeDiagram { internal class TypeDiagramCacheService : BasicCacheService, IProvideDataType { public string DisplayName => AssociatedEnvoy.Name.Last; public async Task<NIType> GetDataTypeAsync() { await InitializeAsync(null); return TypeDiagramCache?.DataType ?? NIType.Unset; } /// <inheritdoc /> protected override BasicModelCache CreateBasicModelCache() => new TypeDiagramCache(); private TypeDiagramCache TypeDiagramCache => BasicModelCache as TypeDiagramCache; /// <inheritdoc /> protected override IEnumerable<string> GetExportChangesFromTransaction(TransactionEventArgs e) => TypeDiagramCache?.OnModelEdits(e) ?? Enumerable.Empty<string>(); } /// <summary> /// Factory class for <see cref="GTypeDefinitionCacheService"/> /// </summary> [ExportEnvoyServiceFactory(typeof(IProvideDataType))] [ProvidedInterface(typeof(IDependencyTargetExport))] [BindsToModelDefinitionType(TypeDiagramDefinition.TypeDiagramDefinitionType)] [BindOnTargeted] // TODO: US151337 - This service must be attached on the UI thread (see CAR# 651774 for more info) but there is not a good way to specify this. Use BindOnTargeted to ensure attach occurs on the UI thread. Ideally, this should be BindOnLoaded. public class TypeDiagramCacheServiceFactory : EnvoyServiceFactory { /// <inheritdoc/> protected override EnvoyService CreateService() { return new TypeDiagramCacheService(); } } }
39.255319
263
0.723577
[ "MIT" ]
ni/rebar
src/Rebar/SourceModel/TypeDiagram/TypeDiagramCacheService.cs
1,847
C#
namespace MassTransit.Context { using System; using System.Threading.Tasks; using GreenPipes; public interface RequestHandlerHandle : ConnectHandle { void TrySetException(Exception exception); void TrySetCanceled(); Task<T> GetTask<T>(); } }
17.705882
50
0.644518
[ "ECL-2.0", "Apache-2.0" ]
MathiasZander/ServiceFabricPerfomanceTest
src/MassTransit/Context/RequestHandlerHandle.cs
301
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace ordercloud.integrations.library { public class ApiParameter : ApiField { public ParameterInfo ParamInfo { get; set; } public bool IsListArg { get; set; } public override Type Type => ParamInfo.ParameterType; public override bool HasDefaultValue => ParamInfo.HasDefaultValue; public override object DefaultValue => ParamInfo.DefaultValue; } }
29.294118
74
0.718876
[ "MIT" ]
Labedlam/headstart
src/Middleware/integrations/ordercloud.integrations.library/openapispec/ApiParameter.cs
500
C#
/* * Precisely APIs * * Enhance & enrich your data, applications, business processes, and workflows with rich location, information, and identify APIs. * * OpenAPI spec version: 11.8.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace com.precisely.apis.Model { /// <summary> /// EarthquakeRiskLocationResponse /// </summary> [DataContract] public partial class EarthquakeRiskLocationResponse : IEquatable<EarthquakeRiskLocationResponse> { /// <summary> /// Initializes a new instance of the <see cref="EarthquakeRiskLocationResponse" /> class. /// </summary> /// <param name="RiskLevel">RiskLevel.</param> /// <param name="EventsCount">EventsCount.</param> /// <param name="Grid">Grid.</param> public EarthquakeRiskLocationResponse(string RiskLevel = null, EventsCount EventsCount = null, Grid Grid = null) { this.RiskLevel = RiskLevel; this.EventsCount = EventsCount; this.Grid = Grid; } /// <summary> /// Gets or Sets RiskLevel /// </summary> [DataMember(Name="riskLevel", EmitDefaultValue=false)] public string RiskLevel { get; set; } /// <summary> /// Gets or Sets EventsCount /// </summary> [DataMember(Name="eventsCount", EmitDefaultValue=false)] public EventsCount EventsCount { get; set; } /// <summary> /// Gets or Sets Grid /// </summary> [DataMember(Name="grid", EmitDefaultValue=false)] public Grid Grid { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class EarthquakeRiskLocationResponse {\n"); sb.Append(" RiskLevel: ").Append(RiskLevel).Append("\n"); sb.Append(" EventsCount: ").Append(EventsCount).Append("\n"); sb.Append(" Grid: ").Append(Grid).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as EarthquakeRiskLocationResponse); } /// <summary> /// Returns true if EarthquakeRiskLocationResponse instances are equal /// </summary> /// <param name="other">Instance of EarthquakeRiskLocationResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(EarthquakeRiskLocationResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.RiskLevel == other.RiskLevel || this.RiskLevel != null && this.RiskLevel.Equals(other.RiskLevel) ) && ( this.EventsCount == other.EventsCount || this.EventsCount != null && this.EventsCount.Equals(other.EventsCount) ) && ( this.Grid == other.Grid || this.Grid != null && this.Grid.Equals(other.Grid) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.RiskLevel != null) hash = hash * 59 + this.RiskLevel.GetHashCode(); if (this.EventsCount != null) hash = hash * 59 + this.EventsCount.GetHashCode(); if (this.Grid != null) hash = hash * 59 + this.Grid.GetHashCode(); return hash; } } } }
35.923567
130
0.569149
[ "Apache-2.0" ]
PreciselyData/PreciselyAPIsSDK-CSharp
src/com.precisely.apis/Model/EarthquakeRiskLocationResponse.cs
5,640
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SimpleInterrogationRoomLoader.cs" company=""> // </copyright> // <summary> // The simple interrogation room loader. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Holmes.Infrastructure.Services { using System.Collections.Generic; using Holmes.Core.Interfaces; using Holmes.Core.Models; /// <summary> /// The simple interrogation room loader. /// </summary> public class SimpleInterrogationRoomLoader : IInterrogationRoomRepository { /// <summary> /// The suspect repository. /// </summary> private readonly ISuspectRepository suspectRepository; /// <summary> /// Initializes a new instance of the <see cref="SimpleInterrogationRoomLoader"/> class. /// </summary> /// <param name="suspectRepository"> /// The suspect repository. /// </param> public SimpleInterrogationRoomLoader(ISuspectRepository suspectRepository) { this.suspectRepository = suspectRepository; } /// <summary> /// The get interrogation rooms. /// </summary> /// <returns> /// The <see cref="List{T}"/>. /// </returns> public List<InterrogationRoom> GetInterrogationRooms() { List<InterrogationRoom> rooms = new List<InterrogationRoom>(); var suspects = this.suspectRepository.GetSuspects(); foreach (var suspect in suspects) { rooms.Add(new InterrogationRoom() { Suspect = suspect }); } return rooms; } } }
32.732143
120
0.516094
[ "MIT" ]
neoKushan/Holmes
src/Holmes/Holmes.Infrastructure/Services/SimpleInterrogationRoomLoader.cs
1,835
C#
// See the LICENSE file in the project root for more information. using System.IO; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.Internal.Internallearn; using Microsoft.ML.Runtime.Model; namespace Scikit.ML.XGBoostWrapper { /// <summary> /// Implements a base class for all predictor in XGBoost. /// </summary> /// <typeparam name="TOutput"></typeparam> public abstract class XGBoostPredictorBase<TOutput> : PredictorBase<TOutput>, ISchemaBindableMapper, ICanSaveModel, IValueMapper { /// <summary> /// XGBoost does not return the same output as Microsoft.ML. /// For Binary Classification, the raw output is [0, 1]. /// </summary> /// <param name="output"></param> public delegate void UpdateOutputType(ref TOutput output); private readonly Booster _booster; private readonly int _numFeaturesML; private ColumnType _inputType; public ColumnType InputType { get { return _inputType; } } public abstract ColumnType OutputType { get; } internal Booster GetBooster() { return _booster; } public int GetNumTrees() { return _booster.GetNumTrees(); } /// <summary> /// This function create a a delegate function which post process the output of the predictor. /// It should be empty. Check parameter outputMargin when calling the predictions before tweaking XGBoost output. /// </summary> public virtual UpdateOutputType GetOutputPostProcessor() { return (ref TOutput src) => { }; } protected XGBoostPredictorBase(IHostEnvironment env, string name, byte[] model, int numFeaturesXGBoost, int numFeaturesML) : base(env, name) { env.Check(numFeaturesXGBoost > 0, nameof(numFeaturesXGBoost)); env.Check(numFeaturesML >= numFeaturesXGBoost, nameof(numFeaturesML)); _booster = new Booster(model, numFeaturesXGBoost); _numFeaturesML = numFeaturesML; _inputType = new VectorType(NumberType.R4, _numFeaturesML); } protected XGBoostPredictorBase(IHostEnvironment env, string name, ModelLoadContext ctx) : base(env, name, ctx) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(ctx, nameof(ctx)); // *** Binary format *** // <base> // int // int (version > 0x00010003) byte[] model = null; bool load = ctx.TryLoadBinaryStream("xgboost.model", br => { using (var memStream = new MemoryStream()) { br.BaseStream.CopyTo(memStream); model = memStream.ToArray(); } }); Host.CheckDecode(load); Host.CheckDecode(model != null && model.Length > 0); int numFeatures = ctx.Reader.ReadInt32(); Host.CheckDecode(numFeatures > 0); // The XGBoost model is loaded, if it fails, it probably means that the model is corrupted // or XGBoost library changed its format. The error message comes from XGBoost. _booster = new Booster(model, numFeatures); if (ctx.Header.ModelVerWritten >= 0x00010003) _numFeaturesML = ctx.Reader.ReadInt32(); else _numFeaturesML = _booster.NumFeatures; Host.CheckDecode(_numFeaturesML >= numFeatures); _inputType = new VectorType(NumberType.R4, _numFeaturesML); } protected override void SaveCore(ModelSaveContext ctx) { Host.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(); // *** Binary format *** // <base> // int (_booster.NumFeatures) // int (_numFeaturesML) (version >= 0x00010003) base.SaveCore(ctx); ctx.SaveBinaryStream("xgboost.model", bw => bw.Write(_booster.SaveRaw())); ctx.Writer.Write(_booster.NumFeatures); ctx.Writer.Write(_numFeaturesML); } public abstract ISchemaBoundMapper Bind(IHostEnvironment env, RoleMappedSchema schema); public abstract ValueMapper<TSrc, TDst> GetMapper<TSrc, TDst>(); protected ValueMapper<VBuffer<float>, VBuffer<float>> GetMapperVFloat() { var buffer = Booster.CreateInternalBuffer(); return (ref VBuffer<float> src, ref VBuffer<float> dst) => { _booster.PredictOneOff(ref src, ref dst, ref buffer); }; } protected ValueMapper<VBuffer<float>, float> GetMapperFloat() { var buffer = Booster.CreateInternalBuffer(); VBuffer<float> dstBuffer = new VBuffer<float>(); return (ref VBuffer<float> src, ref float dst) => { _booster.PredictOneOff(ref src, ref dstBuffer, ref buffer); dst = dstBuffer.Values[0]; }; } } }
39.263566
148
0.602764
[ "MIT" ]
xadupre/machinelearning_xgboost
machinelearning_xgboost/XGBoostWrapper/XGBoostPredictorBase.cs
5,067
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 clouddirectory-2017-01-11.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CloudDirectory.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudDirectory.Model.Internal.MarshallTransformations { /// <summary> /// GetDirectory Request Marshaller /// </summary> public class GetDirectoryRequestMarshaller : IMarshaller<IRequest, GetDirectoryRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetDirectoryRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetDirectoryRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.CloudDirectory"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-01-11"; request.HttpMethod = "POST"; string uriResourcePath = "/amazonclouddirectory/2017-01-11/directory/get"; request.ResourcePath = uriResourcePath; if(publicRequest.IsSetDirectoryArn()) request.Headers["x-amz-data-partition"] = publicRequest.DirectoryArn; return request; } private static GetDirectoryRequestMarshaller _instance = new GetDirectoryRequestMarshaller(); internal static GetDirectoryRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetDirectoryRequestMarshaller Instance { get { return _instance; } } } }
34.224719
139
0.652988
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/CloudDirectory/Generated/Model/Internal/MarshallTransformations/GetDirectoryRequestMarshaller.cs
3,046
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("confyre")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("confyre")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("361e82f5-99fe-44d0-a7a4-95222319110b")] // 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.351351
84
0.74602
[ "MIT" ]
FyreByrns/confyre
confyre/confyre/Properties/AssemblyInfo.cs
1,385
C#
// SPDX-License-Identifier: Apache-2.0 // Licensed to the Ed-Fi Alliance under one or more agreements. // The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0. // See the LICENSE and NOTICES files in the project root for more information. using MappingEdu.Tests.Business.Core.Services.Validation.SystemEnumerationItemValidationRules; namespace MappingEdu.Tests.Business.Builders { public class SystemEnumerationItemRuleBuilder { private readonly SystemEnumerationItemRuleStub _systemEnumerationItemRuleStub = new SystemEnumerationItemRuleStub(); public SystemEnumerationItemRuleBuilder AlwaysValid { get { _systemEnumerationItemRuleStub.StubIsValid = true; return this; } } public static implicit operator SystemEnumerationItemRuleStub(SystemEnumerationItemRuleBuilder builder) { return builder._systemEnumerationItemRuleStub; } public SystemEnumerationItemRuleBuilder WithFailureMessage(string message) { _systemEnumerationItemRuleStub.StubIsValid = false; _systemEnumerationItemRuleStub.StubFailureMessage = message; return this; } } }
36.6
124
0.708041
[ "Apache-2.0" ]
Ed-Fi-Exchange-OSS/MappingEDU
src/MappingEdu.Tests.Business/Builders/SystemEnumerationItemRuleBuilder.cs
1,283
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. // <auto-generated/> // Template Source: MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsOddFYieldRequestBuilder. /// </summary> public partial class WorkbookFunctionsOddFYieldRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsOddFYieldRequest>, IWorkbookFunctionsOddFYieldRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsOddFYieldRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="settlement">A settlement parameter for the OData method call.</param> /// <param name="maturity">A maturity parameter for the OData method call.</param> /// <param name="issue">A issue parameter for the OData method call.</param> /// <param name="firstCoupon">A firstCoupon parameter for the OData method call.</param> /// <param name="rate">A rate parameter for the OData method call.</param> /// <param name="pr">A pr parameter for the OData method call.</param> /// <param name="redemption">A redemption parameter for the OData method call.</param> /// <param name="frequency">A frequency parameter for the OData method call.</param> /// <param name="basis">A basis parameter for the OData method call.</param> public WorkbookFunctionsOddFYieldRequestBuilder( string requestUrl, IBaseClient client, System.Text.Json.JsonDocument settlement, System.Text.Json.JsonDocument maturity, System.Text.Json.JsonDocument issue, System.Text.Json.JsonDocument firstCoupon, System.Text.Json.JsonDocument rate, System.Text.Json.JsonDocument pr, System.Text.Json.JsonDocument redemption, System.Text.Json.JsonDocument frequency, System.Text.Json.JsonDocument basis) : base(requestUrl, client) { this.SetParameter("settlement", settlement, true); this.SetParameter("maturity", maturity, true); this.SetParameter("issue", issue, true); this.SetParameter("firstCoupon", firstCoupon, true); this.SetParameter("rate", rate, true); this.SetParameter("pr", pr, true); this.SetParameter("redemption", redemption, true); this.SetParameter("frequency", frequency, true); this.SetParameter("basis", basis, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsOddFYieldRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsOddFYieldRequest(functionUrl, this.Client, options); if (this.HasParameter("settlement")) { request.RequestBody.Settlement = this.GetParameter<System.Text.Json.JsonDocument>("settlement"); } if (this.HasParameter("maturity")) { request.RequestBody.Maturity = this.GetParameter<System.Text.Json.JsonDocument>("maturity"); } if (this.HasParameter("issue")) { request.RequestBody.Issue = this.GetParameter<System.Text.Json.JsonDocument>("issue"); } if (this.HasParameter("firstCoupon")) { request.RequestBody.FirstCoupon = this.GetParameter<System.Text.Json.JsonDocument>("firstCoupon"); } if (this.HasParameter("rate")) { request.RequestBody.Rate = this.GetParameter<System.Text.Json.JsonDocument>("rate"); } if (this.HasParameter("pr")) { request.RequestBody.Pr = this.GetParameter<System.Text.Json.JsonDocument>("pr"); } if (this.HasParameter("redemption")) { request.RequestBody.Redemption = this.GetParameter<System.Text.Json.JsonDocument>("redemption"); } if (this.HasParameter("frequency")) { request.RequestBody.Frequency = this.GetParameter<System.Text.Json.JsonDocument>("frequency"); } if (this.HasParameter("basis")) { request.RequestBody.Basis = this.GetParameter<System.Text.Json.JsonDocument>("basis"); } return request; } } }
45.268908
177
0.603304
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsOddFYieldRequestBuilder.cs
5,387
C#
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2016 Hotcakes Commerce, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion namespace Hotcakes.Commerce.Membership { public class RolePermissionsMatrix { public static string GetRoleNameByPermission(HotcakesApplication hccApp, string permission) { if (hccApp.CurrentStore != null) { //var rType = _permissionToRoles[permission]; var adminRoles = hccApp.CurrentStore.Settings.AdminRoles; switch (permission) { case SystemPermissions.CatalogView: case SystemPermissions.ContentView: case SystemPermissions.MarketingView: return adminRoles.RoleCatalogManagement; case SystemPermissions.PeopleView: case SystemPermissions.OrdersView: case SystemPermissions.OrdersEdit: case SystemPermissions.ReportsView: return adminRoles.RoleOrdersAndCustomers; case SystemPermissions.SettingsView: return adminRoles.RoleStoreAdministration; default: return string.Empty; } } return string.Empty; } } }
41.229508
101
0.634195
[ "MIT" ]
ketangarala/core
Libraries/Hotcakes.Commerce/Membership/RolePermissionsMatrix.cs
2,517
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Adnc.Application.Shared.RpcServices; using Refit; namespace Adnc.Whse.Application.Contracts.RpcServices { public interface IOrdersRpcService : IRpcService { /// <summary> /// 获取字典数据 /// </summary> /// <param name="jwtToken">token</param> /// <param name="id">id</param> /// <returns></returns> //[Get("/orders/{id}")] //[Headers("Authorization: Bearer")] //Task<ApiResponse<DictRto>> GetOrderAsync(long id); } }
27.272727
60
0.625
[ "MIT" ]
18142552937/Adnc
src/ServerApi/Services/Adnc.Whse/Adnc.Whse.Application.Contracts/RpcServices/IOrdersRpcService.cs
614
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { public float scaleMultiplier; public float posMultiplier; public float xPosOffset; public float yPosOffset; private float yPosStart; private float baseScale; private Camera _camera; // Start is called before the first frame update void Start() { yPosStart = transform.position.y; _camera = GetComponent<Camera>(); baseScale = _camera.orthographicSize; } // Update is called once per frame void Update() { Vector3 newPos = transform.position; newPos.x = PlayerMovement.PlayerTransform.position.x + xPosOffset; if (PlayerMovement.PlayerTransform.position.y>yPosStart+yPosOffset) { float diff = PlayerMovement.PlayerTransform.position.y - (yPosOffset + yPosStart); newPos.y = posMultiplier * diff; _camera.orthographicSize = baseScale + diff * scaleMultiplier; } transform.position = newPos; } }
28.657895
94
0.672176
[ "MIT" ]
DoubleAMJunior/DuneCloneWithProceduralGroundMesh
Assets/Scripts/CameraFollow.cs
1,091
C#
namespace ServerConnection.Admin { partial class ServerConnectionAddUserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBoxName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // textBoxName // this.textBoxName.Location = new System.Drawing.Point(94, 25); this.textBoxName.Name = "textBoxName"; this.textBoxName.Size = new System.Drawing.Size(279, 20); this.textBoxName.TabIndex = 3; this.textBoxName.Text = "Enter a name"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(23, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 2; this.label1.Text = "Name:"; // // ServerConnectionAddUserControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.textBoxName); this.Controls.Add(this.label1); this.Name = "ServerConnectionAddUserControl"; this.Size = new System.Drawing.Size(407, 67); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBoxName; private System.Windows.Forms.Label label1; } }
28.169014
101
0.6875
[ "MIT" ]
Silex/mipsdk-samples-plugin
ServerConnectionLicense/Admin/ServerConnectionAddUserControl.Designer.cs
2,000
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Rulesets.Mods; namespace osu.Game.Rulesets.Tau.Mods { public class TauModSuddenDeath : ModSuddenDeath { } }
23.916667
79
0.724739
[ "MIT" ]
Coppertine/tau
osu.Game.Rulesets.tau/Mods/TauModSuddenDeath.cs
289
C#
 // Copyright (c) 2017 Mark A. Olbert some rights reserved // // This software is licensed under the terms of the MIT License // (https://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Windows; using System.Windows.Media; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Messaging; namespace Olbert.JumpForJoy { /// <summary> /// The view-model for a J4JMessage box object /// </summary> public class MessageBoxViewModel : ViewModelBase { /// <summary> /// Gets a color, if one exists, from a ResourceDictionary, based on a key, or /// a default color /// </summary> /// <param name="key">the key of the color to find</param> /// <param name="dict">the ResourceDictionary to search</param> /// <param name="defaultColor">the color returned if the ResourceDictionary does /// not contain a key defining a Color</param> /// <returns>a Color</returns> internal static Color GetColor(string key, ResourceDictionary dict, string defaultColor) { Color retVal = (Color?)ColorConverter.ConvertFromString(defaultColor) ?? Colors.LightGray; try { retVal = (Color)dict[key]; } catch { } return retVal; } /// <summary> /// Raised to indicate that the J4JMessageBox should close /// </summary> public event EventHandler Close; private string _title; private string _mesg; private MessageButtonViewModel _btn1; private MessageButtonViewModel _btn2; private MessageButtonViewModel _btn3; /// <summary> /// Creates an instance using display parameters (e.g., button colors) defined in /// a ResourceDictionary /// </summary> /// <param name="j4jRes">the ResourceDictionary to use to initialize the appearance /// of the J4JMessageBox; can be null, in which case defaults will be used</param> public MessageBoxViewModel( ResourceDictionary j4jRes ) { Button0 = new MessageButtonViewModel(j4jRes) { Text = "Yes", Visibility = Visibility.Visible, NormalBackground = new SolidColorBrush(GetColor("J4JButton0Color", j4jRes, "#835434")) }; Button1 = new MessageButtonViewModel(j4jRes) { Text = "No", Visibility = Visibility.Visible, NormalBackground = new SolidColorBrush(GetColor("J4JButton1Color", j4jRes, "#bb8149")) }; Button2 = new MessageButtonViewModel(j4jRes) { Text = "Cancel", Visibility = Visibility.Visible, NormalBackground = new SolidColorBrush(GetColor("J4JButton2Color", j4jRes, "#fa9599")) }; Messenger.Default.Register<ButtonClickMessage>( this, ButtonClickHandler ); Messenger.Default.Register<ResetMarginsMessage>( this, ResetMarginsHandler ); } /// <summary> /// The message box's window title /// </summary> public string Title { get => _title; set => Set<string>( ref _title, value ); } /// <summary> /// The message dispalyed in the message box /// </summary> public string Message { get => _mesg; set => Set<string>( ref _mesg, value ); } /// <summary> /// The view model for button 0, the left-most button /// </summary> public MessageButtonViewModel Button0 { get => _btn1; set => Set<MessageButtonViewModel>( ref _btn1, value ); } /// <summary> /// The view model for button 1 /// </summary> public MessageButtonViewModel Button1 { get => _btn2; set => Set<MessageButtonViewModel>( ref _btn2, value ); } /// <summary> /// The view model for button 2, the right-most button /// </summary> public MessageButtonViewModel Button2 { get => _btn3; set => Set<MessageButtonViewModel>( ref _btn3, value ); } /// <summary> /// The ID of the button that was clicked (0, 1 or 2); the buttons /// are numbered from left to right, starting with 0 /// </summary> public int ButtonClicked { get; private set; } /// <summary> /// Gets a list of the buttons that are currently visible /// </summary> public List<MessageButtonViewModel> VisibleButtons { get { List<MessageButtonViewModel> retVal = new List<MessageButtonViewModel>(); if( Button0.Visibility == Visibility.Visible ) retVal.Add( Button0 ); if( Button1.Visibility == Visibility.Visible ) retVal.Add( Button1 ); if( Button2.Visibility == Visibility.Visible ) retVal.Add( Button2 ); return retVal; } } private void ButtonClickHandler( ButtonClickMessage clickMesg ) { if( clickMesg != null ) { ButtonClicked = clickMesg.ButtonID; Close?.Invoke( this, EventArgs.Empty ); } } private void ResetMarginsHandler( ResetMarginsMessage obj ) { if( Button0.Visibility == Visibility.Visible && ( Button1.Visibility == Visibility.Visible || Button2.Visibility == Visibility.Visible ) ) Button0.Margin = new Thickness( 0, 0, 5, 0 ); else Button0.Margin = new Thickness( 0 ); if( Button1.Visibility == Visibility.Visible && Button2.Visibility == Visibility.Visible ) Button1.Margin = new Thickness( 0, 0, 5, 0 ); else Button1.Margin = new Thickness( 0 ); } } }
33.855556
106
0.563013
[ "MIT" ]
markolbert/WPFUtilities
J4JUI/MessageBoxViewModel.cs
6,096
C#
using System; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using Moq; using NetDaemon.HassModel.Common; using NetDaemon.HassModel.Entities; using FluentAssertions; using NetDaemon.HassModel.Tests.TestHelpers; using Xunit; namespace NetDaemon.HassModel.Tests.Entities { public class EntityTest { [Fact] public void ShouldWrapStateFromHaContext() { // Arrange var haContextMock = new Mock<IHaContext>(); var entityState = new EntityState() { State = "CurrentState", AttributesJson = new { name = "FirstName" }.AsJsonElement() }; haContextMock.Setup(t => t.GetState("domain.testEntity")).Returns(entityState); // Act var target = new TestEntity(haContextMock.Object, "domain.testEntity"); // Assert target.State.Should().Be("CurrentState"); target.Attributes!.Name.Should().Be("FirstName"); target.EntityState!.State.Should().Be("CurrentState"); target.EntityState!.Attributes!.Name.Should().Be("FirstName"); // Act2: update the state var newEntityState = new EntityState() { State = "NewState", AttributesJson = new { name = "SecondName" }.AsJsonElement() }; haContextMock.Setup(t => t.GetState("domain.testEntity")).Returns(newEntityState); // Assert target.State.Should().Be("NewState"); target.Attributes!.Name.Should().Be("SecondName"); target.EntityState!.State.Should().Be("NewState"); target.EntityState!.Attributes!.Name.Should().Be("SecondName"); } [Fact] public void ShouldShowStateChangesFromContext() { var stateChangesSubject = new Subject<StateChange>(); var haContextMock = new Mock<IHaContext>(); haContextMock.Setup(h => h.StateAllChanges()).Returns(stateChangesSubject); var target = new TestEntity(haContextMock.Object, "domain.testEntity"); var stateChangeObserverMock = new Mock<IObserver<StateChange>>(); var stateAllChangeObserverMock = new Mock<IObserver<StateChange>>(); target.StateAllChanges().Subscribe(stateAllChangeObserverMock.Object); target.StateChanges().Subscribe(stateChangeObserverMock.Object); stateChangesSubject.OnNext( new StateChange(target, new EntityState {State = "old"}, new EntityState {State = "new"})); stateChangesSubject.OnNext( new StateChange(target, new EntityState(){State = "same"}, new EntityState {State = "same"})); stateChangeObserverMock.Verify(o => o.OnNext(It.IsAny<StateChange>() ), Times.Once); stateAllChangeObserverMock.Verify(o => o.OnNext(It.IsAny<StateChange>() ), Times.Exactly(2)); } [Fact] public void ShouldCallServiceOnContext() { var haContextMock = new Mock<IHaContext>(); var entity = new TestEntity(haContextMock.Object, "domain.testEntity"); var data = "payload"; entity.CallService("service", data); haContextMock.Verify(h => h.CallService("domain", "service", It.Is<ServiceTarget>(t => t.EntityIds.Single() == entity.EntityId), data), Times.Once); } } }
37.444444
160
0.572161
[ "MIT" ]
Hatles/netdaemon
src/HassModel/NetDaemon.HassModel.Tests/Entities/EntityTest.cs
3,709
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal abstract partial class AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> { private class IntroduceParameterDocumentRewriter { private readonly AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> _service; private readonly Document _originalDocument; private readonly SyntaxGenerator _generator; private readonly ISyntaxFactsService _syntaxFacts; private readonly ISemanticFactsService _semanticFacts; private readonly TExpressionSyntax _expression; private readonly IMethodSymbol _methodSymbol; private readonly SyntaxNode _containerMethod; private readonly IntroduceParameterCodeActionKind _actionKind; private readonly CodeGenerationOptionsProvider _fallbackOptions; private readonly bool _allOccurrences; public IntroduceParameterDocumentRewriter( AbstractIntroduceParameterService<TExpressionSyntax, TInvocationExpressionSyntax, TObjectCreationExpressionSyntax, TIdentifierNameSyntax> service, Document originalDocument, TExpressionSyntax expression, IMethodSymbol methodSymbol, SyntaxNode containingMethod, IntroduceParameterCodeActionKind selectedCodeAction, CodeGenerationOptionsProvider fallbackOptions, bool allOccurrences) { _service = service; _originalDocument = originalDocument; _generator = SyntaxGenerator.GetGenerator(originalDocument); _syntaxFacts = originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); _semanticFacts = originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); _expression = expression; _methodSymbol = methodSymbol; _containerMethod = containingMethod; _actionKind = selectedCodeAction; _allOccurrences = allOccurrences; _fallbackOptions = fallbackOptions; } public async Task<SyntaxNode> RewriteDocumentAsync(Compilation compilation, Document document, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var insertionIndex = GetInsertionIndex(compilation); if (_actionKind is IntroduceParameterCodeActionKind.Overload or IntroduceParameterCodeActionKind.Trampoline) { return await ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync( compilation, document, invocations, insertionIndex, cancellationToken).ConfigureAwait(false); } else { return await ModifyDocumentInvocationsAndIntroduceParameterAsync( compilation, document, insertionIndex, invocations, cancellationToken).ConfigureAwait(false); } } /// <summary> /// Ties the identifiers within the expression back to their associated parameter. /// </summary> private async Task<Dictionary<TIdentifierNameSyntax, IParameterSymbol>> MapExpressionToParametersAsync(CancellationToken cancellationToken) { var nameToParameterDict = new Dictionary<TIdentifierNameSyntax, IParameterSymbol>(); var variablesInExpression = _expression.DescendantNodes().OfType<TIdentifierNameSyntax>(); var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var variable in variablesInExpression) { var symbol = semanticModel.GetSymbolInfo(variable, cancellationToken).Symbol; if (symbol is IParameterSymbol parameterSymbol) { nameToParameterDict.Add(variable, parameterSymbol); } } return nameToParameterDict; } /// <summary> /// Gets the parameter name, if the expression's grandparent is a variable declarator then it just gets the /// local declarations name. Otherwise, it generates a name based on the context of the expression. /// </summary> private async Task<string> GetNewParameterNameAsync(CancellationToken cancellationToken) { if (ShouldRemoveVariableDeclaratorContainingExpression(out var varDeclName, out _)) { return varDeclName; } var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var semanticFacts = _originalDocument.GetRequiredLanguageService<ISemanticFactsService>(); return semanticFacts.GenerateNameForExpression(semanticModel, _expression, capitalize: false, cancellationToken); } /// <summary> /// Determines if the expression's grandparent is a variable declarator and if so, /// returns the name /// </summary> private bool ShouldRemoveVariableDeclaratorContainingExpression([NotNullWhen(true)] out string? varDeclName, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var declarator = _expression?.Parent?.Parent; localDeclaration = null; if (!_syntaxFacts.IsVariableDeclarator(declarator)) { varDeclName = null; return false; } localDeclaration = _service.GetLocalDeclarationFromDeclarator(declarator); if (localDeclaration is null) { varDeclName = null; return false; } // TODO: handle in the future if (_syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclaration).Count > 1) { varDeclName = null; localDeclaration = null; return false; } varDeclName = _syntaxFacts.GetIdentifierOfVariableDeclarator(declarator).ValueText; return true; } /// <summary> /// Goes through the parameters of the original method to get the location that the parameter /// and argument should be introduced. /// </summary> private int GetInsertionIndex(Compilation compilation) { var parameterList = _syntaxFacts.GetParameterList(_containerMethod); Contract.ThrowIfNull(parameterList); var insertionIndex = 0; foreach (var parameterSymbol in _methodSymbol.Parameters) { // Want to skip optional parameters, params parameters, and CancellationToken since they should be at // the end of the list. if (ShouldParameterBeSkipped(compilation, parameterSymbol)) { insertionIndex++; } } return insertionIndex; } /// <summary> /// For the trampoline case, it goes through the invocations and adds an argument which is a /// call to the extracted method. /// Introduces a new method overload or new trampoline method. /// Updates the original method site with a newly introduced parameter. /// /// ****Trampoline Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) // Generated method /// { /// return x * y; /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6, GetF(5, 6)); //Fills in with call to generated method /// } /// /// ----------------------------------------------------------------------- /// ****Overload Example:**** /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y) /// } /// /// public void M(int x, int y, int f) /// { /// Console.WriteLine(f); /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsTrampolineOverloadAndIntroduceParameterAsync(Compilation compilation, Document currentDocument, List<SyntaxNode> invocations, int insertionIndex, CancellationToken cancellationToken) { var invocationSemanticModel = await currentDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await currentDocument.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var expressionParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); // Creating a new method name by concatenating the parameter name that has been upper-cased. var newMethodIdentifier = "Get" + parameterName.ToPascalCase(); var validParameters = _methodSymbol.Parameters.Intersect(expressionParameterMap.Values).ToImmutableArray(); if (_actionKind is IntroduceParameterCodeActionKind.Trampoline) { // Creating an empty map here to reuse so that we do not create a new dictionary for // every single invocation. var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); foreach (var invocation in invocations) { var argumentListSyntax = _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); if (argumentListSyntax == null) continue; editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { return GenerateNewArgumentListSyntaxForTrampoline(compilation, invocationSemanticModel, parameterToArgumentMap, currentArgumentListSyntax, argumentListSyntax, invocation, validParameters, parameterName, newMethodIdentifier, insertionIndex, cancellationToken); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (currentDocument.Id == _originalDocument.Id) { var newMethodNode = _actionKind is IntroduceParameterCodeActionKind.Trampoline ? await ExtractMethodAsync(validParameters, newMethodIdentifier, _generator, cancellationToken).ConfigureAwait(false) : await GenerateNewMethodOverloadAsync(insertionIndex, _generator, cancellationToken).ConfigureAwait(false); editor.InsertBefore(_containerMethod, newMethodNode); await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(parameterName, _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); // Adds an argument which is an invocation of the newly created method to the callsites // of the method invocations where a parameter was added. // Example: // public void M(int x, int y) // { // int f = [|x * y|]; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6); // } // // ----------------------------------------------------> // // public int GetF(int x, int y) // { // return x * y; // } // // public void M(int x, int y) // { // int f = x * y; // Console.WriteLine(f); // } // // public void InvokeMethod() // { // M(5, 6, GetF(5, 6)); // This is the generated invocation which is a new argument at the call site // } SyntaxNode GenerateNewArgumentListSyntaxForTrampoline(Compilation compilation, SemanticModel invocationSemanticModel, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SyntaxNode currentArgumentListSyntax, SyntaxNode argumentListSyntax, SyntaxNode invocation, ImmutableArray<IParameterSymbol> validParameters, string parameterName, string newMethodIdentifier, int insertionIndex, CancellationToken cancellationToken) { var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); var currentInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var requiredArguments = new List<SyntaxNode>(); foreach (var parameterSymbol in validParameters) { if (parameterToArgumentMap.TryGetValue(parameterSymbol, out var index)) { requiredArguments.Add(currentInvocationArguments[index]); } } var conditionalRoot = _syntaxFacts.GetRootConditionalAccessExpression(invocation); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var newMethodInvocation = GenerateNewMethodInvocation(invocation, requiredArguments, newMethodIdentifier); SeparatedSyntaxList<SyntaxNode> allArguments; if (conditionalRoot is null) { allArguments = AddArgumentToArgumentList(currentInvocationArguments, newMethodInvocation, parameterName, insertionIndex, named); } else { // Conditional Access expressions are parents of invocations, so it is better to just replace the // invocation in place then rebuild the tree structure. var expressionsWithConditionalAccessors = conditionalRoot.ReplaceNode(invocation, newMethodInvocation); allArguments = AddArgumentToArgumentList(currentInvocationArguments, expressionsWithConditionalAccessors, parameterName, insertionIndex, named); } return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); } } private async Task<ITypeSymbol> GetTypeOfExpressionAsync(CancellationToken cancellationToken) { var semanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeSymbol = semanticModel.GetTypeInfo(_expression, cancellationToken).ConvertedType ?? semanticModel.Compilation.ObjectType; return typeSymbol; } private SyntaxNode GenerateNewMethodInvocation(SyntaxNode invocation, List<SyntaxNode> arguments, string newMethodIdentifier) { var methodName = _generator.IdentifierName(newMethodIdentifier); var fullExpression = _syntaxFacts.GetExpressionOfInvocationExpression(invocation); if (_syntaxFacts.IsMemberAccessExpression(fullExpression)) { var receiverExpression = _syntaxFacts.GetExpressionOfMemberAccessExpression(fullExpression); methodName = _generator.MemberAccessExpression(receiverExpression, newMethodIdentifier); } else if (_syntaxFacts.IsMemberBindingExpression(fullExpression)) { methodName = _generator.MemberBindingExpression(_generator.IdentifierName(newMethodIdentifier)); } return _generator.InvocationExpression(methodName, arguments); } /// <summary> /// Generates a method declaration containing a return expression of the highlighted expression. /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public int GetF(int x, int y) /// { /// return x * y; /// } /// /// public void M(int x, int y) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> ExtractMethodAsync(ImmutableArray<IParameterSymbol> validParameters, string newMethodIdentifier, SyntaxGenerator generator, CancellationToken cancellationToken) { // Remove trivia so the expression is in a single line and does not affect the spacing of the following line var returnStatement = generator.ReturnStatement(_expression.WithoutTrivia()); var typeSymbol = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var newMethodDeclaration = await CreateMethodDeclarationAsync(returnStatement, validParameters, newMethodIdentifier, typeSymbol, isTrampoline: true, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } /// <summary> /// Generates a method declaration containing a call to the method that introduced the parameter. /// Example: /// /// ***This is an intermediary step in which the original function has not be updated yet /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y) // Generated overload /// { /// M(x, y, x * y); /// } /// /// public void M(int x, int y) // Original function (which will be mutated in a later step) /// { /// int f = x * y; /// } /// </summary> private async Task<SyntaxNode> GenerateNewMethodOverloadAsync(int insertionIndex, SyntaxGenerator generator, CancellationToken cancellationToken) { // Need the parameters from the original function as arguments for the invocation var arguments = generator.CreateArguments(_methodSymbol.Parameters); // Remove trivia so the expression is in a single line and does not affect the spacing of the following line arguments = arguments.Insert(insertionIndex, generator.Argument(_expression.WithoutTrivia())); var memberName = _methodSymbol.IsGenericMethod ? generator.GenericName(_methodSymbol.Name, _methodSymbol.TypeArguments) : generator.IdentifierName(_methodSymbol.Name); var invocation = generator.InvocationExpression(memberName, arguments); var newStatement = _methodSymbol.ReturnsVoid ? generator.ExpressionStatement(invocation) : generator.ReturnStatement(invocation); var newMethodDeclaration = await CreateMethodDeclarationAsync(newStatement, validParameters: null, newMethodIdentifier: null, typeSymbol: null, isTrampoline: false, cancellationToken).ConfigureAwait(false); return newMethodDeclaration; } private async Task<SyntaxNode> CreateMethodDeclarationAsync(SyntaxNode newStatement, ImmutableArray<IParameterSymbol>? validParameters, string? newMethodIdentifier, ITypeSymbol? typeSymbol, bool isTrampoline, CancellationToken cancellationToken) { var codeGenerationService = _originalDocument.GetRequiredLanguageService<ICodeGenerationService>(); var codeGenOptions = await _originalDocument.GetCodeGenerationOptionsAsync(_fallbackOptions, cancellationToken).ConfigureAwait(false); var info = codeGenOptions.GetInfo(CodeGenerationContext.Default, _originalDocument.Project); var newMethod = isTrampoline ? CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, name: newMethodIdentifier, parameters: validParameters, statements: ImmutableArray.Create(newStatement), returnType: typeSymbol) : CodeGenerationSymbolFactory.CreateMethodSymbol(_methodSymbol, statements: ImmutableArray.Create(newStatement), containingType: _methodSymbol.ContainingType); var newMethodDeclaration = codeGenerationService.CreateMethodDeclaration(newMethod, CodeGenerationDestination.Unspecified, info, cancellationToken); Contract.ThrowIfNull(newMethodDeclaration); return newMethodDeclaration; } /// <summary> /// This method goes through all the invocation sites and adds a new argument with the expression to be added. /// It also introduces a parameter at the original method site. /// /// Example: /// public void M(int x, int y) /// { /// int f = [|x * y|]; /// } /// /// public void InvokeMethod() /// { /// M(5, 6); /// } /// /// ----------------------------------------------------> /// /// public void M(int x, int y, int f) // parameter gets introduced /// { /// } /// /// public void InvokeMethod() /// { /// M(5, 6, 5 * 6); // argument gets added to callsite /// } /// </summary> private async Task<SyntaxNode> ModifyDocumentInvocationsAndIntroduceParameterAsync(Compilation compilation, Document document, int insertionIndex, List<SyntaxNode> invocations, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, _generator); var invocationSemanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var parameterToArgumentMap = new Dictionary<IParameterSymbol, int>(); var expressionToParameterMap = await MapExpressionToParametersAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); foreach (var invocation in invocations) { var expressionEditor = new SyntaxEditor(_expression, _generator); var argumentListSyntax = invocation is TObjectCreationExpressionSyntax ? _syntaxFacts.GetArgumentListOfObjectCreationExpression(invocation) : _syntaxFacts.GetArgumentListOfInvocationExpression(invocation); if (argumentListSyntax == null) continue; var invocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(argumentListSyntax); parameterToArgumentMap.Clear(); MapParameterToArgumentsAtInvocation(parameterToArgumentMap, invocationArguments, invocationSemanticModel, cancellationToken); if (argumentListSyntax is not null) { editor.ReplaceNode(argumentListSyntax, (currentArgumentListSyntax, _) => { var updatedInvocationArguments = _syntaxFacts.GetArgumentsOfArgumentList(currentArgumentListSyntax); var updatedExpression = CreateNewArgumentExpression(expressionEditor, expressionToParameterMap, parameterToArgumentMap, updatedInvocationArguments); var named = ShouldArgumentBeNamed(compilation, invocationSemanticModel, invocationArguments, insertionIndex, cancellationToken); var allArguments = AddArgumentToArgumentList(updatedInvocationArguments, updatedExpression.WithAdditionalAnnotations(Formatter.Annotation), parameterName, insertionIndex, named); return _service.UpdateArgumentListSyntax(currentArgumentListSyntax, allArguments); }); } } // If you are at the original document, then also introduce the new method and introduce the parameter. if (document.Id == _originalDocument.Id) { await UpdateExpressionInOriginalFunctionAsync(editor, cancellationToken).ConfigureAwait(false); var parameterType = await GetTypeOfExpressionAsync(cancellationToken).ConfigureAwait(false); var parameter = _generator.ParameterDeclaration(name: parameterName, type: _generator.TypeExpression(parameterType)); editor.InsertParameter(_containerMethod, insertionIndex, parameter); } return editor.GetChangedRoot(); } /// <summary> /// This method iterates through the variables in the expression and maps the variables back to the parameter /// it is associated with. It then maps the parameter back to the argument at the invocation site and gets the /// index to retrieve the updated arguments at the invocation. /// </summary> private TExpressionSyntax CreateNewArgumentExpression(SyntaxEditor editor, Dictionary<TIdentifierNameSyntax, IParameterSymbol> mappingDictionary, Dictionary<IParameterSymbol, int> parameterToArgumentMap, SeparatedSyntaxList<SyntaxNode> updatedInvocationArguments) { foreach (var (variable, mappedParameter) in mappingDictionary) { var parameterMapped = parameterToArgumentMap.TryGetValue(mappedParameter, out var index); if (parameterMapped) { var updatedInvocationArgument = updatedInvocationArguments[index]; var argumentExpression = _syntaxFacts.GetExpressionOfArgument(updatedInvocationArgument); var parenthesizedArgumentExpression = editor.Generator.AddParentheses(argumentExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedArgumentExpression); } else if (mappedParameter.HasExplicitDefaultValue) { var generatedExpression = _service.GenerateExpressionFromOptionalParameter(mappedParameter); var parenthesizedGeneratedExpression = editor.Generator.AddParentheses(generatedExpression, includeElasticTrivia: false); editor.ReplaceNode(variable, parenthesizedGeneratedExpression); } } return (TExpressionSyntax)editor.GetChangedRoot(); } /// <summary> /// If the parameter is optional and the invocation does not specify the parameter, then /// a named argument needs to be introduced. /// </summary> private SeparatedSyntaxList<SyntaxNode> AddArgumentToArgumentList( SeparatedSyntaxList<SyntaxNode> invocationArguments, SyntaxNode newArgumentExpression, string parameterName, int insertionIndex, bool named) { var argument = named ? _generator.Argument(parameterName, RefKind.None, newArgumentExpression) : _generator.Argument(newArgumentExpression); return invocationArguments.Insert(insertionIndex, argument); } private bool ShouldArgumentBeNamed(Compilation compilation, SemanticModel semanticModel, SeparatedSyntaxList<SyntaxNode> invocationArguments, int methodInsertionIndex, CancellationToken cancellationToken) { var invocationInsertIndex = 0; foreach (var invocationArgument in invocationArguments) { var argumentParameter = _semanticFacts.FindParameterForArgument(semanticModel, invocationArgument, cancellationToken); if (argumentParameter is not null && ShouldParameterBeSkipped(compilation, argumentParameter)) { invocationInsertIndex++; } else { break; } } return invocationInsertIndex < methodInsertionIndex; } private static bool ShouldParameterBeSkipped(Compilation compilation, IParameterSymbol parameter) => !parameter.HasExplicitDefaultValue && !parameter.IsParams && !parameter.Type.Equals(compilation.GetTypeByMetadataName(typeof(CancellationToken)?.FullName!)); private void MapParameterToArgumentsAtInvocation( Dictionary<IParameterSymbol, int> mapping, SeparatedSyntaxList<SyntaxNode> arguments, SemanticModel invocationSemanticModel, CancellationToken cancellationToken) { for (var i = 0; i < arguments.Count; i++) { var argumentParameter = _semanticFacts.FindParameterForArgument(invocationSemanticModel, arguments[i], cancellationToken); if (argumentParameter is not null) { mapping[argumentParameter] = i; } } } /// <summary> /// Gets the matches of the expression and replaces them with the identifier. /// Special case for the original matching expression, if its parent is a LocalDeclarationStatement then it can /// be removed because assigning the local dec variable to a parameter is repetitive. Does not need a rename /// annotation since the user has already named the local declaration. /// Otherwise, it needs to have a rename annotation added to it because the new parameter gets a randomly /// generated name that the user can immediately change. /// </summary> private async Task UpdateExpressionInOriginalFunctionAsync(SyntaxEditor editor, CancellationToken cancellationToken) { var generator = editor.Generator; var matches = await FindMatchesAsync(cancellationToken).ConfigureAwait(false); var parameterName = await GetNewParameterNameAsync(cancellationToken).ConfigureAwait(false); var replacement = (TIdentifierNameSyntax)generator.IdentifierName(parameterName); foreach (var match in matches) { // Special case the removal of the originating expression to either remove the local declaration // or to add a rename annotation. if (!match.Equals(_expression)) { editor.ReplaceNode(match, replacement); } else { if (ShouldRemoveVariableDeclaratorContainingExpression(out _, out var localDeclaration)) { editor.RemoveNode(localDeclaration); } else { // Found the initially selected expression. Replace it with the new name we choose, but also annotate // that name with the RenameAnnotation so a rename session is started where the user can pick their // own preferred name. replacement = (TIdentifierNameSyntax)generator.IdentifierName(generator.Identifier(parameterName) .WithAdditionalAnnotations(RenameAnnotation.Create())); editor.ReplaceNode(match, replacement); } } } } /// <summary> /// Finds the matches of the expression within the same block. /// </summary> private async Task<IEnumerable<TExpressionSyntax>> FindMatchesAsync(CancellationToken cancellationToken) { if (!_allOccurrences) { return SpecializedCollections.SingletonEnumerable(_expression); } var syntaxFacts = _originalDocument.GetRequiredLanguageService<ISyntaxFactsService>(); var originalSemanticModel = await _originalDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matches = from nodeInCurrent in _containerMethod.DescendantNodesAndSelf().OfType<TExpressionSyntax>() where NodeMatchesExpression(originalSemanticModel, nodeInCurrent, cancellationToken) select nodeInCurrent; return matches; } private bool NodeMatchesExpression(SemanticModel originalSemanticModel, TExpressionSyntax currentNode, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (currentNode == _expression) { return true; } return SemanticEquivalence.AreEquivalent( originalSemanticModel, originalSemanticModel, _expression, currentNode); } } } }
53.757102
212
0.587185
[ "MIT" ]
BillWagner/roslyn
src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceParameterDocumentRewriter.cs
37,847
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dapplo.Confluence.Query { /// <summary> /// An interface for a space clause /// </summary> public interface ISpaceClause { /// <summary> /// This allows fluent constructs like Space.InFavouriteSpaces /// </summary> IFinalClause InFavouriteSpaces { get; } /// <summary> /// Negates the expression /// </summary> ISpaceClause Not { get; } /// <summary> /// This allows fluent constructs like Space.In("DEV", "PRODUCTION") /// </summary> IFinalClause In(params string[] values); /// <summary> /// This allows fluent constructs like Space.InFavouriteSpacesAnd("DEV", "PRODUCTION") /// </summary> IFinalClause InFavouriteSpacesAnd(params string[] values); /// <summary> /// This allows fluent constructs like Space.InRecentlyViewedSpaces(10) /// </summary> IFinalClause InRecentlyViewedSpaces(int limit); /// <summary> /// This allows fluent constructs like Space.Is("blub") /// </summary> IFinalClause Is(string spaceId); } }
32.095238
101
0.594214
[ "MIT" ]
DannySotzny/Dapplo.Confluence
src/Dapplo.Confluence/Query/ISpaceClause.cs
1,350
C#
/* * Copyright (c) Contributors, http://virtual-planets.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * For an explanation of the license of each contributor and the content it * covers please see the Licenses directory. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Virtual Universe Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Concurrent; using System.Net; using System.Threading; using Universe.Framework.ConsoleFramework; namespace Universe.Framework.Servers.HttpServer { public sealed class HttpListenerManager : IDisposable { //Error codes to ignore if something goes wrong // 1229 - An operation was attempted on a nonexistent network connection // 995 - The I/O operation has been aborted because of either a thread exit or an application request. public static readonly int[] IGNORE_ERROR_CODES = new int[3] { 64, 1229, 995 }; public event Action<HttpListenerContext> ProcessRequest; ConcurrentQueue<HttpListenerContext> _queue; ManualResetEvent _newQueueItem = new ManualResetEvent(false), _listenForNextRequest = new ManualResetEvent(false); readonly HttpListener _listener; readonly Thread _listenerThread; readonly Thread[] _workers; bool _isSecure; bool _isRunning; int _lockedQueue; public HttpListenerManager(uint maxThreads, bool isSecure) { _workers = new Thread[maxThreads]; _queue = new ConcurrentQueue<HttpListenerContext>(); _listener = new HttpListener(); #if LINUX _listener.IgnoreWriteExceptions = true; #endif _listenerThread = new Thread(HandleRequests); _isSecure = isSecure; } public void Start(uint port) { _isRunning = true; _listener.Prefixes.Add(String.Format(@"http{0}://+:{1}/", _isSecure ? "s" : "", port)); _listener.Start(); _listenerThread.Start(); for (int i = 0; i < _workers.Length; i++) { _workers[i] = new Thread(Worker); _workers[i].Start(); } } public void Dispose() { Stop(); } public void Stop() { if (!_isRunning) return; _isRunning = false; _listener.Stop(); _listenForNextRequest.Set(); _listenerThread.Join(); _newQueueItem.Set(); foreach (Thread worker in _workers) worker.Join(); _listener.Close(); } #if true //LINUX void HandleRequests() { while (_listener.IsListening) { _listener.BeginGetContext(ListenerCallback, null); _listenForNextRequest.WaitOne(); _listenForNextRequest.Reset(); } } void ListenerCallback(IAsyncResult result) { HttpListenerContext context = null; try { if(_listener.IsListening) context = _listener.EndGetContext(result); } catch (Exception ex) { MainConsole.Instance.ErrorFormat("[HttpListenerManager]: Exception occurred: {0}", ex.ToString()); return; } finally { _listenForNextRequest.Set(); } if (context == null) return; _queue.Enqueue(context); _newQueueItem.Set(); } #else private void HandleRequests() { while (_listener.IsListening) { var context = _listener.BeginGetContext(ContextReady, null); if (0 == WaitHandle.WaitAny(new[] {_stop, context.AsyncWaitHandle})) return; } } private void ContextReady(IAsyncResult ar) { try { if (!_listener.IsListening) return; _queue.Enqueue(_listener.EndGetContext(ar)); _newQueueItem.Set(); } catch { return; } } #endif void Worker() { while ((_queue.Count > 0 || _newQueueItem.WaitOne()) && _listener.IsListening) { _newQueueItem.Reset(); HttpListenerContext context = null; if (Interlocked.CompareExchange(ref _lockedQueue, 1, 0) == 0) { _queue.TryDequeue(out context); //All done Interlocked.Exchange(ref _lockedQueue, 0); } try { if(context != null) ProcessRequest(context); } catch (Exception e) { MainConsole.Instance.ErrorFormat("[HttpListenerManager]: Exception occurred: {0}", e.ToString()); } } } } }
35.6
123
0.563572
[ "MIT" ]
johnfelipe/Virtual-Universe
Universe/Framework/Servers/HttpServer/HttpListenerManager.cs
6,766
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nile.Stores { /// <summary>Base Class for product database.</summary> public class FileProductDatabase : MemoryProductDatabase { public FileProductDatabase(string filename) { // Validate argument if (filename == null) throw new ArgumentNullException(nameof(filename)); if (String.IsNullOrEmpty(filename)) throw new ArgumentException("Filename cannot be empty.", nameof(filename)); _filename = filename; LoadFile(filename); } /// <summary>Adds a product.</summary> /// <param name="product">The product to add.</param> /// <returns>The added product.</returns> protected override Product AddCore( Product product ) { var newProduct = base.AddCore(product); SaveFile(_filename); return newProduct; } /// <summary>Removes the product.</summary> /// <param name="product">The product to remove.</param> protected override void RemoveCore(int id) { base.RemoveCore(id); SaveFile(_filename); } /// <summary>Updates a product.</summary> /// <param name="product">The product to update.</param> /// <returns>The updated product.</returns> protected override Product UpdateCore(Product existing, Product product) { var newProduct = base.UpdateCore(existing, product); SaveFile(_filename); return newProduct; } private void LoadFile( string filename ) { if (!File.Exists(filename)) return; var lines = File.ReadAllLines(filename); foreach(var line in lines) { if (String.IsNullOrEmpty(line)) continue; var fields = line.Split(','); var product = new Product() { Id = Int32.Parse(fields[0]), Name = fields[1], Description = fields[2], Price = Decimal.Parse(fields[3]), IsDiscontinued = Boolean.Parse(fields[4]) }; base.AddCore(product); }; } private void SaveFile(string filename) { ////Streaming //var stream = File.OpenWrite(filename); //StreamWriter writer = null; //try //{ // // Write stuff // writer = new StreamWriter(stream); //} finally //{ // writer?.Dispose(); // stream.Close(); //}; //Streaming using (var writer = new StreamWriter(filename)) { // Write stuff foreach (var product in GetAllCore()) { var row = String.Join(",", product.Id, product.Name, product.Description, product.Price, product.IsDiscontinued); writer.WriteLine(row); } }; } private readonly string _filename; } }
30.362069
94
0.499716
[ "MIT" ]
ThomasWhiteTCCD/ITSE-1430
Classwork/Section4/Nile/Nile/Stores/FileProductDatabase.cs
3,524
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace WebApiTokenAuth.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
38.445087
176
0.555255
[ "MIT" ]
shivakanthch99/WebApiTokenAuth
Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
6,651
C#
//------------------------------------------------------------------------------ // <copyright file="PrologCodeEmptyList.cs" company="Axiom"> // // Copyright (c) 2006 Ali Hodroj. All rights reserved. // // The use and distribution terms for this source code are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // </copyright> //------------------------------------------------------------------------------ using System; namespace Axiom.Compiler.CodeObjectModel { /// <summary> /// Represents a Prolog empty list ([]). /// </summary> public class PrologCodeEmptyList : PrologCodeList { public override string ToString() { return "[]"; } } }
31.272727
85
0.495155
[ "MIT" ]
FacticiusVir/prologdotnet
Prolog.Compiler/CodeObjectModel/PrologCodeEmptyList.cs
1,032
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("xUnitExtensions")] [assembly: AssemblyDescription("Xunit.Net Extensions")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Sean Sobey")] [assembly: AssemblyProduct("xUnitExtensions")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2fcefb8a-1c24-4d9a-9a6a-f633c8abc42d")] // 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")] [assembly: InternalsVisibleTo("xUnitExtensions.Tests")]
39.184211
84
0.752183
[ "MIT" ]
R2dical/Xunit
xUnitExtensions/Properties/AssemblyInfo.cs
1,492
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CommandLine; namespace aggregator.cli { [Verb("map.local.rule", HelpText = "Maps an Aggregator Rule to existing Azure DevOps Server Projects.")] class MapLocalRuleCommand : CommandBase { [Option('p', "project", Required = true, HelpText = "Azure DevOps project name.")] public string Project { get; set; } [ShowInTelemetry] [Option('e', "event", Required = true, HelpText = "Azure DevOps event.")] public string Event { get; set; } [Option('t', "targetUrl", Required = true, HelpText = "Aggregator instance URL.")] public string TargetUrl { get; set; } [ShowInTelemetry] [Option('r', "rule", Required = true, HelpText = "Aggregator rule name.")] public string Rule { get; set; } [ShowInTelemetry] [Option("impersonate", Required = false, HelpText = "Do rule changes on behalf of the person triggered the rule execution. See wiki for details, requires special account privileges.")] public bool ImpersonateExecution { get; set; } // event filters: but cannot make AreaPath & Tag work //[Option("filterAreaPath", Required = false, HelpText = "Filter Azure DevOps event to include only Work Items under the specified Area Path.")] public string FilterAreaPath { get; set; } [ShowInTelemetry] [Option("filterType", Required = false, HelpText = "Filter Azure DevOps event to include only Work Items of the specified Work Item Type.")] public string FilterType { get; set; } //[Option("filterTag", Required = false, HelpText = "Filter Azure DevOps event to include only Work Items containing the specified Tag.")] public string FilterTag { get; set; } [ShowInTelemetry] [Option("filterFields", Required = false, HelpText = "Filter Azure DevOps event to include only work items with the specified Field(s) changed.")] public IEnumerable<string> FilterFields { get; set; } [ShowInTelemetry] [Option("filterOnlyLinks", Required = false, HelpText = "Filter Azure DevOps event to include only work items with links added or removed.")] public bool FilterOnlyLinks { get; set; } internal override async Task<int> RunAsync(CancellationToken cancellationToken) { var context = await Context .WithDevOpsLogon() .BuildAsync(cancellationToken); var mappings = new AggregatorMappings(context.Devops, context.Azure, context.Logger, context.Naming); bool ok = DevOpsEvents.IsValidEvent(Event); if (!ok) { context.Logger.WriteError($"Invalid event type."); return ExitCodes.InvalidArguments; } var filters = new EventFilters { AreaPath = FilterAreaPath, Type = FilterType, Tag = FilterTag, Fields = FilterFields, OnlyLinks = FilterOnlyLinks, }; var targetUrl = new Uri(TargetUrl); var id = await mappings.AddFromUrlAsync(Project, Event, filters, targetUrl, Rule, ImpersonateExecution, cancellationToken); return id.Equals(Guid.Empty) ? ExitCodes.Failure : ExitCodes.Success; } } }
46.876712
192
0.637347
[ "Apache-2.0" ]
tfsaggregator/aggregator-cli
src/aggregator-cli/Mappings/MapLocalRuleCommand.cs
3,424
C#
using BookStoreMvc.Data; using BookStoreMvc.Helpers; using BookStoreMvc.Models; using BookStoreMvc.Repository; using BookStoreMvc.Services; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; namespace BookStoreMvc { public class Startup { private readonly IConfiguration configuration; public Startup(IConfiguration configuration) { this.configuration = configuration; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDbContext<BookStoreContext>( options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")) ); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<BookStoreContext>() .AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 5; options.Password.RequireLowercase = false; options.Password.RequiredUniqueChars = 1; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.SignIn.RequireConfirmedEmail = true; options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(20); options.Lockout.AllowedForNewUsers = true; options.Lockout.MaxFailedAccessAttempts = 3; }); services.Configure<DataProtectionTokenProviderOptions>(options => { options.TokenLifespan = TimeSpan.FromMinutes(5); }); // Cookie settings services.ConfigureApplicationCookie(config => { config.Cookie.Name = "BookStore"; config.LoginPath = configuration["Application:loginPath"]; // User defined login path config.ExpireTimeSpan = TimeSpan.FromMinutes(5); }); services.AddControllersWithViews(); #if DEBUG services.AddRazorPages().AddRazorRuntimeCompilation(); // Umcomment this code to disable client-side validations. //.AddViewOptions(option => //{ // option.HtmlHelperOptions.ClientValidationEnabled = false; //}); #endif services.AddScoped<IBookRepository, BookRepository>(); services.AddScoped<ILanguageRepository, LanguageRepository>(); services.AddScoped<IAccountRepository, AccountRepository>(); services.AddScoped<ICategoryRepository, CategoryRepository>(); services.AddScoped<IAuthorRepository, AuthorRepository>(); services.AddScoped<IGenreRepository, GenreRepository>(); services.AddSingleton<IMessageRepository, MessageRepository>(); services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, ApplicationUserClaimsPrincipalFactory>(); services.AddScoped<IUserService, UserService>(); services.AddScoped<IEmailService, EmailService>(); services.Configure<NewBookAlertConfig>("InternalBook", configuration.GetSection("NewBookAlert")); services.Configure<NewBookAlertConfig>("ThirdPartyBook", configuration.GetSection("ThirdPartyBookAlert")); services.Configure<SMTPConfigModel>(configuration.GetSection("SMTPConfig")); //services.AddHsts(options => //{ // options.Preload = true; // options.IncludeSubDomains = true; // options.MaxAge = TimeSpan.FromDays(60); // //options.ExcludedHosts.Add("example.com"); // //options.ExcludedHosts.Add("www.example.com"); //}); //services.AddHttpsRedirection(options => //{ // options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect; // options.HttpsPort = 443; //}); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); app.Use(async (ctx, next) => { await next(); if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted) { //Re-execute the request so the user gets the error page string originalPath = ctx.Request.Path.Value; ctx.Items["originalPath"] = originalPath; ctx.Request.Path = "/error/404"; await next(); } }); } //app.UseStatusCodePages(); //app.UseStatusCodePagesWithReExecute("/Error"); //app.UseStatusCodePagesWithReExecute("/Error/{0}"); //app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); //endpoints.MapControllerRoute( // name: "Default", // pattern: "{controller}/{action}/{id?}" // ); //endpoints.MapControllerRoute( // name: "AboutUs", // pattern: "about-us", // defaults: new { controller = "Home", action = "AboutUs"} // ); endpoints.MapControllerRoute( name: "MyArea", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}" ); }); } } }
38.710227
122
0.577132
[ "MIT" ]
sorani-dev/AspNetCoreMVC-bookstore
BookStoreMvc/Startup.cs
6,813
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace App01_ControleXF { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
15.277778
44
0.752727
[ "MIT" ]
hitalofm/CursoProgramacaoXamarin
Controles Visuais/App01_ControleXF/App01_ControleXF/App01_ControleXF/MainPage.xaml.cs
277
C#
using Apollo.AdminStore.WebForm.Classes; using Apollo.Core.Model; using Apollo.Core.Services.Interfaces; using System; using System.Linq; using System.Web.UI.WebControls; namespace Apollo.AdminStore.WebForm.Marketing { public partial class promo_catalog_offer_default : BasePage { public IOfferService OfferService { get; set; } public IUtilityService UtilityService { get; set; } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) LoadRules(); } protected void lbResetFilter_Click(object sender, EventArgs e) { DisposeState(OFFER_RULE_ID_FILTER); DisposeState(NAME_FILTER); DisposeState(FROM_DATE_FILTER); DisposeState(TO_DATE_FILTER); DisposeState(IS_ACTIVE_FILTER); gvRules.CustomPageIndex = 0; LoadRules(); } protected void lbSearch_Click(object sender, EventArgs e) { SetState(OFFER_RULE_ID_FILTER, ((TextBox)gvRules.HeaderRow.FindControl("txtFilterId")).Text.Trim()); SetState(NAME_FILTER, ((TextBox)gvRules.HeaderRow.FindControl("txtRuleName")).Text.Trim()); SetState(FROM_DATE_FILTER, ((TextBox)gvRules.HeaderRow.FindControl("txtFromDate")).Text.Trim()); SetState(TO_DATE_FILTER, ((TextBox)gvRules.HeaderRow.FindControl("txtToDate")).Text.Trim()); DropDownList ddl = (DropDownList)gvRules.HeaderRow.FindControl("ddlStatus"); SetState(IS_ACTIVE_FILTER, ddl.SelectedIndex != 0 ? ddl.SelectedValue.ToString() : string.Empty); gvRules.CustomPageIndex = 0; LoadRules(); } protected void btnGoPage_Click(object sender, EventArgs e) { int gotoIndex = Convert.ToInt32(((TextBox)gvRules.TopPagerRow.FindControl("txtPageIndex")).Text) - 1; if ((gvRules.CustomPageCount > gotoIndex) && (gotoIndex >= 0)) gvRules.CustomPageIndex = gotoIndex; LoadRules(); } protected void lbCleanBasket_Click(object sender, EventArgs e) { OfferService.RemoveOfferedItemsFromBaskets(); enbNotice.Message = "All items which are related to offers were successfully to be removed from basket."; } protected void gvRules_PageIndexChanging(object sender, GridViewPageEventArgs e) { gvRules.CustomPageIndex = gvRules.CustomPageIndex + e.NewPageIndex; if (gvRules.CustomPageIndex < 0) gvRules.CustomPageIndex = 0; LoadRules(); } protected void gvRules_Sorting(object sender, GridViewSortEventArgs e) { OfferRuleSortingType orderBy = OfferRuleSortingType.IdAsc; switch (e.SortExpression) { default: case "Id": orderBy = OfferRuleSortingType.IdDesc; if (e.SortDirection == SortDirection.Ascending) orderBy = OfferRuleSortingType.IdAsc; break; case "Name": orderBy = OfferRuleSortingType.NameDesc; if (e.SortDirection == SortDirection.Ascending) orderBy = OfferRuleSortingType.NameAsc; break; case "Priority": orderBy = OfferRuleSortingType.PriorityDesc; if (e.SortDirection == SortDirection.Ascending) orderBy = OfferRuleSortingType.PriorityAsc; break; } SetState("OrderBy", (int)orderBy); LoadRules(); } protected void gvRules_PreRender(object sender, EventArgs e) { if (gvRules.TopPagerRow != null) { gvRules.TopPagerRow.Visible = true; } ((TextBox)gvRules.HeaderRow.FindControl("txtFilterId")).Text = GetStringState(OFFER_RULE_ID_FILTER); ((TextBox)gvRules.HeaderRow.FindControl("txtRuleName")).Text = GetStringState(NAME_FILTER); ((TextBox)gvRules.HeaderRow.FindControl("txtFromDate")).Text = GetStringState(FROM_DATE_FILTER); ((TextBox)gvRules.HeaderRow.FindControl("txtToDate")).Text = GetStringState(TO_DATE_FILTER); DropDownList ddl = (DropDownList)gvRules.HeaderRow.FindControl("ddlStatus"); if (GetStringState(IS_ACTIVE_FILTER) != string.Empty) ddl.Items.FindByValue(GetStringState(IS_ACTIVE_FILTER)).Selected = true; } protected string GetStatus(object objOfferRuleId) { int offerRuleId = Convert.ToInt32(objOfferRuleId); if (offerRuleId != 0) { var offer = OfferService.GetOfferRuleById(offerRuleId); if (offer.Condition == null) return "No condition setup."; return "Valid."; } return string.Empty; } protected void lbPublish_Click(object sender, EventArgs e) { var result = UtilityService.RefreshCache(CacheEntityKey.Offer | CacheEntityKey.Category | CacheEntityKey.Brand | CacheEntityKey.Product); if (result) enbNotice.Message = "All offers and products related data on store front has been refreshed successfully."; else enbNotice.Message = "Failed to refresh data on store front. Please contact administrator for help."; } private void LoadRules() { int[] offerRuleIds = null; string name = null; string promocode = null; string fromDate = null; string toDate = null; bool? isActive = null; OfferRuleSortingType orderBy = OfferRuleSortingType.IdAsc; if (HasState(OFFER_RULE_ID_FILTER)) { string value = GetStringState(OFFER_RULE_ID_FILTER); int temp; offerRuleIds = value.Split(',') .Where(x => int.TryParse(x.ToString(), out temp)) .Select(x => int.Parse(x)) .ToArray(); } if (HasState(NAME_FILTER)) name = GetStringState(NAME_FILTER); if (HasState(PROMO_CODE_FILTER)) promocode = GetStringState(PROMO_CODE_FILTER); if (HasState(FROM_DATE_FILTER)) fromDate = GetStringState(FROM_DATE_FILTER); if (HasState(TO_DATE_FILTER)) toDate = GetStringState(TO_DATE_FILTER); if (HasState(IS_ACTIVE_FILTER)) isActive = Convert.ToBoolean(GetStringState(IS_ACTIVE_FILTER)); if (HasState("OrderBy")) orderBy = (OfferRuleSortingType)GetIntState("OrderBy"); var result = OfferService.GetOfferRuleLoadPaged( pageIndex: gvRules.CustomPageIndex, pageSize: gvRules.PageSize, offerRuleIds: offerRuleIds, name: name, promocode: promocode, fromDate: fromDate, toDate: toDate, isActive: isActive, isCart: false, orderBy: orderBy); if (result != null) { gvRules.DataSource = result.Items; gvRules.RecordCount = result.TotalCount; gvRules.CustomPageCount = result.TotalPages; } gvRules.DataBind(); if (gvRules.Rows.Count <= 0) enbNotice.Message = "No records found."; } } }
38.954082
149
0.588605
[ "MIT" ]
hancheester/apollo
Store Admin/Apollo.AdminStore.WebForm/Marketing/promo_catalog_offer_default.aspx.cs
7,637
C#
 namespace Group_OOP { partial class Form2 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersWidth = 62; this.dataGridView1.RowTemplate.Height = 33; this.dataGridView1.Size = new System.Drawing.Size(1209, 783); this.dataGridView1.TabIndex = 0; // // button1 // this.button1.Location = new System.Drawing.Point(1090, 801); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(131, 52); this.button1.TabIndex = 1; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(895, 801); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(189, 52); this.button2.TabIndex = 2; this.button2.Text = "Удаление записи"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // Form2 // this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1233, 865); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.dataGridView1); this.Name = "Form2"; this.Text = "Список группы"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; } }
39.58427
131
0.58189
[ "MIT" ]
Ilyadevin/Group_OOP
Group_OOP/Form2.Designer.cs
3,551
C#
using System; namespace MyMessenger.Core { public interface IMessage { int MessageId { get; set; } string Text { get; } DateTimeOffset SendDateTime { get; } int DialogId { get; } int AuthorId { get; } } }
13.235294
38
0.648889
[ "MIT" ]
prekel/MyMessenger
MyMessenger.Core/IMessage.cs
227
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.LanguageServer.Common; using Microsoft.AspNetCore.Razor.LanguageServer.ProjectSystem; using Microsoft.CodeAnalysis.Razor; using Microsoft.CodeAnalysis.Text; using Microsoft.Extensions.Logging; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Server; using HoverModel = OmniSharp.Extensions.LanguageServer.Protocol.Models.Hover; namespace Microsoft.AspNetCore.Razor.LanguageServer.Hover { internal class RazorHoverEndpoint : IHoverHandler { private HoverCapability _capability; private readonly ILogger _logger; private readonly ForegroundDispatcher _foregroundDispatcher; private readonly DocumentResolver _documentResolver; private readonly RazorHoverInfoService _hoverInfoService; public RazorHoverEndpoint( ForegroundDispatcher foregroundDispatcher, DocumentResolver documentResolver, RazorHoverInfoService hoverInfoService, ILoggerFactory loggerFactory) { if (foregroundDispatcher is null) { throw new ArgumentNullException(nameof(foregroundDispatcher)); } if (documentResolver is null) { throw new ArgumentNullException(nameof(documentResolver)); } if (hoverInfoService is null) { throw new ArgumentNullException(nameof(hoverInfoService)); } if (loggerFactory is null) { throw new ArgumentNullException(nameof(loggerFactory)); } _foregroundDispatcher = foregroundDispatcher; _documentResolver = documentResolver; _hoverInfoService = hoverInfoService; _logger = loggerFactory.CreateLogger<RazorHoverEndpoint>(); } public TextDocumentRegistrationOptions GetRegistrationOptions() { return new TextDocumentRegistrationOptions() { DocumentSelector = RazorDefaults.Selector }; } public async Task<HoverModel> Handle(HoverParams request, CancellationToken cancellationToken) { if (request is null) { throw new ArgumentNullException(nameof(request)); } var document = await Task.Factory.StartNew(() => { _documentResolver.TryResolveDocument(request.TextDocument.Uri.AbsolutePath, out var documentSnapshot); return documentSnapshot; }, cancellationToken, TaskCreationOptions.None, _foregroundDispatcher.ForegroundScheduler); if (document is null) { return null; } var codeDocument = await document.GetGeneratedOutputAsync(); if (codeDocument.IsUnsupported()) { return null; } var tagHelperDocumentContext = codeDocument.GetTagHelperContext(); var sourceText = await document.GetTextAsync(); var linePosition = new LinePosition((int)request.Position.Line, (int)request.Position.Character); var hostDocumentIndex = sourceText.Lines.GetPosition(linePosition); var location = new SourceSpan(hostDocumentIndex, (int)request.Position.Line, (int)request.Position.Character, 0); var hoverItem = _hoverInfoService.GetHoverInfo(codeDocument, location); _logger.LogTrace($"Found hover info items."); return hoverItem; } public void SetCapability(HoverCapability capability) { _capability = capability; } } }
36.327434
125
0.659683
[ "Apache-2.0" ]
Pilchie/aspnetcore-tooling
src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hover/RazorHoverEndpoint.cs
4,107
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.ebpp.inspect.create /// </summary> public class AlipayEbppInspectCreateRequest : IAopRequest<AlipayEbppInspectCreateResponse> { /// <summary> /// 巡检平台数据同步 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.ebpp.inspect.create"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.318182
94
0.601949
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Request/AlipayEbppInspectCreateRequest.cs
2,581
C#
using System; using LanguageServer.Client; using LanguageServer.Parameters.General; namespace LanguageServer.Server { public class GeneralServiceTemplate : Service { public override Connection Connection { get => base.Connection; set { base.Connection = value; Proxy = new Proxy(value); } } public Proxy Proxy { get; private set; } [JsonRpcMethod("initialize")] protected virtual Result<InitializeResult, ResponseError<InitializeErrorData>> Initialize(InitializeParams @params) { throw new NotImplementedException(); } [JsonRpcMethod("initialized")] protected virtual void Initialized() { } [JsonRpcMethod("shutdown")] protected virtual VoidResult<ResponseError> Shutdown() { throw new NotImplementedException(); } [JsonRpcMethod("exit")] protected virtual void Exit() { } } }
22.395349
120
0.635514
[ "MIT" ]
DustLanguage/LanguageServerProtocol
LanguageServer/Server/GeneralServiceTemplate.cs
965
C#
namespace ClassLib126 { public class Class060 { public static string Property => "ClassLib126"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib126/Class060.cs
120
C#
using System; using System.Runtime.InteropServices; using NUnit.Framework; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI41; using Net.RutokenPkcs11Interop.LowLevelAPI41; using NativeULong = System.UInt32; namespace Net.RutokenPkcs11InteropTests.LowLevelAPI41 { [TestFixture()] public class _LL_04_TokenInfoTest { /// <summary> /// Basic C_GetTokenInfo test. /// </summary> [Test()] public void _LL_04_01_TokenInfoTest() { Helpers.CheckPlatform(); CKR rv = CKR.CKR_OK; using (RutokenPkcs11Library pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath)) { // Инициализация библиотеки rv = pkcs11.C_Initialize(Settings.InitArgs41); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Установление соединения с Рутокен в первом доступном слоте NativeULong slotId = Helpers.GetUsableSlot(pkcs11); // Получение информации о токене var tokenInfo = new CK_TOKEN_INFO(); rv = pkcs11.C_GetTokenInfo(slotId, ref tokenInfo); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsFalse(String.IsNullOrEmpty(ConvertUtils.BytesToUtf8String(tokenInfo.ManufacturerId))); // Завершение сессии rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EX_GetTokenInfoExtended test. /// </summary> [Test()] public void _LL_04_02_TokenInfoExtendedTest() { Helpers.CheckPlatform(); CKR rv = CKR.CKR_OK; using (var pkcs11 = new RutokenPkcs11Library(Settings.Pkcs11LibraryPath)) { // Инициализация библиотеки rv = pkcs11.C_Initialize(Settings.InitArgs41); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Установление соединения с Рутокен в первом доступном слоте NativeULong slotId = Helpers.GetUsableSlot(pkcs11); // Получение расширенной информации о токене var tokenInfo = new CK_TOKEN_INFO_EXTENDED { SizeofThisStructure = Convert.ToUInt32(Marshal.SizeOf(typeof(CK_TOKEN_INFO_EXTENDED))) }; rv = pkcs11.C_EX_GetTokenInfoExtended(slotId, ref tokenInfo); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsFalse(String.IsNullOrEmpty(ConvertUtils.BytesToUtf8String(tokenInfo.ATR))); // Завершение сессии rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
34.777778
111
0.567732
[ "Apache-2.0" ]
AktivCo/RutokenPkcs11Interop
src/RutokenPkcs11Interop.Tests/LowLevelAPI41/_LL_04_TokenInfoTest.cs
3,375
C#
using System; using System.Collections.Generic; public class Student { public static HashSet<Student> allStudents = new HashSet<string>(); public string name; public Student(string name) { this.name = name; } public override bool Equals(object other) { return this.GetHashCode().Equals(other.GetHashCode()); } public override int GetHashCode() { return this.name.GetHashCode(); } } class UniqueStudenNameExecution { static void Main() { var students = new HashSet<string>(); while (true) { var inputLine = Console.ReadLine(); var isTimeToStopLoop = inputLine.Equals("end", StringComparison.InvariantCultureIgnoreCase); if (isTimeToStopLoop) { break; } var student = new Student(inputLine); Student.allStudents.Add(student); } Console.WriteLine(StudentGroup.allStudents.Count); } }
20.653061
104
0.59585
[ "MIT" ]
NikolaVodenicharov/OOP-Basics
StaticMembers/UniqueStudenNameExerices/UniqueStudenNameExecution.cs
1,014
C#
using System; using System.Collections.Generic; using System.Windows.Forms; namespace Thinksea.LogTest { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
20.714286
65
0.577011
[ "MIT" ]
thinksea/ThinkseaGeneric
Thinksea.LogTest/Program.cs
457
C#
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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 SharpDX.DirectWrite { public partial struct LineBreakpoint { /// <summary> /// Indicates a breaking condition before the character. /// </summary> /// <unmanaged>byte breakConditionBefore</unmanaged> public BreakCondition BreakConditionBefore { get { return (BreakCondition) BreakConditionBefore_; } set { BreakConditionBefore_ = (byte)value; } } /// <summary> /// Indicates a breaking condition after the character. /// </summary> /// <unmanaged>byte breakConditionAfter</unmanaged> public BreakCondition BreakConditionAfter { get { return (BreakCondition)BreakConditionAfter_; } set { BreakConditionAfter_ = (byte)value; } } } }
37.431034
81
0.624597
[ "MIT" ]
shoelzer/SharpDX
Source/SharpDX.Direct2D1/DirectWrite/LineBreakpoint.cs
2,171
C#
using System.Reflection; 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("ESFA.DC.ILR.ValidationService.Console")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ESFA.DC.ILR.ValidationService.Console")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("f58eebec-3db3-4096-8b68-fc3c09a80400")] // 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.972222
84
0.747684
[ "MIT" ]
SkillsFundingAgency/DC-ILR-1819-ValidationService
src/ESFA.DC.ILR.ValidationService.Console/Properties/AssemblyInfo.cs
1,406
C#
using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using SharpGen.Model; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace SharpGen.Generator.Marshallers { internal sealed class RemappedTypeMarshaller : MarshallerBase, IMarshaller { public bool CanMarshal(CsMarshalBase csElement) => csElement.MappedToDifferentPublicType; public ArgumentSyntax GenerateManagedArgument(CsParameter csElement) => GenerateManagedValueTypeArgument(csElement); public ParameterSyntax GenerateManagedParameter(CsParameter csElement) => GenerateManagedValueTypeParameter(csElement); public StatementSyntax GenerateManagedToNative(CsMarshalBase csElement, bool singleStackFrame) => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, GetMarshalStorageLocation(csElement), CastExpression(GetMarshalTypeSyntax(csElement), IdentifierName(csElement.Name)) ) ); public IEnumerable<StatementSyntax> GenerateManagedToNativeProlog(CsMarshalCallableBase csElement) { yield return LocalDeclarationStatement( VariableDeclaration( GetMarshalTypeSyntax(csElement), SingletonSeparatedList(VariableDeclarator(GetMarshalStorageLocationIdentifier(csElement))) ) ); } public ArgumentSyntax GenerateNativeArgument(CsMarshalCallableBase csElement) => Argument( csElement.PassedByNativeReference ? PrefixUnaryExpression(SyntaxKind.AddressOfExpression, GetMarshalStorageLocation(csElement)) : GetMarshalStorageLocation(csElement) ); public StatementSyntax GenerateNativeCleanup(CsMarshalBase csElement, bool singleStackFrame) => null; public StatementSyntax GenerateNativeToManaged(CsMarshalBase csElement, bool singleStackFrame) => ExpressionStatement( AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, IdentifierName(csElement.Name), GeneratorHelpers.CastExpression( ParseTypeName(csElement.PublicType.QualifiedName), GetMarshalStorageLocation(csElement) ) ) ); public IEnumerable<StatementSyntax> GenerateNativeToManagedExtendedProlog(CsMarshalCallableBase csElement) => Enumerable.Empty<StatementSyntax>(); public FixedStatementSyntax GeneratePin(CsParameter csElement) => null; public bool GeneratesMarshalVariable(CsMarshalCallableBase csElement) => true; public TypeSyntax GetMarshalTypeSyntax(CsMarshalBase csElement) => ParseTypeName(csElement.MarshalType.QualifiedName); public RemappedTypeMarshaller(Ioc ioc) : base(ioc) { } } }
42.054795
117
0.689577
[ "MIT" ]
JetBrains/SharpGenTools
SharpGen/Generator/Marshallers/RemappedTypeMarshaller.cs
3,072
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("PhoneBook.Api")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("PhoneBook.Api")] [assembly: System.Reflection.AssemblyTitleAttribute("PhoneBook.Api")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.208333
80
0.647118
[ "MIT" ]
takudzwa-dot/Phone-Book
PhoneBook/obj/Debug/netcoreapp3.1/PhoneBook.Api.AssemblyInfo.cs
989
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace NetCoreWebJob.Pages { public class PrivacyModel : PageModel { public void OnGet() { } } }
19.3125
42
0.705502
[ "MIT" ]
SanderRossel/NetCoreWebJob
NetCoreWebJob/NetCoreWebJob/Pages/Privacy.cshtml.cs
311
C#
using System; using System.Collections; using UnityEngine; using UnityEngine.Networking; namespace SubiNoOnibus.Networking.Requests { public static class UserAuthRequestHandler { public const string authKey = "Auth"; public static void SaveAuthCookie(UnityWebRequest request) { string cookie = request.GetResponseHeader("Set-Cookie"); if (!string.IsNullOrEmpty(cookie)) { PlayerPrefs.SetString(authKey, cookie); } } public static IEnumerator GetSession(SessionData data, Action OnSuccess, Action<UnityWebRequest> OnFailure = null) { RaycastBlockEvent.Invoke(true); using UnityWebRequest request = WebRequestFactory.PostJson(Endpoints.Login_get_session_url, JsonUtility.ToJson(data)); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { OnFailure?.Invoke(request); } else { SaveAuthCookie(request); OnSuccess?.Invoke(); } RaycastBlockEvent.Invoke(false); } public static IEnumerator Logout(Action OnSuccess, Action<UnityWebRequest> OnFailure = null) { RaycastBlockEvent.Invoke(true); using UnityWebRequest request = WebRequestFactory.AuthPostJson(Endpoints.Logout_url); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { OnFailure?.Invoke(request); } else { UnityWebRequest.ClearCookieCache(); PlayerPrefs.DeleteKey(authKey); OnSuccess?.Invoke(); } RaycastBlockEvent.Invoke(false); } public static IEnumerator ValidateSession(Action OnSuccess, Action OnFailure = null) { RaycastBlockEvent.Invoke(true); using UnityWebRequest request = WebRequestFactory.AuthGet(Endpoints.Session_validate_url); yield return request.SendWebRequest(); RaycastBlockEvent.Invoke(false); if (request.result == UnityWebRequest.Result.Success) { OnSuccess?.Invoke(); } else { OnFailure?.Invoke(); } } } }
30.777778
130
0.572804
[ "MIT" ]
FellowshipOfTheGame/semcomp-24
Assets/Scripts/Backend/RequestHandlers/UserAuthRequestHandler.cs
2,495
C#
using Dfc.CourseDirectory.Services.Models; using Dfc.CourseDirectory.Web.ViewModels; using Dfc.CourseDirectory.WebV2; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace Dfc.CourseDirectory.Web.Controllers { [Authorize("Fe")] public class CoursesController : Controller { private readonly IProviderContextProvider _providerContextProvider; public CoursesController(IProviderContextProvider providerContextProvider) { _providerContextProvider = providerContextProvider; } public IActionResult LandingOptions(CoursesLandingViewModel model) { switch (model.CoursesLandingOptions) { case CoursesLandingOptions.Add: return RedirectToAction("Index", "RegulatedQualification"); case CoursesLandingOptions.Upload: return RedirectToAction("Index", "CoursesDataManagement") .WithProviderContext(_providerContextProvider.GetProviderContext(withLegacyFallback: true)); case CoursesLandingOptions.View: return RedirectToAction("Index","ProviderCourses"); default: return RedirectToAction("LandingOptions", "Qualifications"); } } } }
37.305556
116
0.666418
[ "MIT" ]
SkillsFundingAgency/dfc-coursedirectory
src/Dfc.CourseDirectory.Web/Controllers/CoursesController.cs
1,343
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Cake.Core.IO; namespace Cake.Common.Tools.OctopusDeploy { /// <summary> /// Possible arguments to pass to Octo.exe for promoting a release. See <see href="https://octopus.com/docs/api-and-integration/octo.exe-command-line/promoting-releases">Octopus Deploy documentation</see>. /// </summary> public sealed class OctopusDeployPromoteReleaseSettings : OctopusDeployCommonToolSettings { /// <summary> /// Initializes a new instance of the <see cref="OctopusDeployPromoteReleaseSettings"/> class. /// </summary> public OctopusDeployPromoteReleaseSettings() { Variables = new Dictionary<string, string>(); } /// <summary> /// Gets or sets a value indicating whether overwrite the variable snapshot for the release by re-importing the variables from the project. /// </summary> public bool UpdateVariables { get; set; } /// <summary> /// Gets or sets a value indicating whether progress of the deployment should be followed. (Sets --waitfordeployment and --norawlog to true.) /// </summary> public bool ShowProgress { get; set; } /// <summary> /// Gets or sets a value indicating whether to force downloading of already installed packages. Default false. /// </summary> public bool ForcePackageDownload { get; set; } /// <summary> /// Gets or sets a value indicating whether to wait synchronously for deployment to finish. /// </summary> public bool WaitForDeployment { get; set; } /// <summary> /// Gets or sets maximum time (timespan format) that the console session will wait for the deployment to finish (default 00:10:00). /// This will not stop the deployment. Requires WaitForDeployment parameter set. /// </summary> public TimeSpan? DeploymentTimeout { get; set; } /// <summary> /// Gets or sets a value indicating whether to cancel the deployment if the deployment timeout is reached(default false). /// </summary> public bool CancelOnTimeout { get; set; } /// <summary> /// Gets or sets how much time should elapse between deployment status checks(default 00:00:10). /// </summary> public TimeSpan? DeploymentChecksLeepCycle { get; set; } /// <summary> /// Gets or sets a value indicating whether to use Guided Failure mode. If not specified, will use default setting from environment. /// </summary> public bool? GuidedFailure { get; set; } /// <summary> /// Gets or sets list of machines names to target in the deployed environment.If not specified all machines in the environment will be considered. /// </summary> public string[] SpecificMachines { get; set; } /// <summary> /// Gets or sets a value indicating whether a project is configured to skip packages with already-installed versions, override this setting to force re-deployment (flag, default false). /// </summary> public bool Force { get; set; } /// <summary> /// Gets or sets a list of steps to be skipped. Takes step names. /// </summary> public string[] SkipSteps { get; set; } /// <summary> /// Gets or sets a value indicating whether print the raw log of failed tasks or not. /// </summary> public bool NoRawLog { get; set; } /// <summary> /// Gets or sets a file where to redirect the raw log of failed tasks. /// </summary> public FilePath RawLogFile { get; set; } /// <summary> /// Gets or sets values for any prompted variables. /// </summary> public IDictionary<string, string> Variables { get; set; } /// <summary> /// Gets or sets time at which deployment should start (scheduled deployment), specified as any valid DateTimeOffset format, and assuming the time zone is the current local time zone. /// </summary> public DateTimeOffset? DeployAt { get; set; } /// <summary> /// Gets or sets a tenant the deployment will be performed for; specify this argument multiple times to add multiple tenants or use `*` wildcard to deploy to tenants able to deploy. /// </summary> public string[] Tenant { get; set; } /// <summary> /// Gets or sets a tenant tags used to match tenants that the deployment will be performed for; specify this argument multiple times to add multiple tenant tags. /// </summary> public string[] TenantTags { get; set; } } }
44.495495
209
0.640008
[ "MIT" ]
Acidburn0zzz/cake
src/Cake.Common/Tools/OctopusDeploy/OctopusDeployPromoteReleaseSettings.cs
4,941
C#
using WPILib.Commands; namespace ChopShop2016.Commands { public class CancelShot : InstantCommand { public CancelShot() { Requires(ChopShop2016.aimShooter); Requires(ChopShop2016.intakeRoller); Requires(ChopShop2016.shooter); } // Called just before this Command runs the first time protected override void Initialize() { ChopShop2016.aimShooter.Stop(); ChopShop2016.intakeRoller.Stop(); ChopShop2016.shooter.SetSpeedOpenLoop(0.0); ChopShop2016.intake.MotorStop(); } } }
26.083333
62
0.607029
[ "MIT" ]
chopshop-166/frc-2016-cs
Commands/CancelShot.cs
628
C#
namespace Albion.Network { public enum EventCodes { evevLeave = 1, evJoinFinished, evMove, evPartyInvitation, evChangeEquipment, evHealthUpdate, evEnergyUpdate, evDamageShieldUpdate, evCraftingFocusUpdate, evActiveSpellEffectsUpdate, evResetCooldowns, evGetAttacked, evCastStart, evCastCancel, evCastTimeUpdate, evCastFinished, evCastSpell, evCastHit, evCastHits, evChannelingEnded, evAttackBuilding, evInventoryPutItem, evMovedItemInInventory, evTrashItem, evNewEquipmentItem, evNewSimpleItem, evSplitItemStack, evNewJournalItem, evNewLaborerItem, evMove2, evNewSimpleHarvestableObjectList, evStopsMoving, evNewSilverObject, evNewBuilding, evMove3, evMobChangeState, evFactionBuildingInfo, evCraftBuildingInfo, evRepairBuildingInfo, evMeldBuildingInfo, evConstructionSiteInfo, evPlayerBuildingInfo, evFarmBuildingInfo, evTutorialBuildingInfo, evLaborerObjectInfo, evLaborerObjectJobInfo, evMarketPlaceBuildingInfo, evHarvestStart, evHarvestCancel, evHarvestFinished, evTakeSilver, evActionOnBuildingStart, evActionOnBuildingCancel, evActionOnBuildingFinished, evItemRerollQualityStart, evItemRerollQualityCancel, evItemRerollQualityFinished, evInstallResourceStart, evInstallResourceCancel, evInstallResourceFinished, evCraftItemFinished, evLogoutCancel, evChatMessage, evChatSay, evChatWhisper, evChatMuted, evPlayEmote, evStopEmote, evSystemMessage, evUtilityTextMessage, evUpdateMoney, evUpdateFame, evUpdateLearningPoints, evUpdateReSpecPoints, evUpdateCurrency, evUpdateFactionStanding, evRespawn, evServerDebugLog, evCharacterEquipmentChanged, evRegenerationHealthChanged, evRegenerationEnergyChanged, evRegenerationMountHealthChanged, evRegenerationCraftingChanged, evRegenerationHealthEnergyComboChanged, evRegenerationPlayerComboChanged, evDurabilityChanged, evNewLoot, evAttachItemContainer, evDetachItemContainer, evGuildUpdate, evGuildPlayerUpdated, evInvitedToGuild, evUnknown, evPlayerGetonline, evObjectEvent, evNewMonolithObject, evNewSiegeCampObject, evNewOrbObject, evNewCastleObject, evNewSpellEffectArea, evNewChainSpell, evUpdateChainSpell, evCastSpell2, evStartMatch, evStartTerritoryMatchInfos, evStartArenaMatchInfos, evEndTerritoryMatch, evEndArenaMatch, evMatchUpdate, evActiveMatchUpdate, evNewMob, evDebugAggroInfo, evDebugVariablesInfo, evDebugReputationInfo, evDebugDiminishingReturnInfo, evDebugSmartClusterQueueInfo, evClaimOrbStart, evClaimOrbFinished, evClaimOrbCancel, evOrbUpdate, evOrbClaimed, evNewWarCampObject, evNewMatchLootChestObject, evNewArenaExit, evGuildMemberTerritoryUpdate, evInvitedMercenaryToMatch, evClusterInfoUpdate, evForcedMovement, evForcedMovementCancel, evCharacterStats, evCharacterStatsKillHistory, evCharacterStatsDeathHistory, evGuildStats, evKillHistoryDetails, evFullAchievementInfo, evFinishedAchievement, evAchievementProgressInfo, evFullAchievementProgressInfo, evFullTrackedAchievementInfo, evFullAutoLearnAchievementInfo, evQuestGiverQuestOffered, evQuestGiverDebugInfo, evConsoleEvent, evTimeSync, evChangeAvatar, evChangeMountSkin, evGameEvent, evUnknown3, evDied, evKnockedDown, evMatchPlayerJoinedEvent, evMatchPlayerStatsEvent, evMatchPlayerStatsCompleteEvent, evMatchTimeLineEventEvent, evMatchPlayerMainGearStatsEvent, evMatchPlayerChangedAvatarEvent, evInvitationPlayerTrade, evPlayerTradeStart, evPlayerTradeCancel, evPlayerTradeUpdate, evPlayerTradeFinished, evPlayerTradeAcceptChange, evMiniMapPing, evMarketPlaceNotification, evDuellingChallengePlayer, evNewDuellingPost, evPingOnMap, evDuelEnded, evDuelDenied, evDuelLeftArea, evDuelReEnteredArea, evNewRealEstate, evMiniMapOwnedBuildingsPositions, evRealEstateListUpdate, evGuildLogoUpdate, evGuildLogoChanged, evPlaceableObjectPlace, evPlaceableObjectPlaceCancel, evFurnitureObjectBuffProviderInfo, evFurnitureObjectCheatProviderInfo, evFarmableObjectInfo, evNewUnreadMails, evGuildLogoObjectUpdate, evStartLogout, evMove1, evJoinedChatChannel, evLeftChatChannel, evRemovedChatChannel, evAccessStatus, evMounted, evMountStart, evMountCancel, evNewTravelpoint, evNewIslandAccessPoint, evZonethroughNewZone, evPlayerZoneInTheMap,//there is a max range on this evUpdateChatSettings, evResurrectionOffer, evResurrectionReply, evLootEquipmentChanged, evUpdateUnlockedGuildLogos, evUpdateUnlockedAvatars, evUpdateUnlockedAvatarRings, evUpdateUnlockedBuildings, evNewIslandManagement, evNewTeleportStone, evCloak, evTeleport, evPartySilverGained, evPartyLootSettingChangedPlayer, evPartyPlayerSomething, evPartyChangedOrder, evPartyInvitationPlayerBusy, evPartySomething3, evPartyCreated, evPartyPlayerLeft, evPartyPlayerJoined, evPartyPlayerSomething2, evPartyPlayerLeave, evPartyLeaderChanged, evPartySetRoleFlag, evSpellCooldownUpdate, evNewHellgate, evPartyInvitationDeclinedBusy, evNewExpeditionExit, evNewExpeditionNarrator, evExitEnterStart, evExitEnterCancel, evExitEnterFinished, evHellClusterTimeUpdate, evNewQuestGiverObject, evFullQuestInfo, evQuestProgressInfo, evQuestGiverInfoForPlayer, evFullExpeditionInfo, evExpeditionQuestProgressInfo, evInvitedToExpedition, evExpeditionRegistrationInfo, evEnteringExpeditionStart, evEnteringExpeditionCancel, evRewardGranted, evArenaRegistrationInfo, evEnteringArenaStart, evEnteringArenaCancel, evEnteringArenaLockStart, evEnteringArenaLockCancel, evInvitedToArenaMatch, evPlayerCounts, evInCombatStateUpdate, evOtherGrabbedLoot, evSiegeCampClaimStart, evSiegeCampClaimCancel, evSiegeCampClaimFinished, evSiegeCampScheduleResult, evTreasureChestUsingStart, evTreasureChestUsingFinished, evTreasureChestUsingCancel, evUnknown2, evTreasureChestForceCloseInventory, evPremiumChanged, evPremiumExtended, evPremiumLifeTimeRewardGained, evLaborerGotUpgraded, evJournalGotFull, evJournalFillError, evFriendRequest, evFriendRequestInfos, evFriendInfos, evFriendRequestAnswered, evFriendOnlineStatus, evFriendRequestCanceled, evFriendRemoved, evFriendUpdated, evPartyLootItems, evPartyLootItemsRemoved, evReputationUpdate, evPlayerLoginOrLogOff, evDefenseUnitAttackEnd, evDefenseUnitAttackDamage, evUnrestrictedPvpZoneUpdate, evReputationImplicationUpdate, evNewMountObject, evMountHealthUpdate, evMountCooldownUpdate, evNewExpeditionAgent, evNewExpeditionCheckPoint, evExpeditionStartEvent, evVoteEvent, evRatingEvent, evNewArenaAgent, evBoostFarmable, evUseFunction, evNewPortalEntrance, evNewPortalExit, evNewRandomDungeonExit, evWaitingQueueUpdate, evPlayerMovementRateUpdate, evObserveStart, evMinimapZergs, evPaymentTransactions, evPerformanceStatsUpdate, evOverloadModeUpdate, evDebugDrawEvent, evRecordCameraMove, evRecordStart, evTerritoryClaimStart, evTerritoryClaimCancel, evTerritoryClaimFinished, evTerritoryScheduleResult, evUpdateAccountState, evStartDeterministicRoam, evGuildFullAccessTagsUpdated, evGuildAccessTagUpdated, evGvgSeasonUpdate, evGvgSeasonCheatCommand, evSeasonPointsByKillingBooster, evFishingStart, evFishingCast, evFishingCatch, evFishingFinished, evFishingCancel, evNewFloatObject, evNewFishingZoneObject, evFishingMiniGame, evSteamAchievementCompleted, evUpdatePuppet, evChangeFlaggingFinished, evNewOutpostObject, evOutpostUpdate, evOutpostClaimed, evOutpostReward, evOverChargeEnd, evOverChargeStatus, evPartyFinderFullUpdate, evPartyFinderUpdate, evPartyFinderApplicantsUpdate, evPartyFinderEquipmentSnapshot, evPartyFinderJoinRequestDeclined, evNewUnlockedPersonalSeasonRewards, evPersonalSeasonPointsGained, evEasyAntiCheatMessageToClient, evMatchLootChestOpeningStart, evMatchLootChestOpeningFinished, evMatchLootChestOpeningCancel, evNotifyCrystalMatchReward, evCrystalRealmFeedback, evNewLocationMarker, evNewTutorialBlocker, evNewTileSwitch, evNewInformationProvider, evNewDynamicGuildLogo, evTutorialUpdate, evTriggerHintBox, evRandomDungeonPositionInfo, evNewLootChest, evUpdateLootChest, evLootChestOpened, evNewShrine, evUpdateShrine, evMutePlayerUpdate, evShopTileUpdate, evShopUpdate, evUnknown4, evUnlockVanityUnlock, evCustomizationChanged, evBaseVaultInfo, evGuildVaultInfo, evBankVaultInfo, evRecoveryVaultPlayerInfo, evRecoveryVaultGuildInfo, evUpdateWardrobe, evCastlePhaseChanged, evGuildAccountLogEvent, evNewHideoutObject, evNewHideoutManagement, evNewHideoutExit, evInitHideoutAttackStart, evInitHideoutAttackCancel, evInitHideoutAttackFinished, evHideoutManagementUpdate, evIpChanged, evSmartClusterQueueUpdateInfo, evSmartClusterQueueActiveInfo, evSmartClusterQueueKickWarning, evSmartClusterQueueInvite, evReceivedGvgSeasonPoints, evTerritoryBonusLevelUpdate, evOpenWorldAttackScheduleStart, evOpenWorldAttackScheduleFinished, evOpenWorldAttackScheduleCancel, evOpenWorldAttackConquerStart, evOpenWorldAttackConquerFinished, evOpenWorldAttackConquerCancel, evOpenWorldAttackConquerStatus, evOpenWorldAttackStart, evOpenWorldAttackEnd, evNewRandomResourceBlocker, evUnknown5, evUnknown6, evUnknown7, evUnknown8, evUnknown9, evUnknown10, evUnknown11, evUnknown12, evUnknown13, evUnknown14, evUnknown15, evUnknown16, evUnknown17, evUnknown18, evUnknown19, evUnknown20, evUnknown21, evUnknown22, evUnknown23, evUnknown24, evUnknown25, evUnknown26, evUnknown27, evUnknown28, evUnknown29, evUnknown30, evUnknown31, evUnknown32, evUnknown33, evUnknown34, evUnknown35, evUnknown36, evUnknown37, evUnknown38, evUnknown39, evUnknown40, evUnknown41, evUnknown42, evUnknown43, evUnknown44, evUnknown45, evUnknown46, evUnknown47, evUnknown48, evUnknown49, evUnknown50, evUnknown51 } }
28.502212
59
0.652022
[ "MIT" ]
ItsNotMyFault/AlbionDataReader
albion-data-reader-new/handlers/EventCodes.cs
12,885
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using Abilifier; using BattleTech; using UnityEngine; using static StrategicOperations.Framework.Classes; namespace StrategicOperations.Framework { public static class ModState { public static List<BA_Spawner> CurrentContractBASpawners = new List<BA_Spawner>(); public static float SwarmSuccessChance = 0f; public static float DeSwarmSuccessChance = 0f; public static Dictionary<string, Dictionary<string, List<string>>> CachedFactionAssociations = new Dictionary<string, Dictionary<string, List<string>>>(); public static Dictionary<string, int> CurrentBattleArmorSquads = new Dictionary<string, int>(); public static List<AI_FactionCommandAbilitySetting> CurrentFactionSettingsList = new List<AI_FactionCommandAbilitySetting>(); public static bool IsStrafeAOE = false; public static Dictionary<string, PendingStrafeWave> PendingStrafeWaves = new Dictionary<string, PendingStrafeWave>(); public static List<ArmorLocation> MechArmorMountOrder = new List<ArmorLocation>(); public static List<ArmorLocation> MechArmorSwarmOrder = new List<ArmorLocation>(); public static List<VehicleChassisLocations> VehicleMountOrder = new List<VehicleChassisLocations>(); public static Dictionary<string, BA_DamageTracker> BADamageTrackers = new Dictionary<string, BA_DamageTracker>(); // key is GUID of BA squad public static Dictionary<string, Vector3> SavedBAScale = new Dictionary<string, Vector3>(); public static Dictionary<string, Vector3> CachedUnitCoordinates = new Dictionary<string, Vector3>(); public static Dictionary<string, string> PositionLockMount = new Dictionary<string, string>(); // key is mounted unit, value is carrier public static Dictionary<string, string> PositionLockSwarm = new Dictionary<string, string>(); // key is mounted unit, value is carrier public static List<Ability> CommandAbilities = new List<Ability>(); public static List<KeyValuePair<string, Action>> DeferredInvokeSpawns = new List<KeyValuePair<string, Action>>(); public static List<KeyValuePair<string, Action>> DeferredInvokeBattleArmor = new List<KeyValuePair<string, Action>>(); public static string DeferredActorResource = ""; public static string PopupActorResource = ""; public static int StrafeWaves; public static string PilotOverride= null; public static bool DeferredSpawnerFromDelegate; public static bool DeferredBattleArmorSpawnerFromDelegate; public static bool OutOfRange; public static Dictionary<string, AI_DealWithBAInvocation> AiDealWithBattleArmorCmds = new Dictionary<string, AI_DealWithBAInvocation>(); public static Dictionary<string, AI_CmdInvocation> AiCmds = new Dictionary<string, AI_CmdInvocation>(); public static Dictionary<string, BA_MountOrSwarmInvocation> AiBattleArmorAbilityCmds = new Dictionary<string, BA_MountOrSwarmInvocation>(); public static List<CmdUseInfo> CommandUses = new List<CmdUseInfo>(); public static List<CmdUseStat> DeploymentAssetsStats = new List<CmdUseStat>(); public static BA_TargetEffect BAUnhittableEffect = new BA_TargetEffect(); public static void Initialize() { MechArmorMountOrder.Add(ArmorLocation.CenterTorso); MechArmorMountOrder.Add(ArmorLocation.CenterTorsoRear); MechArmorMountOrder.Add(ArmorLocation.RightTorso); MechArmorMountOrder.Add(ArmorLocation.RightTorsoRear); MechArmorMountOrder.Add(ArmorLocation.LeftTorso); MechArmorMountOrder.Add(ArmorLocation.LeftTorsoRear); MechArmorSwarmOrder.Add(ArmorLocation.CenterTorso); MechArmorSwarmOrder.Add(ArmorLocation.CenterTorsoRear); MechArmorSwarmOrder.Add(ArmorLocation.RightTorso); MechArmorSwarmOrder.Add(ArmorLocation.RightTorsoRear); MechArmorSwarmOrder.Add(ArmorLocation.LeftTorso); MechArmorSwarmOrder.Add(ArmorLocation.LeftTorsoRear); MechArmorSwarmOrder.Add(ArmorLocation.LeftArm); // LA, RA, LL, RL, HD are for swarm only MechArmorSwarmOrder.Add(ArmorLocation.RightArm); MechArmorSwarmOrder.Add(ArmorLocation.LeftLeg); MechArmorSwarmOrder.Add(ArmorLocation.RightLeg); MechArmorSwarmOrder.Add(ArmorLocation.Head); VehicleMountOrder.Add(VehicleChassisLocations.Front); VehicleMountOrder.Add(VehicleChassisLocations.Rear); VehicleMountOrder.Add(VehicleChassisLocations.Left); VehicleMountOrder.Add(VehicleChassisLocations.Right); VehicleMountOrder.Add(VehicleChassisLocations.Turret); BAUnhittableEffect = ModInit.modSettings.BATargetEffect; foreach (var jObject in ModInit.modSettings.BATargetEffect.effectDataJO) { var effectData = new EffectData(); effectData.FromJSON(jObject.ToString()); BAUnhittableEffect.effects.Add(effectData); } } public static void ResetAll() { CurrentContractBASpawners = new List<BA_Spawner>(); SwarmSuccessChance = 0f; DeSwarmSuccessChance = 0f; CurrentBattleArmorSquads = new Dictionary<string, int>(); CurrentFactionSettingsList = new List<AI_FactionCommandAbilitySetting>(); PendingStrafeWaves = new Dictionary<string, PendingStrafeWave>(); BADamageTrackers = new Dictionary<string, BA_DamageTracker>(); CommandAbilities = new List<Ability>(); DeferredInvokeSpawns = new List<KeyValuePair<string, Action>>(); DeferredInvokeBattleArmor = new List<KeyValuePair<string, Action>>(); CommandUses = new List<CmdUseInfo>(); DeploymentAssetsStats = new List<CmdUseStat>(); SavedBAScale = new Dictionary<string, Vector3>(); CachedUnitCoordinates = new Dictionary<string, Vector3>(); PositionLockMount = new Dictionary<string, string>(); PositionLockSwarm = new Dictionary<string, string>(); DeferredActorResource = ""; PopupActorResource = ""; StrafeWaves = 0; // this is TBD-> want to make beacons define # of waves. PilotOverride = null; DeferredSpawnerFromDelegate = false; DeferredBattleArmorSpawnerFromDelegate = false; OutOfRange = false; AiCmds = new Dictionary<string, AI_CmdInvocation>(); AiBattleArmorAbilityCmds = new Dictionary<string, BA_MountOrSwarmInvocation>(); IsStrafeAOE = false; } public static void ResetDelegateInfos() { DeferredSpawnerFromDelegate = false; DeferredActorResource = ""; PopupActorResource = ""; PilotOverride = null; } public static void ResetDeferredSpawners() { DeferredInvokeSpawns = new List<KeyValuePair<string, Action>>(); } public static void ResetDeferredBASpawners() { DeferredInvokeBattleArmor = new List<KeyValuePair<string, Action>>(); } } }
48.542484
162
0.688569
[ "MIT" ]
ajkroeg/StrategicOperations
StrategicOperations/StrategicOperations/Framework/ModState.cs
7,429
C#
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using NerdStore.Catalogo.Domain; using NerdStore.Core.Data; using NerdStore.Core.Messages; namespace NerdStore.Catalogo.Data { public class CatalogoContext : DbContext, IUnitOfWork { public CatalogoContext(DbContextOptions<CatalogoContext> options) : base(options) { } public DbSet<Produto> Produtos { get; set; } public DbSet<Categoria> Categorias { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { foreach (var property in modelBuilder.Model.GetEntityTypes().SelectMany( e => e.GetProperties().Where(p => p.ClrType == typeof(string)))) property.Relational().ColumnType = "varchar(100)"; modelBuilder.Ignore<Event>(); modelBuilder.ApplyConfigurationsFromAssembly(typeof(CatalogoContext).Assembly); } public async Task<bool> Commit() { foreach (var entry in ChangeTracker.Entries().Where(entry => entry.Entity.GetType().GetProperty("DataCadastro") != null)) { if (entry.State == EntityState.Added) { entry.Property("DataCadastro").CurrentValue = DateTime.Now; } if (entry.State == EntityState.Modified) { entry.Property("DataCadastro").IsModified = false; } } return await base.SaveChangesAsync() > 0; } } }
33.5
133
0.600124
[ "MIT" ]
caiobarretta/desenvolvedor.io
NerdStore/src/NerdStore.Catalogo.Data/CatalogoContext.cs
1,610
C#
namespace Main.Sql { public interface ISqlValidator { int CalculateRowCount( string sql ); bool TryCheckSql( string innerSql, out string errorMessage ); } }
16.4
35
0.5
[ "MIT" ]
Dimsday/ReSequel
Main/Sql/ISqlValidator.cs
246
C#
using System; using System.Collections.Generic; using MailCheck.Spf.Contracts.SharedDomain; namespace MailCheck.Spf.Contracts.Poller { public class SpfRecordsPolled : Common.Messaging.Abstractions.Message { public SpfRecordsPolled(string id, SpfRecords records, int? dnsQueryCount, TimeSpan? elapsedQueryTime, List<Message> messages = null) : base(id) { Records = records; DnsQueryCount = dnsQueryCount; ElapsedQueryTime = elapsedQueryTime; Messages = messages ?? new List<Message>(); } public SpfRecords Records { get; } public int? DnsQueryCount { get; } public TimeSpan? ElapsedQueryTime { get; } public List<Message> Messages { get; } } }
30.444444
73
0.614355
[ "Apache-2.0" ]
ukncsc/MailCheck.Public.Spf
src/MailCheck.Spf.Contracts/Poller/SpfRecordsPolled.cs
824
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Services.Common.Authorization; using Services.Common.RunTime; using System.Threading.Tasks; namespace Services.Common.APIs.Filters { public class AuthorizeCheckOperationFilter : IAsyncAuthorizationFilter { #region fields private const string Controller = nameof(Controller); private readonly EAuthorizeType _authorizeType; private readonly string _crudName; private readonly IPermissionChecker _permissionChecker; private readonly IUserSessionInfo _userSessionInfo; #endregion fields public AuthorizeCheckOperationFilter(EAuthorizeType authorizeType, IPermissionChecker permissionChecker, IUserSessionInfo userSessionInfo, string crudName = "") { _authorizeType = authorizeType; _permissionChecker = permissionChecker; _userSessionInfo = userSessionInfo; _crudName = crudName; } public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var controllerActionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor; bool skipAuthorization = controllerActionDescriptor.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), true); if (skipAuthorization || _authorizeType == EAuthorizeType.Everyone) return; if (_userSessionInfo.UserId == null) { context.Result = new ForbidResult(); return; } if (_userSessionInfo.UserId != null) { if (_authorizeType == EAuthorizeType.MustHavePermission) { string controllerName = controllerActionDescriptor.ControllerName + Controller; string actionName = !string.IsNullOrEmpty(_crudName) ? _crudName : controllerActionDescriptor.MethodInfo.Name; if (!await _permissionChecker.IsGrantedAsync(controllerName, actionName)) { context.Result = new ForbidResult(); } } } } } }
39.070175
168
0.678042
[ "MIT" ]
horseznguyen/HCMTAX
src/CoreServices/01.Services.Common/Services.Common.APIs/Filters/AuthorizeCheckOperationFilter.cs
2,229
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusicMink.ViewModels.DesignData { public class SongDesignData { public string Name { get; set; } public ArtistDesignData Artist { get; set; } public AlbumDesignData Album { get; set; } public int Rating { get; set; } public SongDesignData() { this.Name = "Bang!"; this.Artist = new ArtistDesignData(); this.Album = new AlbumDesignData(); this.Rating = 8; } } }
19.741935
52
0.598039
[ "Apache-2.0" ]
cluckyb/musicmink
MusicMink/ViewModels/DesignData/SongDesignData.cs
614
C#
// <copyright file="ManagersContext.cs" company="Microsoft"> // Copyright (c) Microsoft. All rights reserved. // </copyright> namespace SocialPlus.UnitTests { using SocialPlus.OAuth; using SocialPlus.Server.Managers; using SocialPlus.Server.Metrics; using SocialPlus.Server.Queues; /// <summary> /// Class encapsulating the context needed for managers /// </summary> public class ManagersContext : StoresContext { /// <summary> /// Initializes a new instance of the <see cref="ManagersContext"/> class. /// </summary> public ManagersContext() : base() { // for the queue manager int serviceBusBatchIntervalMs = int.Parse(this.FileSettingsReader.ReadValue("ServiceBusBatchIntervalMs")); // Initialize the queues this.QueueManager = new QueueManager(this.ConnectionStringProvider, serviceBusBatchIntervalMs); this.FanoutActivitiesQueue = new FanoutActivitiesQueue(this.QueueManager); this.FanoutTopicsQueue = new FanoutTopicsQueue(this.QueueManager); this.FollowingImportsQueue = new FollowingImportsQueue(this.QueueManager); this.ModerationQueue = new ModerationQueue(this.QueueManager); this.RelationshipsQueue = new RelationshipsQueue(this.QueueManager); this.ResizeImagesQueue = new ResizeImagesQueue(this.QueueManager); this.SearchQueue = new SearchQueue(this.QueueManager); // Initializes the managers this.AppsManager = new AppsManager(this.AppsStore); this.PopularUsersManager = new PopularUsersManager(this.UsersStore); this.ViewsManager = new ViewsManager( this.Log, this.AppsStore, this.UsersStore, this.UserRelationshipsStore, this.TopicsStore, this.TopicRelationshipsStore, this.CommentsStore, this.RepliesStore, this.LikesStore, this.PinsStore, this.BlobsStore); this.PushNotificationsManager = new PushNotificationsManager( this.Log, this.PushRegistrationStore, this.AppsStore, this.ViewsManager, this.ConnectionStringProvider); this.UsersManager = new UsersManager( this.UsersStore, this.PushNotificationsManager, this.PopularUsersManager, this.SearchQueue); this.AADAuthManager = new AADAuthManager(this.Log, this.AppsManager, this.UsersManager); this.SessionTokenManager = new SessionTokenManager(this.KeyVault, this.ConnectionStringProvider); this.SocialPlusAuthManager = new SocialPlusAuthManager( this.Log, this.AppsManager, this.UsersManager, this.SessionTokenManager); this.ActivitiesManager = new ActivitiesManager( this.ActivitiesStore, this.UserRelationshipsStore, this.TopicRelationshipsStore); this.AnonAuthManager = new AnonAuthManager(this.Log, this.AppsManager, this.UsersManager); this.MSAAuthManager = new OAuthManager(this.Log, this.AppsManager, this.UsersManager, IdentityProviders.Microsoft); this.FBAuthManager = new OAuthManager(this.Log, this.AppsManager, this.UsersManager, IdentityProviders.Facebook); this.GAuthManager = new OAuthManager(this.Log, this.AppsManager, this.UsersManager, IdentityProviders.Google); this.TAuthManager = new OAuthManager(this.Log, this.AppsManager, this.UsersManager, IdentityProviders.Twitter); this.AuthManager = new CompositeAuthManager( this.AADAuthManager, this.SocialPlusAuthManager, this.AnonAuthManager, this.MSAAuthManager, this.FBAuthManager, this.GAuthManager, this.TAuthManager); this.CommonAuthManager = new CommonAuthManager(this.Log, this.AppsManager, this.UsersManager); this.NotificationsManager = new NotificationsManager(this.NotificationsStore, this.PushNotificationsManager); this.CommentsManager = new CommentsManager(this.CommentsStore, this.FanoutActivitiesQueue, this.NotificationsManager); this.RepliesManager = new RepliesManager(this.RepliesStore, this.FanoutActivitiesQueue, this.NotificationsManager); this.IdentitiesManager = new IdentitiesManager(); this.PopularTopicsManager = new PopularTopicsManager(this.TopicsStore, this.UsersStore, this.AppsStore); this.RelationshipsManager = new RelationshipsManager( this.Log, this.UserRelationshipsStore, this.TopicRelationshipsStore, this.RelationshipsQueue, this.FanoutActivitiesQueue, this.FollowingImportsQueue, this.PopularUsersManager, this.NotificationsManager); this.SearchManager = new SearchManager(this.Log, this.ConnectionStringProvider); this.TopicsManager = new TopicsManager( this.TopicsStore, this.UserRelationshipsStore, this.FanoutTopicsQueue, this.SearchQueue, this.PopularTopicsManager); this.TopicNamesManager = new TopicNamesManager(this.TopicNamesStore); this.BlobsManager = new BlobsManager(this.Log, this.BlobsStore, this.BlobsMetadataStore, this.ResizeImagesQueue); this.CVSModerationManager = new CVSModerationManager( this.Log, this.UsersManager, this.CVSTransactionStore, this.ModerationStore, this.ModerationQueue, this.BlobsManager, this.TopicsManager, this.CommentsManager, this.RepliesManager, this.AppsManager, this.ConnectionStringProvider); // Metrics managers this.ApplicationMetrics = new LogApplicationMetrics(this.Log); } /// <summary> /// Gets queue manager /// </summary> public QueueManager QueueManager { get; private set; } /// <summary> /// Gets fanout activities queue for comments /// </summary> public FanoutActivitiesQueue FanoutActivitiesQueue { get; private set; } /// <summary> /// Gets fanout topics queue /// </summary> public FanoutTopicsQueue FanoutTopicsQueue { get; private set; } /// <summary> /// Gets following imports queue /// </summary> public FollowingImportsQueue FollowingImportsQueue { get; private set; } /// <summary> /// Gets moderation queue /// </summary> public ModerationQueue ModerationQueue { get; private set; } /// <summary> /// Gets relationships queue /// </summary> public RelationshipsQueue RelationshipsQueue { get; private set; } /// <summary> /// Gets resize images queue /// </summary> public ResizeImagesQueue ResizeImagesQueue { get; private set; } /// <summary> /// Gets search queue /// </summary> public SearchQueue SearchQueue { get; private set; } /// <summary> /// Gets AAD auth manager /// </summary> public AADAuthManager AADAuthManager { get; private set; } /// <summary> /// Gets activities manager /// </summary> public ActivitiesManager ActivitiesManager { get; private set; } /// <summary> /// Gets Anon auth manager /// </summary> public AnonAuthManager AnonAuthManager { get; private set; } /// <summary> /// Gets apps manager /// </summary> public AppsManager AppsManager { get; private set; } /// <summary> /// Gets auth manager /// </summary> public CompositeAuthManager AuthManager { get; private set; } /// <summary> /// Gets blobs manager /// </summary> public BlobsManager BlobsManager { get; private set; } /// <summary> /// Gets comments manager /// </summary> public CommentsManager CommentsManager { get; private set; } /// <summary> /// Gets CVS moderation manager /// </summary> public CVSModerationManager CVSModerationManager { get; private set; } /// <summary> /// Gets Facebook auth manager /// </summary> public OAuthManager FBAuthManager { get; private set; } /// <summary> /// Gets Google auth manager /// </summary> public OAuthManager GAuthManager { get; private set; } /// <summary> /// Gets identities manager /// </summary> public IdentitiesManager IdentitiesManager { get; private set; } /// <summary> /// Gets MSA auth manager /// </summary> public OAuthManager MSAAuthManager { get; private set; } /// <summary> /// Gets Common auth manager /// </summary> public CommonAuthManager CommonAuthManager { get; private set; } /// <summary> /// Gets notifications manager for comments /// </summary> public NotificationsManager NotificationsManager { get; private set; } /// <summary> /// Gets popular topics manager /// </summary> public PopularTopicsManager PopularTopicsManager { get; private set; } /// <summary> /// Gets popular users manager /// </summary> public PopularUsersManager PopularUsersManager { get; private set; } /// <summary> /// Gets push notification manager /// </summary> public PushNotificationsManager PushNotificationsManager { get; private set; } /// <summary> /// Gets relationships manager /// </summary> public RelationshipsManager RelationshipsManager { get; private set; } /// <summary> /// Gets replies manager /// </summary> public RepliesManager RepliesManager { get; private set; } /// <summary> /// Gets search manager /// </summary> public SearchManager SearchManager { get; private set; } /// <summary> /// Gets session token manager /// </summary> public SessionTokenManager SessionTokenManager { get; private set; } /// <summary> /// Gets SocialPlus auth manager /// </summary> public SocialPlusAuthManager SocialPlusAuthManager { get; private set; } /// <summary> /// Gets Twitter auth manager /// </summary> public OAuthManager TAuthManager { get; private set; } /// <summary> /// Gets topics manager /// </summary> public TopicsManager TopicsManager { get; private set; } /// <summary> /// Gets topic names manager /// </summary> public TopicNamesManager TopicNamesManager { get; private set; } /// <summary> /// Gets users manager /// </summary> public UsersManager UsersManager { get; private set; } /// <summary> /// Gets views manager /// </summary> public ViewsManager ViewsManager { get; private set; } /// <summary> /// Gets application metrics /// </summary> public LogApplicationMetrics ApplicationMetrics { get; private set; } } }
38.538961
130
0.599747
[ "MIT" ]
Bhaskers-Blu-Org2/EmbeddedSocial-Service
code/Tests/UnitTests/Contexts/ManagersContext.cs
11,872
C#
namespace Snow.Extensions { using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Linq; using Models; using Nancy; public class SitemapResponse : Response { private readonly string siteUrl; public SitemapResponse(IEnumerable<Post> model, string siteUrl) { this.siteUrl = siteUrl; Contents = GetXmlContents(model); ContentType = "application/xml"; StatusCode = HttpStatusCode.OK; } private Action<Stream> GetXmlContents(IEnumerable<Post> model) { var blank = XNamespace.Get(@"http://www.sitemaps.org/schemas/sitemap/0.9"); var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement(blank+"urlset", new XAttribute("xmlns", blank.NamespaceName))); foreach (Post post in model) { var xElement = new XElement(blank+"url", new XElement(blank + "loc", siteUrl + post.Url), new XElement(blank + "lastmod", post.Date.ToString("yyyy-MM-dd")), new XElement(blank + "changefreq", "weekly"), new XElement(blank + "priority", "1.00")); xDocument.Root.Add(xElement); } return stream => { using (XmlWriter writer = XmlWriter.Create(stream)) { xDocument.Save(writer); } }; } } }
34.77551
160
0.494131
[ "MIT" ]
DanRigby/Sandra.Snow
src/Snow/Extensions/SitemapResponse.cs
1,706
C#
using UnityEngine; using System.Collections; using System.Reflection; using Microsoft.CSharp; using System; using System.CodeDom; using System.Linq; using UnityEditor; using System.IO; namespace Sabresaurus.Sidekick { public class UtilityPane : BasePane { public void Draw(Type componentType, object component) { OldSettings settings = OldInspectorSidekick.Current.Settings; // Grab the active window's settings if (component is MonoScript) { MonoScript monoScript = (MonoScript)component; Type classType = monoScript.GetClass(); if (classType != null) { if (classType.IsSubclassOf(typeof(ScriptableObject))) { if (GUILayout.Button("Instantiate Asset")) { ScriptableObject asset = ScriptableObject.CreateInstance(classType); string fullPath = AssetDatabase.GenerateUniqueAssetPath("Assets/" + classType + ".asset"); AssetDatabase.CreateAsset(asset, fullPath); AssetDatabase.SaveAssets(); } } } } else if (component is GameObject) { GameObject gameObject = (GameObject)component; if (GUILayout.Button("Set Name From First Script")) { MonoBehaviour[] behaviours = gameObject.GetComponents<MonoBehaviour>(); // Attempt to name it after the first script if (behaviours.Length >= 1) { gameObject.name = behaviours[0].GetType().Name; } else { // No scripts found, so name after the first optional component Component[] components = gameObject.GetComponents<Component>(); if (components.Length >= 2) // Ignore Transform { gameObject.name = components[1].GetType().Name; } } } } if (GUILayout.Button("Copy As JSON")) { string json = JsonUtility.ToJson(component, true); EditorGUIUtility.systemCopyBuffer = json; } } } }
35.971429
118
0.49444
[ "MIT" ]
Kerfuffles/Sidekick
Editor/LegacyInspector/Panes/UtilityPane.cs
2,520
C#
namespace RJCP.Diagnostics.CpuIdWin.Controls { partial class CpuTopologyControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblApicId = new System.Windows.Forms.Label(); this.lbltxtApicId = new System.Windows.Forms.Label(); this.lvwCpuTopo = new RJCP.Diagnostics.CpuIdWin.Controls.ThemeListView(); this.hdrPackageLevel = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.hdrIdentifier = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.hdrMask = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.SuspendLayout(); // // lblApicId // this.lblApicId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lblApicId.AutoEllipsis = true; this.lblApicId.Location = new System.Drawing.Point(141, 14); this.lblApicId.Name = "lblApicId"; this.lblApicId.Size = new System.Drawing.Size(310, 14); this.lblApicId.TabIndex = 1; this.lblApicId.Text = "-"; // // lbltxtApicId // this.lbltxtApicId.Location = new System.Drawing.Point(3, 14); this.lbltxtApicId.Name = "lbltxtApicId"; this.lbltxtApicId.Size = new System.Drawing.Size(132, 14); this.lbltxtApicId.TabIndex = 0; this.lbltxtApicId.Text = "APIC Identifier:"; this.lbltxtApicId.TextAlign = System.Drawing.ContentAlignment.TopRight; // // lvwCpuTopo // this.lvwCpuTopo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lvwCpuTopo.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.hdrPackageLevel, this.hdrIdentifier, this.hdrMask}); this.lvwCpuTopo.FullRowSelect = true; this.lvwCpuTopo.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.lvwCpuTopo.HideSelection = false; this.lvwCpuTopo.Location = new System.Drawing.Point(144, 48); this.lvwCpuTopo.Name = "lvwCpuTopo"; this.lvwCpuTopo.Size = new System.Drawing.Size(333, 269); this.lvwCpuTopo.TabIndex = 2; this.lvwCpuTopo.UseCompatibleStateImageBehavior = false; this.lvwCpuTopo.View = System.Windows.Forms.View.Details; // // hdrPackageLevel // this.hdrPackageLevel.Text = "Package Level"; // // hdrIdentifier // this.hdrIdentifier.Text = "Identifier"; // // hdrMask // this.hdrMask.Text = "Mask"; // // CpuTopologyControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lvwCpuTopo); this.Controls.Add(this.lblApicId); this.Controls.Add(this.lbltxtApicId); this.Name = "CpuTopologyControl"; this.Size = new System.Drawing.Size(480, 320); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label lblApicId; private System.Windows.Forms.Label lbltxtApicId; private ThemeListView lvwCpuTopo; private System.Windows.Forms.ColumnHeader hdrPackageLevel; private System.Windows.Forms.ColumnHeader hdrIdentifier; private System.Windows.Forms.ColumnHeader hdrMask; } }
43.339286
159
0.596209
[ "MIT" ]
jcurl/CpuId
CpuIdWin/Controls/CpuTopologyControl.Designer.cs
4,856
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace simulation_game { class Melee:Unit { public Melee(int x, int y, string team, int health = 20, int speed = 1, int attack = 4, int range = 1, string symbol = " ! ") : base(x, y, health, speed, attack, range, team, symbol) { base.x = x; base.y = y; base.health = health; base.maxHealth = health; base.speed = speed; base.attack = attack; base.attackRange = range; base.team = team; base.symbol = symbol; } public override string ToString() { if (Health <= 0) { return "Melee: DEAD";//if dead } else { return "Melee unit: \n Health: " + Health + "\n Range: " + attackRange + "\n Speed: " + speed + "\n Team: " + team;//if alive show stats } } } }
26.846154
191
0.495702
[ "MIT" ]
Tatheon/Task-1
simulation game/simulation game/Melee.cs
1,049
C#
#pragma checksum "C:\Users\user\Documents\dotnetexperiments\project_forum\Pages\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(project_forum.Pages.Pages__ViewStart), @"mvc.1.0.view", @"/Pages/_ViewStart.cshtml")] namespace project_forum.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\user\Documents\dotnetexperiments\project_forum\Pages\_ViewImports.cshtml" using project_forum; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Pages/_ViewStart.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5765f8b6d14092acbc40ab57abeee7e1ca64c4eb", @"/Pages/_ViewImports.cshtml")] public class Pages__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 1 "C:\Users\user\Documents\dotnetexperiments\project_forum\Pages\_ViewStart.cshtml" Layout = "_Layout"; #line default #line hidden #nullable disable } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
50.192308
182
0.768199
[ "MIT" ]
inspiringhobbyist/project_forum
obj/Debug/netcoreapp3.1/Razor/Pages/_ViewStart.cshtml.g.cs
2,610
C#
using System.Collections.Generic; using System.Linq; using Automation.ResultFiles; using CalculationController.CalcFactories; using Common.JSON; using Database; namespace CalculationController.Helpers { public class CalcDeviceTaggingSetFactory { [JetBrains.Annotations.NotNull] private readonly CalcParameters _calcParameters; [JetBrains.Annotations.NotNull] private readonly CalcLoadTypeDtoDictionary _ltDict; public CalcDeviceTaggingSetFactory([JetBrains.Annotations.NotNull] CalcParameters calcParameters, [JetBrains.Annotations.NotNull] CalcLoadTypeDtoDictionary ltDict) { _calcParameters = calcParameters; _ltDict = ltDict; } [JetBrains.Annotations.NotNull] public CalcDeviceTaggingSets GetDeviceTaggingSets([JetBrains.Annotations.NotNull] Simulator sim, int personCount) { CalcDeviceTaggingSets cs = new CalcDeviceTaggingSets { AllCalcDeviceTaggingSets = new List<DeviceTaggingSetInformation>() }; foreach (var deviceTaggingSet in sim.DeviceTaggingSets.Items) { var calcset = new DeviceTaggingSetInformation(deviceTaggingSet.Name); foreach (var entry in deviceTaggingSet.Entries) { if (entry.Device == null) { throw new LPGException("Device was null"); } if (entry.Tag == null) { throw new LPGException("Tag was null"); } var devname = entry.Device.Name; //sim.MyGeneralConfig.CSVCharacter); var tagname = CalcAffordanceFactory.FixAffordanceName(entry.Tag.Name, _calcParameters.CSVCharacter); calcset.AddTag(devname, tagname); } foreach (var reference in deviceTaggingSet.References.Where(x => x.PersonCount == personCount)) { if (reference.Tag == null) { throw new LPGException("Tag was null"); } calcset.AddRefValue(reference.Tag.Name, reference.ReferenceValue, reference.LoadType.Name); } foreach (var loadType in deviceTaggingSet.LoadTypes) { if (loadType.LoadType == null) { throw new LPGException("Loadtype was null"); } if (_ltDict.SimulateLoadtype(loadType.LoadType)) { var clt = _ltDict.GetLoadtypeDtoByLoadType(loadType.LoadType); calcset.AddLoadType(clt.ConvertToLoadTypeInformation()); } } cs.AllCalcDeviceTaggingSets.Add(calcset); } return cs; } } }
40.722222
121
0.574352
[ "MIT" ]
kyleniemeyer/LoadProfileGenerator
CalculationController/Helpers/CalcDeviceTaggingSets.cs
2,934
C#
// <auto-generated/> using System.Reflection; [assembly: AssemblyTitleAttribute("Topshelf")] [assembly: AssemblyDescriptionAttribute("Topshelf is an open source project for hosting services without friction. By referencing Topshelf, your console application *becomes* a service installer with a comprehensive set of command-line options for installing, configuring, and running your application as a service.")] [assembly: AssemblyProductAttribute("Topshelf")] [assembly: AssemblyVersionAttribute("4.0.0.0")] [assembly: AssemblyFileVersionAttribute("4.0.0.0")] [assembly: AssemblyInformationalVersionAttribute("4.0.0.0 (drb/a3ac1e81)")] [assembly: AssemblyCopyrightAttribute("Copyright 2012 Chris Patterson, Dru Sellers, Travis Smith, All rights reserved.")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "4.0.0.0"; internal const string InformationalVersion = "4.0.0.0 (drb/a3ac1e81)"; } }
58.176471
319
0.764408
[ "Apache-2.0" ]
RyanHauert/Topshelf
src/SolutionVersion.cs
991
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Sultanlar.UI { public partial class frmDepoDenetlemeResim : Form { public frmDepoDenetlemeResim(Image[] resim) { InitializeComponent(); Resim = resim; } Image[] Resim; int imageindex; private void frmDepoDenetlemeResim_Load(object sender, EventArgs e) { if (Resim.Length != 0) { pictureBox1.Image = Resim[0]; imageindex = 0; this.Text = "Resimler (1 / " + Resim.Length.ToString() + ")"; } else { imageindex = -1; this.Text = "Resimler (0 / 0)"; } } private void simpleButton1_Click(object sender, EventArgs e) { if (imageindex + 1 < Resim.Length) { imageindex++; pictureBox1.Image = Resim[imageindex]; this.Text = "Resimler (" + (imageindex + 1).ToString() + " / " + Resim.Length.ToString() + ")"; } } private void simpleButton2_Click(object sender, EventArgs e) { if (imageindex > 0) { imageindex--; pictureBox1.Image = Resim[imageindex]; this.Text = "Resimler (" + (imageindex + 1).ToString() + " / " + Resim.Length.ToString() + ")"; } } private void frmDepoDenetlemeResim_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.S) { simpleButton1.PerformClick(); } else if (e.KeyCode == Keys.A) { simpleButton2.PerformClick(); } } } }
27.352113
111
0.493306
[ "MIT" ]
dogukanalan/Sultanlar
Sultanlar/Sultanlar.UI/frmDepoDenetlemeResim.cs
1,944
C#
namespace TapHoaCode.GUI.Form1.BanHang { partial class FrmChiTietEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtTenHang = new System.Windows.Forms.TextBox(); this.btnSave = new DevExpress.XtraEditors.SimpleButton(); this.btnCancel = new DevExpress.XtraEditors.SimpleButton(); this.txtSL = new DevExpress.XtraEditors.SpinEdit(); this.dxErrorProvider1 = new DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(this.components); this.txtDG = new DevExpress.XtraEditors.TextEdit(); ((System.ComponentModel.ISupportInitialize)(this.txtSL.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtDG.Properties)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(14, 28); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(59, 15); this.label1.TabIndex = 0; this.label1.Text = "Tên hàng"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(14, 59); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(58, 15); this.label2.TabIndex = 0; this.label2.Text = "Số lượng"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(14, 85); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(51, 15); this.label3.TabIndex = 0; this.label3.Text = "Đơn giá"; // // txtTenHang // this.txtTenHang.Enabled = false; this.txtTenHang.Location = new System.Drawing.Point(83, 24); this.txtTenHang.Name = "txtTenHang"; this.txtTenHang.Size = new System.Drawing.Size(221, 21); this.txtTenHang.TabIndex = 0; // // btnSave // this.btnSave.Location = new System.Drawing.Point(83, 126); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(87, 27); this.btnSave.TabIndex = 3; this.btnSave.Text = "Cập nhật"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(176, 126); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(87, 27); this.btnCancel.TabIndex = 4; this.btnCancel.Text = "Hủy"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // txtSL // this.txtSL.EditValue = new decimal(new int[] { 0, 0, 0, 0}); this.txtSL.Location = new System.Drawing.Point(83, 57); this.txtSL.Name = "txtSL"; this.txtSL.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton()}); this.txtSL.Size = new System.Drawing.Size(222, 20); this.txtSL.TabIndex = 1; // // dxErrorProvider1 // this.dxErrorProvider1.ContainerControl = this; // // txtDG // this.txtDG.Location = new System.Drawing.Point(83, 88); this.txtDG.Name = "txtDG"; this.txtDG.Size = new System.Drawing.Size(222, 20); this.txtDG.TabIndex = 2; // // FrmChiTietEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(331, 165); this.Controls.Add(this.txtDG); this.Controls.Add(this.txtSL); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Controls.Add(this.txtTenHang); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "FrmChiTietEdit"; this.Text = "FrmChiTietEdit"; this.Load += new System.EventHandler(this.FrmChiTietEdit_Load); ((System.ComponentModel.ISupportInitialize)(this.txtSL.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dxErrorProvider1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtDG.Properties)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private DevExpress.XtraEditors.SimpleButton btnSave; private DevExpress.XtraEditors.SimpleButton btnCancel; public System.Windows.Forms.TextBox txtTenHang; private DevExpress.XtraEditors.SpinEdit txtSL; private DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider dxErrorProvider1; private DevExpress.XtraEditors.TextEdit txtDG; } }
42.45
112
0.571849
[ "Apache-2.0" ]
hynguyen2610/OlympicGym
GymFitnessOlympic/View/UserControls/TacNghiep/BanHang/FrmChiTietEdit.designer.cs
6,810
C#
version https://git-lfs.github.com/spec/v1 oid sha256:babe45637b7a6701d0543582d23f43ed984ab544e8f228e4091a005f03c2b4e2 size 1707
32.25
75
0.883721
[ "MIT" ]
bakiya-sefer/bakiya-sefer
Assets/Best HTTP (Pro)/BestHTTP/SecureProtocol/crypto/tls/TlsContext.cs
129
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mammola.Uramaki.Base; using WeifenLuo.WinFormsUI.Docking; using System.Windows.Forms; using System.Xml; namespace Mammola.Uramaki.Base { public class UramakiDesktopManager { private class TMenuItemInfo { public UramakiPublisher Publisher; public UramakiTransformer Transformer; } private UramakiFramework Framework; private Form ParentForm; private DockPanel DockMainPanel; private ToolStrip MainToolbar; private DeserializeDockContent hDeserializeDockContent; int LastActivePanelHashCode; private ToolStripButton LoadMenuButton; private ToolStripButton SaveMenuButton; private ToolStripDropDownButton AddNewButton; private ToolStripButton AddChildButton; private ContextMenuStrip TransformersPopupMenu; private void CreateStandardToolbar() { LoadMenuButton = new ToolStripButton("Load"); MainToolbar.Items.Add(LoadMenuButton); LoadMenuButton.Click += LoadMenuButton_Click; SaveMenuButton = new ToolStripButton("Save"); MainToolbar.Items.Add(SaveMenuButton); SaveMenuButton.Click += SaveMenuButton_Click; } private IDockContent GetContentFromPersistString(string persistString) { string[] parsedStrings = persistString.Split(new char[] { '#' }); if (parsedStrings.Length != 2) return null; UramakiPlate plate = (UramakiPlate) System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(parsedStrings[0]); Guid tempGuid; Guid.TryParse(parsedStrings[1], out tempGuid); plate.Init(tempGuid); return plate; } private void LoadMenuButton_Click(object sender, EventArgs e) { DockMainPanel.LoadFromXml("c:\\temp\\prova2.xml", hDeserializeDockContent); } private void SaveMenuButton_Click(object sender, EventArgs e) { XmlWriter writer = XmlWriter.Create("c:\\temp\\prova.xml"); writer.WriteStartDocument(); writer.WriteStartElement("layout"); writer.WriteAttributeString("version", "1"); Framework.SaveToXml(ref writer); writer.WriteStartElement("docking"); System.IO.MemoryStream ms = new System.IO.MemoryStream(); DockMainPanel.SaveAsXml(ms, Encoding.UTF8); ms.Position = 0; writer.WriteBase64(ms.ToArray(), 0, (int)ms.Length); writer.WriteEndElement(); // docking writer.WriteEndElement(); // layout writer.WriteEndDocument(); writer.Flush(); DockMainPanel.SaveAsXml("c:\\temp\\prova2.xml"); } private void CreateCustomizeToolbar() { AddNewButton = new ToolStripDropDownButton("New"); MainToolbar.Items.Add(AddNewButton); TransformersPopupMenu = new ContextMenuStrip(); TransformersPopupMenu.Opening += FTransformersPopupMenu_Popup; AddNewButton.DropDown = TransformersPopupMenu; List<UramakiTransformer> availableTransformers = this.Framework.GetAvailableTransformers(UramakiRoll.NullUramakiId); foreach (UramakiTransformer TempTransformer in availableTransformers) { ToolStripMenuItem itm = new ToolStripMenuItem(TempTransformer.GetDescription()); itm.Tag = TempTransformer.GetMyId(); TransformersPopupMenu.Items.Add(itm); List<UramakiPublisher>AvailablePublishers = this.Framework.GetAvailablePublishers(TempTransformer.GetOutputUramakiId()); foreach (UramakiPublisher TempPublisher in AvailablePublishers) { TMenuItemInfo tempMenuInfo = new TMenuItemInfo(); tempMenuInfo.Publisher = TempPublisher; tempMenuInfo.Transformer = TempTransformer; ToolStripMenuItem itm2 = new ToolStripMenuItem(TempPublisher.GetDescription()); itm2.Tag = tempMenuInfo; itm2.Click += FBarManager_ItemClick; itm.DropDownItems.Add(itm2); } } } private void FTransformersPopupMenu_Popup(object sender, EventArgs e) { //throw new NotImplementedException(); } void FBarManager_ItemClick(object sender, EventArgs e) { ToolStripMenuItem currentButton = sender as ToolStripMenuItem; if (currentButton == null) return; if ((currentButton.Tag != null) && (currentButton.Tag is TMenuItemInfo)) { UramakiPublisher tempPublisher = (currentButton.Tag as TMenuItemInfo).Publisher; UramakiTransformer tempTransformer = (currentButton.Tag as TMenuItemInfo).Transformer; List<UramakiActualTransformation> actualTransformations = new List<UramakiActualTransformation>(); UramakiActualTransformation tmpTransformation = new UramakiActualTransformation(); tmpTransformation.Transformer = tempTransformer; tmpTransformation.TransformationContext = tempTransformer.CreateTransformerContext(); actualTransformations.Add(tmpTransformation); UramakiActualPublication tempPublication = new UramakiActualPublication(); tempPublication.Publisher = tempPublisher; tempPublication.PublicationContext = tempPublisher.CreatePublisherContext(); UramakiPlate actualPlate = Framework.BuildPlate(UramakiFramework.NullId, ref actualTransformations, ref tempPublication); actualPlate.Text = "Report"; actualPlate.Show(DockMainPanel, DockState.Float); } } public void Init(ref UramakiFramework framework, Form parentForm) { this.Framework = framework; this.ParentForm = parentForm; this.ParentForm.IsMdiContainer = true; this.DockMainPanel = new DockPanel(); this.DockMainPanel.Dock = DockStyle.Fill; ParentForm.Controls.Add(DockMainPanel); this.DockMainPanel.ActiveContentChanged += FDockPanel_ActiveContentChanged; MainToolbar = new ToolStrip(); MainToolbar.Parent = ParentForm; MainToolbar.Dock = DockStyle.Top; CreateStandardToolbar(); CreateCustomizeToolbar(); hDeserializeDockContent = new DeserializeDockContent(GetContentFromPersistString); } private void FDockPanel_ActiveContentChanged(object sender, EventArgs e) { if ((sender as DockPanel).ActiveContent == null) { return; } int TempNewHashCode = ((sender as DockPanel).ActiveContent as DockContent).GetHashCode(); if (LastActivePanelHashCode != TempNewHashCode) { LastActivePanelHashCode = TempNewHashCode; ((sender as DockPanel).ActiveContent as DockContent).Text = TempNewHashCode.ToString(); //MessageBox.Show(TempNewHashCode.ToString()); } } } }
35.989744
130
0.681248
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
DomenicoMammola/Uramaki
Framework/Base/UramakiDesktop.cs
7,020
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using BookCave.Data; using BookCave.Data.EntityModels; using BookCave.Models.InputModels; namespace BookCave { public class Program { public static void Main(string[] args) { var host = BuildWebHost(args); //seedData(); host.Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); public static void seedData() { var db = new DataContext(); var initialBooks = new List<Book>() { new Book { Title = "Hamlet", Description = "Hamlet is a tragedy by William Shakespeare, believed to have been written between 1599 and 1601. The play, set in Denmark, recounts how Prince Hamlet exacts revenge on his uncle Claudius, who has murdered Hamlet's father, the King, and then taken the throne and married Hamlet's mother. The play vividly charts the course of real and feigned madness-from overwhelming grief to seething rage-and explores themes of treachery, revenge, incest, and moral corruption.", Price = 6, Rating = 7, ReleaseYear = 2016, Image = "https://images-na.ssl-images-amazon.com/images/I/41IETeONh-L._SX331_BO1,204,203,200_.jpg", AuthorId = 16 }, }; db.AddRange(initialBooks); db.SaveChanges(); var initialArtists = new List<Author>() { new Author { Name = "Arthur Miller", DateOfBirth = "17 October 1915", Image = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Arthur-miller.jpg/220px-Arthur-miller.jpg", BookId = 67 } }; db.AddRange(initialArtists); db.SaveChanges(); /*var initialGenres = new List<Genre>() { new Genre { Title = "Fantasy", BookId = 10} }; db.AddRange(initialGenres); db.SaveChanges();*/ } public static void CreateBook(BookCreateViewModel book) { var db = new DataContext(); var newBook = new Book() { Title = book.Title, Description = book.Description, Price = book.Price, Rating = book.Rating, ReleaseYear = book.ReleaseYear, AuthorId = book.AuthorId, GenreId = book.GenreId, Image = book.Image }; db.Add(newBook); db.SaveChanges(); } } }
38.513158
690
0.571917
[ "MIT" ]
eliasandri/BookCave
Program.cs
2,929
C#
namespace VAdvantage.Model { /** Generated Model - DO NOT CHANGE */ using System; using System.Text; using VAdvantage.DataBase; using VAdvantage.Common; using VAdvantage.Classes; using VAdvantage.Process; using VAdvantage.Model; using VAdvantage.Utility; using System.Data; /** Generated Model for B_BuyerFunds * @author Jagmohan Bhatt (generated) * @version Vienna Framework 1.1.1 - $Id$ */ public class X_B_BuyerFunds : PO { public X_B_BuyerFunds (Context ctx, int B_BuyerFunds_ID, Trx trxName) : base (ctx, B_BuyerFunds_ID, trxName) { /** if (B_BuyerFunds_ID == 0) { SetAD_User_ID (0); SetB_BuyerFunds_ID (0); SetCommittedAmt (0.0); SetNonCommittedAmt (0.0); } */ } public X_B_BuyerFunds (Ctx ctx, int B_BuyerFunds_ID, Trx trxName) : base (ctx, B_BuyerFunds_ID, trxName) { /** if (B_BuyerFunds_ID == 0) { SetAD_User_ID (0); SetB_BuyerFunds_ID (0); SetCommittedAmt (0.0); SetNonCommittedAmt (0.0); } */ } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_B_BuyerFunds (Context ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName) { } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_B_BuyerFunds (Ctx ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName) { } /** Load Constructor @param ctx context @param rs result set @param trxName transaction */ public X_B_BuyerFunds (Ctx ctx, IDataReader dr, Trx trxName) : base(ctx, dr, trxName) { } /** Static Constructor Set Table ID By Table Name added by ->Harwinder */ static X_B_BuyerFunds() { Table_ID = Get_Table_ID(Table_Name); model = new KeyNamePair(Table_ID,Table_Name); } /** Serial Version No */ //static long serialVersionUID 27562514367344L; /** Last Updated Timestamp 7/29/2010 1:07:30 PM */ public static long updatedMS = 1280389050555L; /** AD_Table_ID=683 */ public static int Table_ID; // =683; /** TableName=B_BuyerFunds */ public static String Table_Name="B_BuyerFunds"; protected static KeyNamePair model; protected Decimal accessLevel = new Decimal(3); /** AccessLevel @return 3 - Client - Org */ protected override int Get_AccessLevel() { return Convert.ToInt32(accessLevel.ToString()); } /** Load Meta Data @param ctx context @return PO Info */ protected override POInfo InitPO (Ctx ctx) { POInfo poi = POInfo.GetPOInfo (ctx, Table_ID); return poi; } /** Load Meta Data @param ctx context @return PO Info */ protected override POInfo InitPO(Context ctx) { POInfo poi = POInfo.GetPOInfo (ctx, Table_ID); return poi; } /** Info @return info */ public override String ToString() { StringBuilder sb = new StringBuilder ("X_B_BuyerFunds[").Append(Get_ID()).Append("]"); return sb.ToString(); } /** Set User/Contact. @param AD_User_ID User within the system - Internal or Business Partner Contact */ public void SetAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) throw new ArgumentException ("AD_User_ID is mandatory."); Set_Value ("AD_User_ID", AD_User_ID); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int GetAD_User_ID() { Object ii = Get_Value("AD_User_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair GetKeyNamePair() { return new KeyNamePair(Get_ID(), GetAD_User_ID().ToString()); } /** Set Buyer Funds. @param B_BuyerFunds_ID Buyer Funds for Bids on Topics */ public void SetB_BuyerFunds_ID (int B_BuyerFunds_ID) { if (B_BuyerFunds_ID < 1) throw new ArgumentException ("B_BuyerFunds_ID is mandatory."); Set_ValueNoCheck ("B_BuyerFunds_ID", B_BuyerFunds_ID); } /** Get Buyer Funds. @return Buyer Funds for Bids on Topics */ public int GetB_BuyerFunds_ID() { Object ii = Get_Value("B_BuyerFunds_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Set Order. @param C_Order_ID Order */ public void SetC_Order_ID (int C_Order_ID) { if (C_Order_ID <= 0) Set_ValueNoCheck ("C_Order_ID", null); else Set_ValueNoCheck ("C_Order_ID", C_Order_ID); } /** Get Order. @return Order */ public int GetC_Order_ID() { Object ii = Get_Value("C_Order_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Set Payment. @param C_Payment_ID Payment identifier */ public void SetC_Payment_ID (int C_Payment_ID) { if (C_Payment_ID <= 0) Set_ValueNoCheck ("C_Payment_ID", null); else Set_ValueNoCheck ("C_Payment_ID", C_Payment_ID); } /** Get Payment. @return Payment identifier */ public int GetC_Payment_ID() { Object ii = Get_Value("C_Payment_ID"); if (ii == null) return 0; return Convert.ToInt32(ii); } /** Set Committed Amount. @param CommittedAmt The (legal) commitment amount */ public void SetCommittedAmt (Decimal? CommittedAmt) { if (CommittedAmt == null) throw new ArgumentException ("CommittedAmt is mandatory."); Set_Value ("CommittedAmt", (Decimal?)CommittedAmt); } /** Get Committed Amount. @return The (legal) commitment amount */ public Decimal GetCommittedAmt() { Object bd =Get_Value("CommittedAmt"); if (bd == null) return Env.ZERO; return Convert.ToDecimal(bd); } /** Set Not Committed Aount. @param NonCommittedAmt Amount not committed yet */ public void SetNonCommittedAmt (Decimal? NonCommittedAmt) { if (NonCommittedAmt == null) throw new ArgumentException ("NonCommittedAmt is mandatory."); Set_Value ("NonCommittedAmt", (Decimal?)NonCommittedAmt); } /** Get Not Committed Aount. @return Amount not committed yet */ public Decimal GetNonCommittedAmt() { Object bd =Get_Value("NonCommittedAmt"); if (bd == null) return Env.ZERO; return Convert.ToDecimal(bd); } } }
25.231818
108
0.740587
[ "Apache-2.0" ]
AsimKhan2019/ERP-CMR-DMS
ViennaAdvantageWeb/ModelLibrary/Model/X_B_BuyerFunds.cs
5,551
C#
namespace Revit.SDK.Samples.WinderStairs.CS { partial class LWinderOptions { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.numAtStartTextBox = new System.Windows.Forms.TextBox(); this.numInCornerTextBox = new System.Windows.Forms.TextBox(); this.numAtEndTextBox = new System.Windows.Forms.TextBox(); this.runWidthTextBox = new System.Windows.Forms.TextBox(); this.startStepLabel = new System.Windows.Forms.Label(); this.cornerStepsNLabel = new System.Windows.Forms.Label(); this.endStepsLabel = new System.Windows.Forms.Label(); this.runWidthLabel = new System.Windows.Forms.Label(); this.cancelButton = new System.Windows.Forms.Button(); this.previewPictureBox = new System.Windows.Forms.PictureBox(); this.inputParamGroupBox = new System.Windows.Forms.GroupBox(); this.centerOffsetFLabel = new System.Windows.Forms.Label(); this.centerOffsetELabel = new System.Windows.Forms.Label(); this.centerOffsetFTextBox = new System.Windows.Forms.TextBox(); this.centerOffsetETextBox = new System.Windows.Forms.TextBox(); this.dmuCheckBox = new System.Windows.Forms.CheckBox(); this.sketchCheckBox = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize)(this.previewPictureBox)).BeginInit(); this.inputParamGroupBox.SuspendLayout(); this.SuspendLayout(); // // okButton // this.okButton.Location = new System.Drawing.Point(190, 279); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 26); this.okButton.TabIndex = 0; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // numAtStartTextBox // this.numAtStartTextBox.Location = new System.Drawing.Point(113, 64); this.numAtStartTextBox.Name = "numAtStartTextBox"; this.numAtStartTextBox.Size = new System.Drawing.Size(100, 20); this.numAtStartTextBox.TabIndex = 1; // // numInCornerTextBox // this.numInCornerTextBox.Location = new System.Drawing.Point(113, 124); this.numInCornerTextBox.Name = "numInCornerTextBox"; this.numInCornerTextBox.Size = new System.Drawing.Size(100, 20); this.numInCornerTextBox.TabIndex = 2; // // numAtEndTextBox // this.numAtEndTextBox.Location = new System.Drawing.Point(113, 94); this.numAtEndTextBox.Name = "numAtEndTextBox"; this.numAtEndTextBox.Size = new System.Drawing.Size(100, 20); this.numAtEndTextBox.TabIndex = 3; // // runWidthTextBox // this.runWidthTextBox.Location = new System.Drawing.Point(113, 34); this.runWidthTextBox.Name = "runWidthTextBox"; this.runWidthTextBox.Size = new System.Drawing.Size(100, 20); this.runWidthTextBox.TabIndex = 4; // // startStepLabel // this.startStepLabel.AutoSize = true; this.startStepLabel.Location = new System.Drawing.Point(24, 64); this.startStepLabel.Name = "startStepLabel"; this.startStepLabel.Size = new System.Drawing.Size(78, 13); this.startStepLabel.TabIndex = 6; this.startStepLabel.Text = "Start Steps (A):"; // // cornerStepsNLabel // this.cornerStepsNLabel.AutoSize = true; this.cornerStepsNLabel.Location = new System.Drawing.Point(14, 124); this.cornerStepsNLabel.Name = "cornerStepsNLabel"; this.cornerStepsNLabel.Size = new System.Drawing.Size(88, 13); this.cornerStepsNLabel.TabIndex = 7; this.cornerStepsNLabel.Text = "Corner Steps (N):"; // // endStepsLabel // this.endStepsLabel.AutoSize = true; this.endStepsLabel.Location = new System.Drawing.Point(27, 94); this.endStepsLabel.Name = "endStepsLabel"; this.endStepsLabel.Size = new System.Drawing.Size(75, 13); this.endStepsLabel.TabIndex = 8; this.endStepsLabel.Text = "End Steps (B):"; // // runWidthLabel // this.runWidthLabel.AutoSize = true; this.runWidthLabel.Location = new System.Drawing.Point(25, 34); this.runWidthLabel.Name = "runWidthLabel"; this.runWidthLabel.Size = new System.Drawing.Size(77, 13); this.runWidthLabel.TabIndex = 9; this.runWidthLabel.Text = "Run Width (C):"; // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(282, 279); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 26); this.cancelButton.TabIndex = 0; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // previewPictureBox // this.previewPictureBox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.previewPictureBox.Image = global::Revit.SDK.Samples.WinderStairs.CS.Properties.Resources.LWinder; this.previewPictureBox.Location = new System.Drawing.Point(258, 12); this.previewPictureBox.Name = "previewPictureBox"; this.previewPictureBox.Size = new System.Drawing.Size(269, 234); this.previewPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.previewPictureBox.TabIndex = 5; this.previewPictureBox.TabStop = false; // // inputParamGroupBox // this.inputParamGroupBox.Controls.Add(this.startStepLabel); this.inputParamGroupBox.Controls.Add(this.runWidthLabel); this.inputParamGroupBox.Controls.Add(this.numAtStartTextBox); this.inputParamGroupBox.Controls.Add(this.centerOffsetFLabel); this.inputParamGroupBox.Controls.Add(this.centerOffsetELabel); this.inputParamGroupBox.Controls.Add(this.endStepsLabel); this.inputParamGroupBox.Controls.Add(this.numInCornerTextBox); this.inputParamGroupBox.Controls.Add(this.cornerStepsNLabel); this.inputParamGroupBox.Controls.Add(this.centerOffsetFTextBox); this.inputParamGroupBox.Controls.Add(this.centerOffsetETextBox); this.inputParamGroupBox.Controls.Add(this.numAtEndTextBox); this.inputParamGroupBox.Controls.Add(this.runWidthTextBox); this.inputParamGroupBox.Location = new System.Drawing.Point(12, 12); this.inputParamGroupBox.Name = "inputParamGroupBox"; this.inputParamGroupBox.Size = new System.Drawing.Size(229, 234); this.inputParamGroupBox.TabIndex = 10; this.inputParamGroupBox.TabStop = false; this.inputParamGroupBox.Text = "Input Parameters"; // // centerOffsetFLabel // this.centerOffsetFLabel.AutoSize = true; this.centerOffsetFLabel.Location = new System.Drawing.Point(15, 184); this.centerOffsetFLabel.Name = "centerOffsetFLabel"; this.centerOffsetFLabel.Size = new System.Drawing.Size(87, 13); this.centerOffsetFLabel.TabIndex = 8; this.centerOffsetFLabel.Text = "Center Offset (F):"; // // centerOffsetELabel // this.centerOffsetELabel.AutoSize = true; this.centerOffsetELabel.Location = new System.Drawing.Point(14, 154); this.centerOffsetELabel.Name = "centerOffsetELabel"; this.centerOffsetELabel.Size = new System.Drawing.Size(88, 13); this.centerOffsetELabel.TabIndex = 8; this.centerOffsetELabel.Text = "Center Offset (E):"; // // centerOffsetFTextBox // this.centerOffsetFTextBox.Location = new System.Drawing.Point(113, 184); this.centerOffsetFTextBox.Name = "centerOffsetFTextBox"; this.centerOffsetFTextBox.Size = new System.Drawing.Size(100, 20); this.centerOffsetFTextBox.TabIndex = 3; // // centerOffsetETextBox // this.centerOffsetETextBox.Location = new System.Drawing.Point(113, 154); this.centerOffsetETextBox.Name = "centerOffsetETextBox"; this.centerOffsetETextBox.Size = new System.Drawing.Size(100, 20); this.centerOffsetETextBox.TabIndex = 3; // // dmuCheckBox // this.dmuCheckBox.AutoSize = true; this.dmuCheckBox.Location = new System.Drawing.Point(378, 285); this.dmuCheckBox.Name = "dmuCheckBox"; this.dmuCheckBox.Size = new System.Drawing.Size(51, 17); this.dmuCheckBox.TabIndex = 11; this.dmuCheckBox.Text = "DMU"; this.dmuCheckBox.UseVisualStyleBackColor = true; // // sketchCheckBox // this.sketchCheckBox.AutoSize = true; this.sketchCheckBox.Location = new System.Drawing.Point(440, 285); this.sketchCheckBox.Name = "sketchCheckBox"; this.sketchCheckBox.Size = new System.Drawing.Size(60, 17); this.sketchCheckBox.TabIndex = 24; this.sketchCheckBox.Text = "Sketch"; this.sketchCheckBox.UseVisualStyleBackColor = true; // // LWinderOptions // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(546, 324); this.ControlBox = false; this.Controls.Add(this.sketchCheckBox); this.Controls.Add(this.dmuCheckBox); this.Controls.Add(this.inputParamGroupBox); this.Controls.Add(this.previewPictureBox); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "LWinderOptions"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "L-Winder Options"; ((System.ComponentModel.ISupportInitialize)(this.previewPictureBox)).EndInit(); this.inputParamGroupBox.ResumeLayout(false); this.inputParamGroupBox.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button okButton; private System.Windows.Forms.TextBox numAtStartTextBox; private System.Windows.Forms.TextBox numInCornerTextBox; private System.Windows.Forms.TextBox numAtEndTextBox; private System.Windows.Forms.TextBox runWidthTextBox; private System.Windows.Forms.PictureBox previewPictureBox; private System.Windows.Forms.Label startStepLabel; private System.Windows.Forms.Label cornerStepsNLabel; private System.Windows.Forms.Label endStepsLabel; private System.Windows.Forms.Label runWidthLabel; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.GroupBox inputParamGroupBox; private System.Windows.Forms.Label centerOffsetFLabel; private System.Windows.Forms.Label centerOffsetELabel; private System.Windows.Forms.TextBox centerOffsetFTextBox; private System.Windows.Forms.TextBox centerOffsetETextBox; private System.Windows.Forms.CheckBox dmuCheckBox; private System.Windows.Forms.CheckBox sketchCheckBox; } }
51.007407
115
0.607973
[ "MIT" ]
xin1627/RevitSdkSamples
SDK/Samples/WinderStairs/CS/Forms/LWinderOptions.Designer.cs
13,774
C#
 namespace Engine.UI { /// <summary> /// Vertical align /// </summary> public enum ScrollVerticalAlign { /// <summary> /// None /// </summary> None, /// <summary> /// Align left /// </summary> Left, /// <summary> /// Align right /// </summary> Right, } }
16.347826
35
0.401596
[ "MIT" ]
Selinux24/SharpDX-Tests
Engine/UI/ScrollVerticalAlign.cs
378
C#
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DSInternals.DataStore.Test { [TestClass] public class DistinguishedNameResolverTester { [TestMethod] public void TestMethod1() { throw new AssertInconclusiveException(); } } }
19.625
52
0.659236
[ "MIT" ]
0xh4di/DSInternals
Src/DSInternals.DataStore.Test/DistinguishedNameResolverTester.cs
316
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Modules; using Microsoft.AspNetCore.Mvc.Modules; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orchard.Environment.Extensions; namespace Harvest.Demo2 { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddJsonFile("logging.json", optional: true, reloadOnChange: true) .AddJsonFile($"logging.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddExtensionLocation("CustomModules"); /* AddModuleServices Is registering default Loaders, Locations, and services for loading up modules. Modules are broken down in to what's deemed Extensions, Features and Manifests. Manifests are how a module is described to the system, without it that module wont be found. */ services.AddModuleServices(configure => configure .AddMvcModules(services.BuildServiceProvider()) .AddConfiguration(Configuration) .WithAllFeatures() // Tell the system, that all tenants will receive all the same features. ); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); loggerFactory.AddConsole(Configuration); // Registers the multi tenant middleware, and router middleware. app.UseModules(apb => { apb.UseStaticFilesModules(); }); } } }
37.968254
111
0.637124
[ "BSD-3-Clause" ]
Jetski5822/OrchardHarvestFeb2017
demo/Harvest.Demo2/Startup.cs
2,394
C#
using System; class DrawingSomeFox { static void Main() { //Input int n = int.Parse(Console.ReadLine()); int width = n * 2 + 3; //Logic for (int i = 1; i <=n; i++) { Console.WriteLine(new string('*',i)+"\\"+new string('-',width-2-i*2)+"/"+ new string('*', i)); }//endOfTop for (int i = 0; i < n/3; i++) { Console.WriteLine("|"+new string('*',n/2+i)+"\\"+ new string('*', n-2*i)+"/"+ new string('*', n / 2+i)+"|"); } for (int i = 1; i <= n; i++) { Console.WriteLine(new string('-', i) + "\\" + new string('*', width - 2 - i * 2) + "/" + new string('-', i)); } } }
27.615385
121
0.406685
[ "MIT" ]
AJMitev/C-Programming-Basics
8.Exam Prerapartion/034.Fox/DrawingSomeFox.cs
720
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 elasticache-2014-09-30.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ElastiCache.Model; using Amazon.ElastiCache.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElastiCache { /// <summary> /// Implementation for accessing ElastiCache /// /// Amazon ElastiCache /// <para> /// Amazon ElastiCache is a web service that makes it easier to set up, operate, and scale /// a distributed cache in the cloud. /// </para> /// /// <para> /// With ElastiCache, customers gain all of the benefits of a high-performance, in-memory /// cache with far less of the administrative burden of launching and managing a distributed /// cache. The service makes setup, scaling, and cluster failure handling much simpler /// than in a self-managed cache deployment. /// </para> /// /// <para> /// In addition, through integration with Amazon CloudWatch, customers get enhanced visibility /// into the key performance statistics associated with their cache and can receive alarms /// if a part of their cache runs hot. /// </para> /// </summary> public partial class AmazonElastiCacheClient : AmazonServiceClient, IAmazonElastiCache { #region Constructors /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient() : base(FallbackCredentialsFactory.GetCredentials(), new AmazonElastiCacheConfig()) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient(RegionEndpoint region) : base(FallbackCredentialsFactory.GetCredentials(), new AmazonElastiCacheConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient Configuration Object</param> public AmazonElastiCacheClient(AmazonElastiCacheConfig config) : base(FallbackCredentialsFactory.GetCredentials(), config) { } /// <summary> /// Constructs AmazonElastiCacheClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonElastiCacheClient(AWSCredentials credentials) : this(credentials, new AmazonElastiCacheConfig()) { } /// <summary> /// Constructs AmazonElastiCacheClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonElastiCacheClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonElastiCacheConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElastiCacheClient with AWS Credentials and an /// AmazonElastiCacheClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonElastiCacheClient Configuration Object</param> public AmazonElastiCacheClient(AWSCredentials credentials, AmazonElastiCacheConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElastiCacheConfig()) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElastiCacheConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonElastiCacheClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElastiCacheClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonElastiCacheClient Configuration Object</param> public AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElastiCacheConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElastiCacheConfig()) { } /// <summary> /// Constructs AmazonElastiCacheClient 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 AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElastiCacheConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElastiCacheClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElastiCacheClient 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 AmazonElastiCacheClient Configuration Object</param> public AmazonElastiCacheClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonElastiCacheConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region AuthorizeCacheSecurityGroupIngress /// <summary> /// The <i>AuthorizeCacheSecurityGroupIngress</i> operation allows network ingress to /// a cache security group. Applications using ElastiCache must be running on Amazon EC2, /// and Amazon EC2 security groups are used as the authorization mechanism. /// </summary> /// <param name="request">Container for the necessary parameters to execute the AuthorizeCacheSecurityGroupIngress service method.</param> /// /// <returns>The response from the AuthorizeCacheSecurityGroupIngress service method, as returned by ElastiCache.</returns> /// <exception cref="AuthorizationAlreadyExistsException"> /// The specified Amazon EC2 security group is already authorized for the specified cache /// security group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InvalidCacheSecurityGroupStateException"> /// The current state of the cache security group does not allow deletion. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public AuthorizeCacheSecurityGroupIngressResponse AuthorizeCacheSecurityGroupIngress(AuthorizeCacheSecurityGroupIngressRequest request) { var marshaller = new AuthorizeCacheSecurityGroupIngressRequestMarshaller(); var unmarshaller = AuthorizeCacheSecurityGroupIngressResponseUnmarshaller.Instance; return Invoke<AuthorizeCacheSecurityGroupIngressRequest,AuthorizeCacheSecurityGroupIngressResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the AuthorizeCacheSecurityGroupIngress operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the AuthorizeCacheSecurityGroupIngress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<AuthorizeCacheSecurityGroupIngressResponse> AuthorizeCacheSecurityGroupIngressAsync(AuthorizeCacheSecurityGroupIngressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new AuthorizeCacheSecurityGroupIngressRequestMarshaller(); var unmarshaller = AuthorizeCacheSecurityGroupIngressResponseUnmarshaller.Instance; return InvokeAsync<AuthorizeCacheSecurityGroupIngressRequest,AuthorizeCacheSecurityGroupIngressResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CopySnapshot /// <summary> /// The <i>CopySnapshot</i> operation makes a copy of an existing snapshot. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CopySnapshot service method.</param> /// /// <returns>The response from the CopySnapshot service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidSnapshotStateException"> /// The current state of the snapshot does not allow the requested action to occur. /// </exception> /// <exception cref="SnapshotAlreadyExistsException"> /// You already have a snapshot with the given name. /// </exception> /// <exception cref="SnapshotNotFoundException"> /// The requested snapshot name does not refer to an existing snapshot. /// </exception> /// <exception cref="SnapshotQuotaExceededException"> /// The request cannot be processed because it would exceed the maximum number of snapshots. /// </exception> public CopySnapshotResponse CopySnapshot(CopySnapshotRequest request) { var marshaller = new CopySnapshotRequestMarshaller(); var unmarshaller = CopySnapshotResponseUnmarshaller.Instance; return Invoke<CopySnapshotRequest,CopySnapshotResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CopySnapshot operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CopySnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CopySnapshotResponse> CopySnapshotAsync(CopySnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CopySnapshotRequestMarshaller(); var unmarshaller = CopySnapshotResponseUnmarshaller.Instance; return InvokeAsync<CopySnapshotRequest,CopySnapshotResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateCacheCluster /// <summary> /// The <i>CreateCacheCluster</i> operation creates a cache cluster. All nodes in the /// cache cluster run the same protocol-compliant cache engine software, either Memcached /// or Redis. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCacheCluster service method.</param> /// /// <returns>The response from the CreateCacheCluster service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterAlreadyExistsException"> /// You already have a cache cluster with the given identifier. /// </exception> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> /// <exception cref="ClusterQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// clusters per customer. /// </exception> /// <exception cref="InsufficientCacheClusterCapacityException"> /// The requested cache node type is not available in the specified Availability Zone. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidReplicationGroupStateException"> /// The requested replication group is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidVPCNetworkStateException"> /// The VPC network is in an invalid state. /// </exception> /// <exception cref="NodeQuotaForClusterExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes in a single cache cluster. /// </exception> /// <exception cref="NodeQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes per customer. /// </exception> /// <exception cref="ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> public CreateCacheClusterResponse CreateCacheCluster(CreateCacheClusterRequest request) { var marshaller = new CreateCacheClusterRequestMarshaller(); var unmarshaller = CreateCacheClusterResponseUnmarshaller.Instance; return Invoke<CreateCacheClusterRequest,CreateCacheClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateCacheCluster operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateCacheClusterResponse> CreateCacheClusterAsync(CreateCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateCacheClusterRequestMarshaller(); var unmarshaller = CreateCacheClusterResponseUnmarshaller.Instance; return InvokeAsync<CreateCacheClusterRequest,CreateCacheClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateCacheParameterGroup /// <summary> /// The <i>CreateCacheParameterGroup</i> operation creates a new cache parameter group. /// A cache parameter group is a collection of parameters that you apply to all of the /// nodes in a cache cluster. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCacheParameterGroup service method.</param> /// /// <returns>The response from the CreateCacheParameterGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupAlreadyExistsException"> /// A cache parameter group with the requested name already exists. /// </exception> /// <exception cref="CacheParameterGroupQuotaExceededException"> /// The request cannot be processed because it would exceed the maximum number of cache /// security groups. /// </exception> /// <exception cref="InvalidCacheParameterGroupStateException"> /// The current state of the cache parameter group does not allow the requested action /// to occur. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public CreateCacheParameterGroupResponse CreateCacheParameterGroup(CreateCacheParameterGroupRequest request) { var marshaller = new CreateCacheParameterGroupRequestMarshaller(); var unmarshaller = CreateCacheParameterGroupResponseUnmarshaller.Instance; return Invoke<CreateCacheParameterGroupRequest,CreateCacheParameterGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateCacheParameterGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheParameterGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateCacheParameterGroupResponse> CreateCacheParameterGroupAsync(CreateCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateCacheParameterGroupRequestMarshaller(); var unmarshaller = CreateCacheParameterGroupResponseUnmarshaller.Instance; return InvokeAsync<CreateCacheParameterGroupRequest,CreateCacheParameterGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateCacheSecurityGroup /// <summary> /// The <i>CreateCacheSecurityGroup</i> operation creates a new cache security group. /// Use a cache security group to control access to one or more cache clusters. /// /// /// <para> /// Cache security groups are only used when you are creating a cache cluster outside /// of an Amazon Virtual Private Cloud (VPC). If you are creating a cache cluster inside /// of a VPC, use a cache subnet group instead. For more information, see <a href="http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_CreateCacheSubnetGroup.html">CreateCacheSubnetGroup</a>. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCacheSecurityGroup service method.</param> /// /// <returns>The response from the CreateCacheSecurityGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSecurityGroupAlreadyExistsException"> /// A cache security group with the specified name already exists. /// </exception> /// <exception cref="CacheSecurityGroupQuotaExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// security groups. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public CreateCacheSecurityGroupResponse CreateCacheSecurityGroup(CreateCacheSecurityGroupRequest request) { var marshaller = new CreateCacheSecurityGroupRequestMarshaller(); var unmarshaller = CreateCacheSecurityGroupResponseUnmarshaller.Instance; return Invoke<CreateCacheSecurityGroupRequest,CreateCacheSecurityGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateCacheSecurityGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheSecurityGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateCacheSecurityGroupResponse> CreateCacheSecurityGroupAsync(CreateCacheSecurityGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateCacheSecurityGroupRequestMarshaller(); var unmarshaller = CreateCacheSecurityGroupResponseUnmarshaller.Instance; return InvokeAsync<CreateCacheSecurityGroupRequest,CreateCacheSecurityGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateCacheSubnetGroup /// <summary> /// The <i>CreateCacheSubnetGroup</i> operation creates a new cache subnet group. /// /// /// <para> /// Use this parameter only when you are creating a cluster in an Amazon Virtual Private /// Cloud (VPC). /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateCacheSubnetGroup service method.</param> /// /// <returns>The response from the CreateCacheSubnetGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSubnetGroupAlreadyExistsException"> /// The requested cache subnet group name is already in use by an existing cache subnet /// group. /// </exception> /// <exception cref="CacheSubnetGroupQuotaExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// subnet groups. /// </exception> /// <exception cref="CacheSubnetQuotaExceededException"> /// The request cannot be processed because it would exceed the allowed number of subnets /// in a cache subnet group. /// </exception> /// <exception cref="InvalidSubnetException"> /// An invalid subnet identifier was specified. /// </exception> public CreateCacheSubnetGroupResponse CreateCacheSubnetGroup(CreateCacheSubnetGroupRequest request) { var marshaller = new CreateCacheSubnetGroupRequestMarshaller(); var unmarshaller = CreateCacheSubnetGroupResponseUnmarshaller.Instance; return Invoke<CreateCacheSubnetGroupRequest,CreateCacheSubnetGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateCacheSubnetGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateCacheSubnetGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateCacheSubnetGroupResponse> CreateCacheSubnetGroupAsync(CreateCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateCacheSubnetGroupRequestMarshaller(); var unmarshaller = CreateCacheSubnetGroupResponseUnmarshaller.Instance; return InvokeAsync<CreateCacheSubnetGroupRequest,CreateCacheSubnetGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateReplicationGroup /// <summary> /// The <i>CreateReplicationGroup</i> operation creates a replication group. A replication /// group is a collection of cache clusters, where one of the cache clusters is a read/write /// primary and the others are read-only replicas. Writes to the primary are automatically /// propagated to the replicas. /// /// /// <para> /// When you create a replication group, you must specify an existing cache cluster that /// is in the primary role. When the replication group has been successfully created, /// you can add one or more read replica replicas to it, up to a total of five read replicas. /// </para> /// /// <para> /// <b>Note:</b> This action is valid only for Redis. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateReplicationGroup service method.</param> /// /// <returns>The response from the CreateReplicationGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> /// <exception cref="ClusterQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// clusters per customer. /// </exception> /// <exception cref="InsufficientCacheClusterCapacityException"> /// The requested cache node type is not available in the specified Availability Zone. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidVPCNetworkStateException"> /// The VPC network is in an invalid state. /// </exception> /// <exception cref="NodeQuotaForClusterExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes in a single cache cluster. /// </exception> /// <exception cref="NodeQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes per customer. /// </exception> /// <exception cref="ReplicationGroupAlreadyExistsException"> /// The specified replication group already exists. /// </exception> public CreateReplicationGroupResponse CreateReplicationGroup(CreateReplicationGroupRequest request) { var marshaller = new CreateReplicationGroupRequestMarshaller(); var unmarshaller = CreateReplicationGroupResponseUnmarshaller.Instance; return Invoke<CreateReplicationGroupRequest,CreateReplicationGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateReplicationGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateReplicationGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateReplicationGroupResponse> CreateReplicationGroupAsync(CreateReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateReplicationGroupRequestMarshaller(); var unmarshaller = CreateReplicationGroupResponseUnmarshaller.Instance; return InvokeAsync<CreateReplicationGroupRequest,CreateReplicationGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateSnapshot /// <summary> /// The <i>CreateSnapshot</i> operation creates a copy of an entire cache cluster at a /// specific moment in time. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateSnapshot service method.</param> /// /// <returns>The response from the CreateSnapshot service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="SnapshotAlreadyExistsException"> /// You already have a snapshot with the given name. /// </exception> /// <exception cref="SnapshotFeatureNotSupportedException"> /// You attempted one of the following actions: /// /// <ul> <li> /// <para> /// Creating a snapshot of a Redis cache cluster running on a <i>t1.micro</i> cache node. /// </para> /// </li> <li> /// <para> /// Creating a snapshot of a cache cluster that is running Memcached rather than Redis. /// </para> /// </li> </ul> /// <para> /// Neither of these are supported by ElastiCache. /// </para> /// </exception> /// <exception cref="SnapshotQuotaExceededException"> /// The request cannot be processed because it would exceed the maximum number of snapshots. /// </exception> public CreateSnapshotResponse CreateSnapshot(CreateSnapshotRequest request) { var marshaller = new CreateSnapshotRequestMarshaller(); var unmarshaller = CreateSnapshotResponseUnmarshaller.Instance; return Invoke<CreateSnapshotRequest,CreateSnapshotResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateSnapshot operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateSnapshotResponse> CreateSnapshotAsync(CreateSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateSnapshotRequestMarshaller(); var unmarshaller = CreateSnapshotResponseUnmarshaller.Instance; return InvokeAsync<CreateSnapshotRequest,CreateSnapshotResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteCacheCluster /// <summary> /// The <i>DeleteCacheCluster</i> operation deletes a previously provisioned cache cluster. /// <i>DeleteCacheCluster</i> deletes all associated cache nodes, node endpoints and the /// cache cluster itself. When you receive a successful response from this operation, /// Amazon ElastiCache immediately begins deleting the cache cluster; you cannot cancel /// or revert this operation. /// /// /// <para> /// This API cannot be used to delete a cache cluster that is the last read replica of /// a replication group that has automatic failover mode enabled. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCacheCluster service method.</param> /// /// <returns>The response from the DeleteCacheCluster service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="SnapshotAlreadyExistsException"> /// You already have a snapshot with the given name. /// </exception> /// <exception cref="SnapshotFeatureNotSupportedException"> /// You attempted one of the following actions: /// /// <ul> <li> /// <para> /// Creating a snapshot of a Redis cache cluster running on a <i>t1.micro</i> cache node. /// </para> /// </li> <li> /// <para> /// Creating a snapshot of a cache cluster that is running Memcached rather than Redis. /// </para> /// </li> </ul> /// <para> /// Neither of these are supported by ElastiCache. /// </para> /// </exception> /// <exception cref="SnapshotQuotaExceededException"> /// The request cannot be processed because it would exceed the maximum number of snapshots. /// </exception> public DeleteCacheClusterResponse DeleteCacheCluster(DeleteCacheClusterRequest request) { var marshaller = new DeleteCacheClusterRequestMarshaller(); var unmarshaller = DeleteCacheClusterResponseUnmarshaller.Instance; return Invoke<DeleteCacheClusterRequest,DeleteCacheClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteCacheCluster operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteCacheClusterResponse> DeleteCacheClusterAsync(DeleteCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteCacheClusterRequestMarshaller(); var unmarshaller = DeleteCacheClusterResponseUnmarshaller.Instance; return InvokeAsync<DeleteCacheClusterRequest,DeleteCacheClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteCacheParameterGroup /// <summary> /// The <i>DeleteCacheParameterGroup</i> operation deletes the specified cache parameter /// group. You cannot delete a cache parameter group if it is associated with any cache /// clusters. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCacheParameterGroup service method.</param> /// /// <returns>The response from the DeleteCacheParameterGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidCacheParameterGroupStateException"> /// The current state of the cache parameter group does not allow the requested action /// to occur. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DeleteCacheParameterGroupResponse DeleteCacheParameterGroup(DeleteCacheParameterGroupRequest request) { var marshaller = new DeleteCacheParameterGroupRequestMarshaller(); var unmarshaller = DeleteCacheParameterGroupResponseUnmarshaller.Instance; return Invoke<DeleteCacheParameterGroupRequest,DeleteCacheParameterGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteCacheParameterGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheParameterGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteCacheParameterGroupResponse> DeleteCacheParameterGroupAsync(DeleteCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteCacheParameterGroupRequestMarshaller(); var unmarshaller = DeleteCacheParameterGroupResponseUnmarshaller.Instance; return InvokeAsync<DeleteCacheParameterGroupRequest,DeleteCacheParameterGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteCacheSecurityGroup /// <summary> /// The <i>DeleteCacheSecurityGroup</i> operation deletes a cache security group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSecurityGroup service method.</param> /// /// <returns>The response from the DeleteCacheSecurityGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InvalidCacheSecurityGroupStateException"> /// The current state of the cache security group does not allow deletion. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DeleteCacheSecurityGroupResponse DeleteCacheSecurityGroup(DeleteCacheSecurityGroupRequest request) { var marshaller = new DeleteCacheSecurityGroupRequestMarshaller(); var unmarshaller = DeleteCacheSecurityGroupResponseUnmarshaller.Instance; return Invoke<DeleteCacheSecurityGroupRequest,DeleteCacheSecurityGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteCacheSecurityGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSecurityGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteCacheSecurityGroupResponse> DeleteCacheSecurityGroupAsync(DeleteCacheSecurityGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteCacheSecurityGroupRequestMarshaller(); var unmarshaller = DeleteCacheSecurityGroupResponseUnmarshaller.Instance; return InvokeAsync<DeleteCacheSecurityGroupRequest,DeleteCacheSecurityGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteCacheSubnetGroup /// <summary> /// The <i>DeleteCacheSubnetGroup</i> operation deletes a cache subnet group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSubnetGroup service method.</param> /// /// <returns>The response from the DeleteCacheSubnetGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSubnetGroupInUseException"> /// The requested cache subnet group is currently in use. /// </exception> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> public DeleteCacheSubnetGroupResponse DeleteCacheSubnetGroup(DeleteCacheSubnetGroupRequest request) { var marshaller = new DeleteCacheSubnetGroupRequestMarshaller(); var unmarshaller = DeleteCacheSubnetGroupResponseUnmarshaller.Instance; return Invoke<DeleteCacheSubnetGroupRequest,DeleteCacheSubnetGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteCacheSubnetGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteCacheSubnetGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteCacheSubnetGroupResponse> DeleteCacheSubnetGroupAsync(DeleteCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteCacheSubnetGroupRequestMarshaller(); var unmarshaller = DeleteCacheSubnetGroupResponseUnmarshaller.Instance; return InvokeAsync<DeleteCacheSubnetGroupRequest,DeleteCacheSubnetGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteReplicationGroup /// <summary> /// The <i>DeleteReplicationGroup</i> operation deletes an existing cluster. By default, /// this operation deletes the entire cluster, including the primary node group and all /// of the read replicas. You can optionally delete only the read replicas, while retaining /// the primary node group. /// /// /// <para> /// When you receive a successful response from this operation, Amazon ElastiCache immediately /// begins deleting the selected resources; you cannot cancel or revert this operation. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationGroup service method.</param> /// /// <returns>The response from the DeleteReplicationGroup service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidReplicationGroupStateException"> /// The requested replication group is not in the <i>available</i> state. /// </exception> /// <exception cref="ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> /// <exception cref="SnapshotAlreadyExistsException"> /// You already have a snapshot with the given name. /// </exception> /// <exception cref="SnapshotFeatureNotSupportedException"> /// You attempted one of the following actions: /// /// <ul> <li> /// <para> /// Creating a snapshot of a Redis cache cluster running on a <i>t1.micro</i> cache node. /// </para> /// </li> <li> /// <para> /// Creating a snapshot of a cache cluster that is running Memcached rather than Redis. /// </para> /// </li> </ul> /// <para> /// Neither of these are supported by ElastiCache. /// </para> /// </exception> /// <exception cref="SnapshotQuotaExceededException"> /// The request cannot be processed because it would exceed the maximum number of snapshots. /// </exception> public DeleteReplicationGroupResponse DeleteReplicationGroup(DeleteReplicationGroupRequest request) { var marshaller = new DeleteReplicationGroupRequestMarshaller(); var unmarshaller = DeleteReplicationGroupResponseUnmarshaller.Instance; return Invoke<DeleteReplicationGroupRequest,DeleteReplicationGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteReplicationGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteReplicationGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteReplicationGroupResponse> DeleteReplicationGroupAsync(DeleteReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteReplicationGroupRequestMarshaller(); var unmarshaller = DeleteReplicationGroupResponseUnmarshaller.Instance; return InvokeAsync<DeleteReplicationGroupRequest,DeleteReplicationGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeleteSnapshot /// <summary> /// The <i>DeleteSnapshot</i> operation deletes an existing snapshot. When you receive /// a successful response from this operation, ElastiCache immediately begins deleting /// the snapshot; you cannot cancel or revert this operation. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot service method.</param> /// /// <returns>The response from the DeleteSnapshot service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidSnapshotStateException"> /// The current state of the snapshot does not allow the requested action to occur. /// </exception> /// <exception cref="SnapshotNotFoundException"> /// The requested snapshot name does not refer to an existing snapshot. /// </exception> public DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request) { var marshaller = new DeleteSnapshotRequestMarshaller(); var unmarshaller = DeleteSnapshotResponseUnmarshaller.Instance; return Invoke<DeleteSnapshotRequest,DeleteSnapshotResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeleteSnapshot operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeleteSnapshotRequestMarshaller(); var unmarshaller = DeleteSnapshotResponseUnmarshaller.Instance; return InvokeAsync<DeleteSnapshotRequest,DeleteSnapshotResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheClusters /// <summary> /// The <i>DescribeCacheClusters</i> operation returns information about all provisioned /// cache clusters if no cache cluster identifier is specified, or about a specific cache /// cluster if a cache cluster identifier is supplied. /// /// /// <para> /// By default, abbreviated information about the cache clusters(s) will be returned. /// You can use the optional <i>ShowDetails</i> flag to retrieve detailed information /// about the cache nodes associated with the cache clusters. These details include the /// DNS address and port for the cache node endpoint. /// </para> /// /// <para> /// If the cluster is in the CREATING state, only cluster level information will be displayed /// until all of the nodes are successfully provisioned. /// </para> /// /// <para> /// If the cluster is in the DELETING state, only cluster level information will be displayed. /// </para> /// /// <para> /// If cache nodes are currently being added to the cache cluster, node endpoint information /// and creation time for the additional nodes will not be displayed until they are completely /// provisioned. When the cache cluster state is <i>available</i>, the cluster is ready /// for use. /// </para> /// /// <para> /// If cache nodes are currently being removed from the cache cluster, no endpoint information /// for the removed nodes is displayed. /// </para> /// </summary> /// /// <returns>The response from the DescribeCacheClusters service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheClustersResponse DescribeCacheClusters() { return DescribeCacheClusters(new DescribeCacheClustersRequest()); } /// <summary> /// The <i>DescribeCacheClusters</i> operation returns information about all provisioned /// cache clusters if no cache cluster identifier is specified, or about a specific cache /// cluster if a cache cluster identifier is supplied. /// /// /// <para> /// By default, abbreviated information about the cache clusters(s) will be returned. /// You can use the optional <i>ShowDetails</i> flag to retrieve detailed information /// about the cache nodes associated with the cache clusters. These details include the /// DNS address and port for the cache node endpoint. /// </para> /// /// <para> /// If the cluster is in the CREATING state, only cluster level information will be displayed /// until all of the nodes are successfully provisioned. /// </para> /// /// <para> /// If the cluster is in the DELETING state, only cluster level information will be displayed. /// </para> /// /// <para> /// If cache nodes are currently being added to the cache cluster, node endpoint information /// and creation time for the additional nodes will not be displayed until they are completely /// provisioned. When the cache cluster state is <i>available</i>, the cluster is ready /// for use. /// </para> /// /// <para> /// If cache nodes are currently being removed from the cache cluster, no endpoint information /// for the removed nodes is displayed. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheClusters service method.</param> /// /// <returns>The response from the DescribeCacheClusters service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheClustersResponse DescribeCacheClusters(DescribeCacheClustersRequest request) { var marshaller = new DescribeCacheClustersRequestMarshaller(); var unmarshaller = DescribeCacheClustersResponseUnmarshaller.Instance; return Invoke<DescribeCacheClustersRequest,DescribeCacheClustersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheClusters operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheClusters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheClustersResponse> DescribeCacheClustersAsync(DescribeCacheClustersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheClustersRequestMarshaller(); var unmarshaller = DescribeCacheClustersResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheClustersRequest,DescribeCacheClustersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheEngineVersions /// <summary> /// The <i>DescribeCacheEngineVersions</i> operation returns a list of the available cache /// engines and their versions. /// </summary> /// /// <returns>The response from the DescribeCacheEngineVersions service method, as returned by ElastiCache.</returns> public DescribeCacheEngineVersionsResponse DescribeCacheEngineVersions() { return DescribeCacheEngineVersions(new DescribeCacheEngineVersionsRequest()); } /// <summary> /// The <i>DescribeCacheEngineVersions</i> operation returns a list of the available cache /// engines and their versions. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheEngineVersions service method.</param> /// /// <returns>The response from the DescribeCacheEngineVersions service method, as returned by ElastiCache.</returns> public DescribeCacheEngineVersionsResponse DescribeCacheEngineVersions(DescribeCacheEngineVersionsRequest request) { var marshaller = new DescribeCacheEngineVersionsRequestMarshaller(); var unmarshaller = DescribeCacheEngineVersionsResponseUnmarshaller.Instance; return Invoke<DescribeCacheEngineVersionsRequest,DescribeCacheEngineVersionsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheEngineVersions operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheEngineVersions operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheEngineVersionsResponse> DescribeCacheEngineVersionsAsync(DescribeCacheEngineVersionsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheEngineVersionsRequestMarshaller(); var unmarshaller = DescribeCacheEngineVersionsResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheEngineVersionsRequest,DescribeCacheEngineVersionsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheParameterGroups /// <summary> /// The <i>DescribeCacheParameterGroups</i> operation returns a list of cache parameter /// group descriptions. If a cache parameter group name is specified, the list will contain /// only the descriptions for that group. /// </summary> /// /// <returns>The response from the DescribeCacheParameterGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheParameterGroupsResponse DescribeCacheParameterGroups() { return DescribeCacheParameterGroups(new DescribeCacheParameterGroupsRequest()); } /// <summary> /// The <i>DescribeCacheParameterGroups</i> operation returns a list of cache parameter /// group descriptions. If a cache parameter group name is specified, the list will contain /// only the descriptions for that group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameterGroups service method.</param> /// /// <returns>The response from the DescribeCacheParameterGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheParameterGroupsResponse DescribeCacheParameterGroups(DescribeCacheParameterGroupsRequest request) { var marshaller = new DescribeCacheParameterGroupsRequestMarshaller(); var unmarshaller = DescribeCacheParameterGroupsResponseUnmarshaller.Instance; return Invoke<DescribeCacheParameterGroupsRequest,DescribeCacheParameterGroupsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheParameterGroups operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameterGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheParameterGroupsResponse> DescribeCacheParameterGroupsAsync(DescribeCacheParameterGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheParameterGroupsRequestMarshaller(); var unmarshaller = DescribeCacheParameterGroupsResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheParameterGroupsRequest,DescribeCacheParameterGroupsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheParameters /// <summary> /// The <i>DescribeCacheParameters</i> operation returns the detailed parameter list for /// a particular cache parameter group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameters service method.</param> /// /// <returns>The response from the DescribeCacheParameters service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheParametersResponse DescribeCacheParameters(DescribeCacheParametersRequest request) { var marshaller = new DescribeCacheParametersRequestMarshaller(); var unmarshaller = DescribeCacheParametersResponseUnmarshaller.Instance; return Invoke<DescribeCacheParametersRequest,DescribeCacheParametersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheParameters operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheParameters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheParametersResponse> DescribeCacheParametersAsync(DescribeCacheParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheParametersRequestMarshaller(); var unmarshaller = DescribeCacheParametersResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheParametersRequest,DescribeCacheParametersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheSecurityGroups /// <summary> /// The <i>DescribeCacheSecurityGroups</i> operation returns a list of cache security /// group descriptions. If a cache security group name is specified, the list will contain /// only the description of that group. /// </summary> /// /// <returns>The response from the DescribeCacheSecurityGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheSecurityGroupsResponse DescribeCacheSecurityGroups() { return DescribeCacheSecurityGroups(new DescribeCacheSecurityGroupsRequest()); } /// <summary> /// The <i>DescribeCacheSecurityGroups</i> operation returns a list of cache security /// group descriptions. If a cache security group name is specified, the list will contain /// only the description of that group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSecurityGroups service method.</param> /// /// <returns>The response from the DescribeCacheSecurityGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeCacheSecurityGroupsResponse DescribeCacheSecurityGroups(DescribeCacheSecurityGroupsRequest request) { var marshaller = new DescribeCacheSecurityGroupsRequestMarshaller(); var unmarshaller = DescribeCacheSecurityGroupsResponseUnmarshaller.Instance; return Invoke<DescribeCacheSecurityGroupsRequest,DescribeCacheSecurityGroupsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheSecurityGroups operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSecurityGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheSecurityGroupsResponse> DescribeCacheSecurityGroupsAsync(DescribeCacheSecurityGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheSecurityGroupsRequestMarshaller(); var unmarshaller = DescribeCacheSecurityGroupsResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheSecurityGroupsRequest,DescribeCacheSecurityGroupsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeCacheSubnetGroups /// <summary> /// The <i>DescribeCacheSubnetGroups</i> operation returns a list of cache subnet group /// descriptions. If a subnet group name is specified, the list will contain only the /// description of that group. /// </summary> /// /// <returns>The response from the DescribeCacheSubnetGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> public DescribeCacheSubnetGroupsResponse DescribeCacheSubnetGroups() { return DescribeCacheSubnetGroups(new DescribeCacheSubnetGroupsRequest()); } /// <summary> /// The <i>DescribeCacheSubnetGroups</i> operation returns a list of cache subnet group /// descriptions. If a subnet group name is specified, the list will contain only the /// description of that group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSubnetGroups service method.</param> /// /// <returns>The response from the DescribeCacheSubnetGroups service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> public DescribeCacheSubnetGroupsResponse DescribeCacheSubnetGroups(DescribeCacheSubnetGroupsRequest request) { var marshaller = new DescribeCacheSubnetGroupsRequestMarshaller(); var unmarshaller = DescribeCacheSubnetGroupsResponseUnmarshaller.Instance; return Invoke<DescribeCacheSubnetGroupsRequest,DescribeCacheSubnetGroupsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeCacheSubnetGroups operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeCacheSubnetGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeCacheSubnetGroupsResponse> DescribeCacheSubnetGroupsAsync(DescribeCacheSubnetGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeCacheSubnetGroupsRequestMarshaller(); var unmarshaller = DescribeCacheSubnetGroupsResponseUnmarshaller.Instance; return InvokeAsync<DescribeCacheSubnetGroupsRequest,DescribeCacheSubnetGroupsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEngineDefaultParameters /// <summary> /// The <i>DescribeEngineDefaultParameters</i> operation returns the default engine and /// system parameter information for the specified cache engine. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEngineDefaultParameters service method.</param> /// /// <returns>The response from the DescribeEngineDefaultParameters service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeEngineDefaultParametersResponse DescribeEngineDefaultParameters(DescribeEngineDefaultParametersRequest request) { var marshaller = new DescribeEngineDefaultParametersRequestMarshaller(); var unmarshaller = DescribeEngineDefaultParametersResponseUnmarshaller.Instance; return Invoke<DescribeEngineDefaultParametersRequest,DescribeEngineDefaultParametersResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeEngineDefaultParameters operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEngineDefaultParameters operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEngineDefaultParametersResponse> DescribeEngineDefaultParametersAsync(DescribeEngineDefaultParametersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEngineDefaultParametersRequestMarshaller(); var unmarshaller = DescribeEngineDefaultParametersResponseUnmarshaller.Instance; return InvokeAsync<DescribeEngineDefaultParametersRequest,DescribeEngineDefaultParametersResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeEvents /// <summary> /// The <i>DescribeEvents</i> operation returns events related to cache clusters, cache /// security groups, and cache parameter groups. You can obtain events specific to a particular /// cache cluster, cache security group, or cache parameter group by providing the name /// as a parameter. /// /// /// <para> /// By default, only the events occurring within the last hour are returned; however, /// you can retrieve up to 14 days' worth of events if necessary. /// </para> /// </summary> /// /// <returns>The response from the DescribeEvents service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeEventsResponse DescribeEvents() { return DescribeEvents(new DescribeEventsRequest()); } /// <summary> /// The <i>DescribeEvents</i> operation returns events related to cache clusters, cache /// security groups, and cache parameter groups. You can obtain events specific to a particular /// cache cluster, cache security group, or cache parameter group by providing the name /// as a parameter. /// /// /// <para> /// By default, only the events occurring within the last hour are returned; however, /// you can retrieve up to 14 days' worth of events if necessary. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeEvents service method.</param> /// /// <returns>The response from the DescribeEvents service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public DescribeEventsResponse DescribeEvents(DescribeEventsRequest request) { var marshaller = new DescribeEventsRequestMarshaller(); var unmarshaller = DescribeEventsResponseUnmarshaller.Instance; return Invoke<DescribeEventsRequest,DescribeEventsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeEvents operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeEvents operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeEventsResponse> DescribeEventsAsync(DescribeEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeEventsRequestMarshaller(); var unmarshaller = DescribeEventsResponseUnmarshaller.Instance; return InvokeAsync<DescribeEventsRequest,DescribeEventsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeReplicationGroups /// <summary> /// The <i>DescribeReplicationGroups</i> operation returns information about a particular /// replication group. If no identifier is specified, <i>DescribeReplicationGroups</i> /// returns information about all replication groups. /// </summary> /// /// <returns>The response from the DescribeReplicationGroups service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> public DescribeReplicationGroupsResponse DescribeReplicationGroups() { return DescribeReplicationGroups(new DescribeReplicationGroupsRequest()); } /// <summary> /// The <i>DescribeReplicationGroups</i> operation returns information about a particular /// replication group. If no identifier is specified, <i>DescribeReplicationGroups</i> /// returns information about all replication groups. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationGroups service method.</param> /// /// <returns>The response from the DescribeReplicationGroups service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> public DescribeReplicationGroupsResponse DescribeReplicationGroups(DescribeReplicationGroupsRequest request) { var marshaller = new DescribeReplicationGroupsRequestMarshaller(); var unmarshaller = DescribeReplicationGroupsResponseUnmarshaller.Instance; return Invoke<DescribeReplicationGroupsRequest,DescribeReplicationGroupsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeReplicationGroups operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReplicationGroups operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeReplicationGroupsResponse> DescribeReplicationGroupsAsync(DescribeReplicationGroupsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeReplicationGroupsRequestMarshaller(); var unmarshaller = DescribeReplicationGroupsResponseUnmarshaller.Instance; return InvokeAsync<DescribeReplicationGroupsRequest,DescribeReplicationGroupsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeReservedCacheNodes /// <summary> /// The <i>DescribeReservedCacheNodes</i> operation returns information about reserved /// cache nodes for this account, or about a specified reserved cache node. /// </summary> /// /// <returns>The response from the DescribeReservedCacheNodes service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReservedCacheNodeNotFoundException"> /// The requested reserved cache node was not found. /// </exception> public DescribeReservedCacheNodesResponse DescribeReservedCacheNodes() { return DescribeReservedCacheNodes(new DescribeReservedCacheNodesRequest()); } /// <summary> /// The <i>DescribeReservedCacheNodes</i> operation returns information about reserved /// cache nodes for this account, or about a specified reserved cache node. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodes service method.</param> /// /// <returns>The response from the DescribeReservedCacheNodes service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReservedCacheNodeNotFoundException"> /// The requested reserved cache node was not found. /// </exception> public DescribeReservedCacheNodesResponse DescribeReservedCacheNodes(DescribeReservedCacheNodesRequest request) { var marshaller = new DescribeReservedCacheNodesRequestMarshaller(); var unmarshaller = DescribeReservedCacheNodesResponseUnmarshaller.Instance; return Invoke<DescribeReservedCacheNodesRequest,DescribeReservedCacheNodesResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeReservedCacheNodes operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeReservedCacheNodesResponse> DescribeReservedCacheNodesAsync(DescribeReservedCacheNodesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeReservedCacheNodesRequestMarshaller(); var unmarshaller = DescribeReservedCacheNodesResponseUnmarshaller.Instance; return InvokeAsync<DescribeReservedCacheNodesRequest,DescribeReservedCacheNodesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeReservedCacheNodesOfferings /// <summary> /// The <i>DescribeReservedCacheNodesOfferings</i> operation lists available reserved /// cache node offerings. /// </summary> /// /// <returns>The response from the DescribeReservedCacheNodesOfferings service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReservedCacheNodesOfferingNotFoundException"> /// The requested cache node offering does not exist. /// </exception> public DescribeReservedCacheNodesOfferingsResponse DescribeReservedCacheNodesOfferings() { return DescribeReservedCacheNodesOfferings(new DescribeReservedCacheNodesOfferingsRequest()); } /// <summary> /// The <i>DescribeReservedCacheNodesOfferings</i> operation lists available reserved /// cache node offerings. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodesOfferings service method.</param> /// /// <returns>The response from the DescribeReservedCacheNodesOfferings service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReservedCacheNodesOfferingNotFoundException"> /// The requested cache node offering does not exist. /// </exception> public DescribeReservedCacheNodesOfferingsResponse DescribeReservedCacheNodesOfferings(DescribeReservedCacheNodesOfferingsRequest request) { var marshaller = new DescribeReservedCacheNodesOfferingsRequestMarshaller(); var unmarshaller = DescribeReservedCacheNodesOfferingsResponseUnmarshaller.Instance; return Invoke<DescribeReservedCacheNodesOfferingsRequest,DescribeReservedCacheNodesOfferingsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeReservedCacheNodesOfferings operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeReservedCacheNodesOfferings operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeReservedCacheNodesOfferingsResponse> DescribeReservedCacheNodesOfferingsAsync(DescribeReservedCacheNodesOfferingsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeReservedCacheNodesOfferingsRequestMarshaller(); var unmarshaller = DescribeReservedCacheNodesOfferingsResponseUnmarshaller.Instance; return InvokeAsync<DescribeReservedCacheNodesOfferingsRequest,DescribeReservedCacheNodesOfferingsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DescribeSnapshots /// <summary> /// The <i>DescribeSnapshots</i> operation returns information about cache cluster snapshots. /// By default, <i>DescribeSnapshots</i> lists all of your snapshots; it can optionally /// describe a single snapshot, or just the snapshots associated with a particular cache /// cluster. /// </summary> /// /// <returns>The response from the DescribeSnapshots service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="SnapshotNotFoundException"> /// The requested snapshot name does not refer to an existing snapshot. /// </exception> public DescribeSnapshotsResponse DescribeSnapshots() { return DescribeSnapshots(new DescribeSnapshotsRequest()); } /// <summary> /// The <i>DescribeSnapshots</i> operation returns information about cache cluster snapshots. /// By default, <i>DescribeSnapshots</i> lists all of your snapshots; it can optionally /// describe a single snapshot, or just the snapshots associated with a particular cache /// cluster. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="SnapshotNotFoundException"> /// The requested snapshot name does not refer to an existing snapshot. /// </exception> public DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance; return Invoke<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DescribeSnapshotsRequestMarshaller(); var unmarshaller = DescribeSnapshotsResponseUnmarshaller.Instance; return InvokeAsync<DescribeSnapshotsRequest,DescribeSnapshotsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ModifyCacheCluster /// <summary> /// The <i>ModifyCacheCluster</i> operation modifies the settings for a cache cluster. /// You can use this operation to change one or more cluster configuration parameters /// by specifying the parameters and the new values. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyCacheCluster service method.</param> /// /// <returns>The response from the ModifyCacheCluster service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InsufficientCacheClusterCapacityException"> /// The requested cache node type is not available in the specified Availability Zone. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidCacheSecurityGroupStateException"> /// The current state of the cache security group does not allow deletion. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidVPCNetworkStateException"> /// The VPC network is in an invalid state. /// </exception> /// <exception cref="NodeQuotaForClusterExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes in a single cache cluster. /// </exception> /// <exception cref="NodeQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes per customer. /// </exception> public ModifyCacheClusterResponse ModifyCacheCluster(ModifyCacheClusterRequest request) { var marshaller = new ModifyCacheClusterRequestMarshaller(); var unmarshaller = ModifyCacheClusterResponseUnmarshaller.Instance; return Invoke<ModifyCacheClusterRequest,ModifyCacheClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ModifyCacheCluster operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ModifyCacheClusterResponse> ModifyCacheClusterAsync(ModifyCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ModifyCacheClusterRequestMarshaller(); var unmarshaller = ModifyCacheClusterResponseUnmarshaller.Instance; return InvokeAsync<ModifyCacheClusterRequest,ModifyCacheClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ModifyCacheParameterGroup /// <summary> /// The <i>ModifyCacheParameterGroup</i> operation modifies the parameters of a cache /// parameter group. You can modify up to 20 parameters in a single request by submitting /// a list parameter name and value pairs. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyCacheParameterGroup service method.</param> /// /// <returns>The response from the ModifyCacheParameterGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidCacheParameterGroupStateException"> /// The current state of the cache parameter group does not allow the requested action /// to occur. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ModifyCacheParameterGroupResponse ModifyCacheParameterGroup(ModifyCacheParameterGroupRequest request) { var marshaller = new ModifyCacheParameterGroupRequestMarshaller(); var unmarshaller = ModifyCacheParameterGroupResponseUnmarshaller.Instance; return Invoke<ModifyCacheParameterGroupRequest,ModifyCacheParameterGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ModifyCacheParameterGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheParameterGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ModifyCacheParameterGroupResponse> ModifyCacheParameterGroupAsync(ModifyCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ModifyCacheParameterGroupRequestMarshaller(); var unmarshaller = ModifyCacheParameterGroupResponseUnmarshaller.Instance; return InvokeAsync<ModifyCacheParameterGroupRequest,ModifyCacheParameterGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ModifyCacheSubnetGroup /// <summary> /// The <i>ModifyCacheSubnetGroup</i> operation modifies an existing cache subnet group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyCacheSubnetGroup service method.</param> /// /// <returns>The response from the ModifyCacheSubnetGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheSubnetGroupNotFoundException"> /// The requested cache subnet group name does not refer to an existing cache subnet group. /// </exception> /// <exception cref="CacheSubnetQuotaExceededException"> /// The request cannot be processed because it would exceed the allowed number of subnets /// in a cache subnet group. /// </exception> /// <exception cref="InvalidSubnetException"> /// An invalid subnet identifier was specified. /// </exception> /// <exception cref="SubnetInUseException"> /// The requested subnet is being used by another cache subnet group. /// </exception> public ModifyCacheSubnetGroupResponse ModifyCacheSubnetGroup(ModifyCacheSubnetGroupRequest request) { var marshaller = new ModifyCacheSubnetGroupRequestMarshaller(); var unmarshaller = ModifyCacheSubnetGroupResponseUnmarshaller.Instance; return Invoke<ModifyCacheSubnetGroupRequest,ModifyCacheSubnetGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ModifyCacheSubnetGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyCacheSubnetGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ModifyCacheSubnetGroupResponse> ModifyCacheSubnetGroupAsync(ModifyCacheSubnetGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ModifyCacheSubnetGroupRequestMarshaller(); var unmarshaller = ModifyCacheSubnetGroupResponseUnmarshaller.Instance; return InvokeAsync<ModifyCacheSubnetGroupRequest,ModifyCacheSubnetGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ModifyReplicationGroup /// <summary> /// The <i>ModifyReplicationGroup</i> operation modifies the settings for a replication /// group. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationGroup service method.</param> /// /// <returns>The response from the ModifyReplicationGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InsufficientCacheClusterCapacityException"> /// The requested cache node type is not available in the specified Availability Zone. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidCacheSecurityGroupStateException"> /// The current state of the cache security group does not allow deletion. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="InvalidReplicationGroupStateException"> /// The requested replication group is not in the <i>available</i> state. /// </exception> /// <exception cref="InvalidVPCNetworkStateException"> /// The VPC network is in an invalid state. /// </exception> /// <exception cref="NodeQuotaForClusterExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes in a single cache cluster. /// </exception> /// <exception cref="NodeQuotaForCustomerExceededException"> /// The request cannot be processed because it would exceed the allowed number of cache /// nodes per customer. /// </exception> /// <exception cref="ReplicationGroupNotFoundException"> /// The specified replication group does not exist. /// </exception> public ModifyReplicationGroupResponse ModifyReplicationGroup(ModifyReplicationGroupRequest request) { var marshaller = new ModifyReplicationGroupRequestMarshaller(); var unmarshaller = ModifyReplicationGroupResponseUnmarshaller.Instance; return Invoke<ModifyReplicationGroupRequest,ModifyReplicationGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ModifyReplicationGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ModifyReplicationGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ModifyReplicationGroupResponse> ModifyReplicationGroupAsync(ModifyReplicationGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ModifyReplicationGroupRequestMarshaller(); var unmarshaller = ModifyReplicationGroupResponseUnmarshaller.Instance; return InvokeAsync<ModifyReplicationGroupRequest,ModifyReplicationGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region PurchaseReservedCacheNodesOffering /// <summary> /// The <i>PurchaseReservedCacheNodesOffering</i> operation allows you to purchase a reserved /// cache node offering. /// </summary> /// <param name="request">Container for the necessary parameters to execute the PurchaseReservedCacheNodesOffering service method.</param> /// /// <returns>The response from the PurchaseReservedCacheNodesOffering service method, as returned by ElastiCache.</returns> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> /// <exception cref="ReservedCacheNodeAlreadyExistsException"> /// You already have a reservation with the given identifier. /// </exception> /// <exception cref="ReservedCacheNodeQuotaExceededException"> /// The request cannot be processed because it would exceed the user's cache node quota. /// </exception> /// <exception cref="ReservedCacheNodesOfferingNotFoundException"> /// The requested cache node offering does not exist. /// </exception> public PurchaseReservedCacheNodesOfferingResponse PurchaseReservedCacheNodesOffering(PurchaseReservedCacheNodesOfferingRequest request) { var marshaller = new PurchaseReservedCacheNodesOfferingRequestMarshaller(); var unmarshaller = PurchaseReservedCacheNodesOfferingResponseUnmarshaller.Instance; return Invoke<PurchaseReservedCacheNodesOfferingRequest,PurchaseReservedCacheNodesOfferingResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the PurchaseReservedCacheNodesOffering operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PurchaseReservedCacheNodesOffering operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<PurchaseReservedCacheNodesOfferingResponse> PurchaseReservedCacheNodesOfferingAsync(PurchaseReservedCacheNodesOfferingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new PurchaseReservedCacheNodesOfferingRequestMarshaller(); var unmarshaller = PurchaseReservedCacheNodesOfferingResponseUnmarshaller.Instance; return InvokeAsync<PurchaseReservedCacheNodesOfferingRequest,PurchaseReservedCacheNodesOfferingResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RebootCacheCluster /// <summary> /// The <i>RebootCacheCluster</i> operation reboots some, or all, of the cache nodes within /// a provisioned cache cluster. This API will apply any modified cache parameter groups /// to the cache cluster. The reboot action takes place as soon as possible, and results /// in a momentary outage to the cache cluster. During the reboot, the cache cluster status /// is set to REBOOTING. /// /// /// <para> /// The reboot causes the contents of the cache (for each cache node being rebooted) to /// be lost. /// </para> /// /// <para> /// When the reboot is complete, a cache cluster event is created. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RebootCacheCluster service method.</param> /// /// <returns>The response from the RebootCacheCluster service method, as returned by ElastiCache.</returns> /// <exception cref="CacheClusterNotFoundException"> /// The requested cache cluster ID does not refer to an existing cache cluster. /// </exception> /// <exception cref="InvalidCacheClusterStateException"> /// The requested cache cluster is not in the <i>available</i> state. /// </exception> public RebootCacheClusterResponse RebootCacheCluster(RebootCacheClusterRequest request) { var marshaller = new RebootCacheClusterRequestMarshaller(); var unmarshaller = RebootCacheClusterResponseUnmarshaller.Instance; return Invoke<RebootCacheClusterRequest,RebootCacheClusterResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RebootCacheCluster operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RebootCacheCluster operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RebootCacheClusterResponse> RebootCacheClusterAsync(RebootCacheClusterRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RebootCacheClusterRequestMarshaller(); var unmarshaller = RebootCacheClusterResponseUnmarshaller.Instance; return InvokeAsync<RebootCacheClusterRequest,RebootCacheClusterResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ResetCacheParameterGroup /// <summary> /// The <i>ResetCacheParameterGroup</i> operation modifies the parameters of a cache parameter /// group to the engine or system default value. You can reset specific parameters by /// submitting a list of parameter names. To reset the entire cache parameter group, specify /// the <i>ResetAllParameters</i> and <i>CacheParameterGroupName</i> parameters. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ResetCacheParameterGroup service method.</param> /// /// <returns>The response from the ResetCacheParameterGroup service method, as returned by ElastiCache.</returns> /// <exception cref="CacheParameterGroupNotFoundException"> /// The requested cache parameter group name does not refer to an existing cache parameter /// group. /// </exception> /// <exception cref="InvalidCacheParameterGroupStateException"> /// The current state of the cache parameter group does not allow the requested action /// to occur. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public ResetCacheParameterGroupResponse ResetCacheParameterGroup(ResetCacheParameterGroupRequest request) { var marshaller = new ResetCacheParameterGroupRequestMarshaller(); var unmarshaller = ResetCacheParameterGroupResponseUnmarshaller.Instance; return Invoke<ResetCacheParameterGroupRequest,ResetCacheParameterGroupResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ResetCacheParameterGroup operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ResetCacheParameterGroup operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ResetCacheParameterGroupResponse> ResetCacheParameterGroupAsync(ResetCacheParameterGroupRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ResetCacheParameterGroupRequestMarshaller(); var unmarshaller = ResetCacheParameterGroupResponseUnmarshaller.Instance; return InvokeAsync<ResetCacheParameterGroupRequest,ResetCacheParameterGroupResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region RevokeCacheSecurityGroupIngress /// <summary> /// The <i>RevokeCacheSecurityGroupIngress</i> operation revokes ingress from a cache /// security group. Use this operation to disallow access from an Amazon EC2 security /// group that had been previously authorized. /// </summary> /// <param name="request">Container for the necessary parameters to execute the RevokeCacheSecurityGroupIngress service method.</param> /// /// <returns>The response from the RevokeCacheSecurityGroupIngress service method, as returned by ElastiCache.</returns> /// <exception cref="AuthorizationNotFoundException"> /// The specified Amazon EC2 security group is not authorized for the specified cache /// security group. /// </exception> /// <exception cref="CacheSecurityGroupNotFoundException"> /// The requested cache security group name does not refer to an existing cache security /// group. /// </exception> /// <exception cref="InvalidCacheSecurityGroupStateException"> /// The current state of the cache security group does not allow deletion. /// </exception> /// <exception cref="InvalidParameterCombinationException"> /// Two or more incompatible parameters were specified. /// </exception> /// <exception cref="InvalidParameterValueException"> /// The value for a parameter is invalid. /// </exception> public RevokeCacheSecurityGroupIngressResponse RevokeCacheSecurityGroupIngress(RevokeCacheSecurityGroupIngressRequest request) { var marshaller = new RevokeCacheSecurityGroupIngressRequestMarshaller(); var unmarshaller = RevokeCacheSecurityGroupIngressResponseUnmarshaller.Instance; return Invoke<RevokeCacheSecurityGroupIngressRequest,RevokeCacheSecurityGroupIngressResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the RevokeCacheSecurityGroupIngress operation. /// <seealso cref="Amazon.ElastiCache.IAmazonElastiCache"/> /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RevokeCacheSecurityGroupIngress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<RevokeCacheSecurityGroupIngressResponse> RevokeCacheSecurityGroupIngressAsync(RevokeCacheSecurityGroupIngressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new RevokeCacheSecurityGroupIngressRequestMarshaller(); var unmarshaller = RevokeCacheSecurityGroupIngressResponseUnmarshaller.Instance; return InvokeAsync<RevokeCacheSecurityGroupIngressRequest,RevokeCacheSecurityGroupIngressResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion } }
53.210678
240
0.675059
[ "Apache-2.0" ]
ermshiperete/aws-sdk-net
AWSSDK_DotNet45/Amazon.ElastiCache/AmazonElastiCacheClient.cs
129,568
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.Enterprise.V1Alpha2 { [OutputType] public sealed class LicenseMasterSpecVolumesGitRepo { /// <summary> /// Target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name. /// </summary> public readonly string Directory; /// <summary> /// Repository URL /// </summary> public readonly string Repository; /// <summary> /// Commit hash for the specified revision. /// </summary> public readonly string Revision; [OutputConstructor] private LicenseMasterSpecVolumesGitRepo( string directory, string repository, string revision) { Directory = directory; Repository = repository; Revision = revision; } } }
30.790698
251
0.635196
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/splunk/dotnet/Kubernetes/Crds/Operators/Splunk/Enterprise/V1Alpha2/Outputs/LicenseMasterSpecVolumesGitRepo.cs
1,324
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts; using Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts.Definition; using Microsoft.VisualStudio.Services.ReleaseManagement.WebApi.Contracts; using Microsoft.VisualStudio.Services.WebApi; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Services.Agent.Worker.Release.Artifacts { public class JenkinsArtifact : AgentService, IArtifactExtension { public Type ExtensionType => typeof(IArtifactExtension); public AgentArtifactType ArtifactType => AgentArtifactType.Jenkins; private const char Backslash = '\\'; private const char ForwardSlash = '/'; public static int CommitDataVersion = 1; public static string CommitIdKey = "commitId"; public static string CommitDateKey = "date"; public static string AuthorKey = "author"; public static string FullNameKey = "fullName"; public static string CommitMessageKey = "msg"; public static string RepoKindKey = "kind"; public static string RemoteUrlsKey = "remoteUrls"; public static string GitRepoName = "git"; public async Task DownloadAsync( IExecutionContext executionContext, ArtifactDefinition artifactDefinition, string localFolderPath) { ArgUtil.NotNull(artifactDefinition, nameof(artifactDefinition)); ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNullOrEmpty(localFolderPath, nameof(localFolderPath)); var jenkinsDetails = artifactDefinition.Details as JenkinsArtifactDetails; executionContext.Output(StringUtil.Loc("RMGotJenkinsArtifactDetails")); executionContext.Output(StringUtil.Loc("RMJenkinsJobName", jenkinsDetails.JobName)); executionContext.Output(StringUtil.Loc("RMJenkinsBuildId", jenkinsDetails.BuildId)); IGenericHttpClient client = HostContext.GetService<IGenericHttpClient>(); if (!IsValidBuild(client, jenkinsDetails)) { throw new ArtifactDownloadException(StringUtil.Loc("RMJenkinsInvalidBuild", jenkinsDetails.BuildId)); } Stream downloadedStream = null; string downloadArtifactsUrl = string.Format( CultureInfo.InvariantCulture, "{0}/job/{1}/{2}/artifact/{3}/*zip*/", jenkinsDetails.Url, jenkinsDetails.JobName, jenkinsDetails.BuildId, jenkinsDetails.RelativePath); executionContext.Output(StringUtil.Loc("RMPrepareToGetFromJenkinsServer")); HttpResponseMessage response = client.GetAsync(downloadArtifactsUrl, jenkinsDetails.AccountName, jenkinsDetails.AccountPassword, jenkinsDetails.AcceptUntrustedCertificates).Result; if (response.IsSuccessStatusCode) { downloadedStream = response.Content.ReadAsStreamAsync().Result; } else if (response.StatusCode == HttpStatusCode.NotFound) { executionContext.Warning(StringUtil.Loc("RMJenkinsNoArtifactsFound", jenkinsDetails.BuildId)); return; } else { throw new ArtifactDownloadException(StringUtil.Loc("RMDownloadArtifactUnexpectedError")); } var parentFolder = GetParentFolderName(jenkinsDetails.RelativePath); Trace.Info($"Found parentFolder {parentFolder} for relative path {jenkinsDetails.RelativePath}"); executionContext.Output(StringUtil.Loc("RMDownloadingJenkinsArtifacts")); var zipStreamDownloader = HostContext.GetService<IZipStreamDownloader>(); await zipStreamDownloader.DownloadFromStream( executionContext, downloadedStream, string.IsNullOrEmpty(parentFolder) ? "archive" : string.Empty, parentFolder, localFolderPath); } public async Task DownloadCommitsAsync(IExecutionContext context, ArtifactDefinition artifactDefinition, string commitsWorkFolder) { Trace.Entering(); var jenkinsDetails = artifactDefinition.Details as JenkinsArtifactDetails; int startJobId = 0, endJobId = 0; if (!string.IsNullOrEmpty(jenkinsDetails.EndCommitArtifactVersion)) { if (int.TryParse(jenkinsDetails.EndCommitArtifactVersion, out endJobId)) { context.Output(StringUtil.Loc("RMDownloadingCommits")); if (int.TryParse(jenkinsDetails.StartCommitArtifactVersion, out startJobId)) { if (startJobId < endJobId) { context.Output(StringUtil.Loc("DownloadingJenkinsCommitsBetween", startJobId, endJobId)); } else if (startJobId > endJobId) { context.Output(StringUtil.Loc("JenkinsRollbackDeployment", startJobId, endJobId)); // swap the job IDs to fetch the roll back commits int swap = startJobId; startJobId = endJobId; endJobId = swap; } else if (startJobId == endJobId) { context.Output(StringUtil.Loc("JenkinsNoCommitsToFetch")); return; } } else { context.Debug(StringUtil.Loc("JenkinsDownloadingChangeFromCurrentBuild")); } try { IEnumerable<Change> changes = await DownloadCommits(context, jenkinsDetails, startJobId, endJobId); if (changes.Any()) { string commitsFileName = GetCommitsFileName(jenkinsDetails.Alias); string commitsFilePath = Path.Combine(commitsWorkFolder, commitsFileName); context.Debug($"Commits will be written to {commitsFilePath}"); WriteCommitsToFile(context, changes, commitsFilePath); context.Debug($"Commits written to {commitsFilePath}"); context.QueueAttachFile(CoreAttachmentType.FileAttachment, commitsFileName, commitsFilePath); } } catch (Exception ex) { context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("DownloadingJenkinsCommitsFailedWithException", jenkinsDetails.Alias, ex.ToString()) }); return; } } else { context.AddIssue(new Issue { Type=IssueType.Warning, Message = StringUtil.Loc("JenkinsCommitsInvalidEndJobId", jenkinsDetails.EndCommitArtifactVersion, jenkinsDetails.Alias) }); return; } } else { context.Debug("No commit details found in the agent artifact. Not downloading the commits"); } } private string GetCommitsFileName(string artifactAlias) { return StringUtil.Format("commits_{0}_v{1}.json", artifactAlias, CommitDataVersion); } private void WriteCommitsToFile(IExecutionContext context, IEnumerable<Change> commits, string commitsFilePath) { IOUtil.DeleteFile(commitsFilePath); if (commits.Any()) { using(StreamWriter sw = File.CreateText(commitsFilePath)) using(JsonTextWriter jw = new JsonTextWriter(sw)) { jw.Formatting = Formatting.Indented; jw.WriteStartArray(); foreach (Change commit in commits) { JObject.FromObject(commit).WriteTo(jw); } jw.WriteEnd(); } } } private Change ConvertCommitToChange(IExecutionContext context, JToken token, bool isGitRepo, string rootUrl) { Trace.Entering(); // Use mustache parser? Change change = new Change(); var resultDictionary = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(token.ToString()); if (resultDictionary.ContainsKey(CommitIdKey)) { change.Id = resultDictionary[CommitIdKey].ToString(); } if (resultDictionary.ContainsKey(CommitMessageKey)) { change.Message = resultDictionary[CommitMessageKey].ToString(); } if (resultDictionary.ContainsKey(AuthorKey)) { string authorDetail = resultDictionary[AuthorKey].ToString(); var author = JsonConvert.DeserializeObject<Dictionary<string, string>>(authorDetail); change.Author = new IdentityRef { DisplayName = author[FullNameKey] }; } if (resultDictionary.ContainsKey(CommitDateKey)) { DateTime value; if (DateTime.TryParse(resultDictionary[CommitDateKey].ToString(), out value)) { change.Timestamp = value; } } if (isGitRepo && !string.IsNullOrEmpty(rootUrl)) { change.DisplayUri = new Uri(StringUtil.Format("{0}/commit/{1}", rootUrl, change.Id)); } context.Debug(StringUtil.Format("Found commit {0}", change.Id)); return change; } private Tuple<int, int> GetCommitJobIdIndex(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int startJobId, int endJobId) { Trace.Entering(); string url = StringUtil.Format("{0}/job/{1}/api/json?tree=allBuilds[number]", artifactDetails.Url, artifactDetails.JobName); int startIndex = -1, endIndex = -1, index = 0; var listOfBuildResult = DownloadCommitsJsonContent(context, url, artifactDetails, "$.allBuilds[*].number").Result; foreach (JToken token in listOfBuildResult) { long value = 0; if (long.TryParse((string)token, out value)) { if (value == startJobId) { startIndex = index; } if (value == endJobId) { endIndex = index; } if (startIndex > 0 && endIndex > 0) { break; } index++; } } context.Debug(StringUtil.Format("Found startIndex {0} and endIndex {1}", startIndex, endIndex)); if (startIndex < 0 || endIndex < 0) { throw new CommitsDownloadException(StringUtil.Loc("JenkinsBuildDoesNotExistsForCommits", startJobId, endJobId, startIndex, endIndex)); } return Tuple.Create<int, int>(startIndex, endIndex); } private async Task<IEnumerable<Change>> DownloadCommits(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int jobId) { context.Output(StringUtil.Format("Getting changeSet associated with build {0} ", jobId)); string commitsUrl = StringUtil.Format("{0}/job/{1}/{2}/api/json?tree=number,result,changeSet[items[commitId,date,msg,author[fullName]]]", artifactDetails.Url, artifactDetails.JobName, jobId); var commitsResult = await DownloadCommitsJsonContent(context, commitsUrl, artifactDetails, "$.changeSet.items[*]"); string rootUrl; bool isGitRepo = IsGitRepo(context, artifactDetails, jobId, out rootUrl); return commitsResult.Select(x => ConvertCommitToChange(context, x, isGitRepo, rootUrl)); } private async Task<IEnumerable<Change>> DownloadCommits(IExecutionContext context, JenkinsArtifactDetails artifactDetails, int startJobId, int endJobId) { Trace.Entering(); if (startJobId == 0) { context.Debug($"StartJobId does not exist, downloading changeSet from build {endJobId}"); return await DownloadCommits(context, artifactDetails, endJobId); } //#1. Figure out the index of build numbers Tuple<int, int> result = GetCommitJobIdIndex(context, artifactDetails, startJobId, endJobId); int startIndex = result.Item1; int endIndex = result.Item2; //#2. Download the commits using range string buildParameter = (startIndex >= 100 || endIndex >= 100) ? "allBuilds" : "builds"; // jenkins by default will return only 100 top builds. Have to use "allBuilds" if we are dealing with build which are older than 100 builds string commitsUrl = StringUtil.Format("{0}/job/{1}/api/json?tree={2}[number,result,changeSet[items[commitId,date,msg,author[fullName]]]]{{{3},{4}}}", artifactDetails.Url, artifactDetails.JobName, buildParameter, endIndex, startIndex); var changeSetResult = await DownloadCommitsJsonContent(context, commitsUrl, artifactDetails, StringUtil.Format("$.{0}[*].changeSet.items[*]", buildParameter)); string rootUrl; bool isGitRepo = IsGitRepo(context, artifactDetails, endJobId, out rootUrl); return changeSetResult.Select(x => ConvertCommitToChange(context, x, isGitRepo, rootUrl)); } private async Task<string> DownloadCommitsJsonContent(IExecutionContext executionContext, string url, JenkinsArtifactDetails artifactDetails) { Trace.Entering(); executionContext.Debug($"Querying Jenkins server with the api {url}"); string result = await HostContext.GetService<IGenericHttpClient>() .GetStringAsync(url, artifactDetails.AccountName, artifactDetails.AccountPassword, artifactDetails.AcceptUntrustedCertificates); if (!string.IsNullOrEmpty(result)) { executionContext.Debug($"Found result from Jenkins server: {result}"); } return result; } private async Task<IEnumerable<JToken>> DownloadCommitsJsonContent(IExecutionContext executionContext, string url, JenkinsArtifactDetails artifactDetails, string jsonPath) { Trace.Entering(); string result = await DownloadCommitsJsonContent(executionContext, url, artifactDetails); if (!string.IsNullOrEmpty(result)) { executionContext.Debug($"result will be filtered with {jsonPath}"); return ParseToken(result, jsonPath); } return new List<JToken>(); } private bool IsGitRepo(IExecutionContext executionContext, JenkinsArtifactDetails artifactDetails, int jobId, out string rootUrl) { bool isGitRepo = false; rootUrl = string.Empty; executionContext.Debug("Checking if Jenkins job uses git scm"); string repoUrl = StringUtil.Format("{0}/job/{1}/{2}/api/json?tree=actions[remoteUrls],changeSet[kind]", artifactDetails.Url, artifactDetails.JobName, jobId); var repoResult = DownloadCommitsJsonContent(executionContext, repoUrl, artifactDetails).Result; if (repoResult != null) { executionContext.Debug($"repo query result from Jenkins api {repoResult.ToString()}"); var repoKindResult = ParseToken(repoResult.ToString(), "$.changeSet.kind"); if (repoKindResult != null && repoKindResult.Any()) { string repoKind = repoKindResult.First().ToString(); executionContext.Debug($"Parsed repo result {repoKind}"); if (!string.IsNullOrEmpty(repoKind) && repoKind.Equals(GitRepoName, StringComparison.OrdinalIgnoreCase)) { executionContext.Debug("Its a git repo, checking if it has root url"); var rootUrlResult = ParseToken(repoResult.ToString(), "$.actions[?(@.remoteUrls)]"); if (rootUrlResult != null && rootUrlResult.Any()) { var resultDictionary = JsonConvert.DeserializeObject<Dictionary<string, JToken>>(rootUrlResult.First().ToString()); if (resultDictionary.ContainsKey(RemoteUrlsKey) && resultDictionary[RemoteUrlsKey].Any()) { rootUrl = resultDictionary[RemoteUrlsKey].First().ToString(); isGitRepo = true; executionContext.Debug($"Found the git repo root url {rootUrl}"); } } } } } return isGitRepo; } private IEnumerable<JToken> ParseToken(string jsonResult, string jsonPath) { JObject parsedJson = JObject.Parse(jsonResult); return parsedJson.SelectTokens(jsonPath); } public IArtifactDetails GetArtifactDetails(IExecutionContext context, AgentArtifactDefinition agentArtifactDefinition) { Trace.Entering(); var artifactDetails = JsonConvert.DeserializeObject<Dictionary<string, string>>(agentArtifactDefinition.Details); ServiceEndpoint jenkinsEndpoint = context.Endpoints.FirstOrDefault(e => string.Equals(e.Name, artifactDetails["ConnectionName"], StringComparison.OrdinalIgnoreCase)); if (jenkinsEndpoint == null) { throw new InvalidOperationException(StringUtil.Loc("RMJenkinsEndpointNotFound", agentArtifactDefinition.Name)); } string relativePath; var jobName = string.Empty; var allFieldsPresents = artifactDetails.TryGetValue("RelativePath", out relativePath) && artifactDetails.TryGetValue("JobName", out jobName); bool acceptUntrusted = jenkinsEndpoint.Data != null && jenkinsEndpoint.Data.ContainsKey("acceptUntrustedCerts") && StringUtil.ConvertToBoolean(jenkinsEndpoint.Data["acceptUntrustedCerts"]); string startCommitArtifactVersion = string.Empty; string endCommitArtifactVersion = string.Empty; artifactDetails.TryGetValue("StartCommitArtifactVersion", out startCommitArtifactVersion); artifactDetails.TryGetValue("EndCommitArtifactVersion", out endCommitArtifactVersion); if (allFieldsPresents) { return new JenkinsArtifactDetails { RelativePath = relativePath, AccountName = jenkinsEndpoint.Authorization.Parameters[EndpointAuthorizationParameters.Username], AccountPassword = jenkinsEndpoint.Authorization.Parameters[EndpointAuthorizationParameters.Password], BuildId = Convert.ToInt32(agentArtifactDefinition.Version, CultureInfo.InvariantCulture), JobName = jobName, Url = jenkinsEndpoint.Url, AcceptUntrustedCertificates = acceptUntrusted, StartCommitArtifactVersion = startCommitArtifactVersion, EndCommitArtifactVersion = endCommitArtifactVersion, Alias = agentArtifactDefinition.Alias }; } else { throw new InvalidOperationException(StringUtil.Loc("RMArtifactDetailsIncomplete")); } } private bool IsValidBuild(IGenericHttpClient client, JenkinsArtifactDetails jenkinsDetails) { var buildUrl = string.Format( CultureInfo.InvariantCulture, "{0}/job/{1}/{2}/", jenkinsDetails.Url, jenkinsDetails.JobName, jenkinsDetails.BuildId); HttpResponseMessage response = client.GetAsync(buildUrl, jenkinsDetails.AccountName, jenkinsDetails.AccountPassword, jenkinsDetails.AcceptUntrustedCertificates).Result; return response.IsSuccessStatusCode; } private static string GetParentFolderName(string relativePath) { // Sometime the Jenkins artifact relative path would be simply / indicating read from root. This will retrun empty string at such scenarios. return relativePath.TrimEnd(Backslash).TrimEnd(ForwardSlash).Replace(Backslash, ForwardSlash).Split(ForwardSlash).Last(); } } }
47.539957
246
0.596293
[ "MIT" ]
BobSilent/azure-pipelines-agent
src/Agent.Worker/Release/Artifacts/JenkinsArtifact.cs
22,011
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using FluentAssertions; using Microsoft.Toolkit.Collections; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using System.Linq; namespace UnitTests.Collections { [TestClass] public class ObservableGroupedCollectionTests { [TestCategory("Collections")] [TestMethod] public void Ctor_ShouldHaveExpectedValues() { var groupCollection = new ObservableGroupedCollection<string, int>(); groupCollection.Should().BeEmpty(); } [TestCategory("Collections")] [TestMethod] public void Ctor_WithGroups_ShouldHaveExpectedValues() { var groups = new List<IGrouping<string, int>> { new IntGroup("A", new[] { 1, 3, 5 }), new IntGroup("B", new[] { 2, 4, 6 }), }; var groupCollection = new ObservableGroupedCollection<string, int>(groups); groupCollection.Should().HaveCount(2); groupCollection.ElementAt(0).Key.Should().Be("A"); groupCollection.ElementAt(0).Should().BeEquivalentTo(new[] { 1, 3, 5 }, o => o.WithStrictOrdering()); groupCollection.ElementAt(1).Key.Should().Be("B"); groupCollection.ElementAt(1).Should().BeEquivalentTo(new[] { 2, 4, 6 }, o => o.WithStrictOrdering()); } } }
35.909091
113
0.632911
[ "MIT" ]
Cyberh1/WindowsCommunityToolkit
UnitTests/Collections/ObservableGroupedCollectionTests.cs
1,582
C#
using System; using AutoMapper; using NodaTime; namespace Elsa.Mapping { public class NodaTimeProfile : Profile, ITypeConverter<Instant, DateTime>, ITypeConverter<Instant?, DateTime?>, ITypeConverter<DateTime, Instant>, ITypeConverter<DateTime?, Instant?> { public NodaTimeProfile() { CreateMap<Instant, DateTime>().ConvertUsing(this); CreateMap<Instant?, DateTime?>().ConvertUsing(this); CreateMap<DateTime, Instant>().ConvertUsing(this); CreateMap<DateTime?, Instant?>().ConvertUsing(this); } public DateTime Convert(Instant source, DateTime target, ResolutionContext context) => source.ToDateTimeUtc(); public DateTime? Convert(Instant? source, DateTime? target, ResolutionContext context) => source?.ToDateTimeUtc(); public Instant Convert(DateTime source, Instant target, ResolutionContext context) => Convert(source); public Instant? Convert(DateTime? source, Instant? target, ResolutionContext context) => source != null ? Convert(source.Value) : default(Instant?); public Instant Convert(DateTime source) { var utcDateTime = source.Kind == DateTimeKind.Unspecified ? DateTime.SpecifyKind(source, DateTimeKind.Utc) : source.ToUniversalTime(); return Instant.FromDateTimeUtc(utcDateTime); } } }
41.257143
156
0.657202
[ "MIT" ]
1002527441/elsa-core
src/core/Elsa.Core/Mapping/NodaTimeProfile.cs
1,444
C#
namespace TherapeuticStudio.Test.Pipeline { using MyTested.AspNetCore.Mvc; using System; using TherapeuticStudio.Controllers; using TherapeuticStudio.Services.Clients; using TherapeuticStudio.Services.Payments; using TherapeuticStudio.Services.Procedures; using TherapeuticStudio.Test.Data; using Xunit; using static Data.PaymentTest; using static Data.TestConstants; public class PaymentsControllerTest { [Fact] public void GetPaymentPipeReturnUnaoutorized() => MyMvc .Pipeline() .ShouldMap(paymentRouteGetByDates) .To<PaymentController>(p => p.GetDates(DateTimeNow.ToUniversalTime().ToString("R"))) .Which(controller => controller .ShouldReturn() .Unauthorized()); [Fact] public void GetPaymentPipeAdmiUserReturnOk() => MyMvc .Pipeline() .ShouldMap(paymentRouteGetByDates) .To<PaymentController>(p => p.GetDates(DateTimeNow.ToUniversalTime().ToString("R"))) .Which(controller => controller.WithUser(user => user.InRole("Administrator")) .ShouldReturn() .Ok()); } }
31.488372
104
0.575332
[ "MIT" ]
georgidocoff/ASP.NET-Core-Project-Therapeutic-Studio
Tests/TherapeuticStudio.Test/Pipeline/PaymentsControllerTest.cs
1,356
C#
using ResizetizerNT_svg_log_issue.Models; using ResizetizerNT_svg_log_issue.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using Xamarin.Forms; namespace ResizetizerNT_svg_log_issue.ViewModels { public class BaseViewModel : INotifyPropertyChanged { public IDataStore<Item> DataStore => DependencyService.Get<IDataStore<Item>>(); bool isBusy = false; public bool IsBusy { get { return isBusy; } set { SetProperty(ref isBusy, value); } } string title = string.Empty; public string Title { get { return title; } set { SetProperty(ref title, value); } } protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName] string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = "") { var changed = PropertyChanged; if (changed == null) return; changed.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
29.127273
87
0.616729
[ "MIT" ]
bondarenkod/ResizetizerNT_issues1
ResizetizerNT_svg_log_issue/ResizetizerNT_svg_log_issue/ViewModels/BaseViewModel.cs
1,604
C#