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 |
|---|---|---|---|---|---|---|---|---|
namespace SDRSharp.HeatMapView
{
partial class SettingsPanel
{
/// <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.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsPanel));
this.TopPanel = new System.Windows.Forms.Panel();
this.HelpButton = new System.Windows.Forms.Button();
this.EditButton = new System.Windows.Forms.Button();
this.PlusButton = new System.Windows.Forms.Button();
this.MinusButton = new System.Windows.Forms.Button();
this.EnabledCheckBox = new System.Windows.Forms.CheckBox();
this.ListBox = new System.Windows.Forms.ListBox();
this.OpenFileDialog = new System.Windows.Forms.OpenFileDialog();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.TopPanel.SuspendLayout();
this.SuspendLayout();
//
// TopPanel
//
this.TopPanel.Controls.Add(this.HelpButton);
this.TopPanel.Controls.Add(this.EditButton);
this.TopPanel.Controls.Add(this.PlusButton);
this.TopPanel.Controls.Add(this.MinusButton);
this.TopPanel.Controls.Add(this.EnabledCheckBox);
this.TopPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.TopPanel.Location = new System.Drawing.Point(0, 0);
this.TopPanel.Name = "TopPanel";
this.TopPanel.Size = new System.Drawing.Size(250, 30);
this.TopPanel.TabIndex = 2;
//
// HelpButton
//
this.HelpButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.HelpButton.Image = ((System.Drawing.Image)(resources.GetObject("HelpButton.Image")));
this.HelpButton.Location = new System.Drawing.Point(231, 10);
this.HelpButton.Name = "HelpButton";
this.HelpButton.Size = new System.Drawing.Size(19, 19);
this.HelpButton.TabIndex = 6;
this.toolTip1.SetToolTip(this.HelpButton, "Online Help");
this.HelpButton.UseVisualStyleBackColor = true;
this.HelpButton.Click += new System.EventHandler(this.HelpButton_Click);
//
// EditButton
//
this.EditButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.EditButton.Image = ((System.Drawing.Image)(resources.GetObject("EditButton.Image")));
this.EditButton.Location = new System.Drawing.Point(213, 10);
this.EditButton.Name = "EditButton";
this.EditButton.Size = new System.Drawing.Size(19, 19);
this.EditButton.TabIndex = 5;
this.toolTip1.SetToolTip(this.EditButton, "Rename heat map");
this.EditButton.UseVisualStyleBackColor = true;
this.EditButton.Click += new System.EventHandler(this.EditButton_Click);
//
// PlusButton
//
this.PlusButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.PlusButton.Image = ((System.Drawing.Image)(resources.GetObject("PlusButton.Image")));
this.PlusButton.Location = new System.Drawing.Point(177, 10);
this.PlusButton.Name = "PlusButton";
this.PlusButton.Size = new System.Drawing.Size(19, 19);
this.PlusButton.TabIndex = 4;
this.toolTip1.SetToolTip(this.PlusButton, "Create heat map from rtl_sdr data");
this.PlusButton.UseVisualStyleBackColor = true;
this.PlusButton.Click += new System.EventHandler(this.PlusButton_Click);
//
// MinusButton
//
this.MinusButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.MinusButton.Image = ((System.Drawing.Image)(resources.GetObject("MinusButton.Image")));
this.MinusButton.Location = new System.Drawing.Point(195, 10);
this.MinusButton.Name = "MinusButton";
this.MinusButton.Size = new System.Drawing.Size(19, 19);
this.MinusButton.TabIndex = 3;
this.toolTip1.SetToolTip(this.MinusButton, "Delete heat nap");
this.MinusButton.UseVisualStyleBackColor = true;
this.MinusButton.Click += new System.EventHandler(this.MinusButton_Click);
//
// EnabledCheckBox
//
this.EnabledCheckBox.AutoSize = true;
this.EnabledCheckBox.Location = new System.Drawing.Point(3, 3);
this.EnabledCheckBox.Name = "EnabledCheckBox";
this.EnabledCheckBox.Size = new System.Drawing.Size(65, 17);
this.EnabledCheckBox.TabIndex = 2;
this.EnabledCheckBox.Text = "Enabled";
this.EnabledCheckBox.UseVisualStyleBackColor = true;
this.EnabledCheckBox.CheckedChanged += new System.EventHandler(this.EnabledCheckBox_CheckedChanged);
//
// ListBox
//
this.ListBox.DisplayMember = "Name";
this.ListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.ListBox.FormattingEnabled = true;
this.ListBox.IntegralHeight = false;
this.ListBox.Location = new System.Drawing.Point(0, 30);
this.ListBox.Name = "ListBox";
this.ListBox.Size = new System.Drawing.Size(250, 146);
this.ListBox.TabIndex = 3;
this.ListBox.DoubleClick += new System.EventHandler(this.ListBox_DoubleClick);
//
// OpenFileDialog
//
this.OpenFileDialog.DefaultExt = "txt";
this.OpenFileDialog.Filter = "rtl_power files (*.csv)|*.csv|All files (*.*)|*.*";
this.OpenFileDialog.Title = "Import rtl_power Output File";
//
// SettingsPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.ListBox);
this.Controls.Add(this.TopPanel);
this.Name = "SettingsPanel";
this.Size = new System.Drawing.Size(250, 176);
this.TopPanel.ResumeLayout(false);
this.TopPanel.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel TopPanel;
private System.Windows.Forms.Button PlusButton;
private System.Windows.Forms.Button MinusButton;
private System.Windows.Forms.CheckBox EnabledCheckBox;
private System.Windows.Forms.ListBox ListBox;
private System.Windows.Forms.Button HelpButton;
private System.Windows.Forms.Button EditButton;
private System.Windows.Forms.OpenFileDialog OpenFileDialog;
private System.Windows.Forms.ToolTip toolTip1;
}
}
| 46.08589 | 156 | 0.676651 | [
"MIT"
] | VE3NEA/HeatMapView | SDRSharp.HeatMapView/SettingsPanel.Designer.cs | 7,514 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/anjdreas/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\UnitClasses\MyUnit.extra.cs files to add code to generated unit classes.
// Add Extensions\MyUnitExtensions.cs to decorate unit classes with new behavior.
// Add UnitDefinitions\MyUnit.json and run GeneratUnits.bat to generate new units or unit classes.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Copyright (c) 2007 Andreas Gullberg Larsen (anjdreas@gmail.com).
// https://github.com/anjdreas/UnitsNet
//
// 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.
// ReSharper disable once CheckNamespace
namespace UnitsNet.Units
{
public enum DurationUnit
{
Undefined = 0,
Day,
Hour,
Microsecond,
Millisecond,
Minute,
Month,
Nanosecond,
Second,
Week,
Year,
}
}
| 41.157895 | 102 | 0.667519 | [
"MIT"
] | Egor92/UnitsNet | UnitsNet/GeneratedCode/Enums/DurationUnit.g.cs | 2,348 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Tke.V20180525.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeRouteTableConflictsResponse : AbstractModel
{
/// <summary>
/// 路由表是否冲突。
/// </summary>
[JsonProperty("HasConflict")]
public bool? HasConflict{ get; set; }
/// <summary>
/// 路由表冲突列表。
/// 注意:此字段可能返回 null,表示取不到有效值。
/// </summary>
[JsonProperty("RouteTableConflictSet")]
public RouteTableConflict[] RouteTableConflictSet{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// 内部实现,用户禁止调用
/// </summary>
internal override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "HasConflict", this.HasConflict);
this.SetParamArrayObj(map, prefix + "RouteTableConflictSet.", this.RouteTableConflictSet);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 31.779661 | 102 | 0.6416 | [
"Apache-2.0"
] | Darkfaker/tencentcloud-sdk-dotnet | TencentCloud/Tke/V20180525/Models/DescribeRouteTableConflictsResponse.cs | 2,027 | C# |
using CountersPlus.Config;
using BeatSaberMarkupLanguage;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using HMUI;
using CountersPlus.UI.ViewControllers;
using CountersPlus.Utils;
using CountersPlus.Custom;
using CountersPlus.UI.ViewControllers.ConfigModelControllers;
namespace CountersPlus.UI
{
class CountersPlusSettingsFlowCoordinator : FlowCoordinator
{
private Vector3 MainScreenPosition;
private GameObject MainScreen;
private CountersPlusFillerForMainViewController placeholder;
private CountersPlusEditViewController editSettings;
private CountersPlusCreditsViewController credits;
private CountersPlusHorizontalSettingsListViewController horizSettingsList;
private CountersPlusBottomSettingsSelectorViewController bottomSettings;
internal static CountersPlusSettingsFlowCoordinator Instance;
protected override void DidActivate(bool firstActivation, ActivationType activationType)
{
MainScreen = GameObject.Find("MainScreen");
MainScreenPosition = MainScreen.transform.position;
if (firstActivation && activationType == ActivationType.AddedToHierarchy)
{
Instance = this;
title = "Counters+";
showBackButton = true;
editSettings = BeatSaberUI.CreateViewController<CountersPlusEditViewController>();
placeholder = BeatSaberUI.CreateViewController<CountersPlusFillerForMainViewController>();
horizSettingsList = BeatSaberUI.CreateViewController<CountersPlusHorizontalSettingsListViewController>();
bottomSettings = BeatSaberUI.CreateViewController<CountersPlusBottomSettingsSelectorViewController>();
credits = BeatSaberUI.CreateViewController<CountersPlusCreditsViewController>();
}
PushViewControllerToNavigationController(bottomSettings, horizSettingsList);
ProvideInitialViewControllers(placeholder, credits, editSettings, bottomSettings);
MainScreen.transform.position = new Vector3(0, -100, 0); //"If it works it's not stupid"
CounterWarning.Create("Due to limitations, some counters may not reflect their true appearance in-game.", 7.5f);
if (!Plugin.UpToDate) CounterWarning.Create("A new Counters+ update is available to download!", 5);
StartCoroutine(InitMockCounters());
}
protected override void DidDeactivate(DeactivationType deactivationType)
{
}
private IEnumerator InitMockCounters()
{
yield return new WaitForEndOfFrame();
MockCounterInfo info = new MockCounterInfo();
MockCounter.CreateStatic("Combo", $"{info.notesCut}");
MockCounter.CreateStatic("Multiplier", "x8");
UpdateMockCounters();
}
internal static void UpdateMockCounters()
{
foreach (KeyValuePair<MockCounterGroup, ConfigModel> kvp in MockCounter.loadedMockCounters)
{
Destroy(kvp.Key.CounterName);
Destroy(kvp.Key.CounterData);
}
if (TextHelper.CounterCanvas != null) Destroy(TextHelper.CounterCanvas.gameObject);
TextHelper.CounterCanvas = null;
List<ConfigModel> loadedModels = TypesUtility.GetListOfType<ConfigModel>();
loadedModels = loadedModels.Where(x => !(x is CustomConfigModel)).ToList();
loadedModels.ForEach(x => x = ConfigLoader.DeserializeFromConfig(x, x.DisplayName) as ConfigModel);
foreach (CustomCounter potential in CustomCounterCreator.LoadedCustomCounters)
loadedModels.Add(potential.ConfigModel);
loadedModels.RemoveAll(x => x is null);
foreach (ConfigModel counter in loadedModels) MockCounter.Update(counter);
}
protected override void BackButtonWasPressed(ViewController controller)
{
foreach (KeyValuePair<MockCounterGroup, ConfigModel> kvp in MockCounter.loadedMockCounters)
{
Destroy(kvp.Key.CounterName);
Destroy(kvp.Key.CounterData);
}
CountersPlusEditViewController.ClearScreen();
MockCounter.loadedMockCounters.Clear();
CounterWarning.ClearAllWarnings();
Destroy(TextHelper.CounterCanvas.gameObject);
TextHelper.CounterCanvas = null;
MainScreen.transform.position = MainScreenPosition;
MainFlowCoordinator mainFlow = Resources.FindObjectsOfTypeAll<MainFlowCoordinator>().First();
mainFlow.InvokePrivateMethod("DismissFlowCoordinator", new object[] { this, null, false });
ConfigModelController.ClearAllControllers();
//Reload settings from config
CountersController.settings = ConfigLoader.LoadSettings();
}
}
}
| 47.377358 | 124 | 0.68419 | [
"MIT"
] | DonTrolav/CountersPlus | Counters+/UI/CountersPlusSettingsFlowCoordinator.cs | 5,024 | C# |
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
namespace Teronis.ModuleInitializer.AssemblyLoader.Utils
{
public static class ModuleDefinitionUtils
{
public static IEnumerable<MethodDefinition> FindModuleInitializerMethods(ModuleDefinition module)
{
var moduleInitializerClasses = module
.GetTypes()
.Where(x => x.Name == "ModuleInitializer").ToList();
if (moduleInitializerClasses.Count == 0) {
throw new InjectionException(@"Could not find any type with the name 'ModuleInitializer' and content
public static class ModuleInitializer
{
public static void Initialize()
{
//code goes here
}
}");
}
foreach (var moduleInitializer in moduleInitializerClasses) {
var initializeMethod = moduleInitializer.Methods.FirstOrDefault(x => x.Name == "Initialize");
if (initializeMethod == null) {
throw new InjectionException($"Could not find the method 'Initialize' in type '{moduleInitializer.FullName}'.");
}
if (!initializeMethod.IsPublic) {
throw new InjectionException($"The method '{initializeMethod.FullName}' is not public.");
}
if (!initializeMethod.IsStatic) {
throw new InjectionException($"The method '{initializeMethod.FullName}' is not static.");
}
if (initializeMethod.Parameters.Count > 0) {
throw new InjectionException($"The method '{initializeMethod.FullName}' cannot have parameters.");
}
yield return initializeMethod;
}
}
}
}
| 35.48 | 132 | 0.601466 | [
"MIT"
] | DawidIzydor/Teronis.DotNet | src/ModuleInitializer/AssemblyLoader/0/src/Utils/ModuleDefinitionUtils.cs | 1,776 | 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Serilog.Sinks.Trace.Tests")]
[assembly: AssemblyTrademark("")]
// 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("1d56534c-4009-42c2-a573-789cae6b8aa9")]
| 41.75 | 84 | 0.782036 | [
"Apache-2.0"
] | Cheesebaron/serilog-sinks-trace | test/Serilog.Sinks.Trace.Tests/Properties/AssemblyInfo.cs | 837 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.Elasticsearch")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Elasticsearch Service. Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch domains.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Elasticsearch Service. Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch domains.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Amazon Elasticsearch Service. Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch domains.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Elasticsearch Service. Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch domains.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Elasticsearch Service. Use the Amazon Elasticsearch configuration API to create, configure, and manage Elasticsearch domains.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.1.18")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 51 | 224 | 0.778024 | [
"Apache-2.0"
] | altso/aws-sdk-net | sdk/src/Services/Elasticsearch/Properties/AssemblyInfo.cs | 2,703 | 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("AWSSDK.ComprehendMedical")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Comprehend Medical. The first release of Comprehend Medical includes two APIs, detectPHI and detectEntities. DetectPHI extracts PHI from your clinical text, and detectEntities extracts entities such as medication, medical conditions, or anatomy. DetectEntities also extracts attributes (e.g. dosage for medication) and identifies contextual traits (e.g. negation) for each entity.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.0.67")] | 54.21875 | 464 | 0.763112 | [
"Apache-2.0"
] | motoko89/aws-sdk-net-xamarin | sdk/code-analysis/ServiceAnalysis/ComprehendMedical/Properties/AssemblyInfo.cs | 1,735 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class AnimatedSprite : MonoBehaviour {
// A struct for a individual animation.
[System.Serializable]
public class SpriteAnimation {
public string name = "Unnamed";
public float fps = 30;
public int xOffset = 0;
public int yOffset = 0;
public int frameWidth = 100;
public int frameHeight = 100;
public Texture texture = null;
public int xStartTile = 0;
public int yStartTile = 0;
public int frameCount = 1;
}
// A list containing all the animations for this object.
public List<SpriteAnimation> Animations = new List<SpriteAnimation>();
// The current animation
public string CurrentAnimation;
// A dictionary to store all the animations by name.
private Dictionary<string, SpriteAnimation> animations = new Dictionary<string, SpriteAnimation>();
// The timer.
private float timer = 0;
// Whether or not the sprite is flipped horizontally
public bool FlippedHor = false;
public bool FlippedVer = false;
// Public functions
public void ChangeAnimation(string _name, bool _resetTimer) {
CurrentAnimation = _name;
if (_resetTimer)
timer = 0;
}
public void SetFPS(float fps)
{
SpriteAnimation current;
if (animations.TryGetValue(CurrentAnimation, out current))
{
// Change the time passed to be as if it was at this fps.
float frame = timer * current.fps;
current.fps = fps;
timer = frame / current.fps;
}
}
// Use this for initialization
void Start () {
// Fill out the dictionary.
animations.Clear();
foreach (SpriteAnimation anim in Animations) {
animations.Add(anim.name, anim);
}
}
// Update is called once per frame
void Update () {
// Increment the timer
timer += Time.deltaTime;
// Set the UVs for this object.
UpdateRect();
}
// Calculate the area of the image that should be shown at this time.
void UpdateRect() {
// If the current animation cannot be found, then don't do anything.
if (!animations.ContainsKey(CurrentAnimation))
return;
// Get the current animation.
SpriteAnimation current = animations[CurrentAnimation];
// Calculate which frame we are on.
int frame = (int)(timer * current.fps) % current.frameCount;
// Get the area on the texture to use as the UVs
int x = (current.xStartTile * current.frameWidth) + current.xOffset + (current.frameWidth * (frame % (current.texture.width / current.frameWidth)));
int y = (current.yStartTile * current.frameHeight) + current.yOffset + (current.frameHeight * (frame / (current.texture.width / current.frameWidth)));
// Get the mesh filter and mesh.
MeshFilter meshFilter = GetComponent<MeshFilter>();
Mesh mesh = meshFilter.mesh;
// Set the texture.
gameObject.renderer.material.mainTexture = current.texture;
// Set the uvs.
Vector2[] uvs = new Vector2[4];
if (!FlippedHor && !FlippedVer) {
uvs[3].x = (float)x / current.texture.width;
uvs[3].y = 1 - ((float)y / current.texture.height);
uvs[0].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[0].y = 1 - ((float)y / current.texture.height);
uvs[1].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[1].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
uvs[2].x = (float)x / current.texture.width;
uvs[2].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
} else if (FlippedVer && !FlippedHor) {
uvs[2].x = (float)x / current.texture.width;
uvs[2].y = 1 - ((float)y / current.texture.height);
uvs[1].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[1].y = 1 - ((float)y / current.texture.height);
uvs[0].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[0].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
uvs[3].x = (float)x / current.texture.width;
uvs[3].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
} else if (FlippedHor && !FlippedVer) {
uvs[0].x = (float)x / current.texture.width;
uvs[3].y = 1 - ((float)y / current.texture.height);
uvs[3].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[0].y = 1 - ((float)y / current.texture.height);
uvs[2].x = (float)(x + current.frameWidth) / current.texture.width;
uvs[1].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
uvs[1].x = (float)x / current.texture.width;
uvs[2].y = 1 - ((float)(y + current.frameHeight) / current.texture.height);
}
mesh.uv = uvs;
}
}
| 34.469697 | 152 | 0.677143 | [
"BSD-2-Clause"
] | Pillowdrift/StellarSwingClassic | Assets/Scripts/AnimatedSprite.cs | 4,550 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Data.Pdf;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace ComicViewer.ComicModel
{
public class PDFPage : IPageBitmap
{
private PdfDocument _pdfDocument;
private uint _pageNo;
private static PdfPageRenderOptions _defaultOptions;
public static void SetDefaultPageSize(Size pageSize)
{
_defaultOptions = new PdfPageRenderOptions();
_defaultOptions.BackgroundColor = Windows.UI.Colors.Beige;
_defaultOptions.DestinationHeight = (uint)pageSize.Height;
_defaultOptions.DestinationWidth = (uint)pageSize.Width;
}
public PDFPage(PdfDocument pdfDocument, uint pageNo)
{
_pdfDocument = pdfDocument;
_pageNo = pageNo;
}
public void RenderImage(InMemoryRandomAccessStream streamToWriteTo, uint width, uint height)
{
using (PdfPage _page = _pdfDocument.GetPage(_pageNo))
{
PdfPageRenderOptions renderOptions = new PdfPageRenderOptions();
renderOptions.BackgroundColor = _defaultOptions.BackgroundColor;
renderOptions.IsIgnoringHighContrast = false;
Size newSize = ResizeImage(_defaultOptions.DestinationWidth, _defaultOptions.DestinationHeight, _page.Size.Width, _page.Size.Height);
renderOptions.DestinationWidth = (uint)newSize.Width;
renderOptions.DestinationHeight = (uint)newSize.Height;
_page.RenderToStreamAsync(streamToWriteTo, renderOptions).AsTask().Wait();
}
}
public void RenderImage(InMemoryRandomAccessStream streamToWriteTo)
{
using (PdfPage _page = _pdfDocument.GetPage(_pageNo))
{
PdfPageRenderOptions renderOptions = new PdfPageRenderOptions();
renderOptions.BackgroundColor = _defaultOptions.BackgroundColor;
renderOptions.IsIgnoringHighContrast = false;
Size newSize = ResizeImage(_defaultOptions.DestinationWidth, _defaultOptions.DestinationHeight, _page.Dimensions.ArtBox.Width, _page.Dimensions.ArtBox.Height);
renderOptions.DestinationWidth = (uint)newSize.Width;
renderOptions.DestinationHeight = (uint)newSize.Height;
_page.RenderToStreamAsync(streamToWriteTo, renderOptions).AsTask().Wait();
}
}
private Size ResizeImage(double canvasWidth, double canvasHeight, double originalWidth, double originalHeight)
{
// Figure out the ratio
double ratioX = canvasWidth / originalWidth;
//double ratioY = canvasHeight / originalHeight;
// use whichever multiplier is smaller
double ratio = ratioX;// > ratioY ? ratioX : ratioY;
// now we can get the new height and width
Size retVal = new Size();
retVal.Height = Convert.ToInt32(originalHeight * ratio);
retVal.Width = Convert.ToInt32(originalWidth * ratio);
return retVal;
}
}
}
| 41.730769 | 175 | 0.657757 | [
"MIT"
] | softkannan/komicreader | uwpapp/ComicViewer/ComicModel/PDFPage.cs | 3,257 | C# |
namespace Be.Vlaanderen.Basisregisters.ProjectionHandling.Syndication
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Logging;
using Microsoft.SyndicationFeed;
using Microsoft.SyndicationFeed.Atom;
public interface IRegistryAtomFeedReader
{
/// <summary>
/// Reads the entries of an Atom feed at the provided feedUrl.
/// </summary>
/// <returns>A list of <see cref="IAtomEntry "/>.</returns>
Task<IEnumerable<IAtomEntry>> ReadEntriesAsync(Uri feedUrl, long? from, string feedUserName = "", string feedPassword = "", bool embedEvent = true, bool embedObject = true);
}
public class RegistryAtomFeedReader : IRegistryAtomFeedReader
{
public const string HttpClientName = "registryFeedClient";
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
public RegistryAtomFeedReader(IHttpClientFactory httpClientFactory, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger<RegistryAtomFeedReader>();
_httpClient = httpClientFactory.CreateClient(HttpClientName);
}
public async Task<IEnumerable<IAtomEntry>> ReadEntriesAsync(
Uri feedUrl,
long? from,
string feedUserName = "",
string feedPassword = "",
bool embedEvent = true,
bool embedObject = true)
{
var entries = new List<IAtomEntry>();
var embedString = string.Empty;
if (embedObject && embedEvent)
embedString = "embed: \"event,object\"";
else if (embedObject)
embedString = "embed: \"object\"";
else if (embedEvent)
embedString = "embed: \"event\"";
_httpClient.DefaultRequestHeaders.Remove("X-Filtering");
if (from.HasValue)
{
var filter = string.IsNullOrEmpty(embedString) ? $"{{ position: {@from} }}" : $"{{ position: {@from}, {embedString} }}";
_httpClient.DefaultRequestHeaders.Add("X-Filtering", filter);
}
else
_httpClient.DefaultRequestHeaders.Add("X-Filtering", $"{{ {embedString} }}");
if (!string.IsNullOrEmpty(feedUserName) && !string.IsNullOrEmpty(feedPassword))
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{feedUserName}:{feedPassword}")));
try
{
using (var response = await _httpClient.GetAsync(feedUrl))
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var xmlReader = XmlReader.Create(responseStream, new XmlReaderSettings { Async = true }))
{
var atomReader = new AtomFeedReader(xmlReader);
while (await atomReader.Read())
{
if (atomReader.ElementType == SyndicationElementType.Item)
entries.Add(await atomReader.ReadEntry());
}
}
}
catch (Exception e)
{
_logger.LogError(e.Message, e);
throw;
}
return entries;
}
}
}
| 38.619565 | 187 | 0.58908 | [
"MIT"
] | ArneD/projection-handling | src/Be.Vlaanderen.Basisregisters.ProjectionHandling.Syndication/RegistryAtomFeedReader.cs | 3,553 | C# |
using System;
using NUnit.Framework;
namespace Netronics.Test
{
[TestFixture]
public class PacketBufferTest
{
[Test]
public void PacketBufferTest1()
{
PacketBuffer buffer = new PacketBuffer();
buffer.Dispose();
try
{
buffer.Write(1);
}
catch (Exception) { return; }
throw new Exception("error");
}
[Test]
public void PacketBufferInt16Test()
{
var buffer = new PacketBuffer();
buffer.WriteInt16(1);
buffer.WriteInt16(0);
buffer.WriteInt16(0);
buffer.WriteInt16(5);
buffer.BeginBufferIndex();
long m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadInt16();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferInt32Test()
{
var buffer = new PacketBuffer();
buffer.WriteInt32(1);
buffer.WriteInt32(0);
buffer.WriteInt32(0);
buffer.WriteInt32(5);
buffer.BeginBufferIndex();
long m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadInt32();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferInt64Test()
{
var buffer = new PacketBuffer();
buffer.WriteInt64(1);
buffer.WriteInt64(0);
buffer.WriteInt64(0);
buffer.WriteInt64(5);
buffer.BeginBufferIndex();
long m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadInt64();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferUInt16Test()
{
var buffer = new PacketBuffer();
buffer.WriteUInt16(1);
buffer.WriteUInt16(0);
buffer.WriteUInt16(0);
buffer.WriteUInt16(5);
buffer.BeginBufferIndex();
long m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadUInt16();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferUInt32Test()
{
var buffer = new PacketBuffer();
buffer.WriteUInt32(1);
buffer.WriteUInt32(0);
buffer.WriteUInt32(0);
buffer.WriteUInt32(5);
buffer.BeginBufferIndex();
long m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadUInt32();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferUInt64Test()
{
var buffer = new PacketBuffer();
buffer.WriteUInt64(1);
buffer.WriteUInt64(0);
buffer.WriteUInt64(0);
buffer.WriteUInt64(5);
buffer.BeginBufferIndex();
ulong m = 0;
for (int i = 0; i < 4; i++)
m += buffer.ReadUInt64();
if (m != 6)
{
throw new Exception("PacketBuffer error");
}
}
[Test]
public void PacketBufferByteTest()
{
var buffer = new PacketBuffer();
buffer.WriteByte(1);
buffer.WriteByte(0);
buffer.WriteByte(0);
buffer.WriteByte(5);
buffer.BeginBufferIndex();
if(buffer.ReadByte() != 1)
throw new Exception("PacketBuffer error");
if (buffer.ReadByte() != 0)
throw new Exception("PacketBuffer error");
if (buffer.ReadByte() != 0)
throw new Exception("PacketBuffer error");
if (buffer.ReadByte() != 5)
throw new Exception("PacketBuffer error");
}
[Test]
public void PacketBufferBytesTest()
{
var data = new byte[] {1, 0, 0, 5};
var buffer = new PacketBuffer();
buffer.WriteBytes(data);
buffer.BeginBufferIndex();
var temp = buffer.ReadBytes(4);
for (int i = 0; i < temp.Length; i++)
{
if(temp[i] != data[i])
throw new Exception("PacketBuffer error");
}
}
}
}
| 26.220994 | 62 | 0.446481 | [
"MIT"
] | shlee322/Netronics | server/Test/Framework/PacketBufferTest.cs | 4,748 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.ExceptionServices;
namespace Microsoft.AspNetCore.Mvc.Filters;
/// <summary>
/// A context for resource filters, specifically <see cref="IResourceFilter.OnResourceExecuted"/> calls.
/// </summary>
public class ResourceExecutedContext : FilterContext
{
private Exception? _exception;
private ExceptionDispatchInfo? _exceptionDispatchInfo;
/// <summary>
/// Creates a new <see cref="ResourceExecutedContext"/>.
/// </summary>
/// <param name="actionContext">The <see cref="ActionContext"/>.</param>
/// <param name="filters">The list of <see cref="IFilterMetadata"/> instances.</param>
public ResourceExecutedContext(ActionContext actionContext, IList<IFilterMetadata> filters)
: base(actionContext, filters)
{
}
/// <summary>
/// Gets or sets a value which indicates whether or not execution was canceled by a resource filter.
/// If true, then a resource filter short-circuited execution by setting
/// <see cref="ResourceExecutingContext.Result"/>.
/// </summary>
public virtual bool Canceled { get; set; }
/// <summary>
/// Gets or set the current <see cref="Exception"/>.
/// </summary>
/// <remarks>
/// <para>
/// Setting <see cref="Exception"/> or <see cref="ExceptionDispatchInfo"/> to <c>null</c> will treat
/// the exception as handled, and it will not be rethrown by the runtime.
/// </para>
/// <para>
/// Setting <see cref="ExceptionHandled"/> to <c>true</c> will also mark the exception as handled.
/// </para>
/// </remarks>
public virtual Exception? Exception
{
get
{
if (_exception == null && _exceptionDispatchInfo != null)
{
return _exceptionDispatchInfo.SourceException;
}
else
{
return _exception;
}
}
set
{
_exceptionDispatchInfo = null;
_exception = value;
}
}
/// <summary>
/// Gets or set the current <see cref="Exception"/>.
/// </summary>
/// <remarks>
/// <para>
/// Setting <see cref="Exception"/> or <see cref="ExceptionDispatchInfo"/> to <c>null</c> will treat
/// the exception as handled, and it will not be rethrown by the runtime.
/// </para>
/// <para>
/// Setting <see cref="ExceptionHandled"/> to <c>true</c> will also mark the exception as handled.
/// </para>
/// </remarks>
public virtual ExceptionDispatchInfo? ExceptionDispatchInfo
{
get
{
return _exceptionDispatchInfo;
}
set
{
_exception = null;
_exceptionDispatchInfo = value;
}
}
/// <summary>
/// <para>
/// Gets or sets a value indicating whether or not the current <see cref="Exception"/> has been handled.
/// </para>
/// <para>
/// If <c>false</c> the <see cref="Exception"/> will be rethrown by the runtime after resource filters
/// have executed.
/// </para>
/// </summary>
public virtual bool ExceptionHandled { get; set; }
/// <summary>
/// Gets or sets the result.
/// </summary>
/// <remarks>
/// <para>
/// The <see cref="Result"/> may be provided by execution of the action itself or by another
/// filter.
/// </para>
/// <para>
/// The <see cref="Result"/> has already been written to the response before being made available
/// to resource filters.
/// </para>
/// </remarks>
public virtual IActionResult? Result { get; set; }
}
| 31.864407 | 108 | 0.598404 | [
"MIT"
] | 3ejki/aspnetcore | src/Mvc/Mvc.Abstractions/src/Filters/ResourceExecutedContext.cs | 3,760 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace TestServer
{
public class ServerStartup
{
public ServerStartup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddServerSideBlazor();
services.AddSingleton<ResourceRequestLog>();
// Since tests run in parallel, we use an ephemeral key provider to avoid filesystem
// contention issues.
services.AddSingleton<IDataProtectionProvider, EphemeralDataProtectionProvider>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
{
var enUs = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = enUs;
CultureInfo.DefaultThreadCurrentUICulture = enUs;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Mount the server-side Blazor app on /subdir
app.Map("/subdir", app =>
{
app.Use((context, next) =>
{
if (context.Request.Path.Value.EndsWith("/images/blazor_logo_1000x.png", StringComparison.Ordinal))
{
resourceRequestLog.AddRequest(context.Request);
}
return next(context);
});
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapControllerRoute("mvc", "{controller}/{action}");
endpoints.MapFallbackToPage("/_ServerHost");
});
});
}
}
}
| 34.945946 | 119 | 0.604408 | [
"MIT"
] | vchy1997/aspnetcore | src/Components/test/testassets/TestServer/ServerStartup.cs | 2,586 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using GraphQL.Types;
using Shouldly;
using Xunit;
using System.Threading.Tasks;
namespace GraphQL.Tests.Execution
{
public class ResolveFieldContextTests
{
private readonly ResolveFieldContext _context;
public ResolveFieldContextTests()
{
_context = new ResolveFieldContext();
_context.Arguments = new Dictionary<string, object>();
_context.Errors = new ExecutionErrors();
}
[Fact]
public void argument_converts_int_to_long()
{
int val = 1;
_context.Arguments["a"] = val;
var result = _context.GetArgument<long>("a");
result.ShouldBe(1);
}
[Fact]
public void argument_converts_long_to_int()
{
long val = 1;
_context.Arguments["a"] = val;
var result = _context.GetArgument<int>("a");
result.ShouldBe(1);
}
[Fact]
public void argument_returns_boxed_string_uncast()
{
_context.Arguments["a"] = "one";
var result = _context.GetArgument<object>("a");
result.ShouldBe("one");
}
[Fact]
public void argument_returns_long()
{
long val = 1000000000000001;
_context.Arguments["a"] = val;
var result = _context.GetArgument<long>("a");
result.ShouldBe(1000000000000001);
}
[Fact]
public void argument_returns_enum()
{
_context.Arguments["a"] = SomeEnum.Two;
var result = _context.GetArgument<SomeEnum>("a");
result.ShouldBe(SomeEnum.Two);
}
[Fact]
public void argument_returns_enum_from_string()
{
_context.Arguments["a"] = "two";
var result = _context.GetArgument<SomeEnum>("a");
result.ShouldBe(SomeEnum.Two);
}
[Fact]
public void argument_returns_enum_from_number()
{
_context.Arguments["a"] = 1;
var result = _context.GetArgument<SomeEnum>("a");
result.ShouldBe(SomeEnum.Two);
}
[Fact]
public void argument_returns_default_when_missing()
{
_context.GetArgument<string>("wat").ShouldBeNull();
}
[Fact]
public void argument_returns_provided_default_when_missing()
{
_context.GetArgument<string>("wat", "foo").ShouldBe("foo");
}
[Fact]
public void argument_returns_list_from_array()
{
_context.Arguments = "{a: ['one', 'two']}".ToInputs();
var result = _context.GetArgument<List<string>>("a");
result.ShouldNotBeNull();
result.Count.ShouldBe(2);
result[0].ShouldBe("one");
result[1].ShouldBe("two");
}
[Fact]
public async void try_resolve_async_adds_exception_message()
{
var result = await _context.TryAsyncResolve(c => throw new InvalidOperationException("Test Error"));
_context.Errors.First().Message.ShouldBe("Test Error");
}
[Fact]
public async void try_resolve_sets_inner_exception()
{
var exception = new Exception("Test");
var result = await _context.TryAsyncResolve(
c => throw exception);
_context.Errors.First().InnerException.ShouldBe(exception);
}
[Fact]
public async void try_resolve_async_invokes_error_handler()
{
var result = await _context.TryAsyncResolve(
c => throw new InvalidOperationException(),
e => {
e.Add(new ExecutionError("Test Error"));
return null;
}
);
_context.Errors.First().Message.ShouldBe("Test Error");
}
[Fact]
public async void try_resolve_async_properly_resolves_result()
{
var result = await _context.TryAsyncResolve(
c => Task.FromResult<object>("Test Result")
);
result.ShouldBe("Test Result");
}
enum SomeEnum
{
One,
Two
}
}
}
| 29.241611 | 112 | 0.546706 | [
"MIT"
] | Bill-Manning/graphql-dotnet | src/GraphQL.Tests/Execution/ResolveFieldContextTests.cs | 4,357 | C# |
//
// System.Net.NetworkInformation.PingCompletedEventHandler
//
// Author:
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2006 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
namespace System.Net.NetworkInformation {
public delegate void PingCompletedEventHandler (object sender, PingCompletedEventArgs e);
}
#endif
| 41.882353 | 90 | 0.764045 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/class/System/System.Net.NetworkInformation/PingCompletedEventHandler.cs | 1,424 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace jp.netsis.VRMScreenShot
{
public static class EnumExtension
{
public static bool TryParse<T>(string s, out T temp) where T : struct
{
return Enum.TryParse(s, out temp) && Enum.IsDefined(typeof(T), temp);
}
}
} | 25 | 82 | 0.64 | [
"MIT"
] | jp-netsis/VRMScreenShot | Assets/_VRMScreenShot/Scripts/Utilities/EnumExtension.cs | 375 | C# |
namespace Merchello.Web.Search
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using Core;
using Core.Models;
using Core.Persistence.Querying;
using Core.Services;
using Examine;
using global::Examine;
using global::Examine.Providers;
using Merchello.Core.Chains;
using Merchello.Core.ValueConverters;
using Merchello.Examine.Providers;
using Merchello.Web.Caching;
using Merchello.Web.DataModifiers;
using Merchello.Web.DataModifiers.Product;
using Merchello.Web.Models;
using Merchello.Web.Models.ContentEditing.Content;
using Merchello.Web.Models.VirtualContent;
using Models.ContentEditing;
using Models.Querying;
using Umbraco.Core.Cache;
using Umbraco.Core.Events;
/// <summary>
/// Represents a CachedProductQuery
/// </summary>
internal class CachedProductQuery : CachedQueryableCollectionQueryBase<IProduct, ProductDisplay>, ICachedProductQuery
{
/// <summary>
/// The product service.
/// </summary>
private readonly ProductService _productService;
/// <summary>
/// A value indicating whether or not this is being used for back office editors.
/// </summary>
private readonly DetachedValuesConversionType _conversionType;
/// <summary>
/// The <see cref="ProductContentFactory"/>.
/// </summary>
private readonly Lazy<ProductContentFactory> _productContentFactory;
/// <summary>
/// The <see cref="VirtualProductContentCache"/>.
/// </summary>
private VirtualProductContentCache _cache;
/// <summary>
/// The data modifier.
/// </summary>
private Lazy<IDataModifierChain<IProductVariantDataModifierData>> _dataModifier;
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
public CachedProductQuery()
: this(MerchelloContext.Current, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="enableDataModifiers">
/// A value indicating whether or not data modifiers are enabled.
/// </param>
public CachedProductQuery(IMerchelloContext merchelloContext, bool enableDataModifiers)
: this(merchelloContext, enableDataModifiers, DetachedValuesConversionType.Db)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="indexProvider">
/// The index provider.
/// </param>
/// <param name="searchProvider">
/// The search provider.
/// </param>
/// <param name="enableDataModifiers">
/// A value indicating whether or not data modifiers are enabled.
/// </param>
public CachedProductQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers)
: this(merchelloContext, indexProvider, searchProvider, enableDataModifiers, DetachedValuesConversionType.Db)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="enableDataModifiers">
/// The enable data modifiers.
/// </param>
/// <param name="conversionType">
/// The detached value conversion type.
/// </param>
internal CachedProductQuery(IMerchelloContext merchelloContext, bool enableDataModifiers, DetachedValuesConversionType conversionType)
: this(
merchelloContext,
ExamineManager.Instance.IndexProviderCollection["MerchelloProductIndexer"],
ExamineManager.Instance.SearchProviderCollection["MerchelloProductSearcher"],
enableDataModifiers,
conversionType)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CachedProductQuery"/> class.
/// </summary>
/// <param name="merchelloContext">
/// The <see cref="IMerchelloContext"/>.
/// </param>
/// <param name="indexProvider">
/// The index provider.
/// </param>
/// <param name="searchProvider">
/// The search provider.
/// </param>
/// <param name="enableDataModifiers">
/// The enable data modifiers.
/// </param>
/// <param name="conversionType">
/// The is for back office editors.
/// </param>
internal CachedProductQuery(IMerchelloContext merchelloContext, BaseIndexProvider indexProvider, BaseSearchProvider searchProvider, bool enableDataModifiers, DetachedValuesConversionType conversionType)
: base(merchelloContext.Cache, merchelloContext.Services.ProductService, indexProvider, searchProvider, enableDataModifiers)
{
_productService = (ProductService)merchelloContext.Services.ProductService;
this._conversionType = conversionType;
_productContentFactory = new Lazy<ProductContentFactory>(() => new ProductContentFactory());
_cache = new VirtualProductContentCache(merchelloContext.Cache, this.GetProductContent, enableDataModifiers);
this.Initialize();
}
internal event TypedEventHandler<CachedProductQuery, bool> DataModifierChanged;
/// <summary>
/// Gets or sets a value indicating whether enable data modifiers.
/// </summary>
internal override bool EnableDataModifiers
{
get
{
return base.EnableDataModifiers;
}
set
{
base.EnableDataModifiers = value;
if (DataModifierChanged != null)
{
DataModifierChanged.Invoke(this, value);
}
}
}
/// <summary>
/// Gets the key field in index.
/// </summary>
protected override string KeyFieldInIndex
{
get { return "productKey"; }
}
/// <summary>
/// Gets <see cref="IProductContent"/> by it's key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContent(Guid key)
{
return _cache.GetByKey(key);
}
/// <summary>
/// Gets the typed content by it's sku.
/// </summary>
/// <param name="sku">
/// The sku.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContentBySku(string sku)
{
return _cache.GetBySku(sku, GetProductContentBySku);
}
/// <summary>
/// Gets the typed content by it's slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
public IProductContent TypedProductContentBySlug(string slug)
{
return _cache.GetBySlug(slug, GetProductContentBySlug);
}
/// <summary>
/// Gets the typed <see cref="IProductContent"/> for a collection.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentFromCollection(Guid collectionKey)
{
return TypedProductContentFromCollection(collectionKey, 1, long.MaxValue);
}
/// <summary>
/// The typed product content from collection.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentFromCollection(
Guid collectionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
return TypedProductContentPageFromCollection(collectionKey, page, itemsPerPage, sortBy, sortDirection).Items;
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/>.
/// </summary>
/// <param name="collectionKey">
/// The collection key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageFromCollection(
Guid collectionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
var pagedKeys = GetCollectionPagedKeys(collectionKey, page, itemsPerPage, sortBy, sortDirection);
return _cache.GetPagedCollectionByCacheKey(pagedKeys, sortBy);
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> collection.
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentSearch(long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Descending)
{
return TypedProductContentSearchPaged(page, itemsPerPage, sortBy, sortDirection).Items;
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> collection.
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductContent}"/>.
/// </returns>
public IEnumerable<IProductContent> TypedProductContentSearch(
string term,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Ascending)
{
return TypedProductContentSearchPaged(term, page, itemsPerPage, sortBy, sortDirection).Items;
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> paged collection.
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentSearchPaged(
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
if (pagedKeys != null) return _cache.MapPagedCollection(pagedKeys, sortBy);
return
_cache.GetPagedCollectionByCacheKey(
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection)),
sortBy);
}
/// <summary>
/// Search returning an <see cref="IProductContent"/> paged collection.
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentSearchPaged(
string term,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection, new Dictionary<string, string> { { "term", term } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
_cache.GetPagedCollectionByCacheKey(
pagedKeys ?? _productService.GetPagedKeys(term, page, itemsPerPage, sortBy, sortDirection),
sortBy);
}
/// <inheritdoc />
public PagedCollection<IProductContent> TypedProductContentByPriceRange(
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "price",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
_cache.GetPagedCollectionByCacheKey(
pagedKeys ?? _productService.GetProductsKeysInPriceRange(min, max, page, itemsPerPage, sortBy, sortDirection),
sortBy);
}
///// <inheritdoc />
//public PagedCollection<IProductContent> TypedProductContentByPriceRange(
// string searchTerm,
// decimal min,
// decimal max,
// long page,
// long itemsPerPage,
// string sortBy = "price",
// SortDirection sortDirection = SortDirection.Descending)
//{
// throw new NotImplementedException();
//}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in every collection referenced.
/// </summary>
/// <param name="collectionKeys">
/// The collection of collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid CollectionOrderGuid = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, page, itemsPerPage, sortBy, sortDirection, CollectionOrderGuid, fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in every collection referenced.
/// </summary>
/// <param name="collectionKeys">
/// The collection of collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid CollectionOrderGuid = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection, CollectionOrderGuid,fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid CollectionOrderGuid = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection, fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistInAllCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid CollectionOrderGuid = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAllCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that does not exists in any of the collections referenced..
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, page, itemsPerPage, sortBy, sortDirection);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that does not exists in any of the collections referenced..
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatNotInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysNotInAnyCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in any of the collections passed.
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid orderCollectionKey = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, page, itemsPerPage, sortBy, sortDirection, orderCollectionKey, fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="PagedCollection{IProductContent}"/> that exists in any of the collections passed.
/// </summary>
/// <param name="collectionKeys">
/// The collection keys.
/// </param>
/// <param name="searchTerm">
/// The search Term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="PagedCollection"/>.
/// </returns>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid orderCollectionKey = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, searchTerm, page, itemsPerPage, sortBy, sortDirection, orderCollectionKey, fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid orderCollectionKey = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, min, max, page, itemsPerPage, sortBy, sortDirection, orderCollectionKey);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <inheritdoc/>
public PagedCollection<IProductContent> TypedProductContentPageThatExistsInAnyCollections(
IEnumerable<Guid> collectionKeys,
string searchTerm,
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Ascending,
Guid orderCollectionKey = new Guid(),
Action<Umbraco.Core.Persistence.Sql> fn = null)
{
var keys = collectionKeys as Guid[] ?? collectionKeys.ToArray();
if (!keys.Any()) return PagedCollection<IProductContent>.Empty();
var pagedKeys = ((ProductService)Service).GetKeysThatExistInAnyCollections(keys, searchTerm, min, max, page, itemsPerPage, sortBy, sortDirection, orderCollectionKey, fn);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
public PagedCollection<IProductContent> TypedProductContentPages(Func<ICachedProductQuery, Umbraco.Core.Persistence.Page<Guid>> fn, string sortBy = "")
{
var pagedKeys = fn(this);
return _cache.MapPagedCollection(pagedKeys, sortBy);
}
/// <summary>
/// Gets a <see cref="ProductDisplay"/> by it's unique key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public override ProductDisplay GetByKey(Guid key)
{
//// modify data is handled in GetDisplayObject!
return GetDisplayObject(key);
}
/// <summary>
/// Gets a <see cref="ProductDisplay"/> by it's SKU.
/// </summary>
/// <param name="sku">
/// The SKU.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public ProductDisplay GetBySku(string sku)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("sku", sku).And().Field("master", "True");
var displays = SearchProvider.Search(criteria).Select(PerformMapSearchResultToDisplayObject);
var display = displays.FirstOrDefault();
if (display != null) return this.ModifyData(display);
var entity = _productService.GetBySku(sku);
if (entity == null) return null;
ReindexEntity(entity);
return this.ModifyData(entity.ToProductDisplay(this._conversionType));
}
/// <summary>
/// Gets a product by it's slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
public ProductDisplay GetBySlug(string slug)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("slugs", slug).And().Field("master", "True");
var displays = SearchProvider.Search(criteria).Select(PerformMapSearchResultToDisplayObject).ToArray();
var display = displays.FirstOrDefault(x => x.DetachedContents.Any(y => y.Slug.Equals(slug, StringComparison.InvariantCultureIgnoreCase)));
// Don't modifiy the data here as it would have been modified in the PerformMapSearchResultToDisplayObject
if (display != null) return display;
var key = _productService.GetKeyForSlug(slug);
return Guid.Empty.Equals(key) ? null : this.GetByKey(key);
}
/// <summary>
/// Gets a <see cref="ProductVariantDisplay"/> by it's key
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductVariantDisplay"/>.
/// </returns>
public ProductVariantDisplay GetProductVariantByKey(Guid key)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("productVariantKey", key.ToString());
var result = CachedSearch(criteria, ExamineDisplayExtensions.ToProductVariantDisplay).FirstOrDefault();
if (result != null)
{
result.EnsureValueConversion(this._conversionType);
return this.ModifyData(result);
}
var variant = _productService.GetProductVariantByKey(key);
if (variant != null)
{
this.ReindexEntity(variant);
return this.ModifyData(variant.ToProductVariantDisplay(this._conversionType));
}
return null;
}
/// <summary>
/// Gets a <see cref="ProductVariantDisplay"/> by it's unique SKU
/// </summary>
/// <param name="sku">
/// The SKU.
/// </param>
/// <returns>
/// The <see cref="ProductVariantDisplay"/>.
/// </returns>
public ProductVariantDisplay GetProductVariantBySku(string sku)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field("sku", sku).Not().Field("master", "True");
var result = CachedSearch(criteria, ExamineDisplayExtensions.ToProductVariantDisplay).FirstOrDefault();
if (result != null)
{
result.EnsureValueConversion(this._conversionType);
return this.ModifyData(result);
}
var variant = _productService.GetProductVariantBySku(sku);
if (variant != null)
{
this.ReindexEntity(variant);
return this.ModifyData(variant.ToProductVariantDisplay(this._conversionType));
}
return null;
}
/// <summary>
/// Searches all products
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay Search(long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Searches all products for a term
/// </summary>
/// <param name="term">
/// The term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay Search(string term, long page, long itemsPerPage, string sortBy = "name", SortDirection sortDirection = SortDirection.Ascending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>("Search", page, itemsPerPage, sortBy, sortDirection, new Dictionary<string, string> { { "term", term } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(cacheKey, _productService.GetPagedKeys(term, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name.
/// </summary>
/// <param name="optionKey">
/// The option key.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
Guid optionKey,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "optionKey", optionKey.ToString() } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionKey, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name and a collection of choice names
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="choiceNames">
/// The choice names.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
IEnumerable<string> choiceNames,
long page,
long itemsPerPage,
string sortBy = "name",
SortDirection sortDirection = SortDirection.Descending)
{
var choices = choiceNames as string[] ?? choiceNames.ToArray();
var args = new Dictionary<string, string>
{
{ "optionName", optionName },
{ "choiceNames", string.Join(string.Empty, choices.OrderBy(x => x)) }
};
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
args);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, choices, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an option with name.
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "optionName", optionName } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys
?? PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an options with name and choice name
/// </summary>
/// <param name="optionName">
/// The option name.
/// </param>
/// <param name="choiceName">
/// The choice name.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
string optionName,
string choiceName,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "optionName", optionName },
{ "choiceName", choiceName }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(optionName, choiceName, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products with that have an options with names
/// </summary>
/// <param name="optionNames">
/// The option names.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsWithOption(
IEnumerable<string> optionNames,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var names = optionNames as string[] ?? optionNames.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsWithOption",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "optionNames", string.Join(string.Empty, names.OrderBy(x => x)) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysWithOption(names, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products that have prices within a price range
/// </summary>
/// <param name="min">
/// The min.
/// </param>
/// <param name="max">
/// The max.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInPriceRange(
decimal min,
decimal max,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInPriceRange(min, max, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products that have prices within a price range allowing for a tax modifier
/// </summary>
/// <param name="min">
/// The min.
/// </param>
/// <param name="max">
/// The max.
/// </param>
/// <param name="taxModifier">
/// The tax modifier.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInPriceRange(
decimal min,
decimal max,
decimal taxModifier,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInPriceRange",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "min", min.ToString(CultureInfo.InvariantCulture) },
{ "max", max.ToString(CultureInfo.InvariantCulture) },
{ "taxModifier", taxModifier.ToString(CultureInfo.InvariantCulture) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInPriceRange(min, max, taxModifier, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// The get products by barcode.
/// </summary>
/// <param name="barcode">
/// The barcode.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByBarcode(
string barcode,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByBarcode",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "barcode", barcode } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsByBarcode(barcode, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// The get products by barcode.
/// </summary>
/// <param name="barcodes">
/// The barcodes.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByBarcode(
IEnumerable<string> barcodes,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var barcodesArray = barcodes as string[] ?? barcodes.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByBarcode",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{ "barcodes", string.Join(string.Empty, barcodesArray.OrderBy(x => x)) }
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsByBarcode(barcodesArray, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products by manufacturer.
/// </summary>
/// <param name="manufacturer">
/// The manufacturer.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByManufacturer(
string manufacturer,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByManufacturer",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "manufacturer", manufacturer} });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysByManufacturer(manufacturer, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Get products for a list of manufacturers.
/// </summary>
/// <param name="manufacturer">
/// The manufacturer.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsByManufacturer(
IEnumerable<string> manufacturer,
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var manufacturerArray = manufacturer as string[] ?? manufacturer.ToArray();
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsByManufacturer",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string> { { "manufacturer", string.Join(string.Empty, manufacturerArray.OrderBy(x => x)) } });
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysByManufacturer(manufacturerArray, page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products that are in stock or do not track inventory
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <param name="includeAllowOutOfStockPurchase">
/// The include allow out of stock purchase.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsInStock(
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending,
bool includeAllowOutOfStockPurchase = false)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsInStock",
page,
itemsPerPage,
sortBy,
sortDirection,
new Dictionary<string, string>
{
{
"includeAllowOutOfStockPurchase",
includeAllowOutOfStockPurchase.ToString()
}
});
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysInStock(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets products that are marked on sale
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="QueryResultDisplay"/>.
/// </returns>
public QueryResultDisplay GetProductsOnSale(
long page,
long itemsPerPage,
string sortBy = "",
SortDirection sortDirection = SortDirection.Descending)
{
var cacheKey = PagedKeyCache.GetPagedQueryCacheKey<ICachedProductQuery>(
"GetProductsOnSale",
page,
itemsPerPage,
sortBy,
sortDirection);
var pagedKeys = PagedKeyCache.GetPageByCacheKey(cacheKey);
return
this.GetQueryResultDisplay(
pagedKeys ??
PagedKeyCache.CachePage(
cacheKey,
_productService.GetProductsKeysOnSale(page, itemsPerPage, sortBy, sortDirection)));
}
/// <summary>
/// Gets the <see cref="ProductVariantDisplay"/> for a product
/// </summary>
/// <param name="productKey">
/// The product key.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{ProductVariantDisplay}"/>.
/// </returns>
public IEnumerable<ProductVariantDisplay> GetVariantsByProduct(Guid productKey)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field(KeyFieldInIndex, productKey.ToString()).Not().Field("master", "True");
var results = SearchProvider.Search(criteria);
return results.Select(x => this.ModifyData(x.ToProductVariantDisplay()));
}
/// <summary>
/// Re-indexes the <see cref="IProduct"/>
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
internal override void ReindexEntity(IProduct entity)
{
((ProductIndexer)IndexProvider).AddProductToIndex(entity);
}
/// <summary>
/// Re-indexes entity document via Examine.
/// </summary>
/// <param name="entity">
/// The entity.
/// </param>
internal void ReindexEntity(IProductVariant entity)
{
IndexProvider.ReIndexNode(entity.SerializeToXml().Root, IndexTypes.ProductVariant);
}
/// <summary>
/// The modify data.
/// </summary>
/// <param name="data">
/// The data.
/// </param>
/// <typeparam name="T">
/// The type of data to be modified
/// </typeparam>
/// <returns>
/// The <see cref="T"/>.
/// </returns>
internal T ModifyData<T>(T data)
where T : class, IProductVariantDataModifierData
{
var count = ((Merchello.Web.DataModifiers.Product.ProductVariantDataModifierChain)this._dataModifier.Value).TaskCount;
if (count < 2)
{
Umbraco.Core.Logging.LogHelper.Warn(this.GetType(), "Only 1 datamodifier found");
}
if (!EnableDataModifiers) {
//Umbraco.Core.Logging.LogHelper.Warn(this.GetType(), "EnableDataModifiers = false");
return data;
}
var attempt = _dataModifier.Value.Modify(data);
if (!attempt.Success)
{
Umbraco.Core.Logging.LogHelper.Warn(this.GetType(), "Datamodifier failed for: " + data.Name);
return data;
}
var modified = attempt.Result as T;
return modified ?? data;
}
/// <summary>
/// Gets a display object from the Examine cache or falls back the the database if not found
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
protected override ProductDisplay GetDisplayObject(Guid key)
{
var criteria = SearchProvider.CreateSearchCriteria();
criteria.Field(KeyFieldInIndex, key.ToString()).And().Field("master", "True");
var display = SearchProvider.Search(criteria).Select(PerformMapSearchResultToDisplayObject).FirstOrDefault();
if (display != null)
{
display.EnsureValueConversion(this._conversionType);
return display;
}
var entity = Service.GetByKey(key);
if (entity == null) return null;
ReindexEntity(entity);
return this.ModifyData(entity.ToProductDisplay(this._conversionType));
}
/// <summary>
/// Maps a <see cref="SearchResult"/> to <see cref="ProductDisplay"/>
/// </summary>
/// <param name="result">
/// The result.
/// </param>
/// <returns>
/// The <see cref="ProductDisplay"/>.
/// </returns>
protected override ProductDisplay PerformMapSearchResultToDisplayObject(SearchResult result)
{
return this.ModifyData(result.ToProductDisplay(GetVariantsByProduct, this._conversionType));
}
/// <summary>
/// Gets the virtual content.
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContent(Guid key)
{
var display = GetByKey(key);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Gest the <see cref="IProductContent"/> by sku.
/// </summary>
/// <param name="sku">
/// The sku.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContentBySku(string sku)
{
var display = GetBySku(sku);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Gets the <see cref="IProductContent"/> by slug.
/// </summary>
/// <param name="slug">
/// The slug.
/// </param>
/// <returns>
/// The <see cref="IProductContent"/>.
/// </returns>
private IProductContent GetProductContentBySlug(string slug)
{
slug = HttpUtility.UrlDecode(slug);
var display = GetBySlug(slug);
return display == null ? null :
display.AsProductContent(_productContentFactory.Value);
}
/// <summary>
/// Initializes the lazy
/// </summary>
private void Initialize()
{
if (MerchelloContext.HasCurrent)
_dataModifier = new Lazy<IDataModifierChain<IProductVariantDataModifierData>>(() => new ProductVariantDataModifierChain(MerchelloContext.Current));
DataModifierChanged += OnDataModifierChanged;
}
private void OnDataModifierChanged(CachedProductQuery sender, bool e)
{
_cache.ModifiedVersion = e;
}
}
} | 35.539851 | 210 | 0.544688 | [
"MIT"
] | vwa-software/Merchello | src/Merchello.Web/Search/CachedProductQuery.cs | 66,888 | C# |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
namespace MechanikaDesign.WinForms.UI.ColorPicker
{
public static class ColorHelper
{
// r,g,b values are from 0 to 1
// h = [0,360], s = [0,1], v = [0,1]
// if s == 0, then h = -1 (undefined)
/// <summary>
/// Generates the Hue, Saturation, and Value for a given color
/// </summary>
/// <param name="color">The Color to generate the values for</param>
/// <param name="hue">Out value for Hue</param>
/// <param name="saturation">Out value for Saturation</param>
/// <param name="value">Out value for Value</param>
public static void HSVFromRGB(Color color, out double hue, out double saturation, out double value)
{
double min, max, delta, r, g, b;
r = (double)color.R / 255d;
g = (double)color.G / 255d;
b = (double)color.B / 255d;
min = Math.Min(r, Math.Min(g, b));
max = Math.Max(r, Math.Max(g, b));
value = max; // v
delta = max - min;
if (max != 0)
saturation = delta / max; // s
else
{
// r = g = b = 0 // s = 0, v is undefined
saturation = 0;
hue = -1;
return;
}
if (r == max)
hue = (g - b) / delta; // between yellow & magenta
else if (g == max)
hue = 2 + (b - r) / delta; // between cyan & yellow
else
hue = 4 + (r - g) / delta; // between magenta & cyan
hue *= 60; // degrees
if (hue < 0)
hue += 360;
}
/// <summary>
/// Generates a Color from a Hue, Saturation, and Value combination
/// </summary>
/// <param name="hue">Hue to use for the Color. (Max 360)</param>
/// <param name="saturation">Saturation to use for the Color. (Max 1.0)</param>
/// <param name="value">Value to use for the Color. (Max 1.0)</param>
/// <returns>Generated Color</returns>
public static Color ColorFromHSV(double hue, double saturation, double value)
{
try
{
int i;
double f, p, q, t, r, g, b;
if (saturation == 0)
{
// achromatic (grey)
r = g = b = value;
return Color.FromArgb((int)(255 * r), (int)(255 * g), (int)(255 * b));
}
hue /= 60; // sector 0 to 5
i = (int)Math.Floor(hue);
f = hue - i; // factorial part of h
p = value * (1 - saturation);
q = value * (1 - saturation * f);
t = value * (1 - saturation * (1 - f));
switch (i)
{
case 0:
r = value;
g = t;
b = p;
break;
case 1:
r = q;
g = value;
b = p;
break;
case 2:
r = p;
g = value;
b = t;
break;
case 3:
r = p;
g = q;
b = value;
break;
case 4:
r = t;
g = p;
b = value;
break;
default: // case 5:
r = value;
g = p;
b = q;
break;
}
return Color.FromArgb((int)(255 * r), (int)(255 * g), (int)(255 * b));
}
catch
{
}
return Color.Empty;
}
}
}
| 35.01626 | 107 | 0.357325 | [
"MIT"
] | ChristianGreiner/bridge-hub | src/ColorPickerLibrary/ColorWheel/ColorHelper.cs | 4,309 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ToolGood.HtmlExtract.HtmlAgilityPack.Selectors;
namespace ToolGood.HtmlExtract.HtmlAgilityPack
{
public abstract class CssSelector
{
#region Constructor
protected CssSelector()
{
SubSelectors = new List<CssSelector>();
}
#endregion
#region Properties
private static readonly CssSelector[] Selectors = FindSelectors();
public abstract string Token { get; }
protected virtual bool IsSubSelector => false;
public virtual bool AllowTraverse => true;
public IList<CssSelector> SubSelectors { get; set; }
public string Selector { get; set; }
#endregion
#region Methods
protected internal abstract IEnumerable<HtmlNode> FilterCore(IEnumerable<HtmlNode> currentNodes);
public IEnumerable<HtmlNode> Filter(IEnumerable<HtmlNode> currentNodes)
{
var nodes = currentNodes;
IEnumerable<HtmlNode> rt = FilterCore(nodes).Distinct();
if (SubSelectors.Count == 0)
return rt;
foreach (var selector in SubSelectors)
rt = selector.FilterCore(rt);
return rt;
}
public virtual string GetSelectorParameter(string selector)
{
return selector.Substring(Token.Length);
}
public static IList<CssSelector> Parse(string cssSelector)
{
var tokens = Tokenizer.GetTokens(cssSelector);
return tokens.Select(ParseSelector).ToList();
}
private static CssSelector ParseSelector(Token token)
{
var selector = char.IsLetter(token.Filter[0])
? Selectors.First(i => i is TagNameSelector)
: Selectors.Where(s => s.Token.Length > 0).FirstOrDefault(s => token.Filter.StartsWith(s.Token));
if (selector == null)
throw new InvalidOperationException($"Invalid token : {token.Filter}.");
var selectorType = selector.GetType();
var rt = (CssSelector)Activator.CreateInstance(selectorType);
string filter = token.Filter.Substring(selector.Token.Length);
rt.SubSelectors = token.SubTokens.Select(ParseSelector).ToList();
rt.Selector = filter;
return rt;
}
private static CssSelector[] FindSelectors()
{
var defaultAsm = typeof(CssSelector).GetTypeInfo().Assembly;
Func<Type, bool> typeQuery = type => type.GetTypeInfo().IsSubclassOf(typeof(CssSelector)) && !type.GetTypeInfo().IsAbstract;
var defaultTypes = defaultAsm.GetTypes().Where(typeQuery);
var types = defaultAsm.GetTypes().Where(typeQuery);
types = defaultTypes.Concat(types);
var rt = types.Select(Activator.CreateInstance).Cast<CssSelector>().ToArray();
return rt;
}
#endregion
}
} | 33.043478 | 136 | 0.61875 | [
"MIT"
] | toolgood/ToolGood.Bedrock | ToolGood.HtmlExtract/HtmlAgilityPack.CssSelectors/CssSelector.cs | 3,042 | C# |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.Config;
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using Xunit;
public class HostNameLayoutRendererTests : NLogTestBase
{
[Fact]
public void HostNameTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${hostname} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
// Get the actual hostname that the code would use
string h = Environment.GetEnvironmentVariable("HOSTNAME")
?? System.Net.Dns.GetHostName()
?? Environment.GetEnvironmentVariable("COMPUTERNAME");
LogManager.GetLogger("A").Debug("a log message");
AssertDebugLastMessage("debug", h + " a log message");
}
}
} | 42.83871 | 103 | 0.683735 | [
"BSD-3-Clause"
] | AlanLiu90/NLog | tests/NLog.UnitTests/LayoutRenderers/Machine/HostNameLayoutRendererTests.cs | 2,656 | C# |
using System;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using MongoDB.Bson;
using MongoDB.Driver;
namespace MongodbTransactions.TestCases
{
[CoreJob]
public class MultiCollections
{
private IMongoCollection<BsonDocument> _collectionBar;
private IMongoCollection<BsonDocument> _collectionBaz;
private readonly MongoClient _client;
private readonly IMongoDatabase _database;
public MultiCollections()
{
_client = new MongoClient("mongodb://localhost:27017");
_database = _client.GetDatabase("foo");
}
[GlobalSetup]
public void CleanDb()
{
_database.DropCollection("bar");
_database.DropCollection("baz");
_collectionBar = _database.GetCollection<BsonDocument>("bar");
_collectionBaz = _database.GetCollection<BsonDocument>("baz");
Console.WriteLine("Deleted Rows!!!");
}
[GlobalCleanup]
public void GlobalCleanup()
{
CleanDb();
}
[Benchmark(Baseline = true)]
public void Save()
{
var document = new BsonDocument
{
{"name", "MongoDB"},
{"type", "Database"},
{"count", 1},
{
"info", new BsonDocument
{
{"x", 203},
{"y", 102}
}
}
};
_collectionBar.InsertOne(document);
_collectionBaz.InsertOne(document);
}
[Benchmark]
public async Task SaveAsync()
{
var document = new BsonDocument
{
{"name", "MongoDB"},
{"type", "Database"},
{"count", 1},
{
"info", new BsonDocument
{
{"x", 203},
{"y", 102}
}
}
};
await _collectionBar.InsertOneAsync(document);
await _collectionBaz.InsertOneAsync(document);
}
[Benchmark]
public void SaveWithTransaction()
{
using (var session = _client.StartSession())
{
session.StartTransaction();
Save();
session.CommitTransaction();
}
}
[Benchmark]
public async Task SaveWithTransactionAsync()
{
using (var session = _client.StartSession())
{
session.StartTransaction();
await SaveAsync();
session.CommitTransaction();
}
}
}
} | 27.686275 | 74 | 0.470255 | [
"MIT"
] | kroniak/mongodb-benchmark-samples | src/TestCases/MultiCollections.cs | 2,824 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd 2017. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
// Version 4.6.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Draw the tick marks for the track bar.
/// </summary>
public class ViewDrawTrackTicks : ViewLeaf
{
#region Instance Fields
private ViewDrawTrackBar _drawTrackBar;
private bool _topRight;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawTrackTicks class.
/// </summary>
/// <param name="drawTrackBar">Reference to owning track bar.</param>
/// <param name="topRight">Showing ticks to the top/right or bottom/left.</param>
public ViewDrawTrackTicks(ViewDrawTrackBar drawTrackBar, bool topRight)
{
_drawTrackBar = drawTrackBar;
_topRight = topRight;
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawTrackTicks:" + Id;
}
#endregion
#region Layout
/// <summary>
/// Discover the preferred size of the element.
/// </summary>
/// <param name="context">Layout context.</param>
public override Size GetPreferredSize(ViewLayoutContext context)
{
Debug.Assert(context != null);
return _drawTrackBar.TickSize;
}
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// Validate incoming reference
if (context == null) throw new ArgumentNullException("context");
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
}
#endregion
#region Paint
/// <summary>
/// Perform rendering before child elements are rendered.
/// </summary>
/// <param name="context">Rendering context.</param>
public override void RenderBefore(RenderContext context)
{
IPaletteElementColor elementColors;
if (Enabled)
elementColors =_drawTrackBar.StateNormal.Tick;
else
elementColors = _drawTrackBar.StateDisabled.Tick;
context.Renderer.RenderGlyph.DrawTrackTicksGlyph(context, State, elementColors, ClientRectangle,
_drawTrackBar.Orientation, _topRight,
_drawTrackBar.PositionSize,
_drawTrackBar.Minimum,
_drawTrackBar.Maximum,
_drawTrackBar.TickFrequency);
}
#endregion
}
}
| 35.903846 | 109 | 0.566149 | [
"BSD-3-Clause"
] | BMBH/Krypton | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Draw/ViewDrawTrackTicks.cs | 3,737 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class Attack
{
public string attackName;
public bool isEnemy;
public int damage;
public float range;
public List<string> modifiers;
public string damageType;
public float AOERadius;
public string typeOfAttack;
//So the plan in terms of dealing aoe damage is first to determine whether
public string aoeType = null;
public bool isHeal;
public string tooltipText;
public List<(int x, int y)> pattern;
public bool hoverSelectionOn = false;
GameObject BoardObject;
public Attack()
{
attackName = null;
}
public Attack(GameObject BoardObjectarg, bool isEnemyarg, string name, int damageargument, float rangeargument, List<string> modifiersarg, string damageTypearg, string typeOfAttackargument, float AOERadiusArgument = 0, List<(int x, int y)> patternArg = null, bool isHealarg = false, string tooltip = "No Tooltip")
{
attackName = name;
isEnemy = isEnemyarg;
damage = damageargument;
range = rangeargument;
modifiers = modifiersarg;
damageType = damageTypearg;
typeOfAttack = typeOfAttackargument;
BoardObject = BoardObjectarg;
AOERadius = AOERadiusArgument;
pattern = patternArg;
isHeal = isHealarg;
tooltipText = tooltip;
}
public List<(int x, int y, bool enemypresent)> DetermineAttackTiles(int xPos, int yPos)
{
Tilemap groundmap = BoardObject.transform.GetChild(0).GetChild(0).GetComponent<Tilemap>();
var attackLocations = new List<(int x, int y, bool enemypresent)> { };
if (typeOfAttack == "singleTargetMelee")
{
aoeType = null;
for (int y = yPos + Mathf.CeilToInt(range); y >= yPos - Mathf.CeilToInt(range); y--)
{
for (int x = xPos + Mathf.CeilToInt(range); x >= xPos - Mathf.CeilToInt(range); x--)
{
if (groundmap.HasTile(new Vector3Int(x, y, 0)))
{
if (Mathf.Pow(y - yPos, 2) + Mathf.Pow(x - xPos, 2) <= Mathf.Pow((range), 2))
{
attackLocations.Add((x, y, DetermineHostilePresenceOnTile(x, y)));
}
}
}
}
return attackLocations;
}
else if (typeOfAttack == "singleTargetRanged")
{
aoeType = null;
for (int y = yPos + Mathf.CeilToInt(range); y >= yPos - Mathf.CeilToInt(range); y--)
{
for (int x = xPos + Mathf.CeilToInt(range); x >= xPos - Mathf.CeilToInt(range); x--)
{
if (groundmap.HasTile(new Vector3Int(x, y, 0)))
{
if (Mathf.Abs(y - yPos) > 1 || Mathf.Abs(x - xPos) > 1)
{
if (Mathf.Pow(y - yPos, 2) + Mathf.Pow(x - xPos, 2) <= Mathf.Pow((range), 2))
{
attackLocations.Add((x, y, DetermineHostilePresenceOnTile(x, y)));
}
}
}
}
}
return attackLocations;
}
else if (typeOfAttack == "MeleeAOE")
{
aoeType = "all";
for (int y = yPos + Mathf.CeilToInt(range); y >= yPos - Mathf.CeilToInt(range); y--)
{
for (int x = xPos + Mathf.CeilToInt(range); x >= xPos - Mathf.CeilToInt(range); x--)
{
if (groundmap.HasTile(new Vector3Int(x, y, 0)))
{
if (Mathf.Pow(y - yPos, 2) + Mathf.Pow(x - xPos, 2) <= Mathf.Pow((range), 2))
{
attackLocations.Add((x, y, true));
}
}
}
}
return attackLocations;
}
else if (typeOfAttack == "RemoteRadiusAOE") //still need to write this
{
aoeType = "radius";
hoverSelectionOn = true;
for (int y = yPos + Mathf.CeilToInt(range); y >= yPos - Mathf.CeilToInt(range); y--)
{
for (int x = xPos + Mathf.CeilToInt(range); x >= xPos - Mathf.CeilToInt(range); x--)
{
if (groundmap.HasTile(new Vector3Int(x, y, 0)))
{
if (Mathf.Abs(y - yPos) > 1 || Mathf.Abs(x - xPos) > 1)
{
if (Mathf.Pow(y - yPos, 2) + Mathf.Pow(x - xPos, 2) <= Mathf.Pow((range), 2))
{
// Debug.Log("figuring it out");
attackLocations.Add((x, y, false));
}
}
}
}
}
return attackLocations;
}
else if (typeOfAttack == "DirectionalPattern")
{
aoeType = "pattern";
hoverSelectionOn = true;
foreach ((int x, int y) direction in new List<(int x, int y)> { (0, 1), (1, 0), (0, -1), (-1, 0) })
{
List<(int x, int y)> directionTiles = CreateDirectionTilesFromPattern(pattern, direction, (xPos, yPos));
foreach ((int x, int y) tile in directionTiles)
{
if (groundmap.HasTile(new Vector3Int(tile.x, tile.y, 0)))
{
attackLocations.Add((tile.x, tile.y, false));
}
}
}
return attackLocations;
}
else
{
return null;
}
}
public void AnimateAttack(GameObject target)
{
Unit selectedUnit = BoardObject.GetComponent<BoardController>().selectedEntity.GetComponent<Unit>();
GameObject Effect = new GameObject();
Effect.AddComponent<SpriteRenderer>();
Effect.GetComponent<SpriteRenderer>().sortingLayerName = "Effects";
Effect.AddComponent<EffectAnimator>();
Effect.transform.parent = BoardObject.GetComponent<BoardController>().selectedEntity.gameObject.transform;
if (attackName == "Eviscerate")
{
string direction = "";
direction = DetermineDirectionOfSingleTargetCardinalAttack(selectedUnit, target);
Effect.GetComponent<EffectAnimator>().SlashConstructor("Slash", direction, 64);
}
if (attackName == "Longshot" || attackName == "Fireball" || attackName == "Javelin")
{
Effect.GetComponent<EffectAnimator>().ProjectileConstructor(attackName, target, 80);
}
}
public string DetermineDirectionOfSingleTargetCardinalAttack(Unit selectedUnit, GameObject target)
{
string direction = "";
if (attackName == "Eviscerate")
{
if (target.gameObject.transform.position.x > selectedUnit.gameObject.transform.position.x)
{
direction = "right";
}
if (target.gameObject.transform.position.x < selectedUnit.gameObject.transform.position.x)
{
direction = "left";
}
if (target.gameObject.transform.position.y > selectedUnit.gameObject.transform.position.y)
{
direction = "top";
}
if (target.gameObject.transform.position.y < selectedUnit.gameObject.transform.position.y)
{
direction = "bottom";
}
}
return direction;
}
public bool DetermineHostilePresenceOnTile(int x, int y)
{
if (BoardObject.GetComponent<BoardController>().boardData[x, y] != null)
{
//now add a "hostile" condition if the attack belongs to the enemy
if ((!isEnemy && !isHeal) || (isEnemy && isHeal))
{
if (BoardObject.GetComponent<BoardController>().boardData[x, y].CompareTag("Enemy"))
{
return true;
}
}
else if ((isEnemy && !isHeal) || (!isEnemy && isHeal))
{
if (BoardObject.GetComponent<BoardController>().boardData[x, y].CompareTag("Unit"))
{
return true;
}
}
}
return false;
}
public List<(int x, int y)> CreateDirectionTilesFromPattern(List<(int x, int y)> pattern, (int x, int y) direction, (int x, int y) position)
{
List<(int x, int y)> tileList = new List<(int x, int y)> { };
foreach ((int x, int y) patternTile in pattern)
{
if (direction == (0, 1))
tileList.Add((patternTile.x + position.x, patternTile.y + position.y));
else if (direction == (1, 0))
tileList.Add((patternTile.y + position.x, patternTile.x * -1 + position.y));
else if (direction == (0, -1))
tileList.Add((patternTile.x * -1 + position.x, patternTile.y * -1 + position.y));
else if (direction == (-1, 0))
tileList.Add((patternTile.y * -1 + position.x, patternTile.x + position.y));
}
return tileList;
}
public (int x, int y) FindCardinalDirection((int x, int y) charPosition, (float x, float y) mousePosition)
{
if (Mathf.Abs(mousePosition.x - charPosition.x) > Mathf.Abs(mousePosition.y - charPosition.y))
{
if (mousePosition.x > charPosition.x)
return (1, 0);
else if (mousePosition.x < charPosition.x)
return (-1, 0);
}
else
{
if (mousePosition.y > charPosition.y)
return (0, 1);
else if (mousePosition.y < charPosition.y)
return (0, -1);
}
return (-1, 0);
}
}
| 32.469649 | 317 | 0.504772 | [
"MIT"
] | NateCollins11/Xiphos-strategy-game | Assets/Scripts/BattleScripts/Attacks.cs | 10,165 | 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 TSPauser.Properties
{
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TSPauser.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}
| 40.028169 | 175 | 0.587614 | [
"MIT"
] | theznerd/BlogContent | 2021/01/TSPauser/TSPauser-Source/Properties/Resources.Designer.cs | 2,844 | C# |
namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class Evidence : StripeEntity<Evidence>
{
[JsonProperty("access_activity_log")]
public string AccessActivityLog { get; set; }
[JsonProperty("billing_address")]
public string BillingAddress { get; set; }
#region Expandable Cancellation Policy
/// <summary>
/// (ID of a <see cref="File"/>) Your subscription cancellation policy, as shown to the
/// customer.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string CancellationPolicyId
{
get => this.InternalCancellationPolicy?.Id;
set => this.InternalCancellationPolicy = SetExpandableFieldId(value, this.InternalCancellationPolicy);
}
/// <summary>
/// (Expanded) Your subscription cancellation policy, as shown to the customer.
/// </summary>
[JsonIgnore]
public File CancellationPolicy
{
get => this.InternalCancellationPolicy?.ExpandedObject;
set => this.InternalCancellationPolicy = SetExpandableFieldObject(value, this.InternalCancellationPolicy);
}
[JsonProperty("cancellation_policy")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalCancellationPolicy { get; set; }
#endregion
[JsonProperty("cancellation_policy_disclosure")]
public string CancellationPolicyDisclosure { get; set; }
[JsonProperty("cancellation_rebuttal")]
public string CancellationRebuttal { get; set; }
#region Expandable Customer Communication
/// <summary>
/// (ID of a <see cref="File"/>) Any communication with the customer that you feel is
/// relevant to your case. Examples include emails proving that the customer received the
/// product or service, or demonstrating their use of or satisfaction with the product or
/// service.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string CustomerCommunicationId
{
get => this.InternalCustomerCommunication?.Id;
set => this.InternalCustomerCommunication = SetExpandableFieldId(value, this.InternalCustomerCommunication);
}
/// <summary>
/// (Expanded) Any communication with the customer that you feel is relevant to your case.
/// Examples include emails proving that the customer received the product or service, or
/// demonstrating their use of or satisfaction with the product or service.
/// </summary>
[JsonIgnore]
public File CustomerCommunication
{
get => this.InternalCustomerCommunication?.ExpandedObject;
set => this.InternalCustomerCommunication = SetExpandableFieldObject(value, this.InternalCustomerCommunication);
}
[JsonProperty("customer_communication")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalCustomerCommunication { get; set; }
#endregion
[JsonProperty("customer_email_address")]
public string CustomerEmailAddress { get; set; }
[JsonProperty("customer_name")]
public string CustomerName { get; set; }
[JsonProperty("customer_purchase_ip")]
public string CustomerPurchaseIP { get; set; }
#region Expandable Customer Signature
/// <summary>
/// (ID of a <see cref="File"/>) A relevant document or contract showing the customer’s
/// signature.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string CustomerSignatureId
{
get => this.InternalCustomerSignature?.Id;
set => this.InternalCustomerSignature = SetExpandableFieldId(value, this.InternalCustomerSignature);
}
/// <summary>
/// (Expanded) A relevant document or contract showing the customer’s signature.
/// </summary>
[JsonIgnore]
public File CustomerSignature
{
get => this.InternalCustomerSignature?.ExpandedObject;
set => this.InternalCustomerSignature = SetExpandableFieldObject(value, this.InternalCustomerSignature);
}
[JsonProperty("customer_signature")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalCustomerSignature { get; set; }
#endregion
#region Expandable Duplicate Charge Documentation
/// <summary>
/// (ID of a <see cref="File"/>) Documentation for the prior charge that can uniquely
/// identify the charge, such as a receipt, shipping label, work order, etc. This document
/// should be paired with a similar document from the disputed payment that proves the two
/// payments are separate.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string DuplicateChargeDocumentationId
{
get => this.InternalDuplicateChargeDocumentation?.Id;
set => this.InternalDuplicateChargeDocumentation = SetExpandableFieldId(value, this.InternalDuplicateChargeDocumentation);
}
/// <summary>
/// (Expanded) Documentation for the prior charge that can uniquely identify the charge,
/// such as a receipt, shipping label, work order, etc. This document should be paired with
/// a similar document from the disputed payment that proves the two payments are separate.
/// </summary>
[JsonIgnore]
public File DuplicateChargeDocumentation
{
get => this.InternalDuplicateChargeDocumentation?.ExpandedObject;
set => this.InternalDuplicateChargeDocumentation = SetExpandableFieldObject(value, this.InternalDuplicateChargeDocumentation);
}
[JsonProperty("duplicate_charge_documentation")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalDuplicateChargeDocumentation { get; set; }
#endregion
[JsonProperty("duplicate_charge_explanation")]
public string DuplicateChargeExplanation { get; set; }
[JsonProperty("duplicate_charge_id")]
public string DuplicateChargeId { get; set; }
[JsonProperty("product_description")]
public string ProductDescription { get; set; }
#region Expandable Receipt
/// <summary>
/// (ID of a <see cref="File"/>) Any receipt or message sent to the customer notifying them
/// of the charge.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string ReceiptId
{
get => this.InternalReceipt?.Id;
set => this.InternalReceipt = SetExpandableFieldId(value, this.InternalReceipt);
}
/// <summary>
/// (Expanded) Any receipt or message sent to the customer notifying them of the charge.
/// </summary>
[JsonIgnore]
public File Receipt
{
get => this.InternalReceipt?.ExpandedObject;
set => this.InternalReceipt = SetExpandableFieldObject(value, this.InternalReceipt);
}
[JsonProperty("receipt")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalReceipt { get; set; }
#endregion
#region Expandable Refund Policy
/// <summary>
/// (ID of a <see cref="File"/>) Your refund policy, as shown to the customer.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string RefundPolicyId
{
get => this.InternalRefundPolicy?.Id;
set => this.InternalRefundPolicy = SetExpandableFieldId(value, this.InternalRefundPolicy);
}
/// <summary>
/// (Expanded) Your refund policy, as shown to the customer.
/// </summary>
[JsonIgnore]
public File RefundPolicy
{
get => this.InternalRefundPolicy?.ExpandedObject;
set => this.InternalRefundPolicy = SetExpandableFieldObject(value, this.InternalRefundPolicy);
}
[JsonProperty("refund_policy")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalRefundPolicy { get; set; }
#endregion
[JsonProperty("refund_policy_disclosure")]
public string RefundPolicyDisclosure { get; set; }
[JsonProperty("refund_refusal_explanation")]
public string RefundRefusalExplanation { get; set; }
[JsonProperty("service_date")]
public string ServiceDate { get; set; }
#region Expandable Service Documentation
/// <summary>
/// (ID of a <see cref="File"/>) Documentation showing proof that a service was provided to
/// the customer. This could include a copy of a signed contract, work order, or other form
/// of written agreement.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string ServiceDocumentationId
{
get => this.InternalServiceDocumentation?.Id;
set => this.InternalServiceDocumentation = SetExpandableFieldId(value, this.InternalServiceDocumentation);
}
/// <summary>
/// (Expanded) Documentation showing proof that a service was provided to the customer.
/// This could include a copy of a signed contract, work order, or other form of written
/// agreement.
/// </summary>
[JsonIgnore]
public File ServiceDocumentation
{
get => this.InternalServiceDocumentation?.ExpandedObject;
set => this.InternalServiceDocumentation = SetExpandableFieldObject(value, this.InternalServiceDocumentation);
}
[JsonProperty("service_documentation")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalServiceDocumentation { get; set; }
#endregion
[JsonProperty("shipping_address")]
public string ShippingAddress { get; set; }
[JsonProperty("shipping_carrier")]
public string ShippingCarrier { get; set; }
[JsonProperty("shipping_date")]
public string ShippingDate { get; set; }
#region Expandable Shipping Documentation
/// <summary>
/// (ID of a <see cref="File"/>) Documentation showing proof that a product was shipped to
/// the customer at the same address the customer provided to you. This could include a copy
/// of the shipment receipt, shipping label, etc. It should show the customer’s full
/// shipping address, if possible.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string ShippingDocumentationId
{
get => this.InternalShippingDocumentation?.Id;
set => this.InternalShippingDocumentation = SetExpandableFieldId(value, this.InternalShippingDocumentation);
}
/// <summary>
/// (Expanded) Documentation showing proof that a product was shipped to the customer at
/// the same address the customer provided to you. This could include a copy of the shipment
/// receipt, shipping label, etc. It should show the customer’s full shipping address, if
/// possible.
/// </summary>
[JsonIgnore]
public File ShippingDocumentation
{
get => this.InternalShippingDocumentation?.ExpandedObject;
set => this.InternalShippingDocumentation = SetExpandableFieldObject(value, this.InternalShippingDocumentation);
}
[JsonProperty("shipping_documentation")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalShippingDocumentation { get; set; }
#endregion
[JsonProperty("shipping_tracking_number")]
public string ShippingTrackingNumber { get; set; }
#region Expandable Uncategorized File
/// <summary>
/// (ID of a <see cref="File"/>) Any additional evidence or statements.
/// <para>Expandable.</para>
/// </summary>
[JsonIgnore]
public string UncategorizedFileId
{
get => this.InternalUncategorizedFile?.Id;
set => this.InternalUncategorizedFile = SetExpandableFieldId(value, this.InternalUncategorizedFile);
}
/// <summary>
/// (Expanded) Any additional evidence or statements.
/// </summary>
[JsonIgnore]
public File UncategorizedFile
{
get => this.InternalUncategorizedFile?.ExpandedObject;
set => this.InternalUncategorizedFile = SetExpandableFieldObject(value, this.InternalUncategorizedFile);
}
[JsonProperty("uncategorized_file")]
[JsonConverter(typeof(ExpandableFieldConverter<File>))]
internal ExpandableField<File> InternalUncategorizedFile { get; set; }
#endregion
[JsonProperty("uncategorized_text")]
public string UncategorizedText { get; set; }
}
}
| 39.721893 | 138 | 0.640846 | [
"Apache-2.0"
] | formstack/stripe-dotnet | src/Stripe.net/Entities/Disputes/Evidence.cs | 13,434 | C# |
using System;
using System.Threading.Tasks;
using PuppeteerSharp;
namespace stealthmode
{
class Program
{
// Check your API key and web socket endpoint from
// My Products (https://browseasy.com/products/) page.
// Assuming that it's stored in the environment variables,
// e.g. wss://freemium.browseasy.com
static readonly string BROWSEASY_ENDPOINT =
Environment.GetEnvironmentVariable("BROWSEASY_ENDPOINT");
// Assuming that it's stored in the environment variables
// e.g. ccc70169f82f4c7c8a33ecca21c1becf
static readonly string BROWSEASY_API_KEY =
Environment.GetEnvironmentVariable("BROWSEASY_API_KEY");
// Your unique connection string.
static readonly string BROWSEASY_CONNECTION_STRING = $"{BROWSEASY_ENDPOINT}?code={BROWSEASY_API_KEY}";
// Your unique connection string with stealth mode enabled.
static readonly string BROWSEASY_STEALTH_CONNECTION_STRING = $"{BROWSEASY_CONNECTION_STRING}&stealth";
// Debug endpoint
static readonly string BROWSEASY_DEBUG_ENDPOINT = "https://debug.browseasy.com/inspector.html?remoteFrontend=true";
public static void OpenBrowser(string uri)
{
var psi = new System.Diagnostics.ProcessStartInfo();
psi.UseShellExecute = true;
psi.FileName = uri;
System.Diagnostics.Process.Start(psi);
}
public static async Task Main()
{
var options = new ConnectOptions()
{
BrowserWSEndpoint = BROWSEASY_STEALTH_CONNECTION_STRING,
// Always reset default viewport.
// When stealth mode enabled, Browseasy will launch your browser
// with a random resolution based on a sample distribution.
// See https://gs.statcounter.com/screen-resolution-stats/desktop/worldwide
DefaultViewport = null
};
// Run headless browser on the cloud.
using (var browser = await PuppeteerSharp.Puppeteer.ConnectAsync(options))
{
using (var page = await browser.NewPageAsync())
{
// Final debug URL for the page.
var debugURL = $"{BROWSEASY_DEBUG_ENDPOINT}&{(BROWSEASY_ENDPOINT.Replace("://", "="))}/{page.Target.TargetId}";
// Log to your dotnet console.
Console.WriteLine(debugURL);
// Open the debug URL and you can inspect the blank page.
OpenBrowser(debugURL);
// You can remove these timeouts, and replace with break points.
// Wait for 5 seconds, so that debugger can attach to the page.
await Task.Delay(5000);
await page.GoToAsync("https://amiunique.org/fp");
// Log to DevTools console.
await page.EvaluateExpressionAsync("console.log('Hello world..')");
// Wait for any input from console.
Console.ReadLine();
}
}
}
}
}
| 40.580247 | 132 | 0.57986 | [
"Apache-2.0"
] | Browseasy/get-started | puppeteer-sharp/debugging/Program.cs | 3,289 | C# |
// ReSharper disable StringLiteralTypo
// ReSharper disable IdentifierTypo
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedType.Global
namespace InControl.NativeDeviceProfiles
{
// @cond nodoc
[Preserve, NativeInputDeviceProfile]
public class HoriEX2ControllerMacNativeProfile : Xbox360DriverMacNativeProfile
{
public override void Define()
{
base.Define();
DeviceName = "Hori EX2 Controller";
DeviceNotes = "Hori EX2 Controller on Mac";
Matchers = new[]
{
new InputDeviceMatcher
{
VendorID = 0x0f0d,
ProductID = 0x000d,
},
new InputDeviceMatcher
{
VendorID = 0x1bad,
ProductID = 0xf501,
},
new InputDeviceMatcher
{
VendorID = 0x24c6,
ProductID = 0x5500,
},
};
}
}
// @endcond
}
| 19.439024 | 79 | 0.681305 | [
"MIT"
] | EstasAnt/Estsoul | Assets/InControl/Source/Native/DeviceProfiles/Generated/HoriEX2ControllerMacNativeProfile.cs | 797 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Recognizers.Text.Number.English.Extractors;
using Microsoft.Recognizers.Text.Number.English.Parsers;
using Microsoft.Recognizers.Text.Number.Models;
using Microsoft.Recognizers.Text.Number.Parsers;
using Microsoft.Recognizers.Text.Number.Extractors;
namespace Microsoft.Recognizers.Text.Number.Tests
{
[TestClass]
public class TestNumberEnglish
{
private void BasicTest(IModel model, string source, string value)
{
var resultStr = model.Parse(source);
var resultJson = resultStr;
Assert.AreEqual(1, resultJson.Count);
Assert.AreEqual(source.Trim(), resultJson[0].Text);
Assert.AreEqual(value, resultJson[0].Resolution["value"]);
}
private void WrappedTest(IModel model, string source, string extractSrc, string value)
{
var resultStr = model.Parse(source);
var resultJson = resultStr;
Assert.AreEqual(1, resultJson.Count);
Assert.AreEqual(extractSrc, resultJson[0].Text);
Assert.AreEqual(value, resultJson[0].Resolution["value"]);
}
private void MultiTest(IModel model, string source, int count)
{
var resultStr = model.Parse(source);
var resultJson = resultStr;
Assert.AreEqual(count, resultJson.Count);
}
[TestMethod]
public void TestOrdinalModel()
{
var model = GetOrdinalModel();
BasicTest(model,
"three trillionth", "3000000000000");
MultiTest(model,
"a trillionth", 0);
BasicTest(model,
"a hundred trillionth", "100000000000000");
BasicTest(model,
"11th", "11");
BasicTest(model,
"21st", "21");
BasicTest(model,
"30th", "30");
BasicTest(model,
"2nd", "2");
BasicTest(model,
"eleventh", "11");
BasicTest(model,
"twentieth", "20");
BasicTest(model,
"twenty-fifth", "25");
BasicTest(model,
"twenty-first", "21");
BasicTest(model,
"one hundred twenty fifth", "125");
BasicTest(model,
"one hundred twenty-fifth", "125");
BasicTest(model,
"trillionth", "1000000000000");
BasicTest(model,
"twenty-one trillion and three hundred twenty second", "21000000000322");
BasicTest(model,
"two hundredth", "200");
}
[TestMethod]
public void TestNumberModel()
{
var model = GetNumberModel();
WrappedTest(model,
"192.", "192", "192");
MultiTest(model,
"192.168.1.2", 4);
MultiTest(model,
"the 180.25ml liquid", 0);
MultiTest(model,
"the 180ml liquid", 0);
MultiTest(model,
" 29km Road ", 0);
MultiTest(model,
" the May 4th ", 0);
MultiTest(model,
"the .25ml liquid", 0);
BasicTest(model,
".08", "0.08");
MultiTest(model,
"an", 0);
MultiTest(model,
"a", 0);
BasicTest(model,
".23456000", "0.23456");
BasicTest(model,
"4.800", "4.8");
BasicTest(model,
"one hundred and three and two thirds", (103 + (double)2 / 3).ToString());
BasicTest(model,
"sixteen", "16");
BasicTest(model,
"two thirds", ((double)2 / 3).ToString());
BasicTest(model,
"one hundred and sixteen", "116");
BasicTest(model,
"one hundred and six", "106");
BasicTest(model,
"one hundred and sixty-one", "161");
BasicTest(model,
"a trillionth", "1E-12");
BasicTest(model,
"a hundred trillionths", "1E-10");
BasicTest(model,
" half a dozen", "6");
BasicTest(model,
" 3 dozens", "36");
BasicTest(model,
"a dozen", "12");
BasicTest(model,
" three dozens ", "36");
BasicTest(model,
" three hundred and two dozens", "324");
BasicTest(model,
"1,234,567", "1234567");
MultiTest(model,
"1, 234, 567", 3);
BasicTest(model,
"9.2321312", "9.2321312");
BasicTest(model,
" -9.2321312", "-9.2321312");
BasicTest(model,
" -1", "-1");
BasicTest(model,
"-4/5", "-0.8");
BasicTest(model,
"- 1 4/5", "-1.8");
BasicTest(model,
"three", "3");
BasicTest(model,
" 123456789101231", "123456789101231");
BasicTest(model,
"-123456789101231", "-123456789101231");
BasicTest(model,
" -123456789101231", "-123456789101231");
BasicTest(model,
"1", "1");
BasicTest(model,
"10k", "10000");
BasicTest(model,
"10G", "10000000000");
BasicTest(model,
"- 10 k", "-10000");
BasicTest(model,
"2 million", "2000000");
BasicTest(model,
"1 trillion", "1000000000000");
BasicTest(model,
" three ", "3");
BasicTest(model,
"one trillion", "1000000000000");
BasicTest(model,
"twenty-one trillion", "21000000000000");
BasicTest(model,
"twenty-one trillion three hundred", "21000000000300");
BasicTest(model,
"twenty-one trillion and three hundred", "21000000000300");
BasicTest(model,
"fifty - two", "52");
BasicTest(model,
"fifty two", "52");
BasicTest(model,
"Three hundred and thirty one", "331");
BasicTest(model,
"two hundred and two thousand", "202000");
BasicTest(model,
"two thousand and two hundred", "2200");
BasicTest(model,
" 2.33 k", "2330");
BasicTest(model,
" two hundred point zero three", "200.03");
BasicTest(model,
" two hundred point seventy-one", "200.71");
BasicTest(model,
"1e10", "10000000000");
BasicTest(model,
"1.1^23", "8.95430243255239");
BasicTest(model,
" 322 hundred ", "32200");
BasicTest(model,
"three", "3");
BasicTest(model,
"seventy", "70");
BasicTest(model,
"fifty-two", "52");
BasicTest(model,
"2 1/4", "2.25");
BasicTest(model,
"3/4", "0.75");
BasicTest(model,
"one eighth", "0.125");
BasicTest(model,
"five eighths", "0.625");
BasicTest(model,
"a half", "0.5");
BasicTest(model,
"three quarters", "0.75");
BasicTest(model,
"twenty and three fifths", "20.6");
BasicTest(model,
"twenty-three fifths", "4.6");
BasicTest(model,
"twenty and three and three fifths", "23.6");
BasicTest(model,
"one million two thousand two hundred three fifths", "200440.6");
BasicTest(model,
"one and a half", "1.5");
BasicTest(model,
"one and a fourth", "1.25");
BasicTest(model,
"five and a quarter", "5.25");
BasicTest(model,
"one hundred and three quarters", "100.75");
BasicTest(model,
"a hundredth", "0.01");
BasicTest(model,
"1.1^+23", "8.95430243255239");
BasicTest(model,
"2.5^-1", "0.4");
BasicTest(model,
"-2500^-1", "-0.0004");
BasicTest(model,
"-1.1^+23", "-8.95430243255239");
BasicTest(model,
"-2.5^-1", "-0.4");
BasicTest(model,
"-1.1^--23", "-8.95430243255239");
BasicTest(model,
"-127.32e13", "-1.2732E+15");
BasicTest(model,
"12.32e+14", "1.232E+15");
BasicTest(model,
"-12e-1", "-1.2");
BasicTest(model,
"1.2b", "1200000000");
}
[TestMethod]
public void TestFractionModel()
{
var model = GetNumberModel();
BasicTest(model,
"a fifth", "0.2");
BasicTest(model,
"a trillionth", "1E-12");
BasicTest(model,
"a hundred thousand trillionths", "1E-07");
BasicTest(model,
"one fifth", "0.2");
BasicTest(model,
"three fifths", "0.6");
BasicTest(model,
"twenty fifths", "4");
BasicTest(model,
"twenty-three fifths", "4.6");
BasicTest(model,
"three and a fifth", "3.2");
BasicTest(model,
"twenty one fifths", "4.2");
BasicTest(model,
"a twenty-first", ((double)1 / 21).ToString());
BasicTest(model,
"one twenty-fifth", ((double)1 / 25).ToString());
BasicTest(model,
"three twenty-firsts", ((double)3 / 21).ToString());
BasicTest(model,
"three twenty firsts", ((double)3 / 21).ToString());
BasicTest(model,
"twenty twenty fifths", "0.8");
// act like Google
BasicTest(model,
"one hundred and thirty fifths", ((double)130 / 5).ToString());
BasicTest(model,
"one hundred thirty fifths", ((double)100 / 35).ToString());
BasicTest(model,
"one hundred thirty two fifths", ((double)132 / 5).ToString());
BasicTest(model,
"one hundred thirty-two fifths", ((double)132 / 5).ToString());
BasicTest(model,
"one hundred and thirty-two fifths", ((double)132 / 5).ToString());
BasicTest(model,
"one hundred and thirty and two fifths", (130 + (double)2 / 5).ToString());
BasicTest(model,
"one hundred thirty-fifths", ((double)100 / 35).ToString());
BasicTest(model,
"one one hundred fifth", ((double)1 / 105).ToString());
BasicTest(model,
"one one hundred and fifth", ((double)1 / 105).ToString());
BasicTest(model,
"one hundred one thousand fifths", ((double)100 / 1005).ToString());
BasicTest(model,
"one over three", ((double)1 / 3).ToString());
BasicTest(model,
"1 over twenty-one", ((double)1 / 21).ToString());
BasicTest(model,
"1 over one hundred and twenty one", ((double)1 / 121).ToString());
BasicTest(model,
"1 over three", ((double)1 / 3).ToString());
BasicTest(model,
"1 over 3", ((double)1 / 3).ToString());
BasicTest(model,
"one over 3", ((double)1 / 3).ToString());
BasicTest(model,
"one over 20", ((double)1 / 20).ToString());
BasicTest(model,
"one over twenty", ((double)1 / 20).ToString());
BasicTest(model,
"one over one hundred", ((double)1 / 100).ToString());
BasicTest(model,
"one over one hundred and twenty five", ((double)1 / 125).ToString());
BasicTest(model,
"ninety - five hundred fifths", ((double)9500 / 5).ToString());
}
[TestMethod]
public void TestPercentageModel()
{
var model = GetPercentageModel();
BasicTest(model,
"100%", "100%");
BasicTest(model,
" 100% ", "100%");
BasicTest(model,
" 100 percent", "100%");
BasicTest(model,
" 100 percentage", "100%");
BasicTest(model,
"240 percent", "240%");
BasicTest(model,
"twenty percent", "20%");
BasicTest(model,
"thirty percentage", "30%");
BasicTest(model,
"one hundred percent", "100%");
BasicTest(model,
"one hundred percents", "100%");
BasicTest(model,
"percents of twenty", "20%");
BasicTest(model,
"percent of 10", "10%");
BasicTest(model,
"per cent of twenty-two", "22%");
BasicTest(model,
"per cent of 210", "210%");
BasicTest(model,
"10 percent", "10%");
}
private static IModel GetNumberModel()
{
return
new NumberModel(
AgnosticNumberParserFactory.GetParser(AgnosticNumberParserType.Number, new EnglishNumberParserConfiguration()),
new NumberExtractor(NumberMode.PureNumber));
}
private static IModel GetOrdinalModel()
{
return
new OrdinalModel(
AgnosticNumberParserFactory.GetParser(AgnosticNumberParserType.Ordinal, new EnglishNumberParserConfiguration()),
new OrdinalExtractor());
}
private static IModel GetPercentageModel()
{
return
new PercentModel(
AgnosticNumberParserFactory.GetParser(AgnosticNumberParserType.Percentage, new EnglishNumberParserConfiguration()),
new PercentageExtractor());
}
}
} | 28.287823 | 136 | 0.445474 | [
"MIT"
] | SivilTaram/Recognizers-Text | Microsoft.Recognizers.Text.Number.Tests/TestNumberEnglish.cs | 15,334 | C# |
using Newtonsoft.Json;
using System.Text;
namespace Spear.Core.Message.Implementation
{
public class JsonMessageDecoder : IMessageDecoder
{
public MicroMessage Decode(byte[] data)
{
var content = Encoding.UTF8.GetString(data);
var message = JsonConvert.DeserializeObject<MicroMessage>(content);
if (message.IsInvoke)
{
message.Content = JsonConvert.DeserializeObject<InvokeMessage>(message.Content.ToString());
}
if (message.IsResult)
{
message.Content = JsonConvert.DeserializeObject<ResultMessage>(message.Content.ToString());
}
return message;
}
}
}
| 30.458333 | 107 | 0.604651 | [
"Apache-2.0"
] | ohngahng/spear | src/Spear.Core/Message/Implementation/JsonMessageDecoder.cs | 733 | C# |
using Assets.Gameplay.Abstract;
using Assets.Gameplay.Character.Implementation;
using Assets.Gameplay.Inventory;
using Assets.Gameplay.Inventory.Items;
using Assets.IoC;
using Assets.TileGenerator;
using UnityEngine;
namespace Assets.Gameplay
{
public interface IBootstrapper
{
BasicCharacter PlayerPrefab { get; }
TerrainTile[] TerrainTilesPrefabs { get; }
}
public class Bootstrapper : Singleton<Bootstrapper>, IBootstrapper
{
[SerializeField] private BasicCharacter _playerPrefabPlayer;
[SerializeField] private TerrainTile[] _terrainTilesPrefabs;
public BasicCharacter PlayerPrefab => _playerPrefabPlayer;
public TerrainTile[] TerrainTilesPrefabs => _terrainTilesPrefabs;
public RangedWeapon PlayerMainWeapon;
protected override void OnEnableHandle()
{
CreateSingleton(this);
}
protected override void OnDestroyHandle()
{
GCSingleton(this);
}
}
} | 24.731707 | 73 | 0.696252 | [
"MIT"
] | martin-obert/WWI_Trenches | WWI_Trenches_Prototypes/Assets/Gameplay/Bootstrapper.cs | 1,016 | C# |
#if UNITY_EDITOR
namespace UIWidgets
{
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// Menu options.
/// </summary>
public static class MenuOptions
{
#if UIWIDGETS_TMPRO_SUPPORT
/// <summary>
/// Suffix to support different prefabs type.
/// Done public for testing purpose.
/// </summary>
public static string Suffix = "TMPro";
/// <summary>
/// Converter for the TMPro support.
/// Done public for testing purpose.
/// </summary>
public static Action<GameObject> Converter = TMProConverter;
static void TMProConverter(GameObject target)
{
ReplaceTextWithTMPro(target);
foreach (Transform t in target.transform)
{
TMProConverter(t.gameObject);
}
}
static void ReplaceTextWithTMPro(GameObject target)
{
var text = target.GetComponent<Text>();
if (text == null)
{
return;
}
var font_size = text.fontSize;
var font_style = text.fontStyle;
var align = text.alignment;
var color = text.color;
var data = text.text;
UnityEngine.Object.DestroyImmediate(text);
var tmpro = target.AddComponent<TMPro.TextMeshProUGUI>();
#if UNITY_4_6 || UNITY_4_7
tmpro.font = (TMPro.TextMeshProFont)AssetDatabase.LoadAssetAtPath("Assets/TextMesh Pro/Resources/Fonts & Materials/ARIAL SDF.asset", typeof(TMPro.TextMeshProFont));
#else
tmpro.font = (TMPro.TMP_FontAsset)AssetDatabase.LoadAssetAtPath("Assets/TextMesh Pro/Resources/Fonts & Materials/ARIAL SDF.asset", typeof(TMPro.TMP_FontAsset));
#endif
tmpro.fontSize = font_size;
tmpro.fontStyle = (TMPro.FontStyles)font_style;
tmpro.alignment = ConvertAlignment(align);
tmpro.color = color;
tmpro.text = data;
}
/// <summary>
/// Convert text alignment.
/// </summary>
/// <param name="align">Original alignment.</param>
/// <returns>TmPro alignment.</returns>
static TMPro.TextAlignmentOptions ConvertAlignment(TextAnchor align)
{
switch (align)
{
case TextAnchor.UpperLeft:
return TMPro.TextAlignmentOptions.TopLeft;
case TextAnchor.UpperCenter:
return TMPro.TextAlignmentOptions.Top;
case TextAnchor.UpperRight:
return TMPro.TextAlignmentOptions.TopRight;
case TextAnchor.MiddleLeft:
return TMPro.TextAlignmentOptions.MidlineLeft;
case TextAnchor.MiddleCenter:
return TMPro.TextAlignmentOptions.Center;
case TextAnchor.MiddleRight:
return TMPro.TextAlignmentOptions.MidlineRight;
case TextAnchor.LowerLeft:
return TMPro.TextAlignmentOptions.BottomLeft;
case TextAnchor.LowerCenter:
return TMPro.TextAlignmentOptions.Bottom;
case TextAnchor.LowerRight:
return TMPro.TextAlignmentOptions.BottomRight;
}
return TMPro.TextAlignmentOptions.TopLeft;
}
#else
/// <summary>
/// Suffix to support different prefabs type.
/// Done public for testing purpose.
/// </summary>
public static string Suffix = string.Empty;
/// <summary>
/// Converter for the TMPro support.
/// Done public for testing purpose.
/// </summary>
public static Action<GameObject> Converter = null;
#endif
#region Collections
/// <summary>
/// Create AutocompleteCombobox.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/AutocompleteCombobox", false, 1000)]
public static void CreateAutocompleteCombobox()
{
Utilites.CreateWidgetFromAsset("AutocompleteCombobox" + Suffix);
}
/// <summary>
/// Create Combobox.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/Combobox", false, 1005)]
public static void CreateCombobox()
{
Utilites.CreateWidgetFromAsset("Combobox" + Suffix);
}
/// <summary>
/// Create ComboboxIcons.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ComboboxIcons", false, 1010)]
public static void CreateComboboxIcons()
{
Utilites.CreateWidgetFromAsset("ComboboxIcons" + Suffix);
}
/// <summary>
/// Create ComboboxIconsMultiselect.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ComboboxIconsMultiselect", false, 1020)]
public static void CreateComboboxIconsMultiselect()
{
Utilites.CreateWidgetFromAsset("ComboboxIconsMultiselect" + Suffix);
}
/// <summary>
/// Create DirectoryTreeView.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/DirectoryTreeView", false, 1030)]
public static void CreateDirectoryTreeView()
{
Utilites.CreateWidgetFromAsset("DirectoryTreeView" + Suffix);
}
/// <summary>
/// Create FileListView.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/FileListView", false, 1040)]
public static void CreateFileListView()
{
Utilites.CreateWidgetFromAsset("FileListView" + Suffix);
}
/// <summary>
/// Create ListView.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListView", false, 1050)]
public static void CreateListView()
{
Utilites.CreateWidgetFromAsset("ListViewString", true, Converter);
}
/// <summary>
/// Create istViewColors.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListViewColors", false, 1055)]
public static void CreateListViewColors()
{
Utilites.CreateWidgetFromAsset("ListViewColors");
}
/// <summary>
/// Create ListViewInt.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListViewInt", false, 1060)]
public static void CreateListViewInt()
{
Utilites.CreateWidgetFromAsset("ListViewInt" + Suffix);
}
/// <summary>
/// Create ListViewHeight.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListViewHeight", false, 1070)]
public static void CreateListViewHeight()
{
Utilites.CreateWidgetFromAsset("ListViewHeight" + Suffix);
}
/// <summary>
/// Create ListViewIcons.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListViewIcons", false, 1090)]
public static void CreateListViewIcons()
{
Utilites.CreateWidgetFromAsset("ListViewIcons" + Suffix);
}
/// <summary>
/// Create ListViewPaginator.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/ListViewPaginator", false, 1100)]
public static void CreateListViewPaginator()
{
Utilites.CreateWidgetFromAsset("ListViewPaginator" + Suffix);
}
/// <summary>
/// Create TreeView.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Collections/TreeView", false, 1110)]
public static void CreateTreeView()
{
Utilites.CreateWidgetFromAsset("TreeView" + Suffix);
}
#endregion
#region Containers
/// <summary>
/// Create Accordion.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Containers/Accordion", false, 2000)]
public static void CreateAccordion()
{
Utilites.CreateWidgetFromAsset("Accordion" + Suffix);
}
/// <summary>
/// Create Tabs.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Containers/Tabs", false, 2010)]
public static void CreateTabs()
{
Utilites.CreateWidgetFromAsset("Tabs" + Suffix);
}
/// <summary>
/// Create TabsLeft.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Containers/TabsLeft", false, 2020)]
public static void CreateTabsLeft()
{
Utilites.CreateWidgetFromAsset("TabsLeft" + Suffix);
}
/// <summary>
/// Create TabsIcons.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Containers/TabsIcons", false, 2030)]
public static void CreateTabsIcons()
{
Utilites.CreateWidgetFromAsset("TabsIcons" + Suffix);
}
/// <summary>
/// Create TabsIconsLeft.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Containers/TabsIconsLeft", false, 2040)]
public static void CreateTabsIconsLeft()
{
Utilites.CreateWidgetFromAsset("TabsIconsLeft" + Suffix);
}
#endregion
#region Dialogs
/// <summary>
/// Create DatePicker.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/DatePicker", false, 3000)]
public static void CreateDatePicker()
{
Utilites.CreateWidgetFromAsset("DatePicker" + Suffix);
}
/// <summary>
/// Create DateTimePicker.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/DateTimePicker", false, 3005)]
public static void CreateDateTimePicker()
{
Utilites.CreateWidgetFromAsset("DateTimePicker" + Suffix);
}
/// <summary>
/// Create Dialog.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/Dialog Template", false, 3010)]
public static void CreateDialog()
{
Utilites.CreateWidgetFromAsset("DialogTemplate" + Suffix);
}
/// <summary>
/// Create FileDialog.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/FileDialog", false, 3020)]
public static void CreateFileDialog()
{
Utilites.CreateWidgetFromAsset("FileDialog" + Suffix);
}
/// <summary>
/// Create FolderDialog.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/FolderDialog", false, 3030)]
public static void CreateFolderDialog()
{
Utilites.CreateWidgetFromAsset("FolderDialog" + Suffix);
}
/// <summary>
/// Create Notify.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/Notify Template", false, 3040)]
public static void CreateNotify()
{
Utilites.CreateWidgetFromAsset("NotifyTemplate" + Suffix);
}
/// <summary>
/// Create PickerBool.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/PickerBool", false, 3050)]
public static void CreatePickerBool()
{
Utilites.CreateWidgetFromAsset("PickerBool" + Suffix);
}
/// <summary>
/// Create PickerIcons.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/PickerIcons", false, 3060)]
public static void CreatePickerIcons()
{
Utilites.CreateWidgetFromAsset("PickerIcons" + Suffix);
}
/// <summary>
/// Create PickerInt.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/PickerInt", false, 3070)]
public static void CreatePickerInt()
{
Utilites.CreateWidgetFromAsset("PickerInt" + Suffix);
}
/// <summary>
/// Create PickerString.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/PickerString", false, 3080)]
public static void CreatePickerString()
{
Utilites.CreateWidgetFromAsset("PickerString" + Suffix);
}
/// <summary>
/// Create Popup.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/Popup", false, 3090)]
public static void CreatePopup()
{
Utilites.CreateWidgetFromAsset("Popup" + Suffix);
}
/// <summary>
/// Create TimePicker.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Dialogs/TimePicker", false, 3100)]
public static void CreateTimePicker()
{
Utilites.CreateWidgetFromAsset("TimePicker" + Suffix);
}
#endregion
#region Input
/// <summary>
/// Create Autocomplete.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Autocomplete", false, 3980)]
public static void CreateAutocomplete()
{
Utilites.CreateWidgetFromAsset("Autocomplete" + Suffix);
}
/// <summary>
/// Create AutocompleteIcons.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/AutocompleteIcons", false, 3990)]
public static void CreateAutocompleteIcons()
{
Utilites.CreateWidgetFromAsset("AutocompleteIcons" + Suffix);
}
/// <summary>
/// Create ButtonBig.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ButtonBig", false, 4000)]
public static void CreateButtonBig()
{
Utilites.CreateWidgetFromAsset("ButtonBig" + Suffix);
}
/// <summary>
/// Create ButtonSmall.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ButtonSmall", false, 4010)]
public static void CreateButtonSmall()
{
Utilites.CreateWidgetFromAsset("ButtonSmall" + Suffix);
}
/// <summary>
/// Create Calendar.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Calendar", false, 4020)]
public static void CreateCalendar()
{
Utilites.CreateWidgetFromAsset("Calendar" + Suffix);
}
/// <summary>
/// Create CenteredSlider.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/CenteredSlider", false, 4030)]
public static void CreateCenteredSlider()
{
Utilites.CreateWidgetFromAsset("CenteredSlider");
}
/// <summary>
/// Create CenteredSliderVertical.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/CenteredSliderVertical", false, 4040)]
public static void CreateCenteredSliderVertical()
{
Utilites.CreateWidgetFromAsset("CenteredSliderVertical");
}
/// <summary>
/// Create ColorPicker.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ColorPicker", false, 4050)]
public static void CreateColorPicker()
{
Utilites.CreateWidgetFromAsset("ColorPicker" + Suffix);
}
/// <summary>
/// Create ColorPickerRange.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ColorPickerRange", false, 4060)]
public static void CreateColorPickerRange()
{
Utilites.CreateWidgetFromAsset("ColorPickerRange");
}
/// <summary>
/// Create ColorPickerRangeHSV.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ColorPickerRangeHSV", false, 4063)]
public static void CreateColorPickerRangeHSV()
{
Utilites.CreateWidgetFromAsset("ColorPickerRangeHSV");
}
/// <summary>
/// Create ColorsList.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/ColorsList", false, 4065)]
public static void CreateColorsList()
{
Utilites.CreateWidgetFromAsset("ColorsList");
}
/// <summary>
/// Create DateTime.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/DateTime", false, 4067)]
public static void CreateDateTime()
{
Utilites.CreateWidgetFromAsset("DateTime" + Suffix);
}
/// <summary>
/// Create DateScroller.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/DateScroller", false, 4068)]
public static void CreateDateScroller()
{
Utilites.CreateWidgetFromAsset("DateScroller", true, Converter);
}
/// <summary>
/// Create DateTimeScroller.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/DateTimeScroller", false, 4069)]
public static void CreateDateTimeScroller()
{
Utilites.CreateWidgetFromAsset("DateTimeScroller", true, Converter);
}
/// <summary>
/// Create DateTimeScrollerSeparate.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/DateTimeScrollerSeparate", false, 4070)]
public static void CreateDateTimeScrollerSeparate()
{
Utilites.CreateWidgetFromAsset("DateTimeScrollerSeparate", true, Converter);
}
/// <summary>
/// Create RangeSlider.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/RangeSlider", false, 4071)]
public static void CreateRangeSlider()
{
Utilites.CreateWidgetFromAsset("RangeSlider");
}
/// <summary>
/// Create RangeSliderFloat.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/RangeSliderFloat", false, 4080)]
public static void CreateRangeSliderFloat()
{
Utilites.CreateWidgetFromAsset("RangeSliderFloat");
}
/// <summary>
/// Create RangeSliderVertical.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/RangeSliderVertical", false, 4090)]
public static void CreateRangeSliderVertical()
{
Utilites.CreateWidgetFromAsset("RangeSliderVertical");
}
/// <summary>
/// Create RangeSliderFloatVertical.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/RangeSliderFloatVertical", false, 4100)]
public static void CreateRangeSliderFloatVertical()
{
Utilites.CreateWidgetFromAsset("RangeSliderFloatVertical");
}
/// <summary>
/// Create Spinner.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Spinner", false, 4110)]
public static void CreateSpinner()
{
Utilites.CreateWidgetFromAsset("Spinner" + Suffix);
}
/// <summary>
/// Create SpinnerFloat.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/SpinnerFloat", false, 4120)]
public static void CreateSpinnerFloat()
{
Utilites.CreateWidgetFromAsset("SpinnerFloat" + Suffix);
}
/// <summary>
/// Create SplitButton.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/SplitButton", false, 4125)]
public static void CreateSplitButton()
{
Utilites.CreateWidgetFromAsset("SplitButton", true, Converter);
}
/// <summary>
/// Create Switch.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Switch", false, 4130)]
public static void CreateSwitch()
{
Utilites.CreateWidgetFromAsset("Switch");
}
/// <summary>
/// Create Time12.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Time12", false, 4140)]
public static void CreateTime12()
{
Utilites.CreateWidgetFromAsset("Time12" + Suffix);
}
/// <summary>
/// Create Time24.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/Time24", false, 4150)]
public static void CreateTime24()
{
Utilites.CreateWidgetFromAsset("Time24" + Suffix);
}
/// <summary>
/// Create TimeScroller.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Input/TimeScroller", false, 4160)]
public static void CreateTimeScroller()
{
Utilites.CreateWidgetFromAsset("TimeScroller", true, Converter);
}
#endregion
/// <summary>
/// Create AudioPlayer.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/AudioPlayer", false, 5000)]
public static void CreateAudioPlayer()
{
Utilites.CreateWidgetFromAsset("AudioPlayer");
}
/// <summary>
/// Create Progressbar.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/(obsolete) Progressbar", false, 5010)]
public static void CreateProgressbar()
{
Utilites.CreateWidgetFromAsset("Progressbar" + Suffix);
}
/// <summary>
/// Create ProgressbarDeterminate.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/ProgressbarDeterminate", false, 5014)]
public static void CreateProgressbarDeterminate()
{
Utilites.CreateWidgetFromAsset("ProgressbarDeterminate" + Suffix);
}
/// <summary>
/// Create ProgressbarIndeterminate.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/ProgressbarIndeterminate", false, 5017)]
public static void CreateProgressbarIndeterminate()
{
Utilites.CreateWidgetFromAsset("ProgressbarIndeterminate");
}
/// <summary>
/// Create ScrollRectPaginator.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/ScrollRectPaginator", false, 5020)]
public static void CreateScrollRectPaginator()
{
Utilites.CreateWidgetFromAsset("ScrollRectPaginator");
}
/// <summary>
/// Create ScrollRectNumericPaginator.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/ScrollRectNumericPaginator", false, 5030)]
public static void CreateScrollRectNumericPaginator()
{
Utilites.CreateWidgetFromAsset("ScrollRectNumericPaginator" + Suffix);
}
/// <summary>
/// Create Sidebar.
/// </summary>
[MenuItem("GameObject/UI/New UI Widgets/Misc/Sidebar", false, 5040)]
public static void CreateSidebar()
{
Utilites.CreateWidgetFromAsset("Sidebar");
}
}
}
#endif | 27.617052 | 167 | 0.699911 | [
"MIT"
] | cschladetsch/CardChess | Assets/External/NewUIWidgets/Editor/MenuOptions.cs | 19,113 | C# |
using System;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityToCustomEngineExporter.Editor
{
public static class ExportUtils
{
private static readonly char[] InvalidFileNameChars =
{
'\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x09', '\x0A',
'\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15',
'\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D', '\x1E', '\x1F', '\x22',
'\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/'
};
public static string GetGUID(this Object asset)
{
if (asset == null)
return "";
var assetPath = AssetDatabase.GetAssetPath(asset);
if (string.IsNullOrWhiteSpace(assetPath))
return "";
return AssetDatabase.AssetPathToGUID(assetPath);
}
public static AssetKey GetKey(this Object asset)
{
if (asset == null)
return AssetKey.Empty;
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out var guid, out long localId))
return new AssetKey(guid, localId);
var assetPath = AssetDatabase.GetAssetPath(asset);
if (!string.IsNullOrWhiteSpace(assetPath)) return new AssetKey(AssetDatabase.AssetPathToGUID(assetPath), 0);
assetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(asset);
if (!string.IsNullOrWhiteSpace(assetPath)) return new AssetKey(AssetDatabase.AssetPathToGUID(assetPath), 0);
return AssetKey.Empty;
}
public static string ReplaceExtension(string assetUrhoAssetName, string newExt)
{
if (assetUrhoAssetName == null)
return null;
var lastDot = assetUrhoAssetName.LastIndexOf('.');
var lastSlash = assetUrhoAssetName.LastIndexOf('/');
if (lastDot > lastSlash) return assetUrhoAssetName.Substring(0, lastDot) + newExt;
return assetUrhoAssetName + newExt;
}
public static string GetRelPathFromAssetPath(string subfolder, string assetPath)
{
var result = assetPath;
if (result.StartsWith("Assets/", StringComparison.InvariantCultureIgnoreCase))
result = result.Substring("Assets/".Length);
if (!string.IsNullOrWhiteSpace(subfolder))
{
if (subfolder.EndsWith("/"))
result = subfolder + result;
else
result = subfolder + "/" + result;
}
return result;
}
public static string GetRelPathFromAsset(string subfolder, Object asset)
{
if (asset == null)
return null;
var path = AssetDatabase.GetAssetPath(asset);
return GetRelPathFromAssetPath(subfolder, path);
}
public static string GetRelPathFromAsset(string subfolder, Scene asset)
{
var path = asset.path;
return GetRelPathFromAssetPath(subfolder, path);
}
public static DateTime GetLastWriteTimeUtc(Object asset)
{
if (asset == null)
return DateTime.MinValue;
var relPath = GetRelPathFromAsset(null, asset);
return GetLastWriteTimeUtcFromRelPath(relPath);
}
public static DateTime GetLastWriteTimeUtc(params Object[] assets)
{
if (assets == null)
return DateTime.MinValue;
return MaxDateTime(assets.Select(_ => GetLastWriteTimeUtc(_)).ToArray());
}
public static string SafeFileName(string name)
{
if (string.IsNullOrEmpty(name)) return name;
foreach (var invalidFileNameChar in InvalidFileNameChars)
name = name.Replace(invalidFileNameChar, '_');
return name;
}
public static DateTime GetLastWriteTimeUtc(string assetPath)
{
var relPath = GetRelPathFromAssetPath("", assetPath);
return GetLastWriteTimeUtcFromRelPath(relPath);
}
public static DateTime MaxDateTime(params DateTime[] dateTimes)
{
var max = DateTime.MinValue;
foreach (var dateTime in dateTimes)
if (dateTime > max)
max = dateTime;
return max;
}
public static Object[] LoadAllAssetsAtPath(string assetPath)
{
return typeof(SceneAsset).Equals(AssetDatabase.GetMainAssetTypeAtPath(assetPath))
? new[] {AssetDatabase.LoadMainAssetAtPath(assetPath)}
: AssetDatabase.LoadAllAssetsAtPath(assetPath);
}
public static TextureOptions GetTextureOptions(Texture texture)
{
var assetPath = AssetDatabase.GetAssetPath(texture);
var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
if (tImporter != null)
{
var options = new TextureOptions();
var type = tImporter.textureType;
options.sRGBTexture = type == TextureImporterType.Default ? tImporter.sRGBTexture : false;
options.filterMode = tImporter.filterMode;
options.wrapMode = tImporter.wrapMode;
options.mipmapEnabled = tImporter.mipmapEnabled;
options.textureImporterFormat = tImporter.GetAutomaticFormat("Standalone");
return options;
}
// Default texture options.
return new TextureOptions
{
filterMode = FilterMode.Trilinear,
mipmapEnabled = true,
sRGBTexture = true,
textureImporterFormat = null,
wrapMode = TextureWrapMode.Repeat
};
}
public static string Combine(params string[] segments)
{
var path = new StringBuilder();
var separator = "";
foreach (var segment in segments)
{
if (string.IsNullOrWhiteSpace(segment)) continue;
path.Append(separator);
separator = "/";
path.Append(segment);
if (segment.EndsWith("/"))
separator = "";
}
return path.ToString();
}
public static string GetName(Object asset)
{
if (!string.IsNullOrWhiteSpace(asset.name))
return asset.name;
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out var guid, out long localId))
return guid + "_" + localId;
return asset.GetInstanceID().ToString();
//return asset.GetInstanceID().ToString();
}
private static DateTime GetLastWriteTimeUtcFromRelPath(string relPath)
{
if (string.IsNullOrWhiteSpace(relPath))
return DateTime.MaxValue;
var file = Path.Combine(Application.dataPath, relPath);
if (!File.Exists(file))
return DateTime.MaxValue;
return File.GetLastWriteTimeUtc(file);
}
}
} | 36.767327 | 120 | 0.569409 | [
"MIT"
] | elix22/Unity2Urho | Editor/ExportUtils.cs | 7,429 | C# |
using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.UI;
public class DebugWindowManager : MonoBehaviour
{
[SerializeField] [ChildGameObjectsOnly]
private Text param_0, param_1;
[SerializeField] [AssetsOnly] private GeneralParameter param;
void Start()
{
}
void Update()
{
param_0.text = param.param_0;
param_1.text = param.param_1;
}
}
| 20.217391 | 65 | 0.705376 | [
"MIT"
] | TakashiHamada/advent_calendar_2021 | Assets/DebugWindow/DebugWindowManager.cs | 465 | C# |
using CommandLine;
using Howmessy.Cli;
using Howmessy.CodeAnalysis.Analyzers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using System.Dynamic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
Parser.Default.ParseArguments<Options>(args).WithParsed(Process);
static void Process(Options options)
{
if (options is null || options.Path is null || options.Metrics is null)
{
return;
}
var program = GetProgramRoot(options.Path);
var root = GetProgramRoot(options.Path);
var results = new Dictionary<string, ExpandoObject>();
var methods = GetMethods(root).ToList();
foreach (var method in methods)
{
var methodName = GetMemberName(method);
if (!IsTargetMember(methodName, options.Target))
{
continue;
}
if (!results.TryGetValue(methodName, out var result))
{
result = new ExpandoObject();
_ = result.TryAdd("Name", methodName);
results[methodName] = result;
}
foreach (var metric in options.Metrics)
{
var metricName = GetMetricName(metric);
var analyzeResult = AnalyzeMethod(method, metric);
_ = result.TryAdd(metricName!, analyzeResult);
}
}
var output = options.Format switch
{
Format.xml => SerializeToXml(results.Values),
Format.json => SerializeToJson(results.Values),
_ => SerializeToJson(results.Values)
};
Console.WriteLine(output);
}
static string GetMetricName(Metrics metrics)
{
var attribute = metrics.GetType()
.GetMember(metrics.ToString())
.First()
.GetCustomAttributes(typeof(DisplayAttribute), inherit: false)
.First() as DisplayAttribute;
return attribute?.Name ?? throw new ArgumentException("Could not found DisplayAttribute in the specified metrics.", nameof(metrics));
}
static CompilationUnitSyntax GetProgramRoot(string path)
{
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
using var reader = new StreamReader(fs);
var program = reader.ReadToEnd();
var tree = CSharpSyntaxTree.ParseText(program);
var root = tree.GetCompilationUnitRoot();
return root;
}
static object AnalyzeMethod(BaseMethodDeclarationSyntax method, Metrics metrics)
{
switch (metrics)
{
case Metrics.cognitive:
{
return CognitiveComplexityAnalyzer.Analyze(method); ;
}
case Metrics.cyclomatic:
{
return CyclomaticComplexityAnalyzer.Analyze(method);
}
case Metrics.mi:
{
var cyclomatic = CyclomaticComplexityAnalyzer.Analyze(method);
var (_, logicalLoc) = method?.ExpressionBody == null
? LinesOfCodeAnalyzer.Analyze(method?.Body, ignoreBlockBrackets: true)
: LinesOfCodeAnalyzer.Analyze(method?.ExpressionBody?.Expression, ignoreBlockBrackets: false);
return (int)MaintainabilityIndexAnalyzer.Analyze(method, cyclomatic, logicalLoc);
}
case Metrics.loc:
{
var (physicalLoc, logicalLoc) = method?.ExpressionBody == null
? LinesOfCodeAnalyzer.Analyze(method?.Body, ignoreBlockBrackets: true)
: LinesOfCodeAnalyzer.Analyze(method?.ExpressionBody?.Expression, ignoreBlockBrackets: false);
return new
{
Physical = physicalLoc,
Logical = logicalLoc,
};
}
default:
throw new ArgumentOutOfRangeException(nameof(metrics));
}
}
static string GetMemberName(SyntaxNode? node)
{
if (node is null)
{
return string.Empty;
}
switch (node)
{
case AccessorListSyntax accessorList:
return GetMemberName(accessorList.Parent);
case AccessorDeclarationSyntax accessor when accessor.IsKind(SyntaxKind.SetAccessorDeclaration):
return GetMemberName(accessor.Parent) + " { set; }";
case AccessorDeclarationSyntax accessor when accessor.IsKind(SyntaxKind.GetAccessorDeclaration):
return GetMemberName(accessor.Parent) + " { get; }";
case PropertyDeclarationSyntax property:
return GetMemberName(property.Parent) + "." + property.Identifier.ValueText;
case IndexerDeclarationSyntax indexer:
return GetMemberName(indexer.Parent) + ".this" + indexer.ParameterList;
case MethodDeclarationSyntax method:
return GetMemberName(method.Parent) + "." + method.Identifier.ValueText + method.TypeParameterList + method.ParameterList;
case ConstructorDeclarationSyntax constructor:
return GetMemberName(constructor.Parent) + ".ctor" + constructor.ParameterList;
case DestructorDeclarationSyntax destructor:
return GetMemberName(destructor.Parent) + ".dtor" + destructor.ParameterList;
case ConversionOperatorDeclarationSyntax conversion when conversion.ImplicitOrExplicitKeyword.ValueText == "implicit":
return GetMemberName(conversion.Parent) + ".op_Implicit" + conversion.ParameterList;
case ConversionOperatorDeclarationSyntax conversion when conversion.ImplicitOrExplicitKeyword.ValueText == "explicit":
return GetMemberName(conversion.Parent) + ".op_Explicit" + conversion.ParameterList;
case OperatorDeclarationSyntax @operator:
return GetMemberName(@operator.Parent) + ".op_" + @operator.OperatorToken.ValueText + @operator.ParameterList;
case TypeDeclarationSyntax type:
var typeParent = GetMemberName(type.Parent);
return string.IsNullOrEmpty(typeParent)
? "global::" + type.Identifier.ValueText
: typeParent + "." + type.Identifier.ValueText;
case NamespaceDeclarationSyntax @namespace:
return @namespace.Name.ToString();
case FileScopedNamespaceDeclarationSyntax fileScopeNamespace:
return fileScopeNamespace.Name.ToString();
default:
return string.Empty;
}
}
static IEnumerable<BaseMethodDeclarationSyntax> GetMethods(SyntaxNode node)
{
switch (node)
{
case CompilationUnitSyntax root:
foreach (var method in root.Members.SelectMany(GetMethods))
{
yield return method;
}
break;
case NamespaceDeclarationSyntax @namespace:
foreach (var method in @namespace.Members.SelectMany(GetMethods))
{
yield return method;
}
break;
case FileScopedNamespaceDeclarationSyntax fileScopeNamespace:
foreach (var method in fileScopeNamespace.Members.SelectMany(GetMethods))
{
yield return method;
}
break;
case TypeDeclarationSyntax type:
foreach (var method in type.Members.SelectMany(GetMethods))
{
yield return method;
}
break;
case BaseMethodDeclarationSyntax method:
yield return method;
break;
default:
break;
}
}
static bool IsTargetMember(string memberName, string? target)
{
if (string.IsNullOrWhiteSpace(target))
{
return true;
}
var regex = "^" + Regex.Escape(target).Replace("\\*", ".*?").Replace("\\?", ".");
return Regex.IsMatch(memberName, regex);
}
static string SerializeToJson(object result) => JsonConvert.SerializeObject(result, Formatting.Indented);
static string SerializeToXml<T>(T result)
{
var serializer = new XmlSerializer(typeof(T));
using var ms = new MemoryStream();
serializer.Serialize(ms, result);
return Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length);
} | 36.189427 | 138 | 0.637371 | [
"MIT"
] | tackme31/howmessy | Howmessy.Cli/Program.cs | 8,217 | C# |
using System;
namespace Wrox.ProCSharp.WCF
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
public class DemoService : IDemoService
{
public static string Server { get; set; }
public string GetData(string value)
{
string message = string.Format("Message from {0}, You entered: {1}", Server, value);
Console.WriteLine(message);
return message;
}
}
}
| 24.45 | 141 | 0.674847 | [
"MIT"
] | CNinnovation/azureandwebservices | WCF/RoutingSample/DemoService/DemoService.cs | 491 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
using System.IO;
using System.Xml;
using SettingsMigrator;
using CommandLineResources = Microsoft.VisualStudio.TestPlatform.SettingsMigrator.Resources.Resources;
namespace Microsoft.VisualStudio.TestPlatform.SettingsMigrator;
/// <summary>
/// Migrator used to migrate test settings and run settings with embedded testsettings to run settings.
/// </summary>
public class Migrator
{
private const string TestTimeoutAttributeName = "testTimeout";
private const string ParallelTestCountAttributeName = "parallelTestCount";
private const string HostProcessPlatformAttributeName = "hostProcessPlatform";
private const string RunTimeoutAttributeName = "runTimeout";
private const string LegacySettingsNodeName = "LegacySettings";
private const string MSTestNodeName = "MSTest";
private const string ForcedLegacyModeName = "ForcedLegacyMode";
private const string ExecutionNodeName = "Execution";
private const string TimeoutsNodeName = "Timeouts";
private const string TestTypeSpecificNodeName = "TestTypeSpecific";
private const string RunConfigurationNodeName = "RunConfiguration";
private const string TestSessionTimeoutNodeName = "TestSessionTimeout";
private const string DataCollectionRunSettingsNodeName = "DataCollectionRunSettings";
private const string DataCollectorsNodeName = "DataCollectors";
private const string SampleRunSettingsContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<RunSettings></RunSettings>";
private const string AgentNotRespondingTimeoutAttribute = "agentNotRespondingTimeout";
private const string DeploymentTimeoutAttribute = "deploymentTimeout";
private const string ScriptTimeoutAttribute = "scriptTimeout";
private const string TestSettingsExtension = ".testsettings";
private const string RunSettingsExtension = ".runsettings";
/// <summary>
/// Migrates the nodes from given settings to run settings format.
/// </summary>
/// <param name="oldFilePath">Path to old file</param>
/// <param name="newFilePath">Path to new file</param>
public void Migrate(string oldFilePath, string newFilePath)
{
if (!Path.IsPathRooted(oldFilePath))
{
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ValidUsage));
}
if (string.Equals(Path.GetExtension(oldFilePath), TestSettingsExtension, StringComparison.OrdinalIgnoreCase))
{
MigrateTestSettings(oldFilePath, newFilePath);
}
else if (string.Equals(Path.GetExtension(oldFilePath), RunSettingsExtension, StringComparison.OrdinalIgnoreCase))
{
MigrateRunSettings(oldFilePath, newFilePath);
}
else
{
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ValidUsage));
}
}
/// <summary>
/// Given a runSettings with an embedded testSettings, converts it to runSettings.
/// </summary>
/// <param name="oldRunSettingsPath"> Path to old runsettings.</param>
/// <param name="newRunSettingsPath">Path to new runsettings.</param>
private void MigrateRunSettings(string oldRunSettingsPath, string newRunSettingsPath)
{
string? testSettingsPath = null;
using XmlTextReader reader = new(oldRunSettingsPath);
reader.Namespaces = false;
var runSettingsXmlDoc = new XmlDocument();
runSettingsXmlDoc.Load(reader);
var root = runSettingsXmlDoc.DocumentElement;
var testSettingsNode = root.SelectSingleNode(@"/RunSettings/MSTest/SettingsFile");
if (testSettingsNode != null)
{
testSettingsPath = testSettingsNode.InnerText;
}
if (!testSettingsPath.IsNullOrWhiteSpace())
{
// Expand path relative to runSettings location.
if (!Path.IsPathRooted(testSettingsPath))
{
testSettingsPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(oldRunSettingsPath), testSettingsPath));
}
// Remove the embedded testSettings node if it exists.
RemoveEmbeddedTestSettings(runSettingsXmlDoc);
MigrateTestSettingsNodesToRunSettings(testSettingsPath, runSettingsXmlDoc);
runSettingsXmlDoc.Save(newRunSettingsPath);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.RunSettingsCreated, newRunSettingsPath));
}
else
{
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NoEmbeddedSettings));
}
}
/// <summary>
/// Given a testSettings, converts it to runSettings.
/// </summary>
/// <param name="oldTestSettingsPath">Path to old testsettings.</param>
/// <param name="newRunSettingsPath">Path to new runsettings.</param>
private void MigrateTestSettings(string oldTestSettingsPath, string newRunSettingsPath)
{
var runSettingsXmlDoc = new XmlDocument();
runSettingsXmlDoc.LoadXml(SampleRunSettingsContent);
MigrateTestSettingsNodesToRunSettings(oldTestSettingsPath, runSettingsXmlDoc);
runSettingsXmlDoc.Save(newRunSettingsPath);
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.RunSettingsCreated, newRunSettingsPath));
}
/// <summary>
/// Given a testSettings, converts it to runSettings
/// </summary>
/// <param name="testSettingsPath">Path to test settings</param>
/// <param name="runSettingsXmlDoc">Runsettings Xml</param>
private void MigrateTestSettingsNodesToRunSettings(string testSettingsPath, XmlDocument runSettingsXmlDoc)
{
var testSettingsNodes = ReadTestSettingsNodes(testSettingsPath);
string? testTimeout = null;
if (testSettingsNodes.Timeout != null && testSettingsNodes.Timeout.Attributes[TestTimeoutAttributeName] != null)
{
testTimeout = testSettingsNodes.Timeout.Attributes[TestTimeoutAttributeName].Value;
}
string? runTimeout = null;
if (testSettingsNodes.Timeout != null && testSettingsNodes.Timeout.Attributes[RunTimeoutAttributeName] != null)
{
runTimeout = testSettingsNodes.Timeout.Attributes[RunTimeoutAttributeName].Value;
}
string? parallelTestCount = null;
if (testSettingsNodes.Execution != null && testSettingsNodes.Execution.Attributes[ParallelTestCountAttributeName] != null)
{
parallelTestCount = testSettingsNodes.Execution.Attributes[ParallelTestCountAttributeName].Value;
}
string? hostProcessPlatform = null;
if (testSettingsNodes.Execution != null && testSettingsNodes.Execution.Attributes[HostProcessPlatformAttributeName] != null)
{
hostProcessPlatform = testSettingsNodes.Execution.Attributes[HostProcessPlatformAttributeName].Value;
}
// WebTestRunConfiguration node.
if (testSettingsNodes.WebSettings != null)
{
runSettingsXmlDoc.DocumentElement.AppendChild(runSettingsXmlDoc.ImportNode(testSettingsNodes.WebSettings, deep: true));
}
// LegacySettings node.
AddLegacyNodes(testSettingsNodes, testTimeout, parallelTestCount, hostProcessPlatform, runSettingsXmlDoc);
// TestSessionTimeout node.
if (!runTimeout.IsNullOrEmpty())
{
AddRunTimeoutNode(runTimeout, runSettingsXmlDoc);
}
// DataCollectors node.
if (testSettingsNodes.Datacollectors != null && testSettingsNodes.Datacollectors.Count > 0)
{
AddDataCollectorNodes(testSettingsNodes.Datacollectors, runSettingsXmlDoc);
}
}
private TestSettingsNodes ReadTestSettingsNodes(string testSettingsPath)
{
var testSettingsNodes = new TestSettingsNodes();
using (XmlTextReader reader = new(testSettingsPath))
{
reader.Namespaces = false;
var testSettingsXmlDoc = new XmlDocument();
testSettingsXmlDoc.Load(reader);
var testSettingsRoot = testSettingsXmlDoc.DocumentElement;
// Select the interesting nodes from the xml.
testSettingsNodes.Deployment = testSettingsRoot.SelectSingleNode(@"/TestSettings/Deployment");
testSettingsNodes.Script = testSettingsRoot.SelectSingleNode(@"/TestSettings/Scripts");
testSettingsNodes.WebSettings = testSettingsRoot.SelectSingleNode(@"/TestSettings/Execution/TestTypeSpecific/WebTestRunConfiguration");
testSettingsNodes.Datacollectors = testSettingsRoot.SelectNodes(@"/TestSettings/Execution/AgentRule/DataCollectors/DataCollector");
testSettingsNodes.Timeout = testSettingsRoot.SelectSingleNode(@"/TestSettings/Execution/Timeouts");
testSettingsNodes.UnitTestConfig = testSettingsRoot.SelectSingleNode(@"/TestSettings/Execution/TestTypeSpecific/UnitTestRunConfig");
testSettingsNodes.Hosts = testSettingsRoot.SelectSingleNode(@"/TestSettings/Execution/Hosts");
testSettingsNodes.Execution = testSettingsRoot.SelectSingleNode(@"/TestSettings/Execution");
if (testSettingsNodes.Timeout != null && (testSettingsNodes.Timeout.Attributes[AgentNotRespondingTimeoutAttribute] != null ||
testSettingsNodes.Timeout.Attributes[DeploymentTimeoutAttribute] != null || testSettingsNodes.Timeout.Attributes[ScriptTimeoutAttribute] != null))
{
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.UnsupportedAttributes));
}
}
return testSettingsNodes;
}
/// <summary>
/// Removes the embedded testSettings node if present.
/// </summary>
/// <param name="newXmlDoc">Xml doc to process</param>
private void RemoveEmbeddedTestSettings(XmlDocument newXmlDoc)
{
var testSettingsNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/MSTest/SettingsFile");
if (testSettingsNode != null)
{
testSettingsNode.ParentNode.RemoveChild(testSettingsNode);
}
}
/// <summary>
/// Adds the legacy nodes to runSettings xml.
/// </summary>
/// <param name="testSettingsNodes">testSettingsNodes</param>
/// <param name="testTimeout">testTimeout</param>
/// <param name="parallelTestCount">parallelTestCount</param>
/// <param name="hostProcessPlatform">hostProcessPlatform</param>
/// <param name="newXmlDoc">newXmlDoc</param>
private void AddLegacyNodes(TestSettingsNodes testSettingsNodes, string? testTimeout, string? parallelTestCount, string? hostProcessPlatform, XmlDocument newXmlDoc)
{
if (testSettingsNodes.Deployment == null
&& testSettingsNodes.Script == null
&& testSettingsNodes.UnitTestConfig == null
&& parallelTestCount.IsNullOrEmpty()
&& testTimeout.IsNullOrEmpty()
&& hostProcessPlatform.IsNullOrEmpty()
&& testSettingsNodes.Hosts == null)
{
return;
}
// Add ForcedLegacy node.
var mstestNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/MSTest");
XmlNode forcedLegacyNode;
if (mstestNode == null)
{
mstestNode = newXmlDoc.CreateNode(XmlNodeType.Element, MSTestNodeName, null);
newXmlDoc.DocumentElement.AppendChild(mstestNode);
mstestNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/MSTest");
}
forcedLegacyNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/MSTest/ForcedLegacyMode");
if (forcedLegacyNode == null)
{
forcedLegacyNode = newXmlDoc.CreateNode(XmlNodeType.Element, ForcedLegacyModeName, null);
mstestNode.AppendChild(newXmlDoc.ImportNode(forcedLegacyNode, deep: true));
forcedLegacyNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/MSTest/ForcedLegacyMode");
}
forcedLegacyNode.InnerText = "true";
// Remove if the legacy node already exists.
var legacyNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/LegacySettings");
if (legacyNode != null)
{
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.IgnoringLegacySettings));
legacyNode.ParentNode.RemoveChild(legacyNode);
}
legacyNode = newXmlDoc.CreateNode(XmlNodeType.Element, LegacySettingsNodeName, null);
if (testSettingsNodes.Deployment != null)
{
legacyNode.AppendChild(newXmlDoc.ImportNode(testSettingsNodes.Deployment, deep: true));
}
if (testSettingsNodes.Script != null)
{
legacyNode.AppendChild(newXmlDoc.ImportNode(testSettingsNodes.Script, deep: true));
}
// Execution node.
if (testSettingsNodes.UnitTestConfig != null || !parallelTestCount.IsNullOrEmpty() || !testTimeout.IsNullOrEmpty() || testSettingsNodes.Hosts != null)
{
var newExecutionNode = newXmlDoc.CreateNode(XmlNodeType.Element, ExecutionNodeName, null);
if (!parallelTestCount.IsNullOrEmpty())
{
var paralellAttribute = newXmlDoc.CreateAttribute(ParallelTestCountAttributeName);
paralellAttribute.Value = parallelTestCount;
newExecutionNode.Attributes.Append(paralellAttribute);
}
if (!hostProcessPlatform.IsNullOrEmpty())
{
var hostProcessPlatformAttribute = newXmlDoc.CreateAttribute(HostProcessPlatformAttributeName);
hostProcessPlatformAttribute.Value = hostProcessPlatform;
newExecutionNode.Attributes.Append(hostProcessPlatformAttribute);
}
if (!testTimeout.IsNullOrEmpty())
{
var newTimeoutsNode = newXmlDoc.CreateNode(XmlNodeType.Element, TimeoutsNodeName, null);
var testtimeoutattribute = newXmlDoc.CreateAttribute(TestTimeoutAttributeName);
testtimeoutattribute.Value = testTimeout;
newTimeoutsNode.Attributes.Append(testtimeoutattribute);
newExecutionNode.AppendChild(newXmlDoc.ImportNode(newTimeoutsNode, deep: true));
}
if (testSettingsNodes.Hosts != null)
{
newExecutionNode.AppendChild(newXmlDoc.ImportNode(testSettingsNodes.Hosts, deep: true));
}
if (testSettingsNodes.UnitTestConfig != null)
{
var testTypeSpecificNode = newXmlDoc.CreateNode(XmlNodeType.Element, TestTypeSpecificNodeName, null);
testTypeSpecificNode.AppendChild(newXmlDoc.ImportNode(testSettingsNodes.UnitTestConfig, deep: true));
newExecutionNode.AppendChild(newXmlDoc.ImportNode(testTypeSpecificNode, deep: true));
}
legacyNode.AppendChild(newXmlDoc.ImportNode(newExecutionNode, deep: true));
}
newXmlDoc.DocumentElement.AppendChild(legacyNode);
}
/// <summary>
/// Adds the datacollector nodes to the runSettings xml.
/// </summary>
/// <param name="oldDatacollectorNodes"> Datacollector Nodes</param>
/// <param name="newXmlDoc">Xml doc to process</param>
private void AddDataCollectorNodes(XmlNodeList oldDatacollectorNodes, XmlDocument newXmlDoc)
{
var dataCollectionRunSettingsNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/DataCollectionRunSettings");
if (dataCollectionRunSettingsNode == null)
{
dataCollectionRunSettingsNode = newXmlDoc.CreateNode(XmlNodeType.Element, DataCollectionRunSettingsNodeName, null);
}
var dataCollectorsNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/DataCollectionRunSettings/DataCollectors");
if (dataCollectorsNode == null)
{
dataCollectorsNode = newXmlDoc.CreateNode(XmlNodeType.Element, DataCollectorsNodeName, null);
dataCollectionRunSettingsNode.AppendChild(newXmlDoc.ImportNode(dataCollectorsNode, deep: true));
newXmlDoc.DocumentElement.AppendChild(dataCollectionRunSettingsNode);
dataCollectorsNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/DataCollectionRunSettings/DataCollectors");
}
foreach (XmlNode datacollector in oldDatacollectorNodes)
{
dataCollectorsNode.AppendChild(newXmlDoc.ImportNode(datacollector, deep: true));
}
}
/// <summary>
/// Adds run session timeout node.
/// </summary>
/// <param name="runTimeout">Run Timeout</param>
/// <param name="newXmlDoc">Xml doc to process</param>
private void AddRunTimeoutNode(string runTimeout, XmlDocument newXmlDoc)
{
var runConfigurationNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/RunConfiguration");
if (runConfigurationNode == null)
{
runConfigurationNode = newXmlDoc.CreateNode(XmlNodeType.Element, RunConfigurationNodeName, null);
}
var testSessionTimeoutNode = newXmlDoc.CreateNode(XmlNodeType.Element, TestSessionTimeoutNodeName, null);
testSessionTimeoutNode.InnerText = runTimeout;
runConfigurationNode.AppendChild(newXmlDoc.ImportNode(testSessionTimeoutNode, deep: true));
newXmlDoc.DocumentElement.AppendChild(runConfigurationNode);
}
}
| 44.447761 | 200 | 0.695545 | [
"MIT"
] | SimonCropp/vstest | src/SettingsMigrator/Migrator.cs | 17,870 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaymentServiceLib.Enum
{
/// <summary>The style of PaymentTerminal dialog.</summary>
public enum DialogType
{
/// <summary>The standard PaymentTerminal dialog.</summary>
Standard = '0',
/// <summary>The PaymentTerminal dialog for touch screens. Has larger buttons.</summary>
TouchScreen = '1',
/// <summary>Do not show the PaymentTerminal dialogs.</summary>
Hidden = '2'
}
/// <summary>The position of the PaymentTerminal dialog.</summary>
/// <remarks>Currently not supported.</remarks>
public enum DialogPosition
{
/// <summary>The top left position of the screen.</summary>
TopLeft,
/// <summary>The top centre position of the screen.</summary>
TopCentre,
/// <summary>The top right position of the screen.</summary>
TopRight,
/// <summary>The middle left position of the screen.</summary>
MiddleLeft,
/// <summary>The centre position of the screen.</summary>
Centre,
/// <summary>The middle right position of the screen.</summary>
MiddleRight,
/// <summary>The bottom left position of the screen.</summary>
BottomLeft,
/// <summary>The bottom centre position of the screen.</summary>
BottomCentre,
/// <summary>The bottom right position of the screen.</summary>
BottomRight
}
}
| 34.155556 | 96 | 0.639558 | [
"MIT"
] | ramdeoangh/IPaymentService | PaymentServiceLib/Enum/Dialog.cs | 1,539 | C# |
using System;
using System.ComponentModel;
using System.IO;
using PluginCore;
using PluginCore.Bridge;
using PluginCore.Helpers;
using PluginCore.Localization;
using PluginCore.Utilities;
namespace BridgeSettings
{
public class PluginMain: IPlugin
{
private String pluginName = "BridgeSettings";
private String pluginGuid = "30727dde-3e23-4fb8-a8fb-9feb958402fc";
private String pluginHelp = "www.flashdevelop.org/community/";
private String pluginDesc = "Adds virtualization bridge configuration to FlashDevelop.";
private String pluginAuth = "FlashDevelop Team";
private String settingFilename;
private Settings settingObject;
#region Required Properties
/// <summary>
/// Api level of the plugin
/// </summary>
public Int32 Api
{
get { return 1; }
}
/// <summary>
/// Name of the plugin
/// </summary>
public String Name
{
get { return this.pluginName; }
}
/// <summary>
/// GUID of the plugin
/// </summary>
public String Guid
{
get { return this.pluginGuid; }
}
/// <summary>
/// Author of the plugin
/// </summary>
public String Author
{
get { return this.pluginAuth; }
}
/// <summary>
/// Description of the plugin
/// </summary>
public String Description
{
get { return this.pluginDesc; }
}
/// <summary>
/// Web address for help
/// </summary>
public String Help
{
get { return this.pluginHelp; }
}
/// <summary>
/// Object that contains the settings
/// </summary>
[Browsable(false)]
public Object Settings
{
get { return this.settingObject; }
}
#endregion
#region Required Methods
/// <summary>
/// Initializes the plugin
/// </summary>
public void Initialize()
{
this.InitBasics();
this.LoadSettings();
BridgeManager.Settings = settingObject;
}
/// <summary>
/// Disposes the plugin
/// </summary>
public void Dispose()
{
this.SaveSettings();
}
/// <summary>
/// Handles the incoming events
/// </summary>
public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority priority)
{
// Nothing to do here..
}
#endregion
#region Custom methods
/// <summary>
/// Sets up the basic stuff
/// </summary>
private void InitBasics()
{
String dataPath = Path.Combine(PathHelper.DataDir, "BridgeSettings");
if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath);
this.settingFilename = Path.Combine(dataPath, "Settings.fdb");
this.pluginDesc = TextHelper.GetString("Info.Description");
}
/// <summary>
/// Loads the plugin settings
/// </summary>
public void LoadSettings()
{
this.settingObject = new Settings();
if (!File.Exists(this.settingFilename)) this.SaveSettings();
else
{
Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject);
this.settingObject = (Settings)obj;
}
}
/// <summary>
/// Saves the plugin settings
/// </summary>
public void SaveSettings()
{
ObjectSerializer.Serialize(this.settingFilename, this.settingObject);
}
#endregion
}
}
| 25.359477 | 100 | 0.529639 | [
"MIT"
] | Chr0n0AP/flashdevelop | External/Plugins/BridgeSettings/PluginMain.cs | 3,882 | 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("Bloom.Analytics.Controls")]
[assembly: AssemblyDescription("WPF Controls shared by Bloom Analytics.")]
[assembly: AssemblyConfiguration("")]
[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("ba3de89f-f062-4ce2-b3bf-0bd4ed1a8a02")]
| 41.52381 | 84 | 0.776376 | [
"Apache-2.0"
] | RobDixonIII/Bloom | Analytics/Bloom.Analytics.Controls/Properties/AssemblyInfo.cs | 874 | C# |
namespace EnergyTrading.Mdm.Data.Search
{
using System.Collections.Generic;
using EnergyTrading.Contracts.Search;
using EnergyTrading.Data;
public class SearchService<TEntity, TDetails, TMapping>
where TDetails : class, IEntityDetail where TEntity : class, IEntity where TMapping : class, IEntityMapping
{
private readonly IQueryFactory queryFactory;
private readonly ISearchCommand<TEntity, TDetails, TMapping> searchCommand;
public SearchService(IQueryFactory queryFactory, ISearchCommand<TEntity, TDetails, TMapping> searchCommand)
{
this.queryFactory = queryFactory;
this.searchCommand = searchCommand;
}
public IList<int> Search(Search search)
{
int? maxResults = !search.SearchOptions.MultiPage ? search.SearchOptions.ResultsPerPage : null;
string query = this.queryFactory.CreateQuery(search);
if (query == string.Empty)
{
query = "true";
}
return search.SearchOptions.IsMappingSearch ? this.searchCommand.ExecuteMappingSearch(query, search.AsOf, maxResults) :
this.searchCommand.Execute(query, search.AsOf, maxResults, search.SearchOptions.OrderBy);
}
public IList<TEntity> NonTemporalSearch(Search search)
{
int? maxResults = !search.SearchOptions.MultiPage ? search.SearchOptions.ResultsPerPage : null;
string query = this.queryFactory.CreateQuery(search);
if (query == string.Empty)
{
query = "true";
}
return this.searchCommand.ExecuteNonTemporal(query, search.AsOf, maxResults, search.SearchOptions.OrderBy);
}
}
} | 36.204082 | 131 | 0.651635 | [
"MIT"
] | RWE-Nexus/EnergyTrading-MDM | Code/MDM.Core/Data/Search/SearchService.cs | 1,774 | C# |
using MC.ApplicationServices.DTOs;
using MC.Data.Entities;
using MC.Repositories.Implementations;
using System.Collections.Generic;
namespace MC.ApplicationServices.Implementations
{
public class MovieManagementService
{
public List<MovieDto> Get()
{
List<MovieDto> moviesDto = new List<MovieDto>();
using (UnitOfWork unitOfWork = new UnitOfWork())
{
foreach (var item in unitOfWork.MovieRepository.Get())
{
moviesDto.Add(new MovieDto
{
Id = item.Id,
Title = item.Title,
ReleaseDate = item.ReleaseDate,
ReleaseCountry = item.ReleaseCountry,
Genre = new GenreDto
{
Id = item.GenreId,
Name = item.Genre.Name
}
});
}
}
return moviesDto;
}
public MovieDto GetById(int id)
{
MovieDto movieDto = new MovieDto();
using (UnitOfWork unitOfWork = new UnitOfWork())
{
Movie movie = unitOfWork.MovieRepository.GetByID(id);
movieDto = new MovieDto
{
Title = movie.Title,
ReleaseDate = movie.ReleaseDate,
ReleaseCountry = movie.ReleaseCountry,
Genre = new GenreDto
{
Id = movie.GenreId,
Name = movie.Genre.Name
}
};
}
return movieDto;
}
public bool Save(MovieDto movieDto)
{
Movie movie = new Movie
{
Id = movieDto.Id,
Title = movieDto.Title,
ReleaseDate = movieDto.ReleaseDate,
ReleaseCountry = movieDto.ReleaseCountry,
GenreId = movieDto.Genre.Id
};
try
{
using (UnitOfWork unitOfWork = new UnitOfWork())
{
if (movieDto.Id == 0)
unitOfWork.MovieRepository.Insert(movie);
else
unitOfWork.MovieRepository.Update(movie);
unitOfWork.Save();
}
return true;
}
catch
{
return false;
}
}
public bool Delete(int id)
{
try
{
using (UnitOfWork unitOfWork = new UnitOfWork())
{
Movie movie = unitOfWork.MovieRepository.GetByID(id);
unitOfWork.MovieRepository.Delete(movie);
unitOfWork.Save();
}
return true;
}
catch
{
return false;
}
}
}
}
| 28.263636 | 73 | 0.418784 | [
"MIT"
] | pkyurkchiev/distributed-applications-for-se | exercises/03/MovieCatalog/MC.ApplicationServices/Implementations/MovieManagementService.cs | 3,111 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace littlebreadloaf.Areas.Identity.Pages.Account
{
[AllowAnonymous]
public class ConfirmEmailModel : PageModel
{
private readonly UserManager<IdentityUser> _userManager;
public ConfirmEmailModel(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}
public async Task<IActionResult> OnGetAsync(string userId, string code)
{
if (userId == null || code == null)
{
return RedirectToPage("/Index");
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return NotFound($"Unable to load user with ID '{userId}'.");
}
var result = await _userManager.ConfirmEmailAsync(user, code);
if (!result.Succeeded)
{
throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
}
return Page();
}
}
}
| 28.733333 | 108 | 0.613302 | [
"MIT"
] | ZombieFleshEaters/littlebreadloaf | littlebreadloaf/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs | 1,295 | C# |
using System;
class Money
{
static void Main()
{
int numberOfStudents = int.Parse(Console.ReadLine());
int papersPerStudent = int.Parse(Console.ReadLine());
decimal priceOfRealm = decimal.Parse(Console.ReadLine());
long totalAmountOfPaper = numberOfStudents * papersPerStudent;
decimal numberOfReamls = (decimal)totalAmountOfPaper / 400;
decimal moneyBeingSaved = numberOfReamls * priceOfRealm;
Console.WriteLine("{0:F3}", moneyBeingSaved);
}
}
| 25.95 | 70 | 0.674374 | [
"MIT"
] | iliyaST/TelericAcademy | C#1/13-Testing-Exam-Six-2February2015Evening/01.Money/Program.cs | 521 | C# |
namespace PressCenters.Services.Sources.Ministries
{
using System;
using System.Collections.Generic;
using System.Globalization;
using AngleSharp.Dom;
/// <summary>
/// Министерство на труда и социалната политика.
/// </summary>
//// TODO: Rename to MlspGovernmentBgSource
public class MlspBgSource : BaseSource
{
public override string BaseUrl { get; } = "https://www.mlsp.government.bg/";
public override bool UseProxy => true;
public override IEnumerable<RemoteNews> GetLatestPublications() =>
this.GetPublications("novini", ".post__widget .post__title a");
public override IEnumerable<RemoteNews> GetAllPublications()
{
for (var page = 1; page <= 10; page++)
{
var news = this.GetPublications($"novini?page={page}", ".page-content .post__title a");
Console.WriteLine($"Page {page} => {news.Count} news");
foreach (var remoteNews in news)
{
yield return remoteNews;
}
}
}
protected override RemoteNews ParseDocument(IDocument document, string url)
{
var titleElement = document.QuerySelector("h3.post__title");
var title = new CultureInfo("bg-BG", false).TextInfo.ToTitleCase(
titleElement?.TextContent.ToLower() ?? string.Empty);
var timeAsString = document.QuerySelector(".post__created-at")?.TextContent.Trim();
var time = DateTime.Parse(timeAsString, CultureInfo.InvariantCulture);
var imageElement = document.QuerySelector(".post__content img");
var imageUrl = imageElement?.GetAttribute("src");
var contentElement = document.QuerySelector(".post__content");
contentElement.RemoveRecursively(imageElement);
this.NormalizeUrlsRecursively(contentElement);
var content = contentElement?.InnerHtml;
return new RemoteNews(title, content, time, imageUrl);
}
}
}
| 37.267857 | 103 | 0.618112 | [
"MIT"
] | IliyanAng/PressCenters.com | src/Services/PressCenters.Services.Sources/Ministries/MlspBgSource.cs | 2,127 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
#pragma warning disable 1591
namespace Silk.NET.Vulkan
{
public enum DriverId
{
DriverIDAmdProprietary = 1,
DriverIDAmdOpenSource = 2,
DriverIDMesaRadv = 3,
DriverIDNvidiaProprietary = 4,
DriverIDIntelProprietaryWindows = 5,
DriverIDIntelOpenSourceMesa = 6,
DriverIDImaginationProprietary = 7,
DriverIDQualcommProprietary = 8,
DriverIDArmProprietary = 9,
DriverIDGoogleSwiftshader = 10,
DriverIDGgpProprietary = 11,
DriverIDBroadcomProprietary = 12,
DriverIDMesaLlvmpipe = 13,
DriverIDMoltenvk = 14,
}
}
| 25.774194 | 57 | 0.669587 | [
"MIT"
] | FrostByteGER/Silk.NET | src/Vulkan/Silk.NET.Vulkan/Enums/DriverId.gen.cs | 799 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
namespace AspNetCoreBlazor50.Data
{
public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
{
var rng = new Random();
return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
}).ToArray());
}
}
}
| 30.807692 | 111 | 0.556804 | [
"MIT"
] | simpleinjector/SimpleInjector.Integration.AspNetCore | tests/AspNetCoreBlazor50/Data/WeatherForecastService.cs | 801 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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("AWSSDK.RedshiftDataAPIService")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Redshift Data API Service. The Amazon Redshift Data API is generally available. This release enables querying Amazon Redshift data and listing various database objects.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Redshift Data API Service. The Amazon Redshift Data API is generally available. This release enables querying Amazon Redshift data and listing various database objects.")]
#elif NETSTANDARD13
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3) - Redshift Data API Service. The Amazon Redshift Data API is generally available. This release enables querying Amazon Redshift data and listing various database objects.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Redshift Data API Service. The Amazon Redshift Data API is generally available. This release enables querying Amazon Redshift data and listing various database objects.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Redshift Data API Service. The Amazon Redshift Data API is generally available. This release enables querying Amazon Redshift data and listing various database objects.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.5.0.8")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 54.54717 | 260 | 0.780353 | [
"Apache-2.0"
] | atpyatt/aws-sdk-net | sdk/src/Services/RedshiftDataAPIService/Properties/AssemblyInfo.cs | 2,891 | C# |
using System;
using System.IO;
#if UNITY
using UnityEngine;
#else
using System.Numerics;
#endif
namespace Habitat
{
public struct Color32
{
public byte R, G, B, A;
public Color32(byte r, byte g, byte b, byte a)
{
this.R = r;
this.G = g;
this.B = b;
this.A = a;
}
#if !UNITY
public System.Drawing.Color ToDrawingColorNoAlpha()
{
return System.Drawing.Color.FromArgb(255, R, G, B);
}
public System.Drawing.Color ToDrawingColor()
{
return System.Drawing.Color.FromArgb(A, R, G, B);
}
#endif
public Vector4 ToVector4()
{
return new Vector4(R / 255f, G / 255f, B / 255f, A / 255f);
}
public override int GetHashCode()
{
return R + (256 * G) + (512 * B) + (1024 * A);
}
public override string ToString()
{
return $"({R},{G},{B},{A})";
}
public Color32(byte r, byte g, byte b) : this(r, g, b, 255)
{
}
public Color32(Stream dataStream)
{
this.R = (byte)dataStream.ReadByte();
this.G = (byte)dataStream.ReadByte();
this.B = (byte)dataStream.ReadByte();
this.A = (byte)dataStream.ReadByte();
}
public Color32(int bytes)
{
byte[] splitBytes = BitConverter.GetBytes(bytes);
this.R = splitBytes[0];
this.G = splitBytes[1];
this.B = splitBytes[2];
this.A = splitBytes[3];
}
}
}
| 22.611111 | 71 | 0.487101 | [
"MIT"
] | Dummiesman/HabitatExplorer | libhabitat/Data/Color32.cs | 1,630 | C# |
//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2019年8月22日 20:32:18
//------------------------------------------------------------
using NPBehave;
using Sirenix.OdinInspector;
using Action = System.Action;
namespace ETModel
{
public class NP_ServiceNodeData: NP_NodeDataBase
{
[HideInEditorMode]
public Service m_Service;
[LabelText("委托执行时间间隔")]
public float interval;
public NP_ClassForStoreAction NpClassForStoreAction =
new NP_ChangeBlackValueAction() { NPBalckBoardRelationData = new NP_BlackBoardRelationData() { WriteOrCompareToBB = true } };
public override Node NP_GetNode()
{
return this.m_Service;
}
public override Decorator CreateDecoratorNode(long unitId, NP_RuntimeTree runtimeTree, Node node)
{
this.NpClassForStoreAction.Unitid = unitId;
this.NpClassForStoreAction.BelongtoRuntimeTree = runtimeTree;
this.m_Service = new Service(interval, this.NpClassForStoreAction.GetActionToBeDone(), node);
return this.m_Service;
}
}
} | 32.162162 | 141 | 0.603361 | [
"MIT"
] | DBestBean/ETandGF | Server/Model/NKGMOBA/Battle/NPBehave/NodeDatas/Decorator/NP_ServiceNodeData.cs | 1,226 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ExcelChangeHandler.Logging
{
/// <summary>
/// Simple logger interface. An implementation of this interface can be provided to the change handler API to enable logging in the library.
/// </summary>
public interface ILogger
{
/// <summary>
/// Log a debug-level message.
/// </summary>
void Debug(string message);
/// <summary>
/// Log a info-level message.
/// </summary>
void Info(string message);
/// <summary>
/// Log an error-level message with an exception.
/// </summary>
void Error(string message, Exception ex);
}
}
| 26.892857 | 145 | 0.576361 | [
"MIT"
] | hectorjsmith/csharp-excel-changelogger | ExcelChangeHandler/Logging/ILogger.cs | 755 | C# |
using FilterCore.Line;
using FilterPolishUtil.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FilterCore;
namespace FilterDomain.LineStrategy
{
public class EnumLineStrategy : ILineStrategy
{
public EnumLineStrategy(bool sortValues)
{
this.SortValues = sortValues;
}
public bool SortValues = true;
public bool CanHaveOperator => false;
public bool CanHaveComment => false;
public bool CanHaveMultiple => true;
public IFilterLine Construct(string ident, List<LineToken> tokens)
{
var line = this.Construct<EnumValueContainer>(ident, tokens);
(line.Value as EnumValueContainer).PerformSort = SortValues;
return line;
}
}
public class EnumValueContainer : ILineValueCore
{
public bool PerformSort = true;
public HashSet<LineToken> Value = new HashSet<LineToken>();
public string SpecialOperator = string.Empty;
public string SpecialCount = string.Empty;
public void Parse(List<LineToken> tokens)
{
if (tokens.Count == 0)
{
Value.Add(LineToken.CreateValueToken("BLANK"));
return;
}
if (tokens.Count == 1 && tokens[0].value == "==")
{
Value.Add(LineToken.CreateValueToken("=="));
Value.Add(LineToken.CreateValueToken("BLANK"));
return;
}
if (FilterGenerationConfig.FilterOperators.Contains(tokens[0].value))
{
SpecialOperator = tokens[0].value;
tokens.RemoveAt(0);
if (tokens.Count == 0)
{
LoggingFacade.LogWarning("Tokens empty?");
}
var num = 0;
if (int.TryParse(tokens[0].value, out num))
{
SpecialCount = tokens[0].value;
tokens.RemoveAt(0);
}
}
foreach (var item in tokens)
{
if (!Value.Contains(item))
{
Value.Add(item);
}
}
}
public ILineValueCore Clone()
{
return new EnumValueContainer
{
Value = new HashSet<LineToken>(this.Value.Select(x => x.Clone()))
};
}
public string Serialize()
{
List<string> value;
// skip sorting for ExplicitModFiltering
if (this.PerformSort)
{
value = this.Value
.OrderBy(x => x.value)
.Where(y => !FilterGenerationConfig.IgnorableBaseTypes.Contains(y.value))
.Select(z => z.Serialize()).Distinct().ToList();
}
else
{
value = this.Value
.Where(y => !FilterGenerationConfig.IgnorableBaseTypes.Contains(y.value))
.Select(z => z.Serialize()).Distinct().ToList();
}
// add exactsearch operator
if (this.SpecialOperator != string.Empty && this.SpecialCount != string.Empty)
{
value.Insert(0, this.SpecialOperator + this.SpecialCount);
}
else if (this.SpecialOperator != string.Empty)
{
value.Insert(0, this.SpecialOperator);
}
return string.Join(" ", value);
}
public bool IsValid()
{
if (this.Value == null || this.Value.Count == 0 || (this.Value.Count == 1 && this.Value.First().value.ToLower() == "blank"))
{
return false;
}
return true;
}
}
}
| 29.671642 | 136 | 0.500755 | [
"MIT"
] | NeverSinkDev/FilterPolishZ | FilterCore/FilterComponents/Line/LineStrategy/EnumLineStrategy.cs | 3,978 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComposableDelegates
{
// declare the delegate type
public delegate void MyDelegate(int arg1, int arg2);
class Program
{
static void func1(int arg1, int arg2)
{
string result = (arg1 + arg2).ToString();
Console.WriteLine("The number is: " + result);
}
static void func2(int arg1, int arg2)
{
string result = (arg1 * arg2).ToString();
Console.WriteLine("The number is: " + result);
}
static void Main(string[] args)
{
MyDelegate f1 = func1;
MyDelegate f2 = func2;
MyDelegate f1f2 = f1 + f2;
// call each delegate and then the chain
Console.WriteLine("Calling the first delegate");
f1(10, 20);
Console.WriteLine("Calling the second delegate");
f2(10, 20);
Console.WriteLine("\nCalling the chained delegates");
f1f2(10, 20);
// subtract off one of the delegates
Console.WriteLine("\nCalling the unchained delegates");
f1f2 -= f1;
f1f2(20, 20);
Console.WriteLine("\nPress Enter Key to Continue...");
Console.ReadLine();
}
}
}
| 28.854167 | 67 | 0.555957 | [
"MIT"
] | jenmcquade/csharp-snippets | Ex_Files_C_Sharp_events/Exercise Files/FinishedExamples/Delegates/ComposableDelegates/ComposableDelegates/Program.cs | 1,387 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
public partial class ManagedTransparentDataEncryptionData : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("properties");
writer.WriteStartObject();
if (Optional.IsDefined(State))
{
writer.WritePropertyName("state");
writer.WriteStringValue(State.Value.ToSerialString());
}
writer.WriteEndObject();
writer.WriteEndObject();
}
internal static ManagedTransparentDataEncryptionData DeserializeManagedTransparentDataEncryptionData(JsonElement element)
{
ResourceIdentifier id = default;
string name = default;
ResourceType type = default;
Optional<TransparentDataEncryptionState> state = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("id"))
{
id = new ResourceIdentifier(property.Value.GetString());
continue;
}
if (property.NameEquals("name"))
{
name = property.Value.GetString();
continue;
}
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("state"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
property0.ThrowNonNullablePropertyIsNull();
continue;
}
state = property0.Value.GetString().ToTransparentDataEncryptionState();
continue;
}
}
continue;
}
}
return new ManagedTransparentDataEncryptionData(id, name, type, Optional.ToNullable(state));
}
}
}
| 35.9875 | 129 | 0.500174 | [
"MIT"
] | AhmedLeithy/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ManagedTransparentDataEncryptionData.Serialization.cs | 2,879 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetAnimationBoolean : MonoBehaviour, IActivatable
{
public GameObject PortalToOperate;
[SerializeField]
public bool Value;
[SerializeField]
private string BooleanName;
[SerializeField]
public bool verbose;
private Animator Anim;
private void Start()
{
if (PortalToOperate != null)
{
Anim = PortalToOperate.GetComponent<Animator>();
}
else
{
Anim = GetComponent<Animator>();
}
}
public void Activate()
{
Anim.SetBool(BooleanName, Value);
}
}
| 18.324324 | 62 | 0.617994 | [
"MIT"
] | JayneGale/BlankSlate0 | Assets/Scripts/Redevelopment/Activatable/SetAnimationBoolean.cs | 680 | C# |
using System;
using System.Linq;
namespace ZeroLog
{
internal static class LevelStringCache
{
private static readonly string[] _levelStrings;
static LevelStringCache()
{
_levelStrings = Enum.GetNames(typeof(Level)).Select(x => x.ToUpperInvariant()).ToArray();
}
public static string GetLevelString(Level level) => _levelStrings[(byte)level];
}
}
| 23 | 101 | 0.652174 | [
"MIT"
] | Abc-Arbitrage/ZeroLog | src/ZeroLog/LevelStringCache.cs | 416 | C# |
#region Apache Notice
/*****************************************************************************
* $Revision: 469233 $
* $LastChangedDate: 2006-10-30 20:09:11 +0100 (lun., 30 oct. 2006) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* 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.
*
********************************************************************************/
#endregion
#region Using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using SqlBatis.DataMapper.Configuration.ResultMapping;
using SqlBatis.DataMapper.Configuration.ParameterMapping;
using SqlBatis.DataMapper.Configuration.Sql;
#endregion
namespace SqlBatis.DataMapper.Configuration.Statements
{
/// <summary>
/// Summary description for ISql.
/// </summary>
public interface IStatement
{
#region Properties
/// <summary>
/// Allow remapping of dynamic SQL
/// </summary>
bool AllowRemapping
{
get;
set;
}
/// <summary>
/// Identifier used to identify the statement amongst the others.
/// </summary>
string Id
{
get;
set;
}
/// <summary>
/// The type of the statement (text or procedure).
/// </summary>
CommandType CommandType
{
get;
}
/// <summary>
/// Extend statement attribute
/// </summary>
string ExtendStatement
{
get;
set;
}
/// <summary>
/// The sql statement to execute.
/// </summary>
ISql Sql
{
get;
set;
}
/// <summary>
/// The ResultMaps used by the statement.
/// </summary>
ResultMapCollection ResultsMap
{
get;
}
/// <summary>
/// The parameterMap used by the statement.
/// </summary>
ParameterMap ParameterMap
{
get;
set;
}
/// <summary>
/// The list class type to use for strongly typed collection.
/// </summary>
Type ListClass
{
get;
}
/// <summary>
/// The result class type to used.
/// </summary>
Type ResultClass
{
get;
}
/// <summary>
/// The parameter class type to used.
/// </summary>
Type ParameterClass
{
get;
}
#endregion
#region Methods
/// <summary>
/// Create an instance of 'IList' class.
/// </summary>
/// <returns>An object which implement IList.</returns>
IList CreateInstanceOfListClass();
/// <summary>
/// Create an instance of a generic 'IList' class.
/// </summary>
/// <returns>An object which implement IList.</returns>
IList<T> CreateInstanceOfGenericListClass<T>();
#endregion
}
}
| 24.098684 | 82 | 0.521431 | [
"Apache-2.0"
] | rasitha1/IBatisNet.Standard | src/SqlBatis.DataMapper/Configuration/Statements/IStatement.cs | 3,663 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Cooking
{
public class Program
{
static void Main(string[] args)
{
var liquidsInput = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
var ingredientsInput = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
Queue<int> liquids = new Queue<int>(liquidsInput);
Stack<int> ingredients = new Stack<int>(ingredientsInput);
var bread = 0;
var cake = 0;
var pastry = 0;
var fruitPie = 0;
while (liquids.Count != 0 && ingredients.Count != 0)
{
var calc = liquids.Peek() + ingredients.Peek();
if (calc == 25)
{
liquids.Dequeue();
ingredients.Pop();
bread++;
}
else if (calc == 50)
{
liquids.Dequeue();
ingredients.Pop();
cake++;
}
else if (calc == 75)
{
liquids.Dequeue();
ingredients.Pop();
pastry++;
}
else if (calc == 100)
{
liquids.Dequeue();
ingredients.Pop();
fruitPie++;
}
else
{
liquids.Dequeue();
ingredients.Push(ingredients.Pop() + 3);
}
}
if (bread > 0 && cake > 0 && pastry > 0 && fruitPie > 0)
{
Console.WriteLine($"Wohoo! You succeeded in cooking all the food!");
}
else
{
Console.WriteLine($"Ugh, what a pity! You didn't have enough materials to cook everything.");
}
if (liquids.Count > 0)
{
Console.Write($"Liquids left: ");
Console.Write(string.Join(", ", liquids));
Console.WriteLine();
}
else
{
Console.WriteLine($"Liquids left: none");
}
if (ingredients.Count > 0)
{
Console.Write($"Ingredients left: ");
Console.Write(string.Join(", ",ingredients));
Console.WriteLine();
}
else
{
Console.WriteLine($"Ingredients left: none");
}
Console.WriteLine($"Bread: {bread}\nCake: {cake}\nFruit Pie: {fruitPie}\nPastry: {pastry}");
}
}
}
| 33.392857 | 132 | 0.425312 | [
"MIT"
] | hidden16/Softuni-Advanced | Advanced/ExamPreparation/Cooking/Program.cs | 2,807 | C# |
// Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Lappa_ORM;
namespace Framework.Database.Character.Entities
{
public class CharacterTemplateItem : Entity
{
[PrimaryKey]
public int ItemId { get; set; }
public byte ClassId { get; set; }
public bool IsEquipped { get; set; }
[ForeignKey("ClassId")]
public virtual CharacterTemplateClass CharacterTemplateClass { get; set; }
}
}
| 28.105263 | 101 | 0.662921 | [
"MIT"
] | gitter-badger/Project-WoW | Projects/Framework/Database/Character/Entities/CharacterTemplateItem.cs | 536 | C# |
//-----------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Scott Xu">
// Copyright (c) 2015 Scott Xu.
// </copyright>
//-----------------------------------------------------------------------------------------------------
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("EntityFramework.Testing.Ninject")]
[assembly: AssemblyDescription("Testing helpers for using Ninject.MockingKernel with EntityFramework.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Scott Xu")]
[assembly: AssemblyProduct("EntityFramework.Testing.Ninject")]
[assembly: AssemblyCopyright("Copyright 2015 Scott Xu")]
[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("ea523ae2-d940-4122-a6ad-dd9acd2e07f9")]
// 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")]
| 42.651163 | 104 | 0.665758 | [
"Apache-2.0"
] | justinyoo/EntityFramework.Testing | src/EntityFramework.Testing.Ninject/Properties/AssemblyInfo.cs | 1,836 | C# |
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleApp.Contracts.Services;
using SampleApp.Contracts.Views;
using SampleApp.Core.Contracts.Services;
using SampleApp.Core.Services;
using SampleApp.Models;
using SampleApp.Services;
using SampleApp.ViewModels;
using SampleApp.Views;
namespace SampleApp
{
// For more inforation about application lifecyle events see https://docs.microsoft.com/dotnet/framework/wpf/app-development/application-management-overview
public partial class App : Application
{
private IHost _host;
public T GetService<T>()
where T : class
=> _host.Services.GetService(typeof(T)) as T;
public App()
{
}
private async void OnStartup(object sender, StartupEventArgs e)
{
var appLocation = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
// For more information about .NET generic host see https://docs.microsoft.com/aspnet/core/fundamentals/host/generic-host?view=aspnetcore-3.0
_host = Host.CreateDefaultBuilder(e.Args)
.ConfigureAppConfiguration(c =>
{
c.SetBasePath(appLocation);
})
.ConfigureServices(ConfigureServices)
.Build();
await _host.StartAsync();
}
private void ConfigureServices(HostBuilderContext context, IServiceCollection services)
{
// TODO WTS: Register your services, viewmodels and pages here
// App Host
services.AddHostedService<ApplicationHostService>();
// Core Services
services.AddSingleton<IFileService, FileService>();
services.AddSingleton<ISampleDataService, SampleDataService>();
// Services
services.AddSingleton<IApplicationInfoService, ApplicationInfoService>();
services.AddSingleton<ISystemService, SystemService>();
services.AddSingleton<IPersistAndRestoreService, PersistAndRestoreService>();
services.AddSingleton<IThemeSelectorService, ThemeSelectorService>();
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<INavigationService, NavigationService>();
// Views and ViewModels
services.AddTransient<IShellWindow, ShellWindow>();
services.AddTransient<ShellViewModel>();
services.AddTransient<ContentGridViewModel>();
services.AddTransient<ContentGridPage>();
services.AddTransient<ContentGridDetailViewModel>();
services.AddTransient<ContentGridDetailPage>();
services.AddTransient<SettingsViewModel>();
services.AddTransient<SettingsPage>();
// Configuration
services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
}
private async void OnExit(object sender, ExitEventArgs e)
{
await _host.StopAsync();
_host.Dispose();
_host = null;
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// TODO WTS: Please log and handle the exception as appropriate to your scenario
// For more info see https://docs.microsoft.com/dotnet/api/system.windows.application.dispatcherunhandledexception?view=netcore-3.0
}
}
}
| 36.85 | 160 | 0.662687 | [
"MIT"
] | mvegaca/ContentGridMockup | SampleApp/SampleApp/App.xaml.cs | 3,687 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CloudShop.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
var products = this.HttpContext.Application["Products"] as List<string>;
var itemsInSession = this.Session["Cart"] as List<string> ?? new List<string>();
// add all products currently not in session
var filteredProducts = products.Where(item => !itemsInSession.Contains(item));
//// Add additional filters here
return this.View(filteredProducts);
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[HttpPost]
public ActionResult Add(string selectedItem)
{
if (selectedItem != null)
{
List<string> cart = this.Session["Cart"] as List<string> ?? new List<string>();
cart.Add(selectedItem);
this.Session["Cart"] = cart;
}
return this.RedirectToAction("Index");
}
public ActionResult Checkout()
{
var itemsInSession = this.Session["Cart"] as List<string> ?? new List<string>();
return this.View(itemsInSession);
}
[HttpPost]
public ActionResult Remove(string selectedItem)
{
if (selectedItem != null)
{
var itemsInSession = this.Session["Cart"] as List<string>;
if (itemsInSession != null)
{
itemsInSession.Remove(selectedItem);
}
}
return this.RedirectToAction("Checkout");
}
}
}
| 27.054054 | 95 | 0.538961 | [
"Apache-2.0"
] | PankajRawat333/MicrosoftAzureTrainingKit | HOLs/HOL-MigratingAspNetApps/Source/Ex1-MovingMVCAppsToAzure/Begin/CloudShop/Controllers/HomeController.cs | 2,004 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace AjGo.Agents
{
public class Simple2Agent
{
private Dictionary<Position, bool> saved = new Dictionary<Position,bool>();
private Dictionary<Position, bool> killed = new Dictionary<Position, bool>();
private SimpleKillSaveAgent agent2 = new SimpleKillSaveAgent();
int initialsize;
private List<Point> GetPointsToTryKill(Group group, Game game)
{
PointSet ps = new PointSet();
ps.Add(group.Liberties);
ps.Add(group.Liberties.CalculateLiberties(game.Position));
//PointSet frontier = group.Liberties.CalculateFrontier(game.Position);
//ps.Add(frontier.CalculateLiberties(game.Position));
return ps.Points;
}
public bool MoveCanSave(Game game, short xtosave, short ytosave, int maxliberties, Move move)
{
return agent2.MoveCanSave(game, xtosave, ytosave, maxliberties, move);
}
public bool CanSave(Game game, short xtosave, short ytosave, int maxliberties)
{
return agent2.CanSave(game, xtosave, ytosave, maxliberties);
}
public bool MoveCanKill(Game game, short xtokill, short ytokill, int maxliberties, Move move)
{
if (!game.IsValid(move))
return false;
Game newgame = game.Clone();
newgame.Play(move);
Group group = newgame.GetGroup(xtokill, ytokill);
if (group == null)
return true;
if (group.CountLiberties > maxliberties)
return false;
if (group.CountLiberties > 2 && group.Count > initialsize + 10)
return false;
return !CanSave(newgame, xtokill, ytokill, maxliberties);
}
public bool CanKill(Game game, short xtokill, short ytokill, int maxliberties)
{
if (killed.ContainsKey(game.Position))
return killed[game.Position];
Group group = game.GetGroup(xtokill, ytokill);
if (group == null)
{
killed[game.Position] = true;
return true;
}
if (initialsize == 0)
initialsize = group.Count;
Color color;
if (group.Color == Color.Black)
color = Color.White;
else if (group.Color == Color.White)
color = Color.Black;
else
throw new InvalidOperationException();
foreach (Point pt in GetPointsToTryKill(group,game))
{
Move move = new Move(pt.X, pt.Y, color);
if (MoveCanKill(game, xtokill, ytokill, maxliberties, move))
{
killed[game.Position] = true;
return true;
}
}
killed[game.Position] = false;
return false;
}
public List<Move> GetKillMoves(Game game, short xtokill, short ytokill, int maxliberties)
{
List<Move> moves = new List<Move>();
Group group = game.GetGroup(xtokill, ytokill);
if (group == null)
throw new InvalidOperationException();
Color color;
if (group.Color==Color.Black)
color = Color.White;
else if (group.Color == Color.White)
color = Color.Black;
else
throw new InvalidOperationException();
foreach (Point pt in GetPointsToTryKill(group,game))
{
Move move = new Move(pt.X, pt.Y, color);
if (MoveCanKill(game, xtokill, ytokill, maxliberties, move))
moves.Add(move);
}
return moves;
}
public List<Move> GetSaveMoves(Game game, short xtosave, short ytosave, int maxliberties)
{
return agent2.GetSaveMoves(game, xtosave, ytosave, maxliberties);
}
}
}
| 31.125 | 102 | 0.529176 | [
"MIT"
] | ajlopez/AjGo | Src/AjGo/Agents/Simple2Agent.cs | 4,233 | C# |
// -----------------------------------------------------------------------
// <copyright file="NativeMethods.File.cs" company="RossKing">
// Copyright (c) RossKing. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Media.Metadata;
using System;
using System.Runtime.InteropServices;
/// <content>
/// Methods from <c>file.h</c>.
/// </content>
internal static partial class NativeMethods
{
/// <summary>
/// The should parse atom call back.
/// </summary>
/// <param name="atom">The atom.</param>
/// <returns><see langword="true"/> to parse the atom.</returns>
public delegate bool ShouldParseAtomCallback(uint atom);
/// <summary>
/// Close an mp4 file.
/// </summary>
/// <param name="file">handle of file to close.</param>
/// <remarks>MP4Close closes a previously opened mp4 file. If the file was opened writable with <see cref="MP4Modify(byte[], int)"/>, then <see cref="MP4Close(IntPtr)"/> will write out all pending information to disk.</remarks>
[DllImport("libmp4v2.dll", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void MP4Close(IntPtr file);
/// <summary>
/// Modify an existing mp4 file.
/// </summary>
/// <param name="fileName">pathname of the file to be modified. On Windows, this should be a UTF-8 encoded string. On other platforms, it should be an 8-bit encoding that is appropriate for the platform, locale, file system, etc. prefer to use UTF-8 when possible).</param>
/// <param name="flags">flags currently ignored.</param>
/// <remarks>
/// <para>MP4Modify is the first call that should be used when you want to modify an existing mp4 file.It is roughly equivalent to opening a file in read/write mode.</para>
/// <para>Since modifications to an existing mp4 file can result in a sub-optimal file layout, you may want to use MP4Optimize() after you have modified and closed the mp4 file.</para>
/// </remarks>
/// <returns>On success a handle of the target file for use in subsequent calls to the library. On error, #MP4_INVALID_FILE_HANDLE.</returns>
[DllImport("libmp4v2.dll", CharSet = CharSet.Ansi, ExactSpelling = true, BestFitMapping = false, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr MP4Modify(byte[] fileName, int flags);
/// <summary>
/// Optimize the layout of an mp4 file.
/// </summary>
/// <param name="fileName">pathname of (existing) file to be optimized. On Windows, this should be a UTF-8 encoded string. On other platforms, it should be an 8-bit encoding that is appropriate for the platform, locale, file system, etc. (prefer to use UTF-8 when possible).</param>
/// <param name="newName">
/// <para>pathname of the new optimized file. On Windows, this should be a UTF-8 encoded string. On other platforms, it should be an 8-bit encoding that is appropriate for the platform, locale, file system, etc. (prefer to use UTF-8 when possible).</para>
/// <para>If <see langword="null"/> a temporary file in the same directory as the <paramref name="fileName"/> will be used and <paramref name="fileName"/> will be over-written upon successful completion.</para>
/// </param>
/// <remarks>
/// <para>MP4Optimize reads an existing mp4 file and writes a new version of the file with the two important changes:</para>
/// <para>First, the mp4 control information is moved to the beginning of the file. (Frequenty it is at the end of the file due to it being constantly modified as track samples are added to an mp4 file). This optimization is useful in that in allows the mp4 file to be HTTP streamed.</para>
/// <para>Second, the track samples are interleaved so that the samples for a particular instant in time are colocated within the file. This eliminates disk seeks during playback of the file which results in better performance.</para>
/// <para>There are also two important side effects of <see cref="MP4Optimize"/>:</para>
/// <para>First, any free blocks within the mp4 file are eliminated.</para>
/// <para>Second, as a side effect of the sample interleaving process any media data chunks that are not actually referenced by the mp4 control structures are deleted. This is useful if you have called MP4DeleteTrack() which only deletes the control information for a track, and not the actual media data.</para></remarks>
/// <returns><see langword="true"/> on success, <see langword="false"/> on failure.</returns>
[DllImport("libmp4v2.dll", CharSet = CharSet.Ansi, ExactSpelling = true, BestFitMapping = false, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool MP4Optimize(byte[] fileName, byte[]? newName);
/// <summary>
/// Read an existing mp4 file.
/// </summary>
/// <param name="fileName">pathname of the file to be read. On Windows, this should be a UTF-8 encoded string. On other platforms, it should be an 8-bit encoding that is appropriate for the platform, locale, file system, etc. (prefer to use UTF-8 when possible).</param>
/// <param name="cb">The call back.</param>
/// <remarks>MP4Read is the first call that should be used when you want to just read an existing mp4 file.It is equivalent to opening a file for reading, but in addition the mp4 file is parsed and the controlinformation is loaded into memory.Note that actual track samples are notread into memory until MP4ReadSample() is called.</remarks>
/// <returns>On success a handle of the file for use in subsequent calls to the library. On error, #MP4_INVALID_FILE_HANDLE.</returns>
[DllImport("libmp4v2.dll", CharSet = CharSet.Ansi, ExactSpelling = true, BestFitMapping = false, SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr MP4Read(byte[] fileName, IntPtr cb);
} | 81.77027 | 344 | 0.701867 | [
"MIT"
] | rsking/Media.Metadata | Media.Metadata.Mp4v2/NativeMethods.File.cs | 6,053 | C# |
using UnityEngine;
public class Coin : MonoBehaviour
{
public float rotationSpeed = 3f;
public float moveSpeed = 5f;
bool _hasToMove;
private void Start()
{
moveSpeed = Random.Range(moveSpeed - 2, moveSpeed + 2);
}
private void FixedUpdate()
{
transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, transform.eulerAngles.z + Time.deltaTime * rotationSpeed);
if (_hasToMove)
{
transform.position = Vector3.Lerp(transform.position, Player.instance.transform.position, moveSpeed * Time.deltaTime);
moveSpeed += Time.deltaTime;
}
if (Vector3.Distance(transform.position, Player.instance.transform.position) < 1.5)
{
Destroy(gameObject);
}
}
public void MoveToPlayer()
{
_hasToMove = true;
}
}
| 24.583333 | 152 | 0.627119 | [
"MIT"
] | Polifack/Unity2D-BalloonGame | Assets/Coin.cs | 887 | C# |
// <copyright file="Program.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// 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.
// </copyright>
using System.Diagnostics.Metrics;
using OpenTelemetry;
using OpenTelemetry.Metrics;
namespace GettingStarted;
public class Program
{
private static readonly Meter MyMeter = new("MyCompany.MyProduct.MyLibrary", "1.0");
private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter");
public static void Main()
{
using var meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("MyCompany.MyProduct.MyLibrary")
.AddConsoleExporter()
.Build();
MyFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
MyFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow"));
MyFruitCounter.Add(1, new("name", "lemon"), new("color", "yellow"));
MyFruitCounter.Add(2, new("name", "apple"), new("color", "green"));
MyFruitCounter.Add(5, new("name", "apple"), new("color", "red"));
MyFruitCounter.Add(4, new("name", "lemon"), new("color", "yellow"));
}
}
| 39.255814 | 105 | 0.683057 | [
"Apache-2.0"
] | BearerPipelineTest/opentelemetry-dotnet | docs/metrics/getting-started/Program.cs | 1,688 | C# |
namespace Flora.Input {
/// <summary>
/// Interface for handling controller input.
/// </summary>
public interface IControllerHandler {
void OnAxisMotion(int which, ControllerAxis axis, float value);
void OnButtonDown(int which, ControllerButton button);
void OnButtonUp(int which, ControllerButton button);
void OnControllerAdded(int which);
void OnControllerRemoved(int which);
}
} | 36.916667 | 71 | 0.683973 | [
"MIT"
] | sinusinu/Flora | src/Input/IControllerHandler.cs | 443 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Paramore.Brighter.Outbox.MsSql;
using Xunit;
namespace Paramore.Brighter.MSSQL.Tests.Outbox
{
[Trait("Category", "MSSQL")]
public class MsSqlOutboxBulkGetAsyncTests : IDisposable
{
private readonly MsSqlTestHelper _msSqlTestHelper;
private readonly string _Topic1 = "test_topic";
private readonly string _Topic2 = "test_topic3";
private IEnumerable<Message> _messages;
private readonly Message _message1;
private readonly Message _message2;
private readonly Message _message3;
private readonly Message _message;
private readonly MsSqlOutbox _sqlOutbox;
public MsSqlOutboxBulkGetAsyncTests()
{
_msSqlTestHelper = new MsSqlTestHelper();
_msSqlTestHelper.SetupMessageDb();
_sqlOutbox = new MsSqlOutbox(_msSqlTestHelper.OutboxConfiguration);
_message = new Message(new MessageHeader(Guid.NewGuid(), _Topic1, MessageType.MT_COMMAND),
new MessageBody("message body"));
_message1 = new Message(new MessageHeader(Guid.NewGuid(), _Topic2, MessageType.MT_EVENT),
new MessageBody("message body2"));
_message2 = new Message(new MessageHeader(Guid.NewGuid(), _Topic1, MessageType.MT_COMMAND),
new MessageBody("message body3"));
_message3 = new Message(new MessageHeader(Guid.NewGuid(), _Topic2, MessageType.MT_EVENT),
new MessageBody("message body4"));
}
[Fact]
public async Task When_there_are_multiple_messages_and_some_are_received_and_Dispatched_bulk_Async()
{
await _sqlOutbox.AddAsync(_message);
await Task.Delay(100);
await _sqlOutbox.AddAsync(_message1);
await Task.Delay(100);
await _sqlOutbox.AddAsync(_message2);
await Task.Delay(100);
await _sqlOutbox.AddAsync(_message3);
await Task.Delay(100);
_messages = await _sqlOutbox.GetAsync(new[] {_message1.Id, _message2.Id});
//should fetch 1 message
_messages.Should().HaveCount(2);
//should fetch expected message
_messages.Should().Contain(m => m.Id == _message1.Id);
_messages.Should().Contain(m => m.Id == _message2.Id);
await _sqlOutbox.MarkDispatchedAsync(_messages.Select(m => m.Id), DateTime.UtcNow);
var undispatchedMessages = await _sqlOutbox.OutstandingMessagesAsync(0);
undispatchedMessages.Count().Should().Be(2);
}
public void Dispose()
{
_msSqlTestHelper.CleanUpDb();
}
}
}
| 38.410959 | 108 | 0.649073 | [
"MIT"
] | PMamica/Brighter | tests/Paramore.Brighter.MSSQL.Tests/Outbox/When_there_are_multiple_messages_and_some_are_recievied_and_Dispatched_bulk_Async.cs | 2,806 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Security.Membership
{
using System.ComponentModel;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Host;
using DotNetNuke.UI.WebControls;
/// -----------------------------------------------------------------------------
/// Project: DotNetNuke
/// Namespace: DotNetNuke.Security.Membership
/// Class: PasswordConfig
/// -----------------------------------------------------------------------------
/// <summary>
/// The PasswordConfig class provides a wrapper any Portal wide Password Settings.
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class PasswordConfig
{
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets or sets and sets the Password Expiry time in days.
/// </summary>
/// <returns>An integer.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(0)]
[Category("Password")]
public static int PasswordExpiry
{
get
{
return Host.PasswordExpiry;
}
set
{
HostController.Instance.Update("PasswordExpiry", value.ToString());
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Gets or sets and sets the a Reminder time in days (to remind the user that theire password
/// is about to expire.
/// </summary>
/// <returns>An integer.</returns>
/// -----------------------------------------------------------------------------
[SortOrder(1)]
[Category("Password")]
public static int PasswordExpiryReminder
{
get
{
return Host.PasswordExpiryReminder;
}
set
{
HostController.Instance.Update("PasswordExpiryReminder", value.ToString());
}
}
}
}
| 34.971014 | 102 | 0.418152 | [
"MIT"
] | Acidburn0zzz/Dnn.Platform | DNN Platform/Library/Security/Membership/PasswordConfig.cs | 2,415 | C# |
using Sirenix.OdinInspector;
using System.Collections.Generic;
using UnityEditor;
namespace LccEditor
{
public class HotfixEditorWindowBase : AEditorWindowBase
{
[PropertySpace(10)]
[HideLabel, DisplayAsString]
public string info;
public HotfixEditorWindowBase()
{
}
public HotfixEditorWindowBase(EditorWindow editorWindow) : base(editorWindow)
{
BuildTargetGroup buildTargetGroup;
#if UNITY_STANDALONE
buildTargetGroup = BuildTargetGroup.Standalone;
#endif
#if UNITY_ANDROID
buildTargetGroup = BuildTargetGroup.Android;
#endif
#if UNITY_IOS
buildTargetGroup = BuildTargetGroup.iOS;
#endif
string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
List<string> defineList = new List<string>(define.Split(';'));
if (defineList.Contains("ILRuntime"))
{
info = "当前是ILRuntime模式";
}
else
{
info = "当前是Mono模式";
}
if (defineList.Contains("Release"))
{
info += "Release的DLL";
}
else
{
info += "Debug的DLL";
}
}
[PropertySpace(10)]
[LabelText("ILRuntime模式"), Button]
public void ILRuntime()
{
BuildTargetGroup buildTargetGroup;
#if UNITY_STANDALONE
buildTargetGroup = BuildTargetGroup.Standalone;
#endif
#if UNITY_ANDROID
buildTargetGroup = BuildTargetGroup.Android;
#endif
#if UNITY_IOS
buildTargetGroup = BuildTargetGroup.iOS;
#endif
string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
List<string> defineList = new List<string>(define.Split(';'));
if (!defineList.Contains("ILRuntime"))
{
define += ";ILRuntime";
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, define);
}
}
[PropertySpace(10)]
[LabelText("Mono模式"), Button]
public void Mono()
{
BuildTargetGroup buildTargetGroup;
#if UNITY_STANDALONE
buildTargetGroup = BuildTargetGroup.Standalone;
#endif
#if UNITY_ANDROID
buildTargetGroup = BuildTargetGroup.Android;
#endif
#if UNITY_IOS
buildTargetGroup = BuildTargetGroup.iOS;
#endif
string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
List<string> defineList = new List<string>(define.Split(';'));
if (defineList.Contains("ILRuntime"))
{
defineList.Remove("ILRuntime");
define = string.Empty;
foreach (string item in defineList)
{
define += $"{item};";
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, define);
}
}
[PropertySpace(10)]
[LabelText("Release模式"), Button]
public void Release()
{
BuildTargetGroup buildTargetGroup;
#if UNITY_STANDALONE
buildTargetGroup = BuildTargetGroup.Standalone;
#endif
#if UNITY_ANDROID
buildTargetGroup = BuildTargetGroup.Android;
#endif
#if UNITY_IOS
buildTargetGroup = BuildTargetGroup.iOS;
#endif
string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
List<string> defineList = new List<string>(define.Split(';'));
if (!defineList.Contains("Release"))
{
define += ";Release";
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, define);
}
}
[PropertySpace(10)]
[LabelText("Debug模式"), Button]
public void Debug()
{
BuildTargetGroup buildTargetGroup;
#if UNITY_STANDALONE
buildTargetGroup = BuildTargetGroup.Standalone;
#endif
#if UNITY_ANDROID
buildTargetGroup = BuildTargetGroup.Android;
#endif
#if UNITY_IOS
buildTargetGroup = BuildTargetGroup.iOS;
#endif
string define = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
List<string> defineList = new List<string>(define.Split(';'));
if (defineList.Contains("Release"))
{
defineList.Remove("Release");
define = string.Empty;
foreach (string item in defineList)
{
define += $"{item};";
}
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, define);
}
}
}
} | 33.124138 | 95 | 0.590464 | [
"MIT"
] | 404Lcc/Lcc | Assets/Editor/Runtime/Core/OdinEditorWindow/EditorWindowBase/HotfixEditorWindowBase.cs | 4,845 | C# |
using NCPExtension;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace ExtensionExample
{
public class Example : INCPCommand
{
public IEnumerable<INCPMenuItem>? ContextMenu => new[]
{
new ExampleMenuItem()
};
public string? Description => "description";
public byte[]? Image => null;
public string? Name => "Example";
public ICommand? Run => new Command();
public object? Visual => null;
public void Init(InitializationInfo initializationInfo)
{
Console.WriteLine($"plugin location : {initializationInfo.pluginLocation}");
}
private class Command : ICommand
{
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter)
{
return true;
}
public void Execute(object? parameter)
{
Console.WriteLine("run");
try
{
var dialog = new Window();
dialog.Content = new TextBox
{
IsReadOnly = true,
Text = JsonConvert.SerializeObject(new
{
value1 = "test1",
value2 = "test2",
}, Formatting.Indented)
};
dialog.ShowDialog();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
private class ExampleMenuItem : INCPMenuItem
{
public byte[]? Image => null;
public int Index => 0;
public ICommand? Run => new Command();
public string? Title => "some menu item";
public object? Visual => null;
private class Command : ICommand
{
public event EventHandler? CanExecuteChanged;
public bool CanExecute(object? parameter)
{
return true;
}
public void Execute(object? parameter)
{
Console.WriteLine("menu item run");
try
{
var dialog = new Window();
dialog.Content = new TextBox
{
IsReadOnly = true,
Text = JsonConvert.SerializeObject(new
{
value1 = "hello from",
value2 = "the menu item !",
}, Formatting.Indented)
};
dialog.ShowDialog();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
}
} | 28.375 | 88 | 0.425425 | [
"MIT"
] | Wiltoag/NCPanel | ExtensionExample/Example.cs | 3,178 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the quicksight-2018-04-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.QuickSight.Model
{
/// <summary>
/// Container for the parameters to the ListTemplates operation.
/// Lists all the templates in the current Amazon QuickSight account.
/// </summary>
public partial class ListTemplatesRequest : AmazonQuickSightRequest
{
private string _awsAccountId;
private int? _maxResults;
private string _nextToken;
/// <summary>
/// Gets and sets the property AwsAccountId.
/// <para>
/// The ID of the Amazon Web Services account that contains the templates that you're
/// listing.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=12, Max=12)]
public string AwsAccountId
{
get { return this._awsAccountId; }
set { this._awsAccountId = value; }
}
// Check to see if AwsAccountId property is set
internal bool IsSetAwsAccountId()
{
return this._awsAccountId != null;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to be returned per request.
/// </para>
/// </summary>
[AWSProperty(Min=1, Max=100)]
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of results, or null if there are no more results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 30.373737 | 108 | 0.60858 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/QuickSight/Generated/Model/ListTemplatesRequest.cs | 3,007 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
public abstract class AttributeData
{
protected AttributeData()
{
}
/// <summary>
/// The attribute class.
/// </summary>
public INamedTypeSymbol AttributeClass { get { return CommonAttributeClass; } }
protected abstract INamedTypeSymbol CommonAttributeClass { get; }
/// <summary>
/// The constructor on the attribute class.
/// </summary>
public IMethodSymbol AttributeConstructor { get { return CommonAttributeConstructor; } }
protected abstract IMethodSymbol CommonAttributeConstructor { get; }
public SyntaxReference ApplicationSyntaxReference { get { return CommonApplicationSyntaxReference; } }
protected abstract SyntaxReference CommonApplicationSyntaxReference { get; }
/// <summary>
/// Constructor arguments on the attribute.
/// </summary>
public ImmutableArray<TypedConstant> ConstructorArguments { get { return CommonConstructorArguments; } }
internal protected abstract ImmutableArray<TypedConstant> CommonConstructorArguments { get; }
/// <summary>
/// Named (property value) arguments on the attribute.
/// </summary>
public ImmutableArray<KeyValuePair<string, TypedConstant>> NamedArguments { get { return CommonNamedArguments; } }
internal protected abstract ImmutableArray<KeyValuePair<string, TypedConstant>> CommonNamedArguments { get; }
/// <summary>
/// Attribute is conditionally omitted if it is a source attribute and both the following are true:
/// (a) It has at least one applied conditional attribute AND
/// (b) None of conditional symbols are true at the attribute source location.
/// </summary>
internal virtual bool IsConditionallyOmitted
{
get { return false; }
}
internal virtual bool HasErrors
{
get { return false; }
}
/// <summary>
/// Checks if an applied attribute with the given attributeType matches the namespace name and type name of the given early attribute's description
/// and the attribute description has a signature with parameter count equal to the given attributeArgCount.
/// NOTE: We don't allow early decoded attributes to have optional parameters.
/// </summary>
internal static bool IsTargetEarlyAttribute(INamedTypeSymbol attributeType, int attributeArgCount, AttributeDescription description)
{
int attributeCtorsCount = description.Signatures.Length;
for (int i = 0; i < attributeCtorsCount; i++)
{
int parameterCount = description.GetParameterCount(signatureIndex: i);
// NOTE: Below assumption disallows early decoding well-known attributes with optional parameters.
if (attributeArgCount == parameterCount)
{
string actualNamespaceName = attributeType.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat);
StringComparison options = description.MatchIgnoringCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
return actualNamespaceName.Equals(description.Namespace, options) && attributeType.Name.Equals(description.Name, options);
}
}
return false;
}
/// <summary>
/// Returns the value of a constructor argument as type <typeparamref name="T"/>.
/// Throws if no constructor argument exists or the argument cannot be converted to the type.
/// </summary>
internal T GetConstructorArgument<T>(int i, SpecialType specialType)
{
ImmutableArray<TypedConstant> constructorArgs = this.CommonConstructorArguments;
return constructorArgs[i].DecodeValue<T>(specialType);
}
/// <summary>
/// Returns named attribute argument with the given <paramref name="name"/> as type <typeparamref name="T"/>.
/// If there is more than one named argument with this name, it returns the last one.
/// If no named argument is found then the <paramref name="defaultValue"/> is returned.
/// </summary>
/// <param name="name">The metadata property or field name. This name is case sensitive (both VB and C#).</param>
/// <param name="specialType">SpecialType of the named argument.</param>
/// <param name="defaultValue">Default value for the named argument.</param>
/// <remarks>
/// For user defined attributes VB allows duplicate named arguments and uses the last value.
/// Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't.
/// </remarks>
internal T DecodeNamedArgument<T>(string name, SpecialType specialType, T defaultValue = default(T))
{
return DecodeNamedArgument<T>(CommonNamedArguments, name, specialType, defaultValue);
}
private static T DecodeNamedArgument<T>(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name, SpecialType specialType, T defaultValue = default(T))
{
int index = IndexOfNamedArgument(namedArguments, name);
return index >= 0 ? namedArguments[index].Value.DecodeValue<T>(specialType) : defaultValue;
}
private static int IndexOfNamedArgument(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments, string name)
{
// For user defined attributes VB allows duplicate named arguments and uses the last value.
// Dev11 reports an error for pseudo-custom attributes when emitting metadata. We don't.
for (int i = namedArguments.Length - 1; i >= 0; i--)
{
// even for VB this is case sensitive comparison:
if (string.Equals(namedArguments[i].Key, name, StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
#region Decimal and DateTime Constant Decoding
internal ConstantValue DecodeDecimalConstantValue()
{
// There are two decimal constant attribute ctors:
// (byte scale, byte sign, uint high, uint mid, uint low) and
// (byte scale, byte sign, int high, int mid, int low)
// The dev10 compiler only honors the first; Roslyn honours both.
// We should not end up in this code path unless we know we have one of them.
ImmutableArray<IParameterSymbol> parameters = AttributeConstructor.Parameters;
ImmutableArray<TypedConstant> args = this.CommonConstructorArguments;
Debug.Assert(parameters.Length == 5);
Debug.Assert(parameters[0].Type.SpecialType == SpecialType.System_Byte);
Debug.Assert(parameters[1].Type.SpecialType == SpecialType.System_Byte);
int low, mid, high;
byte scale = args[0].DecodeValue<byte>(SpecialType.System_Byte);
bool isNegative = args[1].DecodeValue<byte>(SpecialType.System_Byte) != 0;
if (parameters[2].Type.SpecialType == SpecialType.System_Int32)
{
Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_Int32);
Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_Int32);
Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_Int32);
high = args[2].DecodeValue<int>(SpecialType.System_Int32);
mid = args[3].DecodeValue<int>(SpecialType.System_Int32);
low = args[4].DecodeValue<int>(SpecialType.System_Int32);
}
else
{
Debug.Assert(parameters[2].Type.SpecialType == SpecialType.System_UInt32);
Debug.Assert(parameters[3].Type.SpecialType == SpecialType.System_UInt32);
Debug.Assert(parameters[4].Type.SpecialType == SpecialType.System_UInt32);
high = unchecked((int)args[2].DecodeValue<uint>(SpecialType.System_UInt32));
mid = unchecked((int)args[3].DecodeValue<uint>(SpecialType.System_UInt32));
low = unchecked((int)args[4].DecodeValue<uint>(SpecialType.System_UInt32));
}
return ConstantValue.Create(new decimal(low, mid, high, isNegative, scale));
}
internal ConstantValue DecodeDateTimeConstantValue()
{
long value = this.CommonConstructorArguments[0].DecodeValue<long>(SpecialType.System_Int64);
// if value is outside this range, DateTime would throw when constructed
if (value < DateTime.MinValue.Ticks || value > DateTime.MaxValue.Ticks)
{
return ConstantValue.Bad;
}
return ConstantValue.Create(new DateTime(value));
}
#endregion
/// <summary>
/// Decode the arguments to ObsoleteAttribute. ObsoleteAttribute can have 0,1 or 2 arguments.
/// </summary>
internal ObsoleteAttributeData DecodeObsoleteAttribute()
{
ImmutableArray<TypedConstant> args = this.CommonConstructorArguments;
// ObsoleteAttribute()
string message = null;
bool isError = false;
if (args.Length > 0)
{
// ObsoleteAttribute(string)
// ObsoleteAttribute(string, bool)
Debug.Assert(args.Length <= 2);
message = (string)args[0].Value;
if (args.Length == 2)
{
isError = (bool)args[1].Value;
}
}
return new ObsoleteAttributeData(message, isError);
}
/// <summary>
/// Decode the arguments to DeprecatedAttribute. DeprecatedAttribute can have 3 or 4 arguments.
/// </summary>
internal ObsoleteAttributeData DecodeDeprecatedAttribute()
{
ImmutableArray<TypedConstant> args = this.CommonConstructorArguments;
// DeprecatedAttribute()
string message = null;
bool isError = false;
if (args.Length == 3 || args.Length == 4)
{
// DeprecatedAttribute(String, DeprecationType, UInt32)
// DeprecatedAttribute(String, DeprecationType, UInt32, Platform)
// DeprecatedAttribute(String, DeprecationType, UInt32, String)
message = (string)args[0].Value;
isError = ((int)args[1].Value == 1);
}
return new ObsoleteAttributeData(message, isError);
}
internal static void DecodeMethodImplAttribute<T, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>(
ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments,
CommonMessageProvider messageProvider)
where T : CommonMethodWellKnownAttributeData, new()
where TAttributeSyntaxNode : SyntaxNode
where TAttributeData : AttributeData
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
MethodImplOptions options;
TAttributeData attribute = arguments.Attribute;
if (attribute.CommonConstructorArguments.Length == 1)
{
if (attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_Int16)
{
options = (MethodImplOptions)attribute.CommonConstructorArguments[0].DecodeValue<short>(SpecialType.System_Int16);
}
else
{
options = attribute.CommonConstructorArguments[0].DecodeValue<MethodImplOptions>(SpecialType.System_Enum);
}
// low two bits should only be set via MethodCodeType property
if (((int)options & 3) != 0)
{
messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute);
options = options & ~(MethodImplOptions)3;
}
}
else
{
options = default(MethodImplOptions);
}
MethodImplAttributes codeType = MethodImplAttributes.IL;
int position = 1;
foreach (KeyValuePair<string, TypedConstant> namedArg in attribute.CommonNamedArguments)
{
if (namedArg.Key == "MethodCodeType")
{
MethodImplAttributes value = (MethodImplAttributes)namedArg.Value.DecodeValue<int>(SpecialType.System_Enum);
if (value < 0 || value > MethodImplAttributes.Runtime)
{
messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, "MethodCodeType");
}
else
{
codeType = value;
}
}
position++;
}
arguments.GetOrCreateData<T>().SetMethodImplementation(arguments.Index, (MethodImplAttributes)options | codeType);
}
internal static void DecodeStructLayoutAttribute<TTypeWellKnownAttributeData, TAttributeSyntaxNode, TAttributeData, TAttributeLocation>(
ref DecodeWellKnownAttributeArguments<TAttributeSyntaxNode, TAttributeData, TAttributeLocation> arguments,
CharSet defaultCharSet,
int defaultAutoLayoutSize,
CommonMessageProvider messageProvider)
where TTypeWellKnownAttributeData : CommonTypeWellKnownAttributeData, new()
where TAttributeSyntaxNode : SyntaxNode
where TAttributeData : AttributeData
{
Debug.Assert((object)arguments.AttributeSyntaxOpt != null);
TAttributeData attribute = arguments.Attribute;
CharSet charSet = (defaultCharSet != Cci.Constants.CharSet_None) ? defaultCharSet : CharSet.Ansi;
int? size = null;
int? alignment = null;
bool hasErrors = false;
LayoutKind kind = attribute.CommonConstructorArguments[0].DecodeValue<LayoutKind>(Microsoft.CodeAnalysis.SpecialType.System_Enum);
switch (kind)
{
case LayoutKind.Auto:
case LayoutKind.Explicit:
case LayoutKind.Sequential:
break;
default:
messageProvider.ReportInvalidAttributeArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, 0, attribute);
hasErrors = true;
break;
}
int position = 1;
foreach (KeyValuePair<string, TypedConstant> namedArg in attribute.CommonNamedArguments)
{
switch (namedArg.Key)
{
case "CharSet":
charSet = namedArg.Value.DecodeValue<CharSet>(SpecialType.System_Enum);
switch (charSet)
{
case Cci.Constants.CharSet_None:
charSet = CharSet.Ansi;
break;
case CharSet.Ansi:
case Cci.Constants.CharSet_Auto:
case CharSet.Unicode:
break;
default:
messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key);
hasErrors = true;
break;
}
break;
case "Pack":
alignment = namedArg.Value.DecodeValue<int>(SpecialType.System_Int32);
// only powers of 2 less or equal to 128 are allowed:
if (alignment > 128 || (alignment & (alignment - 1)) != 0)
{
messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key);
hasErrors = true;
}
break;
case "Size":
size = namedArg.Value.DecodeValue<int>(Microsoft.CodeAnalysis.SpecialType.System_Int32);
if (size < 0)
{
messageProvider.ReportInvalidNamedArgument(arguments.Diagnostics, arguments.AttributeSyntaxOpt, position, attribute.AttributeClass, namedArg.Key);
hasErrors = true;
}
break;
}
position++;
}
if (!hasErrors)
{
if (kind == LayoutKind.Auto && size == null && alignment != null)
{
// If size is unspecified
// C# emits size=0
// VB emits size=1 if the type is a struct, auto-layout and has alignment specified; 0 otherwise
size = defaultAutoLayoutSize;
}
arguments.GetOrCreateData<TTypeWellKnownAttributeData>().SetStructLayout(new TypeLayout(kind, size ?? 0, (byte)(alignment ?? 0)), charSet);
}
}
internal AttributeUsageInfo DecodeAttributeUsageAttribute()
{
return DecodeAttributeUsageAttribute(this.CommonConstructorArguments[0], this.CommonNamedArguments);
}
internal static AttributeUsageInfo DecodeAttributeUsageAttribute(TypedConstant positionalArg, ImmutableArray<KeyValuePair<string, TypedConstant>> namedArgs)
{
// BREAKING CHANGE (C#):
// If the well known attribute class System.AttributeUsage is overridden in source,
// we will use the overriding AttributeUsage type for attribute usage validation,
// i.e. we try to find a constructor in that type with signature AttributeUsage(AttributeTargets)
// and public bool properties Inherited and AllowMultiple.
// If we are unable to find any of these, we use their default values.
//
// This behavior matches the approach chosen by native VB and Roslyn VB compilers,
// but breaks compatibility with native C# compiler.
// Native C# compiler preloads all the well known attribute types from mscorlib prior to binding,
// hence it uses the AttributeUsage type defined in mscorlib for attribute usage validation.
//
// See Roslyn Bug 8603: ETA crashes with InvalidOperationException on duplicate attributes for details.
AttributeTargets validOn = (AttributeTargets)positionalArg.Value;
bool allowMultiple = DecodeNamedArgument(namedArgs, "AllowMultiple", SpecialType.System_Boolean, false);
bool inherited = DecodeNamedArgument(namedArgs, "Inherited", SpecialType.System_Boolean, true);
return new AttributeUsageInfo(validOn, allowMultiple, inherited);
}
}
}
| 46.34023 | 182 | 0.605814 | [
"MIT"
] | Ollon/MSBuildTemplates | src/Microsoft.CodeAnalysis.SyntaxTree/Symbols/Attributes/CommonAttributeData.cs | 20,160 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.RecaptchaEnterprise.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.RecaptchaEnterprise.V1;
using System;
public sealed partial class GeneratedRecaptchaEnterpriseServiceClientStandaloneSnippets
{
/// <summary>Snippet for ListKeys</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListKeysRequestObject()
{
// Create client
RecaptchaEnterpriseServiceClient recaptchaEnterpriseServiceClient = RecaptchaEnterpriseServiceClient.Create();
// Initialize request argument(s)
ListKeysRequest request = new ListKeysRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListKeysResponse, Key> response = recaptchaEnterpriseServiceClient.ListKeys(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Key item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListKeysResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Key item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Key> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Key item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 40.584416 | 122 | 0.624 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/recaptchaenterprise/v1/google-cloud-recaptchaenterprise-v1-csharp/Google.Cloud.RecaptchaEnterprise.V1.StandaloneSnippets/RecaptchaEnterpriseServiceClient.ListKeysRequestObjectSnippet.g.cs | 3,125 | 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.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudDirectory.Model
{
/// <summary>
/// Attaches a policy object to a regular object inside a <a>BatchRead</a> operation. For
/// more information, see <a>AttachPolicy</a> and <a>BatchReadRequest$Operations</a>.
/// </summary>
public partial class BatchAttachPolicy
{
private ObjectReference _objectReference;
private ObjectReference _policyReference;
/// <summary>
/// Gets and sets the property ObjectReference.
/// <para>
/// The reference that identifies the object to which the policy will be attached.
/// </para>
/// </summary>
public ObjectReference ObjectReference
{
get { return this._objectReference; }
set { this._objectReference = value; }
}
// Check to see if ObjectReference property is set
internal bool IsSetObjectReference()
{
return this._objectReference != null;
}
/// <summary>
/// Gets and sets the property PolicyReference.
/// <para>
/// The reference that is associated with the policy object.
/// </para>
/// </summary>
public ObjectReference PolicyReference
{
get { return this._policyReference; }
set { this._policyReference = value; }
}
// Check to see if PolicyReference property is set
internal bool IsSetPolicyReference()
{
return this._policyReference != null;
}
}
} | 31.947368 | 112 | 0.644975 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/BatchAttachPolicy.cs | 2,429 | C# |
using System;
using System.Collections.Generic;
class Foo<S>
{
public ICloneable Test (S t)
{
return (ICloneable) t;
}
}
public static class ConvertHelper
{
public static IEnumerator<T> Test<S,T> (S s)
where T : S
{
yield return (T) s;
}
static void Main ()
{ }
}
| 12.217391 | 45 | 0.654804 | [
"Apache-2.0"
] | CRivlaldo/mono | mcs/tests/gtest-263.cs | 281 | C# |
using System;
using System.Collections.Generic;
namespace _07.HotPotato
{
class Program
{
static void Main(string[] args)
{
var names = Console.ReadLine().Split();
var toss = int.Parse(Console.ReadLine());
Queue<string> queue = new Queue<string>(names);
int currrentIndex = 1;
while (queue.Count > 1)
{
var currentName = queue.Dequeue();
if (currrentIndex == toss)
{
Console.WriteLine($"Removed {currentName}");
currrentIndex = 0;
}
else
{
queue.Enqueue(currentName);
}
currrentIndex++;
}
Console.WriteLine($"Last is {queue.Dequeue()}");
}
}
}
| 22.947368 | 64 | 0.447248 | [
"MIT"
] | StelaKaneva/Csharp-Advanced-Repository | StacksAndQueuesLab/07.HotPotato/Program.cs | 874 | C# |
using MediaBrowser.Model.ApiClient;
using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Devices;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Events;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.LiveTv;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Notifications;
using MediaBrowser.Model.Playlists;
using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Querying;
using MediaBrowser.Model.Search;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.Sync;
using MediaBrowser.Model.System;
using MediaBrowser.Model.Tasks;
using MediaBrowser.Model.Users;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Emby.ApiClient.Cryptography;
using Emby.ApiClient.Data;
using Emby.ApiClient.Model;
using Emby.ApiClient.Net;
namespace Emby.ApiClient
{
/// <summary>
/// Provides api methods centered around an HttpClient
/// </summary>
public partial class ApiClient : BaseApiClient, IApiClient
{
public event EventHandler<GenericEventArgs<RemoteLogoutReason>> RemoteLoggedOut;
public event EventHandler<GenericEventArgs<AuthenticationResult>> Authenticated;
/// <summary>
/// Gets the HTTP client.
/// </summary>
/// <value>The HTTP client.</value>
protected IAsyncHttpClient HttpClient { get; private set; }
private readonly ICryptographyProvider _cryptographyProvider;
private readonly ILocalAssetManager _localAssetManager = null;
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="serverAddress">The server address.</param>
/// <param name="accessToken">The access token.</param>
/// <param name="cryptographyProvider">The cryptography provider.</param>
public ApiClient(ILogger logger,
string serverAddress,
string accessToken,
ICryptographyProvider cryptographyProvider)
: base(logger, new NewtonsoftJsonSerializer(), serverAddress, accessToken)
{
CreateHttpClient(logger);
_cryptographyProvider = cryptographyProvider;
ResetHttpHeaders();
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="serverAddress">The server address.</param>
/// <param name="clientName">Name of the client.</param>
/// <param name="device">The device.</param>
/// <param name="applicationVersion">The application version.</param>
/// <param name="cryptographyProvider">The cryptography provider.</param>
public ApiClient(ILogger logger,
string serverAddress,
string clientName,
IDevice device,
string applicationVersion,
ICryptographyProvider cryptographyProvider)
: base(logger, new NewtonsoftJsonSerializer(), serverAddress, clientName, device, applicationVersion)
{
CreateHttpClient(logger);
_cryptographyProvider = cryptographyProvider;
ResetHttpHeaders();
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
/// <param name="serverAddress">The server address.</param>
/// <param name="clientName">Name of the client.</param>
/// <param name="device">The device.</param>
/// <param name="applicationVersion">The application version.</param>
/// <param name="cryptographyProvider">The cryptography provider.</param>
/// <param name="localAssetManager">The local asset manager.</param>
public ApiClient(ILogger logger,
string serverAddress,
string clientName,
IDevice device,
string applicationVersion,
ICryptographyProvider cryptographyProvider,
ILocalAssetManager localAssetManager)
: this(logger, serverAddress, clientName, device, applicationVersion, cryptographyProvider)
{
_localAssetManager = localAssetManager;
}
private void CreateHttpClient(ILogger logger)
{
HttpClient = AsyncHttpClientFactory.Create(logger);
HttpClient.HttpResponseReceived += HttpClient_HttpResponseReceived;
}
void HttpClient_HttpResponseReceived(object sender, HttpResponseEventArgs e)
{
if (e.StatusCode == HttpStatusCode.Unauthorized)
{
if (RemoteLoggedOut != null)
{
RemoteLoggedOut(this, new GenericEventArgs<RemoteLogoutReason>());
}
}
}
private ConnectionMode ConnectionMode { get; set; }
internal ServerInfo ServerInfo { get; set; }
private INetworkConnection NetworkConnection { get; set; }
public void EnableAutomaticNetworking(ServerInfo info, ConnectionMode initialMode, INetworkConnection networkConnection)
{
NetworkConnection = networkConnection;
ConnectionMode = initialMode;
ServerInfo = info;
ServerAddress = info.GetAddress(initialMode);
}
private async Task<Stream> SendAsync(HttpRequest request, bool enableFailover = true)
{
// If not using automatic connection, execute the request directly
if (NetworkConnection == null || !enableFailover)
{
return await HttpClient.SendAsync(request).ConfigureAwait(false);
}
var initialConnectionMode = ConnectionMode;
var originalRequestTime = DateTime.UtcNow;
Exception timeoutException;
try
{
return await HttpClient.SendAsync(request).ConfigureAwait(false);
}
catch (HttpException ex)
{
if (!ex.IsTimedOut)
{
throw;
}
timeoutException = ex;
}
try
{
await ValidateConnection(originalRequestTime, initialConnectionMode, request.CancellationToken).ConfigureAwait(false);
}
catch
{
// Unable to re-establish connection with the server.
// Throw the original exception
throw timeoutException;
}
request.Url = ReplaceServerAddress(request.Url, initialConnectionMode);
return await HttpClient.SendAsync(request).ConfigureAwait(false);
}
private readonly SemaphoreSlim _validateConnectionSemaphore = new SemaphoreSlim(1, 1);
private DateTime _lastConnectionValidationTime = DateTime.MinValue;
private async Task ValidateConnection(DateTime originalRequestTime, ConnectionMode initialConnectionMode, CancellationToken cancellationToken)
{
await _validateConnectionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (originalRequestTime > _lastConnectionValidationTime)
{
await ValidateConnectionInternal(initialConnectionMode, cancellationToken).ConfigureAwait(false);
}
}
finally
{
_validateConnectionSemaphore.Release();
}
}
private async Task ValidateConnectionInternal(ConnectionMode initialConnectionMode, CancellationToken cancellationToken)
{
Logger.Debug("Connection to server dropped. Attempting to reconnect.");
const int maxWaitMs = 10000;
const int waitIntervalMs = 100;
var totalWaitMs = 0;
var networkStatus = NetworkConnection.GetNetworkStatus();
while (!networkStatus.IsNetworkAvailable)
{
if (totalWaitMs >= maxWaitMs)
{
throw new Exception("Network unavailable.");
}
await Task.Delay(waitIntervalMs, cancellationToken).ConfigureAwait(false);
totalWaitMs += waitIntervalMs;
networkStatus = NetworkConnection.GetNetworkStatus();
}
var urlList = new List<Tuple<string, ConnectionMode>>
{
new Tuple<string,ConnectionMode>(ServerInfo.LocalAddress, ConnectionMode.Local),
new Tuple<string,ConnectionMode>(ServerInfo.RemoteAddress, ConnectionMode.Remote)
};
if (!networkStatus.GetIsAnyLocalNetworkAvailable())
{
urlList.Reverse();
}
if (!string.IsNullOrEmpty(ServerInfo.ManualAddress))
{
if (!string.Equals(ServerInfo.ManualAddress, ServerInfo.LocalAddress, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(ServerInfo.ManualAddress, ServerInfo.RemoteAddress, StringComparison.OrdinalIgnoreCase))
{
urlList.Insert(0, new Tuple<string, ConnectionMode>(ServerInfo.ManualAddress, ConnectionMode.Manual));
}
}
foreach (var url in urlList)
{
var connected = await TryConnect(url.Item1, cancellationToken).ConfigureAwait(false);
if (connected)
{
ConnectionMode = url.Item2;
break;
}
}
_lastConnectionValidationTime = DateTime.UtcNow;
}
private async Task<bool> TryConnect(string baseUrl, CancellationToken cancellationToken)
{
var fullUrl = baseUrl + "/system/info/public";
fullUrl = AddDataFormat(fullUrl);
var request = new HttpRequest
{
Url = fullUrl,
RequestHeaders = HttpHeaders,
CancellationToken = cancellationToken,
Method = "GET"
};
try
{
using (var stream = await HttpClient.SendAsync(request).ConfigureAwait(false))
{
return true;
}
}
catch (Exception ex)
{
return false;
}
}
private string ReplaceServerAddress(string url, ConnectionMode initialConnectionMode)
{
var baseUrl = ServerInfo.GetAddress(ConnectionMode);
var index = url.IndexOf("/mediabrowser", StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
return baseUrl.TrimEnd('/') + url.Substring(index);
}
return url;
//return url.Replace(ServerInfo.GetAddress(initialConnectionMode), ServerInfo.GetAddress(ConnectionMode), StringComparison.OrdinalIgnoreCase);
}
public Task<Stream> GetStream(string url, CancellationToken cancellationToken = default(CancellationToken))
{
return SendAsync(new HttpRequest
{
CancellationToken = cancellationToken,
Method = "GET",
RequestHeaders = HttpHeaders,
Url = url
});
}
public Task<HttpResponse> GetResponse(string url, CancellationToken cancellationToken = default(CancellationToken))
{
return HttpClient.GetResponse(new HttpRequest
{
CancellationToken = cancellationToken,
Method = "GET",
RequestHeaders = HttpHeaders,
Url = url
});
}
/// <summary>
/// Gets an image stream based on a url
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{Stream}.</returns>
/// <exception cref="System.ArgumentNullException">url</exception>
public Task<Stream> GetImageStreamAsync(string url, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
return GetStream(url, cancellationToken);
}
/// <summary>
/// Gets a BaseItem
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Task{BaseItemDto}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public async Task<BaseItemDto> GetItemAsync(string id, string userId)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/Items/" + id);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto>(stream);
}
}
/// <summary>
/// Gets the intros async.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Task{System.String[]}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public async Task<QueryResult<BaseItemDto>> GetIntrosAsync(string itemId, string userId)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Intros");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the item counts async.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemCounts}.</returns>
/// <exception cref="System.ArgumentNullException">query</exception>
public async Task<ItemCounts> GetItemCountsAsync(ItemCountsQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNull("IsFavorite", query.IsFavorite);
var url = GetApiUrl("Items/Counts", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<ItemCounts>(stream);
}
}
/// <summary>
/// Gets a BaseItem
/// </summary>
/// <param name="userId">The user id.</param>
/// <returns>Task{BaseItemDto}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<BaseItemDto> GetRootFolderAsync(string userId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/Items/Root");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto>(stream);
}
}
/// <summary>
/// Gets the users async.
/// </summary>
/// <returns>Task{UserDto[]}.</returns>
public async Task<UserDto[]> GetUsersAsync(UserQuery query)
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNull("IsDisabled", query.IsDisabled);
queryString.AddIfNotNull("IsHidden", query.IsHidden);
var url = GetApiUrl("Users", queryString);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<UserDto[]>(stream);
}
}
public async Task<UserDto[]> GetPublicUsersAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("Users/Public");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<UserDto[]>(stream);
}
}
/// <summary>
/// Gets active client sessions.
/// </summary>
/// <returns>Task{SessionInfoDto[]}.</returns>
public async Task<SessionInfoDto[]> GetClientSessionsAsync(SessionQuery query)
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("ControllableByUserId", query.ControllableByUserId);
var url = GetApiUrl("Sessions", queryString);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<SessionInfoDto[]>(stream);
}
}
public Task<PluginSecurityInfo> GetRegistrationInfo()
{
throw new NotImplementedException();
}
/// <summary>
/// Queries for items
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">query</exception>
public async Task<QueryResult<BaseItemDto>> GetItemsAsync(ItemQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var url = GetItemListUrl(query);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the next up async.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">query</exception>
public async Task<QueryResult<BaseItemDto>> GetNextUpEpisodesAsync(NextUpQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var url = GetNextUpUrl(query);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetUpcomingEpisodesAsync(UpcomingEpisodesQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
if (query.Fields != null)
{
dict.Add("fields", query.Fields.Select(f => f.ToString()));
}
dict.Add("ParentId", query.ParentId);
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.Add("UserId", query.UserId);
dict.AddIfNotNull("EnableImages", query.EnableImages);
if (query.EnableImageTypes != null)
{
dict.Add("EnableImageTypes", query.EnableImageTypes.Select(f => f.ToString()));
}
dict.AddIfNotNull("ImageTypeLimit", query.ImageTypeLimit);
var url = GetApiUrl("Shows/Upcoming", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetEpisodesAsync(EpisodeQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNullOrEmpty("StartItemId", query.StartItemId);
dict.AddIfNotNull("Season", query.SeasonNumber);
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNullOrEmpty("SeasonId", query.SeasonId);
if (query.Fields != null)
{
dict.Add("Fields", query.Fields.Select(f => f.ToString()));
}
dict.AddIfNotNull("IsMissing", query.IsMissing);
dict.AddIfNotNull("IsVirtualUnaired", query.IsVirtualUnaired);
var url = GetApiUrl("Shows/" + query.SeriesId + "/Episodes", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetSeasonsAsync(SeasonQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
if (query.Fields != null)
{
dict.Add("Fields", query.Fields.Select(f => f.ToString()));
}
dict.AddIfNotNull("IsMissing", query.IsMissing);
dict.AddIfNotNull("IsVirtualUnaired", query.IsVirtualUnaired);
dict.AddIfNotNull("IsSpecialSeason", query.IsSpecialSeason);
var url = GetApiUrl("Shows/" + query.SeriesId + "/Seasons", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the people async.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<QueryResult<BaseItemDto>> GetPeopleAsync(PersonsQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetItemByNameListUrl("Persons", query);
if (query.PersonTypes != null && query.PersonTypes.Length > 0)
{
url += "&PersonTypes=" + string.Join(",", query.PersonTypes);
}
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the genres async.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
public async Task<QueryResult<BaseItemDto>> GetGenresAsync(ItemsByNameQuery query)
{
var url = GetItemByNameListUrl("Genres", query);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the studios async.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
public async Task<QueryResult<BaseItemDto>> GetStudiosAsync(ItemsByNameQuery query)
{
var url = GetItemByNameListUrl("Studios", query);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the artists.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<QueryResult<BaseItemDto>> GetArtistsAsync(ArtistsQuery query)
{
var url = GetItemByNameListUrl("Artists", query);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Gets the artists.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<QueryResult<BaseItemDto>> GetAlbumArtistsAsync(ArtistsQuery query)
{
var url = GetItemByNameListUrl("Artists/AlbumArtists", query);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
/// <summary>
/// Restarts the server async.
/// </summary>
/// <returns>Task.</returns>
public Task RestartServerAsync()
{
var url = GetApiUrl("System/Restart");
return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary(), CancellationToken.None);
}
/// <summary>
/// Gets the system status async.
/// </summary>
/// <returns>Task{SystemInfo}.</returns>
public async Task<SystemInfo> GetSystemInfoAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("System/Info");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<SystemInfo>(stream);
}
}
/// <summary>
/// get public system information as an asynchronous operation.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task<PublicSystemInfo>.</returns>
public async Task<PublicSystemInfo> GetPublicSystemInfoAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("System/Info/Public");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<PublicSystemInfo>(stream);
}
}
/// <summary>
/// Gets a list of plugins installed on the server
/// </summary>
/// <returns>Task{PluginInfo[]}.</returns>
public async Task<PluginInfo[]> GetInstalledPluginsAsync()
{
var url = GetApiUrl("Plugins");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<PluginInfo[]>(stream);
}
}
/// <summary>
/// Gets the current server configuration
/// </summary>
/// <returns>Task{ServerConfiguration}.</returns>
public async Task<ServerConfiguration> GetServerConfigurationAsync()
{
var url = GetApiUrl("System/Configuration");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<ServerConfiguration>(stream);
}
}
/// <summary>
/// Gets the scheduled tasks.
/// </summary>
/// <returns>Task{TaskInfo[]}.</returns>
public async Task<TaskInfo[]> GetScheduledTasksAsync()
{
var url = GetApiUrl("ScheduledTasks");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<TaskInfo[]>(stream);
}
}
/// <summary>
/// Gets the scheduled task async.
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Task{TaskInfo}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public async Task<TaskInfo> GetScheduledTaskAsync(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("ScheduledTasks/" + id);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<TaskInfo>(stream);
}
}
/// <summary>
/// Gets a user by id
/// </summary>
/// <param name="id">The id.</param>
/// <returns>Task{UserDto}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public async Task<UserDto> GetUserAsync(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("Users/" + id);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<UserDto>(stream);
}
}
/// <summary>
/// Gets the parental ratings async.
/// </summary>
/// <returns>Task{List{ParentalRating}}.</returns>
public async Task<List<ParentalRating>> GetParentalRatingsAsync()
{
var url = GetApiUrl("Localization/ParentalRatings");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<List<ParentalRating>>(stream);
}
}
/// <summary>
/// Gets local trailers for an item
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="itemId">The item id.</param>
/// <returns>Task{ItemsResult}.</returns>
/// <exception cref="System.ArgumentNullException">query</exception>
public async Task<BaseItemDto[]> GetLocalTrailersAsync(string userId, string itemId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/LocalTrailers");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto[]>(stream);
}
}
/// <summary>
/// Gets special features for an item
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="itemId">The item id.</param>
/// <returns>Task{BaseItemDto[]}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<BaseItemDto[]> GetSpecialFeaturesAsync(string userId, string itemId)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/SpecialFeatures");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto[]>(stream);
}
}
/// <summary>
/// Gets the cultures async.
/// </summary>
/// <returns>Task{CultureDto[]}.</returns>
public async Task<CultureDto[]> GetCulturesAsync()
{
var url = GetApiUrl("Localization/Cultures");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<CultureDto[]>(stream);
}
}
/// <summary>
/// Gets the countries async.
/// </summary>
/// <returns>Task{CountryInfo[]}.</returns>
public async Task<CountryInfo[]> GetCountriesAsync()
{
var url = GetApiUrl("Localization/Countries");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<CountryInfo[]>(stream);
}
}
/// <summary>
/// Gets the game system summaries async.
/// </summary>
/// <returns>Task{List{GameSystemSummary}}.</returns>
public async Task<List<GameSystemSummary>> GetGameSystemSummariesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("Games/SystemSummaries");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<List<GameSystemSummary>>(stream);
}
}
public Task<UserItemDataDto> MarkPlayedAsync(string itemId, string userId, DateTime? datePlayed)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var dict = new QueryStringDictionary();
if (datePlayed.HasValue)
{
dict.Add("DatePlayed", datePlayed.Value.ToString("yyyyMMddHHmmss"));
}
var url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId, dict);
return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>(), CancellationToken.None);
}
/// <summary>
/// Marks the unplayed async.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Task{UserItemDataDto}.</returns>
/// <exception cref="System.ArgumentNullException">
/// itemId
/// or
/// userId
/// </exception>
public Task<UserItemDataDto> MarkUnplayedAsync(string itemId, string userId)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/PlayedItems/" + itemId);
return DeleteAsync<UserItemDataDto>(url, CancellationToken.None);
}
/// <summary>
/// Updates the favorite status async.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">The user id.</param>
/// <param name="isFavorite">if set to <c>true</c> [is favorite].</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task<UserItemDataDto> UpdateFavoriteStatusAsync(string itemId, string userId, bool isFavorite)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/FavoriteItems/" + itemId);
if (isFavorite)
{
return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>(), CancellationToken.None);
}
return DeleteAsync<UserItemDataDto>(url, CancellationToken.None);
}
/// <summary>
/// Reports to the server that the user has begun playing an item
/// </summary>
/// <param name="info">The information.</param>
/// <returns>Task{UserItemDataDto}.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task ReportPlaybackStartAsync(PlaybackStartInfo info)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Logger.Debug("ReportPlaybackStart: Item {0}", info.ItemId);
var url = GetApiUrl("Sessions/Playing");
return PostAsync<PlaybackStartInfo, EmptyRequestResult>(url, info, CancellationToken.None);
}
/// <summary>
/// Reports playback progress to the server
/// </summary>
/// <param name="info">The information.</param>
/// <returns>Task{UserItemDataDto}.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task ReportPlaybackProgressAsync(PlaybackProgressInfo info)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
if (IsWebSocketConnected)
{
return SendWebSocketMessage("ReportPlaybackProgress", JsonSerializer.SerializeToString(info));
}
var url = GetApiUrl("Sessions/Playing/Progress");
return PostAsync<PlaybackProgressInfo, EmptyRequestResult>(url, info, CancellationToken.None);
}
/// <summary>
/// Reports to the server that the user has stopped playing an item
/// </summary>
/// <param name="info">The information.</param>
/// <returns>Task{UserItemDataDto}.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task ReportPlaybackStoppedAsync(PlaybackStopInfo info)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
var url = GetApiUrl("Sessions/Playing/Stopped");
return PostAsync<PlaybackStopInfo, EmptyRequestResult>(url, info, CancellationToken.None);
}
/// <summary>
/// Instructs antoher client to browse to a library item.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="itemId">The id of the item to browse to.</param>
/// <param name="itemName">The name of the item to browse to.</param>
/// <param name="itemType">The type of the item to browse to.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">sessionId
/// or
/// itemId
/// or
/// itemName
/// or
/// itemType</exception>
public Task SendBrowseCommandAsync(string sessionId, string itemId, string itemName, string itemType)
{
var cmd = new GeneralCommand
{
Name = "DisplayContent"
};
cmd.Arguments["ItemType"] = itemType;
cmd.Arguments["ItemId"] = itemId;
cmd.Arguments["ItemName"] = itemName;
return SendCommandAsync(sessionId, cmd);
}
/// <summary>
/// Sends the play command async.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="request">The request.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">sessionId
/// or
/// request</exception>
public Task SendPlayCommandAsync(string sessionId, PlayRequest request)
{
if (string.IsNullOrEmpty(sessionId))
{
throw new ArgumentNullException("sessionId");
}
if (request == null)
{
throw new ArgumentNullException("request");
}
var dict = new QueryStringDictionary();
dict.Add("ItemIds", request.ItemIds);
dict.AddIfNotNull("StartPositionTicks", request.StartPositionTicks);
dict.Add("PlayCommand", request.PlayCommand.ToString());
var url = GetApiUrl("Sessions/" + sessionId + "/Playing", dict);
return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
public Task SendMessageCommandAsync(string sessionId, MessageCommand command)
{
var cmd = new GeneralCommand
{
Name = "DisplayMessage"
};
cmd.Arguments["Header"] = command.Header;
cmd.Arguments["Text"] = command.Text;
if (command.TimeoutMs.HasValue)
{
cmd.Arguments["Timeout"] = command.TimeoutMs.Value.ToString(CultureInfo.InvariantCulture);
}
return SendCommandAsync(sessionId, cmd);
}
/// <summary>
/// Sends the system command async.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="command">The command.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">sessionId</exception>
public Task SendCommandAsync(string sessionId, GeneralCommand command)
{
if (string.IsNullOrEmpty(sessionId))
{
throw new ArgumentNullException("sessionId");
}
var url = GetApiUrl("Sessions/" + sessionId + "/Command");
return PostAsync<GeneralCommand, EmptyRequestResult>(url, command, CancellationToken.None);
}
/// <summary>
/// Sends the playstate command async.
/// </summary>
/// <param name="sessionId">The session id.</param>
/// <param name="request">The request.</param>
/// <returns>Task.</returns>
public Task SendPlaystateCommandAsync(string sessionId, PlaystateRequest request)
{
var dict = new QueryStringDictionary();
dict.AddIfNotNull("SeekPositionTicks", request.SeekPositionTicks);
var url = GetApiUrl("Sessions/" + sessionId + "/Playing/" + request.Command.ToString(), dict);
return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
/// <summary>
/// Clears a user's rating for an item
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">The user id.</param>
/// <returns>Task{UserItemDataDto}.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task<UserItemDataDto> ClearUserItemRatingAsync(string itemId, string userId)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating");
return DeleteAsync<UserItemDataDto>(url, CancellationToken.None);
}
/// <summary>
/// Updates a user's rating for an item, based on likes or dislikes
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="userId">The user id.</param>
/// <param name="likes">if set to <c>true</c> [likes].</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">itemId</exception>
public Task<UserItemDataDto> UpdateUserItemRatingAsync(string itemId, string userId, bool likes)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var dict = new QueryStringDictionary { };
dict.Add("likes", likes);
var url = GetApiUrl("Users/" + userId + "/Items/" + itemId + "/Rating", dict);
return PostAsync<UserItemDataDto>(url, new Dictionary<string, string>(), CancellationToken.None);
}
internal Func<IApiClient, AuthenticationResult, Task> OnAuthenticated { get; set; }
/// <summary>
/// Authenticates a user and returns the result
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>Task.</returns>
/// <exception cref="ArgumentNullException">username</exception>
/// <exception cref="System.ArgumentNullException">userId</exception>
public async Task<AuthenticationResult> AuthenticateUserAsync(string username, string password)
{
if (string.IsNullOrWhiteSpace(username))
{
throw new ArgumentNullException("username");
}
var url = GetApiUrl("Users/AuthenticateByName");
var args = new Dictionary<string, string>();
args["username"] = Uri.EscapeDataString(username);
args["pw"] = password;
var bytes = Encoding.UTF8.GetBytes(password ?? string.Empty);
args["password"] = BitConverter.ToString(_cryptographyProvider.CreateSha1(bytes)).Replace("-", string.Empty);
args["passwordMD5"] = ConnectService.GetConnectPasswordMd5(password ?? string.Empty, _cryptographyProvider);
var result = await PostAsync<AuthenticationResult>(url, args, CancellationToken.None);
SetAuthenticationInfo(result.AccessToken, result.User.Id);
if (OnAuthenticated != null)
{
await OnAuthenticated(this, result).ConfigureAwait(false);
}
return result;
}
/// <summary>
/// Updates the server configuration async.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">configuration</exception>
public Task UpdateServerConfigurationAsync(ServerConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
var url = GetApiUrl("System/Configuration");
return PostAsync<ServerConfiguration, EmptyRequestResult>(url, configuration, CancellationToken.None);
}
/// <summary>
/// Updates the scheduled task triggers.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="triggers">The triggers.</param>
/// <returns>Task{RequestResult}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public Task UpdateScheduledTaskTriggersAsync(string id, TaskTriggerInfo[] triggers)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
if (triggers == null)
{
throw new ArgumentNullException("triggers");
}
var url = GetApiUrl("ScheduledTasks/" + id + "/Triggers");
return PostAsync<TaskTriggerInfo[], EmptyRequestResult>(url, triggers, CancellationToken.None);
}
/// <summary>
/// Gets the display preferences.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="userId">The user id.</param>
/// <param name="client">The client.</param>
/// <returns>Task{BaseItemDto}.</returns>
public async Task<DisplayPreferences> GetDisplayPreferencesAsync(string id, string userId, string client, CancellationToken cancellationToken = default(CancellationToken))
{
var dict = new QueryStringDictionary();
dict.Add("userId", userId);
dict.Add("client", client);
var url = GetApiUrl("DisplayPreferences/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<DisplayPreferences>(stream);
}
}
/// <summary>
/// Updates display preferences for a user
/// </summary>
/// <param name="displayPreferences">The display preferences.</param>
/// <returns>Task{DisplayPreferences}.</returns>
/// <exception cref="System.ArgumentNullException">userId</exception>
public Task UpdateDisplayPreferencesAsync(DisplayPreferences displayPreferences, string userId, string client, CancellationToken cancellationToken = default(CancellationToken))
{
if (displayPreferences == null)
{
throw new ArgumentNullException("displayPreferences");
}
var dict = new QueryStringDictionary();
dict.Add("userId", userId);
dict.Add("client", client);
var url = GetApiUrl("DisplayPreferences/" + displayPreferences.Id, dict);
return PostAsync<DisplayPreferences, EmptyRequestResult>(url, displayPreferences, cancellationToken);
}
/// <summary>
/// Posts a set of data to a url, and deserializes the return stream into T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">The URL.</param>
/// <param name="args">The args.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{``0}.</returns>
public async Task<T> PostAsync<T>(string url, Dictionary<string, string> args, CancellationToken cancellationToken = default(CancellationToken))
where T : class
{
url = AddDataFormat(url);
// Create the post body
var strings = args.Keys.Select(key => string.Format("{0}={1}", key, args[key]));
var postContent = string.Join("&", strings.ToArray());
const string contentType = "application/x-www-form-urlencoded";
using (var stream = await SendAsync(new HttpRequest
{
Url = url,
CancellationToken = cancellationToken,
RequestHeaders = HttpHeaders,
Method = "POST",
RequestContentType = contentType,
RequestContent = postContent
}).ConfigureAwait(false))
{
return DeserializeFromStream<T>(stream);
}
}
/// <summary>
/// Deletes the async.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{``0}.</returns>
private async Task<T> DeleteAsync<T>(string url, CancellationToken cancellationToken = default(CancellationToken))
where T : class
{
url = AddDataFormat(url);
using (var stream = await SendAsync(new HttpRequest
{
Url = url,
CancellationToken = cancellationToken,
RequestHeaders = HttpHeaders,
Method = "DELETE"
}).ConfigureAwait(false))
{
return DeserializeFromStream<T>(stream);
}
}
/// <summary>
/// Posts an object of type TInputType to a given url, and deserializes the response into an object of type TOutputType
/// </summary>
/// <typeparam name="TInputType">The type of the T input type.</typeparam>
/// <typeparam name="TOutputType">The type of the T output type.</typeparam>
/// <param name="url">The URL.</param>
/// <param name="obj">The obj.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{``1}.</returns>
private async Task<TOutputType> PostAsync<TInputType, TOutputType>(string url, TInputType obj, CancellationToken cancellationToken = default(CancellationToken))
where TOutputType : class
{
url = AddDataFormat(url);
const string contentType = "application/json";
var postContent = SerializeToJson(obj);
using (var stream = await SendAsync(new HttpRequest
{
Url = url,
CancellationToken = cancellationToken,
RequestHeaders = HttpHeaders,
Method = "POST",
RequestContentType = contentType,
RequestContent = postContent
}).ConfigureAwait(false))
{
return DeserializeFromStream<TOutputType>(stream);
}
}
/// <summary>
/// This is a helper around getting a stream from the server that contains serialized data
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{Stream}.</returns>
public Task<Stream> GetSerializedStreamAsync(string url, CancellationToken cancellationToken)
{
url = AddDataFormat(url);
return GetStream(url, cancellationToken);
}
public Task<Stream> GetSerializedStreamAsync(string url)
{
return GetSerializedStreamAsync(url, CancellationToken.None);
}
public async Task<NotificationsSummary> GetNotificationsSummary(string userId)
{
var url = GetApiUrl("Notifications/" + userId + "/Summary");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<NotificationsSummary>(stream);
}
}
public Task MarkNotificationsRead(string userId, IEnumerable<string> notificationIdList, bool isRead)
{
var url = "Notifications/" + userId;
url += isRead ? "/Read" : "/Unread";
var dict = new QueryStringDictionary();
var ids = notificationIdList.ToArray();
dict.Add("Ids", string.Join(",", ids));
url = GetApiUrl(url, dict);
return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
public async Task<NotificationResult> GetNotificationsAsync(NotificationQuery query)
{
var url = "Notifications/" + query.UserId;
var dict = new QueryStringDictionary();
dict.AddIfNotNull("ItemIds", query.IsRead);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("Limit", query.Limit);
url = GetApiUrl(url, dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<NotificationResult>(stream);
}
}
public async Task<AllThemeMediaResult> GetAllThemeMediaAsync(string userId, string itemId, bool inheritFromParent, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.Add("InheritFromParent", inheritFromParent);
queryString.AddIfNotNullOrEmpty("UserId", userId);
var url = GetApiUrl("Items/" + itemId + "/ThemeMedia", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<AllThemeMediaResult>(stream);
}
}
public async Task<SearchHintResult> GetSearchHintsAsync(SearchQuery query)
{
if (query == null || string.IsNullOrEmpty(query.SearchTerm))
{
throw new ArgumentNullException("query");
}
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("SearchTerm", query.SearchTerm);
queryString.AddIfNotNullOrEmpty("UserId", query.UserId);
queryString.AddIfNotNullOrEmpty("ParentId", query.ParentId);
queryString.AddIfNotNull("StartIndex", query.StartIndex);
queryString.AddIfNotNull("Limit", query.Limit);
queryString.Add("IncludeArtists", query.IncludeArtists);
queryString.Add("IncludeGenres", query.IncludeGenres);
queryString.Add("IncludeMedia", query.IncludeMedia);
queryString.Add("IncludePeople", query.IncludePeople);
queryString.Add("IncludeStudios", query.IncludeStudios);
queryString.AddIfNotNull("ExcludeItemTypes", query.ExcludeItemTypes);
queryString.AddIfNotNull("IncludeItemTypes", query.IncludeItemTypes);
queryString.AddIfNotNull("IsKids", query.IsKids);
queryString.AddIfNotNull("IsMovie", query.IsMovie);
queryString.AddIfNotNull("IsNews", query.IsNews);
queryString.AddIfNotNull("IsSeries", query.IsSeries);
queryString.AddIfNotNull("IsSports", query.IsSports);
queryString.AddIfNotNull("MediaTypes", query.MediaTypes);
var url = GetApiUrl("Search/Hints", queryString);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<SearchHintResult>(stream);
}
}
public async Task<ThemeMediaResult> GetThemeSongsAsync(string userId, string itemId, bool inheritFromParent, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.Add("InheritFromParent", inheritFromParent);
queryString.AddIfNotNullOrEmpty("UserId", userId);
var url = GetApiUrl("Items/" + itemId + "/ThemeSongs", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<ThemeMediaResult>(stream);
}
}
public async Task<ThemeMediaResult> GetThemeVideosAsync(string userId, string itemId, bool inheritFromParent, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.Add("InheritFromParent", inheritFromParent);
queryString.AddIfNotNullOrEmpty("UserId", userId);
var url = GetApiUrl("Items/" + itemId + "/ThemeVideos", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<ThemeMediaResult>(stream);
}
}
/// <summary>
/// Gets the critic reviews.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="startIndex">The start index.</param>
/// <param name="limit">The limit.</param>
/// <returns>Task{ItemReviewsResult}.</returns>
/// <exception cref="System.ArgumentNullException">
/// id
/// or
/// userId
/// </exception>
public async Task<QueryResult<ItemReview>> GetCriticReviews(string itemId, CancellationToken cancellationToken = default(CancellationToken), int? startIndex = null, int? limit = null)
{
if (string.IsNullOrEmpty(itemId))
{
throw new ArgumentNullException("itemId");
}
var queryString = new QueryStringDictionary();
queryString.AddIfNotNull("startIndex", startIndex);
queryString.AddIfNotNull("limit", limit);
var url = GetApiUrl("Items/" + itemId + "/CriticReviews", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<ItemReview>>(stream);
}
}
public async Task<T> GetAsync<T>(string url, CancellationToken cancellationToken = default(CancellationToken))
where T : class
{
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<T>(stream);
}
}
/// <summary>
/// Gets the index of the game player.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{List{ItemIndex}}.</returns>
public async Task<List<ItemIndex>> GetGamePlayerIndex(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("UserId", userId);
var url = GetApiUrl("Games/PlayerIndex", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<List<ItemIndex>>(stream);
}
}
/// <summary>
/// Gets the index of the year.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="includeItemTypes">The include item types.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{List{ItemIndex}}.</returns>
public async Task<List<ItemIndex>> GetYearIndex(string userId, string[] includeItemTypes, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("UserId", userId);
queryString.AddIfNotNull("IncludeItemTypes", includeItemTypes);
var url = GetApiUrl("Items/YearIndex", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<List<ItemIndex>>(stream);
}
}
public Task ReportCapabilities(ClientCapabilities capabilities, CancellationToken cancellationToken = default(CancellationToken))
{
if (capabilities == null)
{
throw new ArgumentNullException("capabilities");
}
var url = GetApiUrl("Sessions/Capabilities/Full");
return PostAsync<ClientCapabilities, EmptyRequestResult>(url, capabilities, cancellationToken);
}
public async Task<LiveTvInfo> GetLiveTvInfoAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("LiveTv/Info");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<LiveTvInfo>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetLiveTvRecordingGroupsAsync(RecordingGroupQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
var url = GetApiUrl("LiveTv/Recordings/Groups", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetLiveTvRecordingsAsync(RecordingQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNullOrEmpty("ChannelId", query.ChannelId);
dict.AddIfNotNullOrEmpty("GroupId", query.GroupId);
dict.AddIfNotNullOrEmpty("Id", query.Id);
dict.AddIfNotNullOrEmpty("SeriesTimerId", query.SeriesTimerId);
dict.AddIfNotNull("IsInProgress", query.IsInProgress);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("Limit", query.Limit);
if (!query.EnableTotalRecordCount)
{
dict.Add("EnableTotalRecordCount", query.EnableTotalRecordCount);
}
var url = GetApiUrl("LiveTv/Recordings", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<ChannelInfoDto>> GetLiveTvChannelsAsync(LiveTvChannelQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNull("IsFavorite", query.IsFavorite);
dict.AddIfNotNull("IsLiked", query.IsLiked);
dict.AddIfNotNull("IsDisliked", query.IsDisliked);
dict.AddIfNotNull("EnableFavoriteSorting", query.EnableFavoriteSorting);
if (query.ChannelType.HasValue)
{
dict.Add("ChannelType", query.ChannelType.Value.ToString());
}
var url = GetApiUrl("LiveTv/Channels", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<ChannelInfoDto>>(stream);
}
}
public Task CancelLiveTvSeriesTimerAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
var url = GetApiUrl("LiveTv/SeriesTimers/" + id, dict);
return SendAsync(new HttpRequest
{
Url = url,
CancellationToken = cancellationToken,
RequestHeaders = HttpHeaders,
Method = "DELETE"
});
}
public Task CancelLiveTvTimerAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
var url = GetApiUrl("LiveTv/Timers/" + id, dict);
return SendAsync(new HttpRequest
{
Url = url,
CancellationToken = cancellationToken,
RequestHeaders = HttpHeaders,
Method = "DELETE"
});
}
public async Task<ChannelInfoDto> GetLiveTvChannelAsync(string id, string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("userId", userId);
var url = GetApiUrl("LiveTv/Channels/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<ChannelInfoDto>(stream);
}
}
public async Task<BaseItemDto> GetLiveTvRecordingAsync(string id, string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("userId", userId);
var url = GetApiUrl("LiveTv/Recordings/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto>(stream);
}
}
public async Task<BaseItemDto> GetLiveTvRecordingGroupAsync(string id, string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("userId", userId);
var url = GetApiUrl("LiveTv/Recordings/Groups/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto>(stream);
}
}
public async Task<SeriesTimerInfoDto> GetLiveTvSeriesTimerAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
var url = GetApiUrl("LiveTv/SeriesTimers/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<SeriesTimerInfoDto>(stream);
}
}
public async Task<QueryResult<SeriesTimerInfoDto>> GetLiveTvSeriesTimersAsync(SeriesTimerQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("SortBy", query.SortBy);
dict.Add("SortOrder", query.SortOrder.ToString());
var url = GetApiUrl("LiveTv/SeriesTimers", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<SeriesTimerInfoDto>>(stream);
}
}
public async Task<TimerInfoDto> GetLiveTvTimerAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
var url = GetApiUrl("LiveTv/Timers/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<TimerInfoDto>(stream);
}
}
public async Task<QueryResult<TimerInfoDto>> GetLiveTvTimersAsync(TimerQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("ChannelId", query.ChannelId);
dict.AddIfNotNullOrEmpty("SeriesTimerId", query.SeriesTimerId);
var url = GetApiUrl("LiveTv/Timers", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<TimerInfoDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetLiveTvProgramsAsync(ProgramQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
const string isoDateFormat = "o";
if (query.MaxEndDate.HasValue)
{
dict.Add("MaxEndDate", query.MaxEndDate.Value.ToUniversalTime().ToString(isoDateFormat));
}
if (query.MaxStartDate.HasValue)
{
dict.Add("MaxStartDate", query.MaxStartDate.Value.ToUniversalTime().ToString(isoDateFormat));
}
if (query.MinEndDate.HasValue)
{
dict.Add("MinEndDate", query.MinEndDate.Value.ToUniversalTime().ToString(isoDateFormat));
}
if (query.MinStartDate.HasValue)
{
dict.Add("MinStartDate", query.MinStartDate.Value.ToUniversalTime().ToString(isoDateFormat));
}
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
if (!query.EnableTotalRecordCount)
{
dict.Add("EnableTotalRecordCount", query.EnableTotalRecordCount);
}
if (query.ChannelIds != null)
{
dict.Add("ChannelIds", string.Join(",", query.ChannelIds));
}
// TODO: This endpoint supports POST if the query string is too long
var url = GetApiUrl("LiveTv/Programs", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetRecommendedLiveTvProgramsAsync(RecommendedProgramQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNull("HasAired", query.HasAired);
dict.AddIfNotNull("IsAiring", query.IsAiring);
if (!query.EnableTotalRecordCount)
{
dict.Add("EnableTotalRecordCount", query.EnableTotalRecordCount);
}
var url = GetApiUrl("LiveTv/Programs/Recommended", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public Task CreateLiveTvSeriesTimerAsync(SeriesTimerInfoDto timer, CancellationToken cancellationToken = default(CancellationToken))
{
if (timer == null)
{
throw new ArgumentNullException("timer");
}
var url = GetApiUrl("LiveTv/SeriesTimers");
return PostAsync<SeriesTimerInfoDto, EmptyRequestResult>(url, timer, cancellationToken);
}
public Task CreateLiveTvTimerAsync(BaseTimerInfoDto timer, CancellationToken cancellationToken = default(CancellationToken))
{
if (timer == null)
{
throw new ArgumentNullException("timer");
}
var url = GetApiUrl("LiveTv/Timers");
return PostAsync<BaseTimerInfoDto, EmptyRequestResult>(url, timer, cancellationToken);
}
public async Task<SeriesTimerInfoDto> GetDefaultLiveTvTimerInfo(string programId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrWhiteSpace(programId))
{
throw new ArgumentNullException("programId");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("programId", programId);
var url = GetApiUrl("LiveTv/Timers/Defaults", dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<SeriesTimerInfoDto>(stream);
}
}
public async Task<SeriesTimerInfoDto> GetDefaultLiveTvTimerInfo(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("LiveTv/Timers/Defaults");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<SeriesTimerInfoDto>(stream);
}
}
public async Task<GuideInfo> GetLiveTvGuideInfo(CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("LiveTv/GuideInfo");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<GuideInfo>(stream);
}
}
public async Task<BaseItemDto> GetLiveTvProgramAsync(string id, string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("userId", userId);
var url = GetApiUrl("LiveTv/Programs/" + id, dict);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto>(stream);
}
}
public Task UpdateLiveTvSeriesTimerAsync(SeriesTimerInfoDto timer, CancellationToken cancellationToken = default(CancellationToken))
{
if (timer == null)
{
throw new ArgumentNullException("timer");
}
var url = GetApiUrl("LiveTv/SeriesTimers/" + timer.Id);
return PostAsync<SeriesTimerInfoDto, EmptyRequestResult>(url, timer, cancellationToken);
}
public Task UpdateLiveTvTimerAsync(TimerInfoDto timer, CancellationToken cancellationToken = default(CancellationToken))
{
if (timer == null)
{
throw new ArgumentNullException("timer");
}
var url = GetApiUrl("LiveTv/Timers/" + timer.Id);
return PostAsync<TimerInfoDto, EmptyRequestResult>(url, timer, cancellationToken);
}
public Task SendString(string sessionId, string text)
{
var cmd = new GeneralCommand
{
Name = "SendString"
};
cmd.Arguments["String"] = text;
return SendCommandAsync(sessionId, cmd);
}
public Task SetAudioStreamIndex(string sessionId, int index)
{
var cmd = new GeneralCommand
{
Name = "SetAudioStreamIndex"
};
cmd.Arguments["Index"] = index.ToString(CultureInfo.InvariantCulture);
return SendCommandAsync(sessionId, cmd);
}
public Task SetSubtitleStreamIndex(string sessionId, int? index)
{
var cmd = new GeneralCommand
{
Name = "SetSubtitleStreamIndex"
};
cmd.Arguments["Index"] = (index ?? -1).ToString(CultureInfo.InvariantCulture);
return SendCommandAsync(sessionId, cmd);
}
public Task SetVolume(string sessionId, int volume)
{
var cmd = new GeneralCommand
{
Name = "SetVolume"
};
cmd.Arguments["Volume"] = volume.ToString(CultureInfo.InvariantCulture);
return SendCommandAsync(sessionId, cmd);
}
public async Task<QueryResult<BaseItemDto>> GetAdditionalParts(string itemId, string userId)
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("UserId", userId);
var url = GetApiUrl("Videos/" + itemId + "/AdditionalParts", queryString);
using (var stream = await GetSerializedStreamAsync(url, CancellationToken.None).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<ChannelFeatures> GetChannelFeatures(string channelId, CancellationToken cancellationToken = default(CancellationToken))
{
var url = GetApiUrl("Channels/" + channelId + "/Features");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<ChannelFeatures>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetChannelItems(ChannelItemQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("UserId", query.UserId);
queryString.AddIfNotNull("StartIndex", query.StartIndex);
queryString.AddIfNotNull("Limit", query.Limit);
queryString.AddIfNotNullOrEmpty("FolderId", query.FolderId);
if (query.Fields != null)
{
queryString.Add("fields", query.Fields.Select(f => f.ToString()));
}
if (query.Filters != null)
{
queryString.Add("Filters", query.Filters.Select(f => f.ToString()));
}
var sortBy = new List<string>();
var sortOrder = new List<string>();
foreach (var order in query.OrderBy)
{
sortBy.Add(order.Item1);
sortOrder.Add(order.Item2.ToString());
}
queryString.AddIfNotNull("SortBy", sortBy);
queryString.AddIfNotNull("SortOrder", sortOrder);
var url = GetApiUrl("Channels/" + query.ChannelId + "/Items", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.AddIfNotNullOrEmpty("UserId", query.UserId);
queryString.AddIfNotNull("SupportsLatestItems", query.SupportsLatestItems);
queryString.AddIfNotNull("StartIndex", query.StartIndex);
queryString.AddIfNotNull("Limit", query.Limit);
queryString.AddIfNotNull("IsFavorite", query.IsFavorite);
var url = GetApiUrl("Channels", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<SessionInfoDto> GetCurrentSessionAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var queryString = new QueryStringDictionary();
queryString.Add("DeviceId", DeviceId);
var url = GetApiUrl("Sessions", queryString);
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
var sessions = DeserializeFromStream<SessionInfoDto[]>(stream);
return sessions.FirstOrDefault();
}
}
public Task StopTranscodingProcesses(string deviceId, string playSessionId)
{
var queryString = new QueryStringDictionary();
queryString.Add("DeviceId", DeviceId);
queryString.AddIfNotNullOrEmpty("PlaySessionId", playSessionId);
var url = GetApiUrl("Videos/ActiveEncodings", queryString);
return SendAsync(new HttpRequest
{
Url = url,
RequestHeaders = HttpHeaders,
Method = "DELETE"
});
}
public async Task<QueryResult<BaseItemDto>> GetLatestChannelItems(AllChannelMediaQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
if (string.IsNullOrEmpty(query.UserId))
{
throw new ArgumentNullException("userId");
}
var queryString = new QueryStringDictionary();
queryString.Add("UserId", query.UserId);
queryString.AddIfNotNull("StartIndex", query.StartIndex);
queryString.AddIfNotNull("Limit", query.Limit);
if (query.Filters != null)
{
queryString.Add("Filters", query.Filters.Select(f => f.ToString()));
}
if (query.Fields != null)
{
queryString.Add("Fields", query.Fields.Select(f => f.ToString()));
}
queryString.AddIfNotNull("ChannelIds", query.ChannelIds);
var url = GetApiUrl("Channels/Items/Latest");
using (var stream = await GetSerializedStreamAsync(url, CancellationToken.None).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task Logout()
{
try
{
var url = GetApiUrl("Sessions/Logout");
await PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
catch (Exception ex)
{
Logger.ErrorException("Error logging out", ex);
}
ClearAuthenticationInfo();
}
public async Task<QueryResult<BaseItemDto>> GetUserViews(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentNullException("userId");
}
var url = GetApiUrl("Users/" + userId + "/Views");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
var result = DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
var serverInfo = ServerInfo;
if (serverInfo != null && _localAssetManager != null)
{
var offlineView = await GetOfflineView(serverInfo.Id, userId).ConfigureAwait(false);
if (offlineView != null)
{
var list = result.Items.ToList();
list.Add(offlineView);
result.Items = list.ToArray();
result.TotalRecordCount = list.Count;
}
}
return result;
}
}
public async Task<BaseItemDto[]> GetLatestItems(LatestItemsQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
if (string.IsNullOrEmpty(query.UserId))
{
throw new ArgumentNullException("userId");
}
var queryString = new QueryStringDictionary();
queryString.AddIfNotNull("GroupItems", query.GroupItems);
queryString.AddIfNotNull("IncludeItemTypes", query.IncludeItemTypes);
queryString.AddIfNotNullOrEmpty("ParentId", query.ParentId);
queryString.AddIfNotNull("IsPlayed", query.IsPlayed);
queryString.AddIfNotNull("StartIndex", query.StartIndex);
queryString.AddIfNotNull("Limit", query.Limit);
if (query.Fields != null)
{
queryString.Add("fields", query.Fields.Select(f => f.ToString()));
}
var url = GetApiUrl("Users/" + query.UserId + "/Items/Latest", queryString);
using (var stream = await GetSerializedStreamAsync(url, CancellationToken.None).ConfigureAwait(false))
{
return DeserializeFromStream<BaseItemDto[]>(stream);
}
}
private async Task<BaseItemDto> GetOfflineView(string serverId, string userId)
{
var views = await _localAssetManager.GetViews(serverId, userId).ConfigureAwait(false);
if (views.Count > 0)
{
return new BaseItemDto
{
Name = "AnyTime",
ServerId = serverId,
Id = "OfflineView",
Type = "OfflineView"
};
}
return null;
}
public Task AddToPlaylist(string playlistId, IEnumerable<string> itemIds, string userId)
{
if (playlistId == null)
{
throw new ArgumentNullException("playlistId");
}
if (itemIds == null)
{
throw new ArgumentNullException("itemIds");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNull("Ids", itemIds);
var url = GetApiUrl(string.Format("Playlists/{0}/Items", playlistId), dict);
return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
public async Task<PlaylistCreationResult> CreatePlaylist(PlaylistCreationRequest request)
{
if (string.IsNullOrEmpty(request.UserId))
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrEmpty(request.MediaType) && (request.ItemIdList == null || !request.ItemIdList.Any()))
{
throw new ArgumentNullException("must provide either MediaType or Ids");
}
var queryString = new QueryStringDictionary();
queryString.Add("UserId", request.UserId);
queryString.Add("Name", request.Name);
if (!string.IsNullOrEmpty(request.MediaType))
queryString.Add("MediaType", request.MediaType);
if (request.ItemIdList != null && request.ItemIdList.Any())
queryString.Add("Ids", request.ItemIdList);
var url = GetApiUrl("Playlists/", queryString);
return await PostAsync<PlaylistCreationResult>(url, new Dictionary<string, string>(), CancellationToken.None);
}
public async Task<QueryResult<BaseItemDto>> GetPlaylistItems(PlaylistItemQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("Limit", query.Limit);
dict.Add("UserId", query.UserId);
if (query.Fields != null)
{
dict.Add("fields", query.Fields.Select(f => f.ToString()));
}
var url = GetApiUrl("Playlists/" + query.Id + "/Items", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public Task RemoveFromPlaylist(string playlistId, IEnumerable<string> entryIds)
{
if (playlistId == null)
{
throw new ArgumentNullException("playlistId");
}
if (entryIds == null)
{
throw new ArgumentNullException("entryIds");
}
var dict = new QueryStringDictionary { };
dict.AddIfNotNull("EntryIds", entryIds);
var url = GetApiUrl(string.Format("Playlists/{0}/Items", playlistId), dict);
return DeleteAsync<EmptyRequestResult>(url, CancellationToken.None);
}
public async Task<ContentUploadHistory> GetContentUploadHistory(string deviceId)
{
var dict = new QueryStringDictionary { };
dict.Add("DeviceId", deviceId);
var url = GetApiUrl("Devices/CameraUploads", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<ContentUploadHistory>(stream);
}
}
public async Task UploadFile(Stream stream, LocalFileInfo file, CancellationToken cancellationToken = default(CancellationToken))
{
var dict = new QueryStringDictionary { };
dict.Add("DeviceId", DeviceId);
dict.Add("Name", file.Name);
dict.Add("Id", file.Id);
dict.AddIfNotNullOrEmpty("Album", file.Album);
var url = GetApiUrl("Devices/CameraUploads", dict);
using (stream)
{
await SendAsync(new HttpRequest
{
CancellationToken = cancellationToken,
Method = "POST",
RequestHeaders = HttpHeaders,
Url = url,
RequestContentType = file.MimeType,
RequestStream = stream
}, false).ConfigureAwait(false);
}
}
public async Task<DevicesOptions> GetDevicesOptions()
{
var dict = new QueryStringDictionary { };
var url = GetApiUrl("System/Configuration/devices", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<DevicesOptions>(stream);
}
}
public async Task<PlaybackInfoResponse> GetPlaybackInfo(PlaybackInfoRequest request)
{
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("UserId", request.UserId);
var url = GetApiUrl("Items/" + request.Id + "/PlaybackInfo", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<PlaybackInfoResponse>(stream);
}
}
public Task<QueryFilters> GetFilters(string userId, string parentId, string[] mediaTypes, string[] itemTypes)
{
throw new NotImplementedException();
}
public Task UpdateItem(BaseItemDto item)
{
throw new NotImplementedException();
}
public Task<SyncJob> CreateSyncJob(SyncJobRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
var url = GetApiUrl("Sync/Jobs");
return PostAsync<SyncJobRequest, SyncJob>(url, request, CancellationToken.None);
}
public Task UpdateSyncJob(SyncJob job)
{
if (job == null)
{
throw new ArgumentNullException("job");
}
var url = GetApiUrl("Sync/Jobs/" + job.Id);
return PostAsync<SyncJob, EmptyRequestResult>(url, job, CancellationToken.None);
}
public async Task<QueryResult<SyncJobItem>> GetSyncJobItems(SyncJobItemQuery query)
{
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("JobId", query.JobId);
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNullOrEmpty("TargetId", query.TargetId);
dict.AddIfNotNull("AddMetadata", query.AddMetadata);
if (query.Statuses.Length > 0)
{
dict.Add("Statuses", string.Join(",", query.Statuses.Select(i => i.ToString()).ToArray()));
}
var url = GetApiUrl("Sync/JobItems", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<SyncJobItem>>(stream);
}
}
public async Task<QueryResult<SyncJob>> GetSyncJobs(SyncJobQuery query)
{
var dict = new QueryStringDictionary { };
dict.AddIfNotNull("Limit", query.Limit);
dict.AddIfNotNull("StartIndex", query.StartIndex);
dict.AddIfNotNull("SyncNewContent", query.SyncNewContent);
dict.AddIfNotNullOrEmpty("TargetId", query.TargetId);
if (query.Statuses.Length > 0)
{
dict.Add("Statuses", string.Join(",", query.Statuses.Select(i => i.ToString()).ToArray()));
}
var url = GetApiUrl("Sync/Jobs", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<SyncJob>>(stream);
}
}
public Task ReportSyncJobItemTransferred(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("Sync/JobItems/" + id + "/Transferred");
return PostAsync<EmptyRequestResult>(url, new Dictionary<string, string>());
}
public Task<Stream> GetSyncJobItemFile(string id, CancellationToken cancellationToken = default(CancellationToken))
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
return GetStream(GetSyncJobItemFileUrl(id), cancellationToken);
}
public string GetSyncJobItemFileUrl(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
return GetApiUrl("Sync/JobItems/" + id + "/File");
}
public Task UpdateUserConfiguration(string userId, UserConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
var url = GetApiUrl("Users/" + userId + "/Configuration");
return PostAsync<UserConfiguration, EmptyRequestResult>(url, configuration, CancellationToken.None);
}
public Task ReportOfflineActions(List<UserAction> actions)
{
if (actions == null || actions.Count == 0)
{
throw new ArgumentNullException("actions");
}
var url = GetApiUrl("Sync/OfflineActions");
return PostAsync<List<UserAction>, EmptyRequestResult>(url, actions, CancellationToken.None);
}
public async Task<List<SyncedItem>> GetReadySyncItems(string targetId)
{
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("TargetId", targetId);
var url = GetApiUrl("Sync/Items/Ready", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<List<SyncedItem>>(stream);
}
}
public Task<SyncDataResponse> SyncData(SyncDataRequest request)
{
var url = GetApiUrl("Sync/Data");
return PostAsync<SyncDataRequest, SyncDataResponse>(url, request, CancellationToken.None);
}
public Task<Stream> GetSyncJobItemAdditionalFile(string id, string name, CancellationToken cancellationToken = default(CancellationToken))
{
var dict = new QueryStringDictionary { };
dict.AddIfNotNullOrEmpty("Name", name);
var url = GetApiUrl("Sync/JobItems/" + id + "/AdditionalFiles", dict);
return GetStream(url, cancellationToken);
}
public Task CancelSyncJob(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("Sync/Jobs/" + id);
return DeleteAsync<EmptyRequestResult>(url, CancellationToken.None);
}
public Task CancelSyncJobItem(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("Sync/JobItems/" + id);
return DeleteAsync<EmptyRequestResult>(url, CancellationToken.None);
}
public Task EnableCancelledSyncJobItem(string id)
{
var url = GetApiUrl("Sync/JobItems/" + id + "/Enable");
return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary(), CancellationToken.None);
}
public Task MarkSyncJobItemForRemoval(string id)
{
var url = GetApiUrl("Sync/JobItems/" + id + "/MarkForRemoval");
return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary(), CancellationToken.None);
}
public Task QueueFailedSyncJobItemForRetry(string id)
{
var url = GetApiUrl("Sync/JobItems/" + id + "/Enable");
return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary(), CancellationToken.None);
}
public Task UnmarkSyncJobItemForRemoval(string id)
{
var url = GetApiUrl("Sync/JobItems/" + id + "/UnmarkForRemoval");
return PostAsync<EmptyRequestResult>(url, new QueryStringDictionary(), CancellationToken.None);
}
public async Task<UserDto> GetOfflineUserAsync(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
var url = GetApiUrl("Users/" + id + "/Offline");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<UserDto>(stream);
}
}
public async Task<SyncDialogOptions> GetSyncOptions(SyncJobRequest jobInfo)
{
var dict = new QueryStringDictionary();
dict.AddIfNotNullOrEmpty("UserId", jobInfo.UserId);
dict.AddIfNotNullOrEmpty("ParentId", jobInfo.ParentId);
dict.AddIfNotNullOrEmpty("TargetId", jobInfo.TargetId);
if (jobInfo.Category.HasValue)
{
dict.AddIfNotNullOrEmpty("Category", jobInfo.Category.Value.ToString());
}
if (jobInfo.ItemIds != null)
{
var list = jobInfo.ItemIds.ToList();
if (list.Count > 0)
{
dict.Add("ItemIds", list);
}
}
var url = GetApiUrl("Sync/Options", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<SyncDialogOptions>(stream);
}
}
public async Task<SyncDialogOptions> GetSyncOptions(SyncJob jobInfo)
{
var dict = new QueryStringDictionary();
dict.AddIfNotNullOrEmpty("UserId", jobInfo.UserId);
dict.AddIfNotNullOrEmpty("ParentId", jobInfo.ParentId);
dict.AddIfNotNullOrEmpty("TargetId", jobInfo.TargetId);
if (jobInfo.Category.HasValue)
{
dict.AddIfNotNullOrEmpty("Category", jobInfo.Category.Value.ToString());
}
if (jobInfo.RequestedItemIds != null)
{
var list = jobInfo.RequestedItemIds.ToList();
if (list.Count > 0)
{
dict.Add("ItemIds", list);
}
}
var url = GetApiUrl("Sync/Options", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<SyncDialogOptions>(stream);
}
}
public async Task<List<RecommendationDto>> GetMovieRecommendations(MovieRecommendationQuery query)
{
var dict = new QueryStringDictionary();
dict.AddIfNotNullOrEmpty("UserId", query.UserId);
dict.AddIfNotNullOrEmpty("ParentId", query.ParentId);
dict.AddIfNotNull("ItemLimit", query.ItemLimit);
dict.AddIfNotNull("CategoryLimit", query.CategoryLimit);
if (query.Fields != null)
{
dict.Add("fields", query.Fields.Select(f => f.ToString()));
}
var url = GetApiUrl("Movies/Recommendations", dict);
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<List<RecommendationDto>>(stream);
}
}
public Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationToken)
{
var url = GetApiUrl("LiveStreams/Open");
return PostAsync<LiveStreamRequest, LiveStreamResponse>(url, request, cancellationToken);
}
public Task CancelSyncLibraryItems(string targetId, IEnumerable<string> itemIds)
{
var dict = new QueryStringDictionary();
dict.Add("ItemIds", itemIds);
var url = GetApiUrl("Sync/" + targetId + "/Items", dict);
return DeleteAsync<EmptyRequestResult>(url, CancellationToken.None);
}
public Task<int> DetectMaxBitrate(CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public async Task<EndPointInfo> GetEndPointInfo(CancellationToken cancellationToken)
{
var url = GetApiUrl("System/Endpoint");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<EndPointInfo>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetInstantMixFromItemAsync(SimilarItemsQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var url = GetInstantMixUrl(query, "Items");
using (var stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
public async Task<QueryResult<BaseItemDto>> GetSimilarItemsAsync(SimilarItemsQuery query, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
{
throw new ArgumentNullException("query");
}
var url = GetSimilarItemListUrl(query, "Items");
using (var stream = await GetSerializedStreamAsync(url, cancellationToken).ConfigureAwait(false))
{
return DeserializeFromStream<QueryResult<BaseItemDto>>(stream);
}
}
}
}
| 37.075692 | 191 | 0.584495 | [
"MIT"
] | BrianCArnold/jellyfin-apiclient-csharp | Emby.ApiClient/ApiClient.cs | 111,192 | C# |
namespace Sitecore.HabitatHome.Feature.Accounts.Services
{
using System.Collections.Generic;
using System.Web.Mvc;
using Sitecore.HabitatHome.Feature.Accounts.Models;
using Sitecore.Security;
using Sitecore.Security.Accounts;
public interface IUserProfileService
{
string GetUserDefaultProfileId();
EditProfile GetEmptyProfile();
EditProfile GetProfile(User user);
void SaveProfile(UserProfile userProfile, EditProfile model);
IEnumerable<string> GetInterests();
}
} | 31.764706 | 69 | 0.725926 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | sumithpdd/Sitecore.HabitatHome.Content | src/Feature/Accounts/code/Services/IUserProfileService.cs | 542 | C# |
/*
* Copyright (c) Johnny Z. All rights reserved.
*
* https://github.com/StormHub/NetUV
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*
* Copyright (c) 2020 The Dotnetty-Span-Fork Project (cuteant@outlook.com)
*
* https://github.com/cuteant/dotnetty-span-fork
*
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
namespace DotNetty.Buffers
{
using System;
using System.Text;
using DotNetty.NetUV;
public readonly struct WritableBuffer : IDisposable
{
private readonly IByteBuffer _buffer;
internal WritableBuffer(IByteBuffer buffer)
{
if (buffer is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); }
_buffer = buffer;
}
public readonly int Count => _buffer.ReadableBytes;
public WritableBuffer Retain()
{
_buffer.Retain();
return this;
}
public static WritableBuffer From(byte[] array)
{
if (array is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); }
IByteBuffer buf = Unpooled.WrappedBuffer(array);
return new WritableBuffer(buf);
}
public readonly IByteBuffer GetBuffer() => _buffer;
public void WriteBoolean(bool value) => _buffer.WriteBoolean(value);
public void WriteByte(byte value) => _buffer.WriteByte(value);
public void WriteSByte(sbyte value) => _buffer.WriteByte((byte)value);
public void WriteInt16(short value) => _buffer.WriteShort(value);
public void WriteInt16LE(short value) => _buffer.WriteShortLE(value);
public void WriteUInt16(ushort value) => _buffer.WriteUnsignedShort(value);
public void WriteUInt16LE(ushort value) => _buffer.WriteUnsignedShortLE(value);
public void WriteInt24(int value) => _buffer.WriteMedium(value);
public void WriteInt24LE(int value) => _buffer.WriteMediumLE(value);
public void WriteInt32(int value) => _buffer.WriteInt(value);
public void WriteInt32LE(int value) => _buffer.WriteIntLE(value);
public void WriteUInt32(uint value) => _buffer.WriteInt((int)value);
public void WriteUInt32LE(uint value) => _buffer.WriteIntLE((int)value);
public void WriteInt64(long value) => _buffer.WriteLong(value);
public void WriteInt64LE(long value) => _buffer.WriteLongLE(value);
public void WriteUInt64(ulong value) => _buffer.WriteLong((long)value);
public void WriteUInt64LE(ulong value) => _buffer.WriteLongLE((long)value);
public void WriteFloat(float value) => _buffer.WriteFloat(value);
public void WriteFloatLE(float value) => _buffer.WriteFloatLE(value);
public void WriteDouble(double value) => _buffer.WriteDouble(value);
public void WriteDoubleLE(double value) => _buffer.WriteDoubleLE(value);
public void WriteString(string value, Encoding encoding) => _buffer.WriteString(value, encoding);
public void Dispose()
{
if (_buffer.IsAccessible)
{
_buffer.Release();
}
}
}
}
| 31.893204 | 105 | 0.664231 | [
"MIT"
] | maksimkim/SpanNetty | src/DotNetty.NetUV/Buffers/WritableBuffer.cs | 3,287 | C# |
/*
Copyright 2016 Esri
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.Runtime.InteropServices;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.ADF.CATIDs;
namespace ACME.GIS.SampleExt
{
[Guid("A7198661-605D-4683-A282-221C154450A1")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ACME.MainMenu")]
public class AcmeMenu : IMenuDef, IRootLevelMenu
{
#region IMenuDef Members
public string Caption
{
get
{
return "ACME";
}
}
public void GetItemInfo(int pos, IItemDef itemDef)
{
// Add some commands to the menu (don't really exist for simplicity sake)
switch (pos)
{
case 0:
itemDef.ID = "ACME.SomeCmd";
itemDef.Group = false;
break;
case 1:
itemDef.ID = "ACME.SomeCmd2";
itemDef.Group = true;
break;
}
}
public int ItemCount
{
get { return 2; }
}
public string Name
{
get { return "ACME Main Menu"; }
}
#endregion
}
}
| 22.535211 | 79 | 0.645 | [
"Apache-2.0"
] | alx1808/arcobjects-sdk-community-samples | Net/Framework/CustomizingAtStartup/CSharp/AcmeMenu.cs | 1,600 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cdb.V20170320.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeInstanceParamRecordsResponse : AbstractModel
{
/// <summary>
/// 符合条件的记录数。
/// </summary>
[JsonProperty("TotalCount")]
public long? TotalCount{ get; set; }
/// <summary>
/// 参数修改记录。
/// </summary>
[JsonProperty("Items")]
public ParamRecord[] Items{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamArrayObj(map, prefix + "Items.", this.Items);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.844828 | 81 | 0.629402 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Cdb/V20170320/Models/DescribeInstanceParamRecordsResponse.cs | 1,879 | C# |
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using VendingMachineApp.Business;
namespace VendingMachineApp.Commands
{
public sealed class BuyCommand
{
public readonly IReadOnlyCollection<Coin> Deposit;
public readonly GoodsIdentity Goods;
public BuyCommand(IReadOnlyCollection<Coin> deposit, GoodsIdentity goods)
{
Contract.Requires(deposit != null);
Contract.Requires(!goods.Equals(default(GoodsIdentity)));
Deposit = deposit;
Goods = goods;
}
}
}
| 26.272727 | 81 | 0.67301 | [
"MIT"
] | DrunkyBard/VendingMachine | src/VendingMachine/Commands/BuyCommand.cs | 580 | 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.
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.FindPackageCommand.FindPackagesByPSSearchService")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.FindPackageCommand.FindPackageStartWithId(System.Boolean)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand.ProcessRecordCore")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.SyncPackageCommand.ProcessRecordCore")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.UpdatePackageCommand.ProcessRecordCore")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "VSTHRD110:Observe result of async calls", Justification = "https://github.com/NuGet/Home/issues/7674", Scope = "member", Target = "~M:NuGet.PackageManagement.PowerShellCmdlets.UninstallPackageCommand.ProcessRecordCore")]
| 135.6875 | 305 | 0.79825 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | src/NuGet.Clients/NuGet.PackageManagement.PowerShellCmdlets/GlobalSuppressions.cs | 2,171 | C# |
//
// This file was auto-generated using the ChilliConnect SDK Generator.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tag Games Ltd
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SdkCore;
namespace ChilliConnect
{
/// <summary>
/// <para>A container for information on any errors that occur during a
/// AddCurrencyBalanceRequest.</para>
///
/// <para>This is immutable after construction and is therefore thread safe.</para>
/// </summary>
public sealed class AddCurrencyBalanceError
{
/// <summary>
/// An enum describing each of the possible error codes that can be returned from a
/// CCAddCurrencyBalanceRequest.
/// </summary>
public enum Error
{
/// <summary>
/// A connection could not be established.
/// </summary>
CouldNotConnect = -2,
/// <summary>
/// An unexpected, fatal error has occured on the server.
/// </summary>
UnexpectedError = 1,
/// <summary>
/// Invalid Request. One of more of the provided fields were not correctly formatted.
/// The data property of the response body will contain specific error messages for
/// each field.
/// </summary>
InvalidRequest = 1007,
/// <summary>
/// Expired Connect Access Token. The Connect Access Token used to authenticate with
/// the server has expired and should be renewed.
/// </summary>
ExpiredConnectAccessToken = 1003,
/// <summary>
/// Invalid Connect Access Token. The Connect Access Token was not valid and cannot
/// be used to authenticate requests.
/// </summary>
InvalidConnectAccessToken = 1004,
/// <summary>
/// Temporary Service Error. A temporary error is preventing the request from being
/// processed.
/// </summary>
TemporaryServiceError = 1008,
/// <summary>
/// Currency Item Not Found. The supplied Currency key did not match a Currency.
/// </summary>
CurrencyItemNotFound = 10203,
/// <summary>
/// Currency Maximum Exceeded. Honouring the request would exceed the maximum as
/// defined by the Currency.
/// </summary>
CurrencyMaximumExceeded = 10201,
/// <summary>
/// Balance Write Conflict. The the WriteLock parameter is out of date. There have
/// been writes since the previous WriteLock given in the request. Details of the
/// Attempted and Existing data will be available in the response data attribute.
/// </summary>
CurrencyBalanceWriteConflict = 10204,
/// <summary>
/// Method Disabled. Public access to this method has been disabled on the
/// ChilliConnect Dashboard.
/// </summary>
MethodDisabled = 1011
}
private const int SuccessHttpResponseCode = 200;
private const int UnexpectedErrorHttpResponseCode = 500;
/// <summary>
/// A code describing the error that has occurred.
/// </summary>
public Error ErrorCode { get; private set; }
/// <summary>
/// A description of the error that as occurred.
/// </summary>
public string ErrorDescription { get; private set; }
/// <summary>
/// A dictionary of additional, error specific information.
/// </summary>
public MultiTypeValue ErrorData { get; private set; }
/// <summary>
/// Initialises a new instance from the given server response. The server response
/// must describe an error otherwise this will throw an error.
/// </summary>
///
/// <param name="serverResponse">The server response from which to initialise this error.
/// The response must describe an error state.</param>
public AddCurrencyBalanceError(ServerResponse serverResponse)
{
ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied.");
ReleaseAssert.IsTrue(serverResponse.Result != HttpResult.Success || serverResponse.HttpResponseCode != SuccessHttpResponseCode, "Input server response must describe an error.");
switch (serverResponse.Result)
{
case HttpResult.Success:
if (serverResponse.HttpResponseCode == UnexpectedErrorHttpResponseCode)
{
ErrorCode = Error.UnexpectedError;
ErrorData = MultiTypeValue.Null;
}
else
{
ErrorCode = GetErrorCode(serverResponse);
ErrorData = GetErrorData(serverResponse.Body);
}
break;
case HttpResult.CouldNotConnect:
ErrorCode = Error.CouldNotConnect;
ErrorData = MultiTypeValue.Null;
break;
default:
throw new ArgumentException("Invalid value for server response result.");
}
ErrorDescription = GetErrorDescription(ErrorCode);
}
/// <summary>
/// Initialises a new instance from the given error code.
/// </summary>
///
/// <param name="errorCode">The error code.</param>
public AddCurrencyBalanceError(Error errorCode)
{
ErrorCode = errorCode;
ErrorData = MultiTypeValue.Null;
ErrorDescription = GetErrorDescription(ErrorCode);
}
/// <summary>
/// Parses the response body to get the response code.
/// </summary>
///
/// <returns>The error code in the given response body.</returns>
///
/// <param name="serverResponse">The server response from which to get the error code. This
/// must describe an successful response from the server which contains an error in the
/// response body.</param>
private static Error GetErrorCode(ServerResponse serverResponse)
{
const string JsonKeyErrorCode = "Code";
ReleaseAssert.IsNotNull(serverResponse, "A server response must be supplied.");
ReleaseAssert.IsTrue(serverResponse.Result == HttpResult.Success, "The result must describe a successful server response.");
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode != SuccessHttpResponseCode && serverResponse.HttpResponseCode != UnexpectedErrorHttpResponseCode,
"Must not be a successful or unexpected HTTP response code.");
object errorCodeObject = serverResponse.Body[JsonKeyErrorCode];
ReleaseAssert.IsTrue(errorCodeObject is long, "'Code' must be a long.");
long errorCode = (long)errorCodeObject;
switch (errorCode)
{
case 1007:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 422, @"Invalid HTTP response code for error code.");
return Error.InvalidRequest;
case 1003:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code.");
return Error.ExpiredConnectAccessToken;
case 1004:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code.");
return Error.InvalidConnectAccessToken;
case 1008:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 503, @"Invalid HTTP response code for error code.");
return Error.TemporaryServiceError;
case 10203:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 401, @"Invalid HTTP response code for error code.");
return Error.CurrencyItemNotFound;
case 10201:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 422, @"Invalid HTTP response code for error code.");
return Error.CurrencyMaximumExceeded;
case 10204:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 409, @"Invalid HTTP response code for error code.");
return Error.CurrencyBalanceWriteConflict;
case 1011:
ReleaseAssert.IsTrue(serverResponse.HttpResponseCode == 403, @"Invalid HTTP response code for error code.");
return Error.MethodDisabled;
default:
return Error.UnexpectedError;
}
}
/// <summary>
/// Extracts the error data json from the given response body.
/// </summary>
///
/// <returns>The additional error data.<returns/>
///
/// <param name="responseBody">The response body containing the error data.</param>
private static MultiTypeValue GetErrorData(IDictionary<string, object> responseBody)
{
const string JsonKeyErrorData = "Data";
ReleaseAssert.IsNotNull(responseBody, "The response body cannot be null.");
if (!responseBody.ContainsKey(JsonKeyErrorData))
{
return MultiTypeValue.Null;
}
return new MultiTypeValue(responseBody[JsonKeyErrorData]);
}
/// <summary>
/// Gets the error message for the given error code.
/// </summary>
///
/// <returns>The error message.</returns>
///
/// <param name="errorCode">The error code.</param>
private static string GetErrorDescription(Error errorCode)
{
switch (errorCode)
{
case Error.CouldNotConnect:
return "A connection could not be established.";
case Error.InvalidRequest:
return "Invalid Request. One of more of the provided fields were not correctly formatted."
+ " The data property of the response body will contain specific error messages for"
+ " each field.";
case Error.ExpiredConnectAccessToken:
return "Expired Connect Access Token. The Connect Access Token used to authenticate with"
+ " the server has expired and should be renewed.";
case Error.InvalidConnectAccessToken:
return "Invalid Connect Access Token. The Connect Access Token was not valid and cannot"
+ " be used to authenticate requests.";
case Error.TemporaryServiceError:
return "Temporary Service Error. A temporary error is preventing the request from being"
+ " processed.";
case Error.CurrencyItemNotFound:
return "Currency Item Not Found. The supplied Currency key did not match a Currency.";
case Error.CurrencyMaximumExceeded:
return "Currency Maximum Exceeded. Honouring the request would exceed the maximum as"
+ " defined by the Currency.";
case Error.CurrencyBalanceWriteConflict:
return "Balance Write Conflict. The the WriteLock parameter is out of date. There have"
+ " been writes since the previous WriteLock given in the request. Details of the"
+ " Attempted and Existing data will be available in the response data attribute.";
case Error.MethodDisabled:
return "Method Disabled. Public access to this method has been disabled on the"
+ " ChilliConnect Dashboard.";
case Error.UnexpectedError:
default:
return "An unexpected server error occurred.";
}
}
}
}
| 38.722973 | 180 | 0.695952 | [
"MIT"
] | ChilliConnect/Samples | UnitySamples/FBLeaderboard/Assets/ChilliConnect/GeneratedSource/Errors/AddCurrencyBalanceError.cs | 11,462 | C# |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using umbraco.cms.presentation.Trees;
using Umbraco.Core;
using Umbraco.Web.Trees;
using umbraco.uicontrols;
namespace umbraco.settings
{
/// <summary>
/// Summary description for editLanguage.
/// </summary>
[WebformsPageTreeAuthorize(Constants.Trees.Languages)]
public partial class editLanguage : BasePages.UmbracoEnsuredPage
{
public editLanguage()
{
CurrentApp = BusinessLogic.DefaultApps.settings.ToString();
}
protected System.Web.UI.WebControls.TextBox NameTxt;
protected System.Web.UI.WebControls.Literal DisplayName;
cms.businesslogic.language.Language currentLanguage;
protected void Page_Load(object sender, System.EventArgs e)
{
currentLanguage = new cms.businesslogic.language.Language(int.Parse(helper.Request("id")));
// Put user code to initialize the page here
Panel1.Text = ui.Text("editlanguage");
pp_language.Text = ui.Text("language", "displayName", base.getUser());
if (!IsPostBack)
{
updateCultureList();
ClientTools
.SetActiveTreeType(Constants.Trees.Languages)
.SyncTree(helper.Request("id"), false);
}
}
private void updateCultureList()
{
SortedList sortedCultures = new SortedList();
Cultures.Items.Clear();
Cultures.Items.Add(new ListItem(ui.Text("choose") + "...", ""));
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
sortedCultures.Add(ci.DisplayName + "|||" + Guid.NewGuid().ToString(), ci.Name);
IDictionaryEnumerator ide = sortedCultures.GetEnumerator();
while (ide.MoveNext())
{
ListItem li = new ListItem(ide.Key.ToString().Substring(0, ide.Key.ToString().IndexOf("|||")), ide.Value.ToString());
if (ide.Value.ToString() == currentLanguage.CultureAlias)
li.Selected = true;
Cultures.Items.Add(li);
}
}
private void save_click(object sender, EventArgs e)
{
currentLanguage.CultureAlias = Cultures.SelectedValue;
currentLanguage.Save();
updateCultureList();
ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "languageSaved"), "");
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
Panel1.hasMenu = true;
var save = Panel1.Menu.NewButton();
save.Click += save_click;
save.Text = ui.Text("save");
save.ButtonType = MenuButtonType.Primary;
save.ID = "save";
Panel1.Text = ui.Text("language", "editLanguage");
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
}
}
| 30.75 | 134 | 0.638061 | [
"MIT"
] | TheWaxMann/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/settings/editLanguage.aspx.cs | 3,321 | C# |
// ReSharper disable All
namespace OpenTl.Schema.Messages
{
using System;
using System.Collections;
using System.Text;
using OpenTl.Schema;
using OpenTl.Schema.Serialization.Attributes;
[Serialize(0xcf1592db)]
public sealed class RequestReportSpam : IRequest<bool>
{
[SerializationOrder(0)]
public OpenTl.Schema.IInputPeer Peer {get; set;}
}
}
| 19.1 | 58 | 0.719895 | [
"MIT"
] | zzz8415/OpenTl.Schema | src/OpenTl.Schema/_generated/Messages/RequestReportSpam.cs | 384 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using ProceduralWorlds.Core;
using ProceduralWorlds.Biomator;
namespace ProceduralWorlds.Node
{
public class NodeBiomeBinder : BaseNode
{
[Input("Partial Biome")]
public PartialBiome inputPartialBiome;
[Input("Terrain"), NotRequired]
public Sampler terrain;
//inputs for 2D topdown map
[Input("Surfaces"), NotRequired]
public BiomeSurfaceGraph biomeSurfaceGraph;
[Input("Details"), NotRequired]
public TerrainDetail biomeDetail;
[Output("biome")]
public Biome outputBiome;
public BaseGraphTerrainType outputMode;
[SerializeField]
Rect colorPreviewRect;
public override void OnNodeCreation()
{
name = "Biome binder";
}
void FillBiomeOutput()
{
if (inputPartialBiome == null)
return ;
outputBiome.biomeSurfaceGraph = biomeSurfaceGraph;
outputBiome.id = inputPartialBiome.id;
outputBiome.name = inputPartialBiome.name;
outputBiome.previewColor = inputPartialBiome.previewColor;
outputBiome.biomeDataReference = inputPartialBiome.biomeDataReference;
//we set our version of the terrain for future merge
outputBiome.modifiedTerrain = terrain;
}
public override void OnNodeProcess()
{
if (outputBiome == null)
outputBiome = new Biome();
FillBiomeOutput();
}
public override void OnNodeProcessOnce()
{
//just pass the biomeSurfaces to the blender for processOnce:
if (outputBiome == null)
outputBiome = new Biome();
FillBiomeOutput();
}
}
}
| 22.041667 | 73 | 0.725268 | [
"MIT"
] | Victorique-GOSICK/Procedural-Worlds-Editor | Assets/ProceduralWorlds/Scripts/PWNodes/Biomes/NodeBiomeBinder.cs | 1,589 | 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 elasticloadbalancingv2-2015-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancingV2.Model
{
/// <summary>
/// The specified subnet is out of available addresses.
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public partial class InvalidSubnetException : AmazonElasticLoadBalancingV2Exception
{
/// <summary>
/// Constructs a new InvalidSubnetException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public InvalidSubnetException(string message)
: base(message) {}
/// <summary>
/// Construct instance of InvalidSubnetException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public InvalidSubnetException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of InvalidSubnetException
/// </summary>
/// <param name="innerException"></param>
public InvalidSubnetException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of InvalidSubnetException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidSubnetException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of InvalidSubnetException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public InvalidSubnetException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the InvalidSubnetException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected InvalidSubnetException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.33871 | 178 | 0.680068 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/ElasticLoadBalancingV2/Generated/Model/InvalidSubnetException.cs | 5,870 | C# |
using System.IO;
using Aspose.Cells;
using System;
namespace Aspose.Cells.Examples.CSharp.Worksheets.Value
{
public class MoveWorksheet
{
public static void Run()
{
// ExStart:1
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string InputPath = dataDir + "book1.xls";
// Open an existing excel file.
Workbook wb = new Workbook(InputPath);
// Create a Worksheets object with reference to
// the sheets of the Workbook.
WorksheetCollection sheets = wb.Worksheets;
// Get the first worksheet.
Worksheet worksheet = sheets[0];
// Move the first sheet to the third position in the workbook.
worksheet.MoveTo(2);
// Save the excel file.
wb.Save(dataDir + "MoveWorksheet_out.xls");
// ExEnd:1
}
}
}
| 28.416667 | 115 | 0.589443 | [
"MIT"
] | aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Worksheets/Value/MoveWorksheet.cs | 1,023 | C# |
// Copyright (c) 2021 ToxicK1dd
// Copyright (C) 2021 Project Contributors
//
// 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.Threading.Tasks;
using System;
namespace Anna.DataAccess.UnitOfWork.Base.Interface
{
public interface IUnitOfWorkBase : IDisposable
{
Task SaveChangesAsync();
}
} | 43.483871 | 81 | 0.760386 | [
"MIT"
] | ToxicK1dd/Anna | Anna.DataAccess/UnitOfWork/Base/Interface/IUnitOfWorkBase.cs | 1,350 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ElsaWorkflowServer.Model
{
public class Claim
{
public int ClaimId { get; set; }
public decimal TotalClaimAmount { get; set; }
public decimal SanctionedAmount { get; set; }
public List<ClaimType> ClaimItemList { get; set; }
}
}
| 23.8125 | 58 | 0.677165 | [
"Apache-2.0"
] | NeoSOFT-Technologies/workflow-plugins | src/Server/Elsa.Server/Models/Claim.cs | 383 | C# |
// The MIT License (MIT)
//
// Copyright (c) 2015 Xamarin
//
// 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 Xamarin.Forms;
using XamarinCRM.Statics;
namespace XamarinCRM.Views.Sales
{
public class LeadListHeaderView : ContentView
{
/// <summary>
/// The command that will be executed when the new lead button is tapped
/// </summary>
readonly Command _NewLeadTappedCommand;
public LeadListHeaderView(Command newLeadTappedCommand)
{
_NewLeadTappedCommand = newLeadTappedCommand;
#region title label
Label headerTitleLabel = new Label()
{
Text = TextResources.Leads_LeadListHeaderTitle.ToUpperInvariant(),
TextColor = Palette._003,
FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
FontAttributes = FontAttributes.Bold,
XAlign = TextAlignment.Start,
YAlign = TextAlignment.Center
};
#endregion
#region new lead image "button"
var newLeadImage = new Image
{
Source = new FileImageSource { File = Device.OnPlatform("add_ios_gray", "add_android_gray", null) },
Aspect = Aspect.AspectFit,
HorizontalOptions = LayoutOptions.EndAndExpand,
};
//Going to use FAB
newLeadImage.IsVisible = false;
newLeadImage.GestureRecognizers.Add(new TapGestureRecognizer()
{
Command = _NewLeadTappedCommand,
NumberOfTapsRequired = 1
});
#endregion
#region absolutLayout
AbsoluteLayout absolutLayout = new AbsoluteLayout();
absolutLayout.Children.Add(
headerTitleLabel,
new Rectangle(0, .5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize),
AbsoluteLayoutFlags.PositionProportional);
absolutLayout.Children.Add(
newLeadImage,
new Rectangle(1, .5, AbsoluteLayout.AutoSize, .5),
AbsoluteLayoutFlags.PositionProportional | AbsoluteLayoutFlags.HeightProportional);
#endregion
#region setup contentView
ContentView contentView = new ContentView()
{
Padding = new Thickness(10, 0), // give the content some padding on the left and right
HeightRequest = Sizes.MediumRowHeight, // set the height of the content view
};
#endregion
#region compose the view hierarchy
contentView.Content = absolutLayout;
#endregion
Content = contentView;
}
}
}
| 40.115789 | 116 | 0.63238 | [
"MIT"
] | rsaggio/app-crm | src/MobileApp/XamarinCRM/Views/Sales/LeadListHeaderView.cs | 3,813 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace BEDA.CITIC.Contracts.Responses
{
/// <summary>
/// 第三方商户提现汇总查询响应内容
/// </summary>
[XmlRoot("stream")]
public class RS_DL3RTXCL : RsBase
{
/// <summary>
/// 中信银行集合列表
/// </summary>
[XmlArray("list")]
[XmlArrayItem("row")]
public List<ThirdPartyCashSummary> List { get; set; }
}
/// <summary>
/// 第三方商户提现汇总
/// </summary>
public class ThirdPartyCashSummary
{
/// <summary>
/// 批次号 varchar(8)
/// </summary>
[XmlElement("batNo")]
public string BatNo { get; set; }
/// <summary>
/// 客户流水号 varchar(20)
/// </summary>
[XmlElement("clientID")]
public string ClientID { get; set; }
/// <summary>
/// 成功总笔数 int
/// </summary>
[XmlElement("succTotal")]
public int SuccTotal { get; set; }
/// <summary>
/// 成功总金额 decimal(15,2)
/// </summary>
[XmlElement("succAmt")]
public decimal SuccAmt { get; set; }
/// <summary>
/// 失败总笔数 int
/// </summary>
[XmlElement("failTotal")]
public int FailTotal { get; set; }
/// <summary>
/// 失败总金额 decimal(15,2)
/// </summary>
[XmlElement("failAmt")]
public decimal FailAmt { get; set; }
/// <summary>
/// 总笔数 int
/// </summary>
[XmlElement("totalNum")]
public int TotalNum { get; set; }
/// <summary>
/// 总金额 decimal(15,2)
/// </summary>
[XmlElement("totalAmt")]
public decimal TotalAmt { get; set; }
/// <summary>
/// 批次受理状态 varchar(2),值域见附录4.2
/// </summary>
[XmlElement("stt")]
public string Stt { get; set; }
/// <summary>
/// 提现日期char(8) 格式YYYYMMDD
/// </summary>
[XmlElement("tranDate")]
public string TranDate { get; set; }
/// <summary>
/// 提现时间char(6) 格式hhmmss
/// </summary>
[XmlElement("tranTime")]
public string TranTime { get; set; }
/// <summary>
/// 提现时间 由<see cref="TranDate"/>和<see cref="TranTime"/>组成
/// </summary>
[XmlIgnore]
public DateTime? TransactionTime
{
get
{
if (DateTime.TryParseExact(string.Format("{0}{1}", this.TranDate, this.TranTime),
new string[] { "yyyyMMdd", "yyyyMMddHHmmss" }, CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime tmp))
{
return tmp;
}
return null;
}
}
}
}
| 28.107843 | 133 | 0.49564 | [
"MIT"
] | fdstar/BankEnterpriseDirectAttach | src/BEDA.CITIC/Contracts/Responses/ElectronicCommerce/RS_DL3RTXCL.cs | 3,065 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using AutoFixture;
using Demo.Domain.Role;
using Demo.Domain.User;
using Demo.Infrastructure.Persistence;
using Demo.Infrastructure.Persistence.Configuration;
using Demo.Infrastructure.Settings;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Demo.WebApi.Tests.Helpers
{
public abstract class TestBase : IClassFixture<CustomWebApplicationFactory>
{
private readonly IList<Role> _allRoles;
private readonly SharedFixture _fixture;
protected readonly Fixture AutoFixture;
protected readonly HttpClient Client;
protected readonly CustomWebApplicationFactory Factory;
protected readonly HubConnection HubConnection;
protected IServiceProvider ServiceProvider;
public TestBase(SharedFixture fixture)
{
_fixture = fixture;
Factory = _fixture.Factory;
ServiceProvider = _fixture.Factory.Services;
Client = _fixture.Client;
HubConnection = _fixture.HubConnection;
AutoFixture = AutoFixtureFactory.CreateAutofixtureWithDefaultConfiguration();
ResetDatabaseAsync().Wait();
_allRoles = FindExistingEntitiesAsync<Role>(x => true).Result.ToList();
}
protected HttpClient CreateHttpClientWithCustomConfiguration(Action<IServiceCollection> servicesConfiguration)
{
var webhost = Factory
.WithWebHostBuilder(builder => { builder.ConfigureTestServices(servicesConfiguration); });
var client = webhost.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TestAuthHandler.DefaultScheme);
ServiceProvider = webhost.Services;
return client;
}
protected async Task ResetDatabaseAsync()
{
using var scope = ServiceProvider.CreateScope();
var environmentSettings = scope.ServiceProvider.GetRequiredService<EnvironmentSettings>();
await _fixture.Checkpoint.Reset(environmentSettings.ConnectionStrings.SqlDatabase);
}
protected async Task SetTestUserToUnauthenticated()
{
await SetTestUser(false, Array.Empty<Guid>());
}
protected async Task SetTestUserToAuthenticated()
{
await SetTestUser(true, new[] { RoleEntityTypeConfiguration.UserRoleId });
}
protected async Task SetTestUserToAuthenticatedWithAdministratorRole()
{
await SetTestUser(true,
new[] { RoleEntityTypeConfiguration.UserRoleId, RoleEntityTypeConfiguration.AdministratorRoleId });
}
private async Task SetTestUser(bool isAuthenticated, IEnumerable<Guid> roleIds)
{
var testUser = ServiceProvider.GetRequiredService<TestUser>();
testUser.IsAuthenticated = isAuthenticated;
testUser.Roles = roleIds.Select(roleId => _allRoles.Single(x => x.Id == roleId)).ToList();
var userId = Guid.NewGuid();
testUser.User = new User
{
Id = userId,
ExternalId = string.Concat("auth0|", userId.ToString().ToLower()),
Email = "test@test.com",
FamilyName = "TestUser",
Fullname = "TestUser",
UserRoles = roleIds.Select(roleId => new UserRole { RoleId = roleId }).ToList()
};
await AddAsExistingEntityAsync(testUser.User);
}
protected async Task AddAsExistingEntityAsync<TEntity>(TEntity entity) where TEntity : class
{
using var scope = ServiceProvider.CreateScope();
await using var applicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
applicationDbContext.Set<TEntity>().Add(entity);
await applicationDbContext.SaveChangesAsync();
}
protected async Task AddAsExistingEntitiesAsync<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
{
using var scope = ServiceProvider.CreateScope();
await using var applicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
applicationDbContext.Set<TEntity>().AddRange(entities);
await applicationDbContext.SaveChangesAsync();
}
protected async Task<TEntity> FindExistingEntityAsync<TEntity>(Expression<Func<TEntity, bool>> predicate)
where TEntity : class
{
return (await FindExistingEntitiesAsync(predicate)).SingleOrDefault();
}
protected async Task<IEnumerable<TEntity>> FindExistingEntitiesAsync<TEntity>(
Expression<Func<TEntity, bool>> predicate) where TEntity : class
{
using var scope = ServiceProvider.CreateScope();
await using var applicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
return await applicationDbContext
.Set<TEntity>()
.AsQueryable()
.Where(predicate)
.ToListAsync();
}
protected static void WithRetry(Action assertion, TimeSpan timeout, TimeSpan pollInterval, string because = "",
params object[] becauseArgs)
{
assertion.Should().NotThrowAfter(timeout, pollInterval, because, becauseArgs);
}
}
}
| 40.763889 | 119 | 0.671721 | [
"MIT"
] | nvdvlies/dotnet-api-and-angular-frontend | test/Demo.WebApi.Tests/Helpers/TestBase.cs | 5,872 | C# |
using System;
using System.Collections.Generic;
using CommandLine;
using CommandLine.Text;
namespace StyleCopCmd
{
// Define a class to receive parsed values
public class CommandLineOptions
{
public IList<string> Items { get; set; }
[OptionArray('s', "solution", HelpText = "Define one or more solution for which the analysation should be done")]
public string[] Solutions { get; set; }
[OptionArray('p', "project", HelpText = "Define one or more projects for which the analysation should be done")]
public List<string> Projects { get; set; }
[Option('w', "strict", DefaultValue = true, HelpText = "Count warnings as errors")]
public bool WarningsAsErrors { get; set; }
[Option('d', "exitCode", HelpText = "Not only log to all reporters, in addition return an error code on exit if and violations has occured")]
public bool EnableExitCode { get; set; }
[Option('c', "console", DefaultValue = false, HelpText = "Report errors and warnings to console")]
public bool Console { get; set; }
[Option("styleCopXml", HelpText = "Specify a file to which the results should be saved in StyleCopXml-Format (ValidationResults.xml)")]
public string StyleCopXml { get; set; }
[Option("nUnitXml", HelpText = "Specify a file to which the results should be saved in NUnitTestXml-Format")]
public string NUnitXml { get; set; }
[Option('t', "teamcity", HelpText = "Send the results via teamcity services messages")]
public bool TeamCityServiceMessages { get; set; }
[HelpOption]
public string GetUsage()
{
return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current));
}
}
}
| 39.955556 | 149 | 0.66129 | [
"MIT"
] | michaelschnyder/StyleCopCmd | StyleCopCmd/CommandLineOptions.cs | 1,800 | C# |
using System.Text.Json;
namespace Opa.Wasm
{
public class DefaultOpaSerializer : IOpaSerializer
{
public static readonly DefaultOpaSerializer Instance = new DefaultOpaSerializer();
private static JsonSerializerOptions _stjDefaultOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public string Serialize(object obj)
{
return JsonSerializer.Serialize(obj, _stjDefaultOptions);
}
public T Deserialize<T>(string json)
{
return JsonSerializer.Deserialize<T>(json, _stjDefaultOptions);
}
}
}
| 22.56 | 85 | 0.771277 | [
"MIT"
] | ben-page/dotnet-opa-wasm | src/Opa.Wasm/DefaultOpaSerializer.cs | 566 | C# |
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
namespace TencentCloud.Cwp.V20180228.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class DescribeEmergencyResponseListResponse : AbstractModel
{
/// <summary>
/// 总条数
/// </summary>
[JsonProperty("TotalCount")]
public ulong? TotalCount{ get; set; }
/// <summary>
/// 应急响应列表
/// </summary>
[JsonProperty("List")]
public EmergencyResponseInfo[] List{ get; set; }
/// <summary>
/// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
/// </summary>
[JsonProperty("RequestId")]
public string RequestId{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "TotalCount", this.TotalCount);
this.SetParamArrayObj(map, prefix + "List.", this.List);
this.SetParamSimple(map, prefix + "RequestId", this.RequestId);
}
}
}
| 30.862069 | 81 | 0.630726 | [
"Apache-2.0"
] | TencentCloud/tencentcloud-sdk-dotnet | TencentCloud/Cwp/V20180228/Models/DescribeEmergencyResponseListResponse.cs | 1,866 | C# |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using NUnit.Framework;
using System;
using Twilio.Converters;
using Twilio.TwiML.Voice;
namespace Twilio.Tests.TwiML
{
[TestFixture]
public class SsmlSTest : TwilioTest
{
[Test]
public void TestEmptyElement()
{
var elem = new SsmlS();
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s></s>",
elem.ToString()
);
}
[Test]
public void TestElementWithParams()
{
var elem = new SsmlS("words");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s>words</s>",
elem.ToString()
);
}
[Test]
public void TestElementWithExtraAttributes()
{
var elem = new SsmlS();
elem.SetOption("newParam1", "value");
elem.SetOption("newParam2", 1);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s newParam1=\"value\" newParam2=\"1\"></s>",
elem.ToString()
);
}
[Test]
public void TestElementWithTextNode()
{
var elem = new SsmlS();
elem.AddText("Here is the content");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s>Here is the content</s>",
elem.ToString()
);
}
[Test]
public void TestAllowGenericChildNodes()
{
var elem = new SsmlS();
elem.AddChild("generic-tag").AddText("Content").SetOption("tag", true);
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s>" + Environment.NewLine +
" <generic-tag tag=\"True\">Content</generic-tag>" + Environment.NewLine +
"</s>",
elem.ToString()
);
}
[Test]
public void TestMixedContent()
{
var elem = new SsmlS();
elem.AddText("before")
.AddChild("Child").AddText("content");
elem.AddText("after");
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine +
"<s>before<Child>content</Child>after</s>",
elem.ToString()
);
}
}
} | 27.555556 | 91 | 0.453079 | [
"MIT"
] | FMV1491/twilio-csharp | test/Twilio.Test/TwiML/SsmlSTest.cs | 2,728 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreStorageAccount.Entities;
namespace AspNetCoreStorageAccount.Repository
{
public interface IDemoRepository
{
Task<List<DemoTableEntity>> GetAllRecords();
}
} | 23.454545 | 52 | 0.775194 | [
"MIT"
] | meanin/asp-net-core-azure-storage-account | AspNetCoreStorageAccount/Repository/IDemoRepository.cs | 260 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.